Skip to content

Commit

Permalink
Add better failure handling
Browse files Browse the repository at this point in the history
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
  • Loading branch information
reegnz committed Nov 10, 2023
1 parent e61804e commit 60d3b6f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
9 changes: 6 additions & 3 deletions bin/jq-repl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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="." \
Expand Down
32 changes: 32 additions & 0 deletions bin/jq-repl-preview
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 60d3b6f

Please sign in to comment.