From ab5c5b01fc165a0a8bc8e818edfc40f49959c77a Mon Sep 17 00:00:00 2001 From: yertto Date: Sat, 3 Sep 2022 09:50:49 +1000 Subject: [PATCH] feat: Define debug/1 in terms of debug/0 ie. so it can be used for logging debug messages. This modifies `debug` to `tee` the `stdin` to `stdout` without consuming it, while printing the debug messages to `stderr` if `LOG_LEVEL=DEBUG` is set in `$ENV`. Example usage: ``` seq 2 | LOG_LEVEL=DEBUG jq ' debug({$ENV}) | debug({line: input_line_number}) | debug("here1: .=\(.)") | . * 10 | debug("here2: .=\(.)") | . + 1 ' ``` => ``` ["DEBUG:",{"ENV":{"PWD":"/tmp","SHELL":"/bin/zsh","PATH":"/usr/bin:/bin", ...}}] ["DEBUG:",{"line":1}] ["DEBUG:","here1: .=1"] ["DEBUG:","here2: .=10"] 11 ["DEBUG:",{"ENV":{"PWD":"/tmp","SHELL":"/bin/zsh","PATH":"/usr/bin:/bin", ...}}] ["DEBUG:",{"line":2}] ["DEBUG:","here1: .=2"] ["DEBUG:","here2: .=20"] 21 ``` Or without `LOG_LEVEL=DEBUG`: ``` seq 2 | jq ' debug({$ENV}) | debug({line: input_line_number}) | debug("here1: .=\(.)") | . * 10 | debug("here2: .=\(.)") | . + 1 ' ``` => ``` 11 21 ``` --- src/builtin.jq | 1 + 1 file changed, 1 insertion(+) diff --git a/src/builtin.jq b/src/builtin.jq index a102fd51a0..3c870ddd03 100644 --- a/src/builtin.jq +++ b/src/builtin.jq @@ -1,5 +1,6 @@ def halt_error: halt_error(5); def error(msg): msg|error; +def debug(msg): . as $dot | if env.LOG_LEVEL == "DEBUG" then msg | debug | $dot else . end; def map(f): [.[] | f]; def select(f): if f then . else empty end; def sort_by(f): _sort_by_impl(map([f]));