Skip to content

Instantly share code, notes, and snippets.

@emanuele6
Last active May 8, 2023 10:57
Show Gist options
  • Save emanuele6/b2f6055a5ac2cca4618f467d84f739fd to your computer and use it in GitHub Desktop.
Save emanuele6/b2f6055a5ac2cca4618f467d84f739fd to your computer and use it in GitHub Desktop.
#!/bin/sh --
# \
exec jq --unbuffered --stream -rn --args -f "$0" -- "$@"
$ARGS.positional |
if length != 1 then
@json "Invalid arguments: \(.).\n" | halt_error(2)
else . end |
(
.[0] |
try (
tonumber
) catch (
@json "Not a number: \($ARGS.positional[0]).\n" | halt_error(2)
) |
if . <= 0 then
"The argument must be positive; it was: \(.).\n" | halt_error(2)
else . end
) as $n |
def or_if_empty(f; if_empty):
. as $dot |
[ f ] |
if length == 0
then $dot | if_empty
else .[]
end;
try repeat(
reduce range($n) as $i ([];
. + [
. as $dot |
or_if_empty(first(inputs);
error(.)) |
until(. != [ [], [] ] and any(., .[0]; length != 1);
or_if_empty(first(inputs);
error($dot))) |
if .[0][0] | type != "number"
then @json "Unexpected input: \(.).\n" | halt_error(4)
else . end |
if length == 2 and (.[0] | length == 1) then
.[1]
else
fromstream(
. as $dot |
1 | truncate_stream(
$dot |
label $recurse |
recurse(input) |
.,
(select(length == 1 and (.[0] | length == 2)) |
break $recurse)
)
)
end
]
)
) catch (
select(. != [])
) |
tojson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment