Skip to content
Myr

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 file

Take it

1def 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]));7def unique_by(f): _unique_by_impl(map([f]));8def 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]}];42def from_entries: add(.[] | { (.key // .Key // .name // .Name):43  if has("value") then .value else .Value end }) // {};44def with_entries(f): to_entries | map(f) | from_entries;45def reverse: [.[range(length-1;-1;-1)]];46def 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");66# 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.68def join($x): reduce .[] as $i (null;69            (if .==null then "" else .+$x end) |70            . + ($i | if type=="boolean" or type=="number" then tostring end)71        ) // "";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);75def range($x;$y): range($x;$y;1);76def 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;81def rtrimstr($right): if endswith($right) then .[:length - ($right | length)] end;82def trimstr($val): ltrimstr($val) | rtrimstr($val);83def 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);105106# splits/1 produces a stream; split/1 is retained for backward compatibility.107def splits($re; $flags):108  .[foreach (match($re; $flags+"g"), null) as {$offset, $length}109      (null; {start: .next, end: $offset, next: ($offset+$length)})];110def splits($re): splits($re; null);111112# split emits an array for backward compatibility113def split($re; $flags): [ splits($re; $flags) ];114115# 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;129130def sub($re; s): sub($re; s; "");131132def gsub($re; s; flags): sub($re; s; flags + "g");133def gsub($re; s): sub($re; s; "g");134135########################################################################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; .);