git.delta.rocks / jrsonnet / refs/commits / a02e7e9bff04

difftreelog

source

crates/jrsonnet-stdlib/src/std.jsonnet19.0 KiBsourcehistory
1{2  local std = self,3  local id = std.id,45  # Those functions aren't normally located in stdlib6  length:: $intrinsic(length),7  type:: $intrinsic(type),8  makeArray:: $intrinsic(makeArray),9  codepoint:: $intrinsic(codepoint),10  objectFieldsEx:: $intrinsic(objectFieldsEx),11  objectHasEx:: $intrinsic(objectHasEx),12  primitiveEquals:: $intrinsic(primitiveEquals),13  modulo:: $intrinsic(modulo),14  floor:: $intrinsic(floor),15  ceil:: $intrinsic(ceil),16  extVar:: $intrinsic(extVar),17  native:: $intrinsic(native),18  filter:: $intrinsic(filter),19  char:: $intrinsic(char),20  encodeUTF8:: $intrinsic(encodeUTF8),21  decodeUTF8:: $intrinsic(decodeUTF8),22  md5:: $intrinsic(md5),23  trace:: $intrinsic(trace),24  id:: $intrinsic(id),25  parseJson:: $intrinsic(parseJson),2627  log:: $intrinsic(log),28  pow:: $intrinsic(pow),29  sqrt:: $intrinsic(sqrt),3031  sin:: $intrinsic(sin),32  cos:: $intrinsic(cos),33  tan:: $intrinsic(tan),34  asin:: $intrinsic(asin),35  acos:: $intrinsic(acos),36  atan:: $intrinsic(atan),3738  exp:: $intrinsic(exp),39  mantissa:: $intrinsic(mantissa),40  exponent:: $intrinsic(exponent),4142  isString(v):: std.type(v) == 'string',43  isNumber(v):: std.type(v) == 'number',44  isBoolean(v):: std.type(v) == 'boolean',45  isObject(v):: std.type(v) == 'object',46  isArray(v):: std.type(v) == 'array',47  isFunction(v):: std.type(v) == 'function',4849  toString(a)::50    if std.type(a) == 'string' then a else '' + a,5152  substr:: $intrinsic(substr),5354  startsWith(a, b)::55    if std.length(a) < std.length(b) then56      false57    else58      std.substr(a, 0, std.length(b)) == b,5960  endsWith(a, b)::61    if std.length(a) < std.length(b) then62      false63    else64      std.substr(a, std.length(a) - std.length(b), std.length(b)) == b,6566  lstripChars(str, chars)::67    if std.length(str) > 0 && std.member(chars, str[0]) then68      std.lstripChars(str[1:], chars)69    else70      str,7172  rstripChars(str, chars)::73    local len = std.length(str);74    if len > 0 && std.member(chars, str[len - 1]) then75      std.rstripChars(str[:len - 1], chars)76    else77      str,7879  stripChars(str, chars)::80    std.lstripChars(std.rstripChars(str, chars), chars),8182  stringChars(str)::83    std.makeArray(std.length(str), function(i) str[i]),8485  local parse_nat(str, base) =86    assert base > 0 && base <= 16 : 'integer base %d invalid' % base;87    // These codepoints are in ascending order:88    local zero_code = std.codepoint('0');89    local upper_a_code = std.codepoint('A');90    local lower_a_code = std.codepoint('a');91    local addDigit(aggregate, char) =92      local code = std.codepoint(char);93      local digit = if code >= lower_a_code then94        code - lower_a_code + 1095      else if code >= upper_a_code then96        code - upper_a_code + 1097      else98        code - zero_code;99      assert digit >= 0 && digit < base : '%s is not a base %d integer' % [str, base];100      base * aggregate + digit;101    std.foldl(addDigit, std.stringChars(str), 0),102103  parseInt(str)::104    assert std.isString(str) : 'Expected string, got ' + std.type(str);105    assert std.length(str) > 0 && str != '-' : 'Not an integer: "%s"' % [str];106    if str[0] == '-' then107      -parse_nat(str[1:], 10)108    else109      parse_nat(str, 10),110111  parseOctal(str)::112    assert std.isString(str) : 'Expected string, got ' + std.type(str);113    assert std.length(str) > 0 : 'Not an octal number: ""';114    parse_nat(str, 8),115116  parseHex(str)::117    assert std.isString(str) : 'Expected string, got ' + std.type(str);118    assert std.length(str) > 0 : 'Not hexadecimal: ""';119    parse_nat(str, 16),120121  split(str, c)::122    assert std.isString(str) : 'std.split first parameter should be a string, got ' + std.type(str);123    assert std.isString(c) : 'std.split second parameter should be a string, got ' + std.type(c);124    assert std.length(c) == 1 : 'std.split second parameter should have length 1, got ' + std.length(c);125    std.splitLimit(str, c, -1),126127  splitLimit:: $intrinsic(splitLimit),128129  strReplace:: $intrinsic(strReplace),130131  asciiUpper:: $intrinsic(asciiUpper),132133  asciiLower:: $intrinsic(asciiLower),134135  range:: $intrinsic(range),136137  repeat(what, count)::138    local joiner =139      if std.isString(what) then ''140      else if std.isArray(what) then []141      else error 'std.repeat first argument must be an array or a string';142    std.join(joiner, std.makeArray(count, function(i) what)),143144  slice:: $intrinsic(slice),145146  member:: $intrinsic(member),147148  count:: $intrinsic(count),149150  mod:: $intrinsic(mod),151152  map:: $intrinsic(map),153154  mapWithIndex(func, arr)::155    if !std.isFunction(func) then156      error ('std.mapWithIndex first param must be function, got ' + std.type(func))157    else if !std.isArray(arr) && !std.isString(arr) then158      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))159    else160      std.makeArray(std.length(arr), function(i) func(i, arr[i])),161162  mapWithKey(func, obj)::163    if !std.isFunction(func) then164      error ('std.mapWithKey first param must be function, got ' + std.type(func))165    else if !std.isObject(obj) then166      error ('std.mapWithKey second param must be object, got ' + std.type(obj))167    else168      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },169170  flatMap:: $intrinsic(flatMap),171172  join:: $intrinsic(join),173174  lines(arr)::175    std.join('\n', arr + ['']),176177  deepJoin(arr)::178    if std.isString(arr) then179      arr180    else if std.isArray(arr) then181      std.join('', [std.deepJoin(x) for x in arr])182    else183      error 'Expected string or array, got %s' % std.type(arr),184185186  format:: $intrinsic(format),187188  foldr:: $intrinsic(foldr),189190  foldl:: $intrinsic(foldl),191192  filterMap(filter_func, map_func, arr)::193    if !std.isFunction(filter_func) then194      error ('std.filterMap first param must be function, got ' + std.type(filter_func))195    else if !std.isFunction(map_func) then196      error ('std.filterMap second param must be function, got ' + std.type(map_func))197    else if !std.isArray(arr) then198      error ('std.filterMap third param must be array, got ' + std.type(arr))199    else200      std.map(map_func, std.filter(filter_func, arr)),201202  assertEqual(a, b)::203    if a == b then204      true205    else206      error 'Assertion failed. ' + a + ' != ' + b,207208  abs(n)::209    if !std.isNumber(n) then210      error 'std.abs expected number, got ' + std.type(n)211    else212      if n > 0 then n else -n,213214  sign(n)::215    if !std.isNumber(n) then216      error 'std.sign expected number, got ' + std.type(n)217    else218      if n > 0 then219        1220      else if n < 0 then221        -1222      else 0,223224  max(a, b)::225    if !std.isNumber(a) then226      error 'std.max first param expected number, got ' + std.type(a)227    else if !std.isNumber(b) then228      error 'std.max second param expected number, got ' + std.type(b)229    else230      if a > b then a else b,231232  min(a, b)::233    if !std.isNumber(a) then234      error 'std.min first param expected number, got ' + std.type(a)235    else if !std.isNumber(b) then236      error 'std.min second param expected number, got ' + std.type(b)237    else238      if a < b then a else b,239240  clamp(x, minVal, maxVal)::241    if x < minVal then minVal242    else if x > maxVal then maxVal243    else x,244245  flattenArrays(arrs)::246    std.foldl(function(a, b) a + b, arrs, []),247248  manifestIni(ini)::249    local body_lines(body) =250      std.join([], [251        local value_or_values = body[k];252        if std.isArray(value_or_values) then253          ['%s = %s' % [k, value] for value in value_or_values]254        else255          ['%s = %s' % [k, value_or_values]]256257        for k in std.objectFields(body)258      ]);259260    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),261          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],262          all_sections = [263      section_lines(k, ini.sections[k])264      for k in std.objectFields(ini.sections)265    ];266    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),267268  manifestToml(value):: std.manifestTomlEx(value, '  '),269270  manifestTomlEx(value, indent)::271    local272      escapeStringToml = std.escapeStringJson,273      escapeKeyToml(key) =274        local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));275        if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),276      isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.foldl(function(a, b) a && std.isObject(b), v, true),277      isSection(v) = std.isObject(v) || isTableArray(v),278      renderValue(v, indexedPath, inline, cindent) =279        if v == true then280          'true'281        else if v == false then282          'false'283        else if v == null then284          error 'Tried to manifest "null" at ' + indexedPath285        else if std.isNumber(v) then286          '' + v287        else if std.isString(v) then288          escapeStringToml(v)289        else if std.isFunction(v) then290          error 'Tried to manifest function at ' + indexedPath291        else if std.isArray(v) then292          if std.length(v) == 0 then293            '[]'294          else295            local range = std.range(0, std.length(v) - 1);296            local new_indent = if inline then '' else cindent + indent;297            local separator = if inline then ' ' else '\n';298            local lines = ['[' + separator]299                          + std.join([',' + separator],300                                     [301                                       [new_indent + renderValue(v[i], indexedPath + [i], true, '')]302                                       for i in range303                                     ])304                          + [separator + (if inline then '' else cindent) + ']'];305            std.join('', lines)306        else if std.isObject(v) then307          local lines = ['{ ']308                        + std.join([', '],309                                   [310                                     [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]311                                     for k in std.objectFields(v)312                                   ])313                        + [' }'];314          std.join('', lines),315      renderTableInternal(v, path, indexedPath, cindent) =316        local kvp = std.flattenArrays([317          [cindent + escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], false, cindent)]318          for k in std.objectFields(v)319          if !isSection(v[k])320        ]);321        local sections = [std.join('\n', kvp)] + [322          (323            if std.isObject(v[k]) then324              renderTable(v[k], path + [k], indexedPath + [k], cindent)325            else326              renderTableArray(v[k], path + [k], indexedPath + [k], cindent)327          )328          for k in std.objectFields(v)329          if isSection(v[k])330        ];331        std.join('\n\n', sections),332      renderTable(v, path, indexedPath, cindent) =333        cindent + '[' + std.join('.', std.map(escapeKeyToml, path)) + ']'334        + (if v == {} then '' else '\n')335        + renderTableInternal(v, path, indexedPath, cindent + indent),336      renderTableArray(v, path, indexedPath, cindent) =337        local range = std.range(0, std.length(v) - 1);338        local sections = [339          (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'340           + (if v[i] == {} then '' else '\n')341           + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))342          for i in range343        ];344        std.join('\n\n', sections);345    if std.isObject(value) then346      renderTableInternal(value, [], [], '')347    else348      error 'TOML body must be an object. Got ' + std.type(value),349350  escapeStringJson:: $intrinsic(escapeStringJson),351352  escapeStringPython(str)::353    std.escapeStringJson(str),354355  escapeStringBash(str_)::356    local str = std.toString(str_);357    local trans(ch) =358      if ch == "'" then359        "'\"'\"'"360      else361        ch;362    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),363364  escapeStringDollars(str_)::365    local str = std.toString(str_);366    local trans(ch) =367      if ch == '$' then368        '$$'369      else370        ch;371    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),372373  manifestJson(value):: std.manifestJsonEx(value, '    '),374375  manifestJsonMinified(value):: std.manifestJsonEx(value, '', '', ':'),376377  manifestJsonExImpl:: $intrinsic(manifestJsonExImpl),378379  manifestJsonEx(value, indent, newline='\n', key_val_sep=': '):: std.manifestJsonExImpl(value, indent, newline, key_val_sep),380381  manifestYamlDocImpl:: $intrinsic(manifestYamlDocImpl),382383  manifestYamlDoc(value, indent_array_in_object=false):: std.manifestYamlDocImpl(value, indent_array_in_object),384385  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::386    if !std.isArray(value) then387      error 'manifestYamlStream only takes arrays, got ' + std.type(value)388    else389      '---\n' + std.join(390        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object) for e in value]391      ) + if c_document_end then '\n...\n' else '\n',392393394  manifestPython(v)::395    if std.isObject(v) then396      local fields = [397        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]398        for k in std.objectFields(v)399      ];400      '{%s}' % [std.join(', ', fields)]401    else if std.isArray(v) then402      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]403    else if std.isString(v) then404      '%s' % [std.escapeStringPython(v)]405    else if std.isFunction(v) then406      error 'cannot manifest function'407    else if std.isNumber(v) then408      std.toString(v)409    else if v == true then410      'True'411    else if v == false then412      'False'413    else if v == null then414      'None',415416  manifestPythonVars(conf)::417    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];418    std.join('\n', vars + ['']),419420  manifestXmlJsonml(value)::421    if !std.isArray(value) then422      error 'Expected a JSONML value (an array), got %s' % std.type(value)423    else424      local aux(v) =425        if std.isString(v) then426          v427        else428          local tag = v[0];429          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);430          local attrs = if has_attrs then v[1] else {};431          local children = if has_attrs then v[2:] else v[1:];432          local attrs_str =433            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);434          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);435436      aux(value),437438  local base64_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',439  local base64_inv = { [base64_table[i]]: i for i in std.range(0, 63) },440441  base64:: $intrinsic(base64),442443  base64DecodeBytes:: $intrinsic(base64DecodeBytes),444445  base64Decode:: $intrinsic(base64Decode),446447  reverse:: $intrinsic(reverse),448449  sortImpl:: $intrinsic(sortImpl),450451  sort(arr, keyF=id)::452    std.sortImpl(arr, keyF),453454  uniq(arr, keyF=id)::455    local f(a, b) =456      if std.length(a) == 0 then457        [b]458      else if keyF(a[std.length(a) - 1]) == keyF(b) then459        a460      else461        a + [b];462    std.foldl(f, arr, []),463464  set(arr, keyF=id)::465    std.uniq(std.sort(arr, keyF), keyF),466467  setMember(x, arr, keyF=id)::468    // TODO(dcunnin): Binary chop for O(log n) complexity469    std.length(std.setInter([x], arr, keyF)) > 0,470471  setUnion(a, b, keyF=id)::472    // NOTE: order matters, values in `a` win473    local aux(a, b, i, j, acc) =474      if i >= std.length(a) then475        acc + b[j:]476      else if j >= std.length(b) then477        acc + a[i:]478      else479        local ak = keyF(a[i]);480        local bk = keyF(b[j]);481        if ak == bk then482          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict483        else if ak < bk then484          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict485        else486          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;487    aux(a, b, 0, 0, []),488489  setInter(a, b, keyF=id)::490    local aux(a, b, i, j, acc) =491      if i >= std.length(a) || j >= std.length(b) then492        acc493      else494        if keyF(a[i]) == keyF(b[j]) then495          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict496        else if keyF(a[i]) < keyF(b[j]) then497          aux(a, b, i + 1, j, acc) tailstrict498        else499          aux(a, b, i, j + 1, acc) tailstrict;500    aux(a, b, 0, 0, []) tailstrict,501502  setDiff(a, b, keyF=id)::503    local aux(a, b, i, j, acc) =504      if i >= std.length(a) then505        acc506      else if j >= std.length(b) then507        acc + a[i:]508      else509        if keyF(a[i]) == keyF(b[j]) then510          aux(a, b, i + 1, j + 1, acc) tailstrict511        else if keyF(a[i]) < keyF(b[j]) then512          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict513        else514          aux(a, b, i, j + 1, acc) tailstrict;515    aux(a, b, 0, 0, []) tailstrict,516517  mergePatch(target, patch)::518    if std.isObject(patch) then519      local target_object =520        if std.isObject(target) then target else {};521522      local target_fields =523        if std.isObject(target_object) then std.objectFields(target_object) else [];524525      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];526      local both_fields = std.setUnion(target_fields, std.objectFields(patch));527528      {529        [k]:530          if !std.objectHas(patch, k) then531            target_object[k]532          else if !std.objectHas(target_object, k) then533            std.mergePatch(null, patch[k]) tailstrict534          else535            std.mergePatch(target_object[k], patch[k]) tailstrict536        for k in std.setDiff(both_fields, null_fields)537      }538    else539      patch,540541  get(o, f, default = null, inc_hidden = true)::542    if std.objectHasEx(o, f, inc_hidden) then o[f] else default,543544  objectFields(o)::545    std.objectFieldsEx(o, false),546547  objectFieldsAll(o)::548    std.objectFieldsEx(o, true),549550  objectHas(o, f)::551    std.objectHasEx(o, f, false),552553  objectHasAll(o, f)::554    std.objectHasEx(o, f, true),555556  objectValues(o)::557    [o[k] for k in std.objectFields(o)],558559  objectValuesAll(o)::560    [o[k] for k in std.objectFieldsAll(o)],561562  equals:: $intrinsic(equals),563564  resolvePath(f, r)::565    local arr = std.split(f, '/');566    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),567568  prune(a)::569    local isContent(b) =570      if b == null then571        false572      else if std.isArray(b) then573        std.length(b) > 0574      else if std.isObject(b) then575        std.length(b) > 0576      else577        true;578    if std.isArray(a) then579      [std.prune(x) for x in a if isContent($.prune(x))]580    else if std.isObject(a) then {581      [x]: $.prune(a[x])582      for x in std.objectFields(a)583      if isContent(std.prune(a[x]))584    } else585      a,586587  findSubstr(pat, str)::588    if !std.isString(pat) then589      error 'findSubstr first parameter should be a string, got ' + std.type(pat)590    else if !std.isString(str) then591      error 'findSubstr second parameter should be a string, got ' + std.type(str)592    else593      local pat_len = std.length(pat);594      local str_len = std.length(str);595      if pat_len == 0 || str_len == 0 || pat_len > str_len then596        []597      else598        std.filter(function(i) str[i:i + pat_len] == pat, std.range(0, str_len - pat_len)),599600  find(value, arr)::601    if !std.isArray(arr) then602      error 'find second parameter should be an array, got ' + std.type(arr)603    else604      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),605}