git.delta.rocks / jrsonnet / refs/commits / 5f0f8de9f52f

difftreelog

source

crates/jrsonnet-stdlib/src/std.jsonnet14.1 KiBsourcehistory
1{2  local std = self,3  local id = std.id,45  thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support.\nThis will slow down stdlib caching a bit, though',67  toString(a):: '' + a,89  lstripChars(str, chars)::10    if std.length(str) > 0 && std.member(chars, str[0]) then11      std.lstripChars(str[1:], chars)12    else13      str,1415  rstripChars(str, chars)::16    local len = std.length(str);17    if len > 0 && std.member(chars, str[len - 1]) then18      std.rstripChars(str[:len - 1], chars)19    else20      str,2122  stripChars(str, chars)::23    std.lstripChars(std.rstripChars(str, chars), chars),2425  stringChars(str)::26    std.makeArray(std.length(str), function(i) str[i]),2728  split(str, c):: std.splitLimit(str, c, -1),2930  repeat(what, count)::31    local joiner =32      if std.isString(what) then ''33      else if std.isArray(what) then []34      else error 'std.repeat first argument must be an array or a string';35    std.join(joiner, std.makeArray(count, function(i) what)),3637  mapWithIndex(func, arr)::38    if !std.isFunction(func) then39      error ('std.mapWithIndex first param must be function, got ' + std.type(func))40    else if !std.isArray(arr) && !std.isString(arr) then41      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))42    else43      std.makeArray(std.length(arr), function(i) func(i, arr[i])),4445  mapWithKey(func, obj)::46    if !std.isFunction(func) then47      error ('std.mapWithKey first param must be function, got ' + std.type(func))48    else if !std.isObject(obj) then49      error ('std.mapWithKey second param must be object, got ' + std.type(obj))50    else51      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },5253  lines(arr)::54    std.join('\n', arr + ['']),5556  deepJoin(arr)::57    if std.isString(arr) then58      arr59    else if std.isArray(arr) then60      std.join('', [std.deepJoin(x) for x in arr])61    else62      error 'Expected string or array, got %s' % std.type(arr),6364  filterMap(filter_func, map_func, arr)::65    if !std.isFunction(filter_func) then66      error ('std.filterMap first param must be function, got ' + std.type(filter_func))67    else if !std.isFunction(map_func) then68      error ('std.filterMap second param must be function, got ' + std.type(map_func))69    else if !std.isArray(arr) then70      error ('std.filterMap third param must be array, got ' + std.type(arr))71    else72      std.map(map_func, std.filter(filter_func, arr)),7374  assertEqual(a, b)::75    if a == b then76      true77    else78      error 'Assertion failed. ' + a + ' != ' + b,7980  abs(n)::81    if !std.isNumber(n) then82      error 'std.abs expected number, got ' + std.type(n)83    else84      if n > 0 then n else -n,8586  sign(n)::87    if !std.isNumber(n) then88      error 'std.sign expected number, got ' + std.type(n)89    else90      if n > 0 then91        192      else if n < 0 then93        -194      else 0,9596  max(a, b)::97    if !std.isNumber(a) then98      error 'std.max first param expected number, got ' + std.type(a)99    else if !std.isNumber(b) then100      error 'std.max second param expected number, got ' + std.type(b)101    else102      if a > b then a else b,103104  min(a, b)::105    if !std.isNumber(a) then106      error 'std.min first param expected number, got ' + std.type(a)107    else if !std.isNumber(b) then108      error 'std.min second param expected number, got ' + std.type(b)109    else110      if a < b then a else b,111112  clamp(x, minVal, maxVal)::113    if x < minVal then minVal114    else if x > maxVal then maxVal115    else x,116117  flattenArrays(arrs)::118    std.foldl(function(a, b) a + b, arrs, []),119120  manifestIni(ini)::121    local body_lines(body) =122      std.join([], [123        local value_or_values = body[k];124        if std.isArray(value_or_values) then125          ['%s = %s' % [k, value] for value in value_or_values]126        else127          ['%s = %s' % [k, value_or_values]]128129        for k in std.objectFields(body)130      ]);131132    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),133          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],134          all_sections = [135      section_lines(k, ini.sections[k])136      for k in std.objectFields(ini.sections)137    ];138    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),139140  manifestToml(value):: std.manifestTomlEx(value, '  '),141142  manifestTomlEx(value, indent)::143    local144      escapeStringToml = std.escapeStringJson,145      escapeKeyToml(key) =146        local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));147        if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),148      isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.foldl(function(a, b) a && std.isObject(b), v, true),149      isSection(v) = std.isObject(v) || isTableArray(v),150      renderValue(v, indexedPath, inline, cindent) =151        if v == true then152          'true'153        else if v == false then154          'false'155        else if v == null then156          error 'Tried to manifest "null" at ' + indexedPath157        else if std.isNumber(v) then158          '' + v159        else if std.isString(v) then160          escapeStringToml(v)161        else if std.isFunction(v) then162          error 'Tried to manifest function at ' + indexedPath163        else if std.isArray(v) then164          if std.length(v) == 0 then165            '[]'166          else167            local range = std.range(0, std.length(v) - 1);168            local new_indent = if inline then '' else cindent + indent;169            local separator = if inline then ' ' else '\n';170            local lines = ['[' + separator]171                          + std.join([',' + separator],172                                     [173                                       [new_indent + renderValue(v[i], indexedPath + [i], true, '')]174                                       for i in range175                                     ])176                          + [separator + (if inline then '' else cindent) + ']'];177            std.join('', lines)178        else if std.isObject(v) then179          local lines = ['{ ']180                        + std.join([', '],181                                   [182                                     [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]183                                     for k in std.objectFields(v)184                                   ])185                        + [' }'];186          std.join('', lines),187      renderTableInternal(v, path, indexedPath, cindent) =188        local kvp = std.flattenArrays([189          [cindent + escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], false, cindent)]190          for k in std.objectFields(v)191          if !isSection(v[k])192        ]);193        local sections = [std.join('\n', kvp)] + [194          (195            if std.isObject(v[k]) then196              renderTable(v[k], path + [k], indexedPath + [k], cindent)197            else198              renderTableArray(v[k], path + [k], indexedPath + [k], cindent)199          )200          for k in std.objectFields(v)201          if isSection(v[k])202        ];203        std.join('\n\n', sections),204      renderTable(v, path, indexedPath, cindent) =205        cindent + '[' + std.join('.', std.map(escapeKeyToml, path)) + ']'206        + (if v == {} then '' else '\n')207        + renderTableInternal(v, path, indexedPath, cindent + indent),208      renderTableArray(v, path, indexedPath, cindent) =209        local range = std.range(0, std.length(v) - 1);210        local sections = [211          (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'212           + (if v[i] == {} then '' else '\n')213           + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))214          for i in range215        ];216        std.join('\n\n', sections);217    if std.isObject(value) then218      renderTableInternal(value, [], [], '')219    else220      error 'TOML body must be an object. Got ' + std.type(value),221222  escapeStringPython(str)::223    std.escapeStringJson(str),224225  escapeStringBash(str_)::226    local str = std.toString(str_);227    local trans(ch) =228      if ch == "'" then229        "'\"'\"'"230      else231        ch;232    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),233234  escapeStringDollars(str_)::235    local str = std.toString(str_);236    local trans(ch) =237      if ch == '$' then238        '$$'239      else240        ch;241    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),242243  manifestJson(value):: std.manifestJsonEx(value, '    ') tailstrict,244245  manifestJsonMinified(value):: std.manifestJsonEx(value, '', '', ':'),246247  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true)::248    if !std.isArray(value) then249      error 'manifestYamlStream only takes arrays, got ' + std.type(value)250    else251      '---\n' + std.join(252        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object) for e in value]253      ) + if c_document_end then '\n...\n' else '\n',254255256  manifestPython(v)::257    if std.isObject(v) then258      local fields = [259        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]260        for k in std.objectFields(v)261      ];262      '{%s}' % [std.join(', ', fields)]263    else if std.isArray(v) then264      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]265    else if std.isString(v) then266      '%s' % [std.escapeStringPython(v)]267    else if std.isFunction(v) then268      error 'cannot manifest function'269    else if std.isNumber(v) then270      std.toString(v)271    else if v == true then272      'True'273    else if v == false then274      'False'275    else if v == null then276      'None',277278  manifestPythonVars(conf)::279    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];280    std.join('\n', vars + ['']),281282  manifestXmlJsonml(value)::283    if !std.isArray(value) then284      error 'Expected a JSONML value (an array), got %s' % std.type(value)285    else286      local aux(v) =287        if std.isString(v) then288          v289        else290          local tag = v[0];291          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);292          local attrs = if has_attrs then v[1] else {};293          local children = if has_attrs then v[2:] else v[1:];294          local attrs_str =295            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);296          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);297298      aux(value),299300  uniq(arr, keyF=id)::301    local f(a, b) =302      if std.length(a) == 0 then303        [b]304      else if keyF(a[std.length(a) - 1]) == keyF(b) then305        a306      else307        a + [b];308    std.foldl(f, arr, []),309310  set(arr, keyF=id)::311    std.uniq(std.sort(arr, keyF), keyF),312313  setMember(x, arr, keyF=id)::314    // TODO(dcunnin): Binary chop for O(log n) complexity315    std.length(std.setInter([x], arr, keyF)) > 0,316317  setUnion(a, b, keyF=id)::318    // NOTE: order matters, values in `a` win319    local aux(a, b, i, j, acc) =320      if i >= std.length(a) then321        acc + b[j:]322      else if j >= std.length(b) then323        acc + a[i:]324      else325        local ak = keyF(a[i]);326        local bk = keyF(b[j]);327        if ak == bk then328          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict329        else if ak < bk then330          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict331        else332          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;333    aux(a, b, 0, 0, []),334335  setInter(a, b, keyF=id)::336    local aux(a, b, i, j, acc) =337      if i >= std.length(a) || j >= std.length(b) then338        acc339      else340        if keyF(a[i]) == keyF(b[j]) then341          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict342        else if keyF(a[i]) < keyF(b[j]) then343          aux(a, b, i + 1, j, acc) tailstrict344        else345          aux(a, b, i, j + 1, acc) tailstrict;346    aux(a, b, 0, 0, []) tailstrict,347348  setDiff(a, b, keyF=id)::349    local aux(a, b, i, j, acc) =350      if i >= std.length(a) then351        acc352      else if j >= std.length(b) then353        acc + a[i:]354      else355        if keyF(a[i]) == keyF(b[j]) then356          aux(a, b, i + 1, j + 1, acc) tailstrict357        else if keyF(a[i]) < keyF(b[j]) then358          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict359        else360          aux(a, b, i, j + 1, acc) tailstrict;361    aux(a, b, 0, 0, []) tailstrict,362363  mergePatch(target, patch)::364    if std.isObject(patch) then365      local target_object =366        if std.isObject(target) then target else {};367368      local target_fields =369        if std.isObject(target_object) then std.objectFields(target_object) else [];370371      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];372      local both_fields = std.setUnion(target_fields, std.objectFields(patch));373374      {375        [k]:376          if !std.objectHas(patch, k) then377            target_object[k]378          else if !std.objectHas(target_object, k) then379            std.mergePatch(null, patch[k]) tailstrict380          else381            std.mergePatch(target_object[k], patch[k]) tailstrict382        for k in std.setDiff(both_fields, null_fields)383      }384    else385      patch,386387  get(o, f, default=null, inc_hidden=true)::388    if std.objectHasEx(o, f, inc_hidden) then o[f] else default,389390  objectFields(o)::391    std.objectFieldsEx(o, false),392393  objectFieldsAll(o)::394    std.objectFieldsEx(o, true),395396  objectHas(o, f)::397    std.objectHasEx(o, f, false),398399  objectHasAll(o, f)::400    std.objectHasEx(o, f, true),401402  objectValues(o)::403    [o[k] for k in std.objectFields(o)],404405  objectValuesAll(o)::406    [o[k] for k in std.objectFieldsAll(o)],407408  resolvePath(f, r)::409    local arr = std.split(f, '/');410    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),411412  prune(a)::413    local isContent(b) =414      if b == null then415        false416      else if std.isArray(b) then417        std.length(b) > 0418      else if std.isObject(b) then419        std.length(b) > 0420      else421        true;422    if std.isArray(a) then423      [std.prune(x) for x in a if isContent($.prune(x))]424    else if std.isObject(a) then {425      [x]: $.prune(a[x])426      for x in std.objectFields(a)427      if isContent(std.prune(a[x]))428    } else429      a,430431  find(value, arr)::432    if !std.isArray(arr) then433      error 'find second parameter should be an array, got ' + std.type(arr)434    else435      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),436}