Skip to content

Commit

Permalink
interp: Don't output raw binary if display is called explicitly
Browse files Browse the repository at this point in the history
So raw binay is only outputted if stdout is not a terminal and "... | d" is not used..
fq -n '[1,2,3] | tobytes' | cat > binary
fq -n '[1,2,3] | tobytes | d' | cat > hexdump
  • Loading branch information
wader committed May 11, 2023
1 parent 1cbc253 commit 033498b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 11 deletions.
20 changes: 11 additions & 9 deletions pkg/interp/init.jq
Original file line number Diff line number Diff line change
Expand Up @@ -137,19 +137,21 @@ def _cli_slurp_error(_):
_eval_error("compile"; "slurp can only be used from interactive repl");
# TODO: rewrite query to reuse _display_default_opts value? also _repl_display
def _cli_display:
display(_display_default_opts);
display_implicit(_display_default_opts);
# _cli_eval halts on compile errors
def _cli_eval($expr; $opts):
eval(
$expr;
$opts + {
slurps: {
help: "_help_slurp",
repl: "_cli_repl_error",
slurp: "_cli_slurp_error"
},
catch_query: _query_func("_cli_eval_on_expr_error"),
};
( $opts
+ {
slurps: {
help: "_help_slurp",
repl: "_cli_repl_error",
slurp: "_cli_slurp_error"
},
catch_query: _query_func("_cli_eval_on_expr_error"),
}
);
_cli_eval_on_error;
_cli_eval_on_compile_error
);
Expand Down
13 changes: 11 additions & 2 deletions pkg/interp/interp.jq
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,18 @@ def _todisplay:
| _format_func($f; "_todisplay")
);

def display($opts):
def display($opts; $explicit_call):
( . as $c
| options($opts) as $opts
| try _todisplay catch $c
| if $opts.value_output then tovalue end
| if _can_display then _display($opts)
| if _can_display then
_display(
( $opts
# don't output raw binary if d/display was call explicitly
| if $explicit_call then .raw_output = false end
)
)
else
( if _is_string and $opts.raw_string then print
else _print_color_json($opts)
Expand All @@ -29,8 +35,11 @@ def display($opts):
end
| error("unreachable")
);
def display($opts): display($opts; true);
def display: display({});

def display_implicit($opts): display($opts; false);

def d($opts): display($opts);
def d: display({});
def da($opts): display({array_truncate: 0} + $opts);
Expand Down
4 changes: 4 additions & 0 deletions pkg/interp/testdata/binary_stdout.fqtest
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ $ _STDOUT_IS_TERMINAL=0 _STDOUT_HEX=1 NO_COLOR=1 fq -n '[1,1,1 | tobits] | tobit
0380\
$ _STDOUT_IS_TERMINAL=0 _STDOUT_HEX=1 NO_COLOR=1 fq -n '[5 | tobits(12)], [3 | tobytes(3)] | tobytes'
0005000003\
# explicit call to display don't output binary
$ _STDOUT_IS_TERMINAL=0 NO_COLOR=1 fq -n '[1,2,3] | tobytes | d'
|00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f|0123456789abcdef|
0x0|01 02 03| |...| |.: raw bits 0x0-0x2.7 (3)

0 comments on commit 033498b

Please sign in to comment.