Skip to content

Commit

Permalink
Implement _experimental_output/2
Browse files Browse the repository at this point in the history
  • Loading branch information
myaaaaaaaaa committed Aug 25, 2024
1 parent 6322b99 commit 9d2cd70
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -1346,7 +1346,31 @@ static jv f_input(jq_state *jq, jv input) {
return v;
return jv_invalid_with_msg(jv_string("break"));
}
static jv f_output(jq_state *jq, jv input, jv filename, jv data) {
if (jv_get_kind(filename) != JV_KIND_STRING)
return ret_error(filename, jv_string("filename must be a string"));

const char *name_str = jv_string_value(filename);
int sandbox = 0; // TODO: --sandbox
if (sandbox) {
fprintf(stderr, "jq: dry run: %s\n", name_str);
} else {
FILE *fp = fopen(name_str, "w");
if (!fp) {
fprintf(stderr, "jq: error: could not open %s\n", name_str);
} else {
if (jv_get_kind(data) == JV_KIND_STRING)
priv_fwrite(jv_string_value(jv_copy(data)), jv_string_length_bytes(jv_copy(data)), fp, 0);
else
jv_dumpf(jv_copy(data), fp, JV_PRINT_ASCII);
fclose(fp);
}
}

jv_free(filename);
jv_free(data);
return input;
}
static jv f_debug(jq_state *jq, jv input) {
jq_msg_cb cb;
void *data;
Expand Down Expand Up @@ -1856,6 +1880,7 @@ BINOPS
{f_match, "_match_impl", 4},
{f_modulemeta, "modulemeta", 1},
{f_input, "input", 1},
{f_output, "_experimental_output", 3},
{f_debug, "debug", 1},
{f_stderr, "stderr", 1},
{f_strptime, "strptime", 2},
Expand Down
16 changes: 16 additions & 0 deletions tests/shtest
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,22 @@ grep "Expected string key after '{', not '\\['" $d/err > /dev/null
echo '{"x":"y",["a","b"]}' | $JQ --stream > /dev/null 2> $d/err || true
grep "Expected string key after ',' in object, not '\\['" $d/err > /dev/null

## Test IO

# output
cat <<EOF | $VALGRIND $Q $JQ -r 'to_entries[] | _experimental_output(.key;.value) | .key' >$d/keys
{
"$d/a.json": "aaa",
"$d/b/b.json": "invalid",
"$d/c/c.json": ["not","valid"],
"$d/d.json": {"e":10},
"$d/f.json": 8
}
EOF
cat $(cat $d/keys) > $d/out || true
printf 'aaa{"e":10}8' > $d/expected
cmp $d/out $d/expected

# debug, stderr
$VALGRIND $Q $JQ -n '"test", {} | debug, stderr' >/dev/null
$JQ -n -c -j '"hello\nworld", null, [false, 0], {"foo":["bar"]}, "\n" | stderr' >$d/out 2>$d/err
Expand Down

0 comments on commit 9d2cd70

Please sign in to comment.