builtin.jq
This file
Path
src/builtin.jq
241 lines · 9.3 KiB
Last changed by
Parse the full ISO 8601 grammar in `fromdateiso8601` (#3617)itchynybefore adoptionfd25c3e
History of this fileTake it
The walk stopped after 200 commits: lines older than fa6a2ff point at it.
website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 1–6why, one step back1def halt_error: halt_error(5);2def error(msg): msg|error;3def map(f): [.[] | f];4def select(f): if f then . else empty end;5def sort_by(f): _sort_by_impl(map([f]));6def group_by(f): _group_by_impl(map([f]));improve performance of `unique` and `unique_by` (#3254)itchynybefore adoption95ee663
line 7why, one step back7def unique_by(f): _unique_by_impl(map([f]));website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 8–41why, one step back8def max_by(f): _max_by_impl(map([f]));9def min_by(f): _min_by_impl(map([f]));10def add(f): reduce f as $x (null; . + $x);11def add: add(.[]);12def del(f): delpaths([path(f)]);13def abs: if . < 0 then - . else . end;14def _assign(paths; $value): reduce path(paths) as $p (.; setpath($p; $value));15def _modify(paths; update):16 reduce path(paths) as $p ([., []];17 . as $dot18 | null19 | label $out20 | ($dot[0] | getpath($p)) as $v21 | (22 ( $$$$v23 | update24 | (., break $out) as $v25 | $$$$dot26 | setpath([0] + $p; $v)27 ),28 (29 $$$$dot30 | setpath([1, (.[1] | length)]; $p)31 )32 )33 ) | . as $dot | $dot[0] | delpaths($dot[1]);34def map_values(f): .[] |= f;3536# recurse37def recurse(f): def r: ., (f | r); r;38def recurse(f; cond): def r: ., (f | select(cond) | r); r;39def recurse: recurse(.[]?);4041def to_entries: [keys_unsorted[] as $k | {key: $k, value: .[$k]}];perf: avoid the intermediate array in from_entries (#3626)A4-Tacksbefore adoption4beed4e
lines 42–43why, one step back42def from_entries: add(.[] | { (.key // .Key // .name // .Name):43 if has("value") then .value else .Value end }) // {};website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
line 44why, one step back44def with_entries(f): to_entries | map(f) | from_entries;Implement `range/3` in C for consistent error handling (#3267)itchynybefore adoptione371bfa
line 45why, one step back45def reverse: [.[range(length-1;-1;-1)]];website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 46–65why, one step back46def indices($i): if type == "array" and ($i|type) == "array" then .[$i]47 elif type == "array" then .[[$i]]48 elif type == "string" and ($i|type) == "string" then _strindices($i)49 else .[$i] end;50def index($i): indices($i) | .[0]; # TODO: optimize51def rindex($i): indices($i) | .[-1:][0]; # TODO: optimize52def paths: path(recurse)|select(length > 0);53def paths(node_filter): path(recurse|select(node_filter))|select(length > 0);54def isfinite: type == "number" and (isinfinite | not);55def arrays: select(type == "array");56def objects: select(type == "object");57def iterables: select(type|. == "array" or . == "object");58def booleans: select(type == "boolean");59def numbers: select(type == "number");60def normals: select(isnormal);61def finites: select(isfinite);62def strings: select(type == "string");63def nulls: select(. == null);64def values: select(. != null);65def scalars: select(type|. != "array" and . != "object");Improve performance of join/1 on large arrays (#3639)Artem Lytkinbefore adoption9a75bb0
lines 66–67why, one step back66# Keep the accumulator the only reference on the left of + so the string is67# appended in place; a nested + or a // inside the reduce copies it every step.website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
line 68why, one step back68def join($x): reduce .[] as $i (null;Improve performance of join/1 on large arrays (#3639)Artem Lytkinbefore adoption9a75bb0
lines 69–70why, one step back69 (if .==null then "" else .+$x end) |70 . + ($i | if type=="boolean" or type=="number" then tostring end)website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 71–74why, one step back71 ) // "";72def _flatten($x): reduce .[] as $i ([]; if $i | type == "array" and $x != 0 then . + ($i | _flatten($x-1)) else . + [$i] end);73def flatten($x): if $x < 0 then error("flatten depth must not be negative") else _flatten($x) end;74def flatten: _flatten(-1);Implement `range/3` in C for consistent error handling (#3267)itchynybefore adoptione371bfa
line 75why, one step back75def range($x;$y): range($x;$y;1);website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 76–80why, one step back76def range($x): range(0;$x);77def todateiso8601: strftime("%Y-%m-%dT%H:%M:%SZ");78def fromdate: fromdateiso8601;79def todate: todateiso8601;80def ltrimstr($left): if startswith($left) then .[$left | length:] end;Fix `rtrimstr("")` always output `""` (#3415)A4-Tacksbefore adoption1694573
line 81why, one step back81def rtrimstr($right): if endswith($right) then .[:length - ($right | length)] end;Add trimstr/1 function (#3319)Gabriel Marinbefore adoption7d8c096
line 82why, one step back82def trimstr($val): ltrimstr($val) | rtrimstr($val);website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 83–104why, one step back83def match(re; mode): _match_impl(re; mode; false)|.[];84def match($val): ($val|type) as $vt | if $vt == "string" then match($val; null)85 elif $vt == "array" and ($val | length) > 1 then match($val[0]; $val[1])86 elif $vt == "array" and ($val | length) > 0 then match($val[0]; null)87 else error( $vt + " not a string or array") end;88def test(re; mode): _match_impl(re; mode; true);89def test($val): ($val|type) as $vt | if $vt == "string" then test($val; null)90 elif $vt == "array" and ($val | length) > 1 then test($val[0]; $val[1])91 elif $vt == "array" and ($val | length) > 0 then test($val[0]; null)92 else error( $vt + " not a string or array") end;93def capture(re; mods): match(re; mods) | reduce ( .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair ({}; . + $pair);94def capture($val): ($val|type) as $vt | if $vt == "string" then capture($val; null)95 elif $vt == "array" and ($val | length) > 1 then capture($val[0]; $val[1])96 elif $vt == "array" and ($val | length) > 0 then capture($val[0]; null)97 else error( $vt + " not a string or array") end;98def scan($re; $flags):99 match($re; "g" + $flags)100 | if (.captures|length > 0)101 then [ .captures | .[] | .string ]102 else .string103 end;104def scan($re): scan($re; null);Refactor splits/2 using foreach syntax (remove private filter _nwise) (#3260)itchynybefore adoptionb088e83
line 105why, one step back105website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
line 106why, one step back106# splits/1 produces a stream; split/1 is retained for backward compatibility.Refactor splits/2 using foreach syntax (remove private filter _nwise) (#3260)itchynybefore adoptionb088e83
lines 107–109why, one step back107def splits($re; $flags):108 .[foreach (match($re; $flags+"g"), null) as {$offset, $length}109 (null; {start: .next, end: $offset, next: ($offset+$length)})];website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
line 110why, one step back110def splits($re): splits($re; null);Refactor splits/2 using foreach syntax (remove private filter _nwise) (#3260)itchynybefore adoptionb088e83
line 111why, one step back111website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
line 112why, one step back112# split emits an array for backward compatibilityRefactor splits/2 using foreach syntax (remove private filter _nwise) (#3260)itchynybefore adoptionb088e83
lines 113–114why, one step back113def split($re; $flags): [ splits($re; $flags) ];114website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 115–128why, one step back115# If s contains capture variables, then create a capture object and pipe it to s, bearing116# in mind that s could be a stream117def sub($re; s; $flags):118 . as $in119 | (reduce match($re; $flags) as $edit120 ({result: [], previous: 0};121 $in[ .previous: ($edit | .offset) ] as $gap122 # create the "capture" objects (one per item in s)123 | [reduce ( $edit | .captures | .[] | select(.name != null) | { (.name) : .string } ) as $pair124 ({}; . + $pair) | s ] as $inserts125 | reduce range(0; $inserts|length) as $ix (.; .result[$ix] += $gap + $inserts[$ix])126 | .previous = ($edit | .offset + .length ) )127 | .result[] + $in[.previous:] )128 // $in;Refactor splits/2 using foreach syntax (remove private filter _nwise) (#3260)itchynybefore adoptionb088e83
line 129why, one step back129website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
line 130why, one step back130def sub($re; s): sub($re; s; "");Refactor splits/2 using foreach syntax (remove private filter _nwise) (#3260)itchynybefore adoptionb088e83
line 131why, one step back131website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 132–133why, one step back132def gsub($re; s; flags): sub($re; s; flags + "g");133def gsub($re; s): sub($re; s; "g");Refactor splits/2 using foreach syntax (remove private filter _nwise) (#3260)itchynybefore adoptionb088e83
line 134why, one step back134website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff
lines 135–241why, one step back135########################################################################136# generic iterator/generator137def while(cond; update):138 def _while:139 if cond then ., (update | _while) else empty end;140 _while;141def until(cond; next):142 def _until:143 if cond then . else (next|_until) end;144 _until;145def limit($n; expr):146 if $n > 0 then label $out | foreach expr as $item ($n; . - 1; $item, if . <= 0 then break $out else empty end)147 elif $n == 0 then empty148 else error("limit doesn't support negative count") end;149def skip($n; expr):150 if $n > 0 then foreach expr as $item ($n; . - 1; if . < 0 then $item else empty end)151 elif $n == 0 then expr152 else error("skip doesn't support negative count") end;153def first(g): label $out | g | ., break $out;154def isempty(g): first((g|false), true);155def all(generator; condition): isempty(generator|condition and empty);156def any(generator; condition): isempty(generator|condition or empty)|not;157def all(condition): all(.[]; condition);158def any(condition): any(.[]; condition);159def all: all(.[]; .);160def any: any(.[]; .);161def nth($n; g):162 if $n < 0 then error("nth doesn't support negative indices")163 else first(skip($n; g)) end;164def first: .[0];165def last: .[-1];166def nth($n): .[$n];167def combinations:168 if length == 0 then [] else169 .[0][] as $x170 | (.[1:] | combinations) as $y171 | [$x] + $y172 end;173def combinations(n):174 . as $dot175 | [range(n) | $dot]176 | combinations;177# transpose a possibly jagged matrix, quickly;178# rows are padded with nulls so the result is always rectangular.179def transpose: [range(0; map(length)|max // 0) as $i | [.[][$i]]];180def in(xs): . as $x | xs | has($x);181def inside(xs): . as $x | xs | contains($x);182def repeat(exp):183 def _repeat:184 exp, _repeat;185 _repeat;186def inputs: try repeat(input) catch if .=="break" then empty else error end;187# like ruby's downcase - only characters A to Z are affected188def ascii_downcase:189 explode | map( if 65 <= . and . <= 90 then . + 32 else . end) | implode;190# like ruby's upcase - only characters a to z are affected191def ascii_upcase:192 explode | map( if 97 <= . and . <= 122 then . - 32 else . end) | implode;193194# Streaming utilities195def truncate_stream(stream):196 . as $n | null | stream | . as $input | if (.[0]|length) > $n then setpath([0];$input[0][$n:]) else empty end;197def fromstream(i): {x: null, e: false} as $init |198 # .x = object being built; .e = emit and reset state199 foreach i as $i ($init200 ; if .e then $init else . end201 | if $i|length == 2202 then setpath(["e"]; $i[0]|length==0) | setpath(["x"]+$i[0]; $i[1])203 else setpath(["e"]; $i[0]|length==1) end204 ; if .e then .x else empty end);205def tostream:206 path(def r: (.[]?|r), .; r) as $p |207 getpath($p) |208 reduce path(.[]?) as $q ([$p, .]; [$p+$q]);209210# Apply f to composite entities recursively, and to atoms211def walk(f):212 def w:213 if type == "object"214 then map_values(w)215 elif type == "array" then map(w)216 else .217 end218 | f;219 w;220221# pathexps could be a stream of dot-paths222def pick(pathexps):223 . as $in224 | reduce path(pathexps) as $a (null;225 setpath($a; $in|getpath($a)) );226227# ensure the output of debug(m1,m2) is kept together:228def debug(msgs): (msgs | debug | empty), .;229230# SQL-ish operators here:231def INDEX(stream; idx_expr):232 reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row);233def INDEX(idx_expr): INDEX(.[]; idx_expr);234def JOIN($idx; idx_expr):235 [.[] | [., $idx[idx_expr]]];236def JOIN($idx; stream; idx_expr):237 stream | [., $idx[idx_expr]];238def JOIN($idx; stream; idx_expr; join_expr):239 stream | [., $idx[idx_expr]] | join_expr;240def IN(s): any(s == .; .);241def IN(src; s): any(src == s; .);