From 60d3b6fb3ca1b885ae402cca6a002601ad482919 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zolt=C3=A1n=20Reegn?= Date: Fri, 10 Nov 2023 16:16:24 +0100 Subject: [PATCH] Add better failure handling With this change the failure handling is improved by printing the jq error in red color, printing the last successful jq query (meaning a query that didn't result in a non-zero exit code), and prints the result to the last successful query as well. Idea was proposed by @bazzargh on hackernews: https://news.ycombinator.com/item?id=38191147 --- bin/jq-repl | 9 ++++++--- bin/jq-repl-preview | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) create mode 100755 bin/jq-repl-preview diff --git a/bin/jq-repl b/bin/jq-repl index 2ca6289..eb026f5 100755 --- a/bin/jq-repl +++ b/bin/jq-repl @@ -5,13 +5,16 @@ # if 1st arg is anything else, treat it as a file set -eu -JQ_REPL_JQ="${JQ_REPL_JQ:-jq}" +export JQ_REPL_JQ="${JQ_REPL_JQ:-jq}" if [ -n "${1:-}" ] && [ "$1" != "-" ] && [ "$1" != "--" ]; then input="$1" + output=$(mktemp) + trap 'rm -f "$output"' EXIT else input=$(mktemp) - trap 'rm -f "$input"' EXIT + output=$(mktemp) + trap 'rm -f "$input" "$output"' EXIT fi if [ -z "${1:-}" ] || [ "$1" = "-" ]; then @@ -34,7 +37,7 @@ fi eval "$FZF_JQ_REPL_COMMAND" | fzf \ - --preview "$JQ_REPL_JQ --color-output ${JQ_REPL_ARGS:-} {q} \"$input\"" \ + --preview "jq-repl-preview {q} $input $output" \ --preview-window="down:90%" \ --height="99%" \ --query="." \ diff --git a/bin/jq-repl-preview b/bin/jq-repl-preview new file mode 100755 index 0000000..2c4111c --- /dev/null +++ b/bin/jq-repl-preview @@ -0,0 +1,32 @@ +#!/bin/bash +set -euo pipefail +JQ_REPL_JQ="${JQ_REPL_JQ:-jq}" + +query=$1 +input_file=$2 +last_success_file=$3 + +out="$last_success_file.new" +trap 'rm -f "$out"' EXIT + +# for colorizing stderr +red() { + while read -r line; do + printf "\033[31m%s\033[0m\n" "$line" + done +} + +# prints preview query result to stdout, colorizes stderr to red +do_query() { + $JQ_REPL_JQ --color-output ${JQ_REPL_ARGS:-} "$query" "$input_file" +} 2> >(red) + +echo "Last successful jq expression: $query" | red >"$out" +echo "Last success output:" | red >>"$out" +if do_query | tee -a "$out"; then + # save successful query plus the result + mv "$out" "$last_success_file" +else + # print previously saved successful query + cat "$last_success_file" +fi