-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathstring.libsonnet
More file actions
61 lines (56 loc) · 1.86 KB
/
string.libsonnet
File metadata and controls
61 lines (56 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet';
{
'#': d.pkg(
name='string',
url='github.com/jsonnet-libs/xtd/string.libsonnet',
help='`string` implements helper functions for processing strings.',
),
// BelRune is a string of the Ascii character BEL which made computers ring in ancient times.
// We use it as "magic" char to temporarily replace an escaped string as it is a non printable
// character and thereby will unlikely be in a valid key by accident. Only when we include it.
local BelRune = std.char(7),
'#splitEscape':: d.fn(
|||
`split` works the same as `std.split` but with support for escaping the dividing
string `c`.
|||,
[
d.arg('str', d.T.string),
d.arg('c', d.T.string),
d.arg('escape', d.T.string, default='\\'),
]
),
splitEscape(str, c, escape='\\'):
std.map(
function(i)
std.strReplace(i, BelRune, escape + c),
std.split(
std.strReplace(str, escape + c, BelRune),
c,
)
),
'#strReplaceMulti':: d.fn(
|||
`strReplaceMulti` replaces multiple substrings in a string.
Example:
```jsonnet
strReplaceMulti('hello world', [['hello', 'goodbye'], ['world', 'universe']])
// 'goodbye universe'
```
|||,
[
d.arg('str', d.T.string),
d.arg('replacements', d.T.array),
]
),
strReplaceMulti(str, replacements):
assert std.isString(str) : 'str must be a string';
assert std.isArray(replacements) : 'replacements must be an array';
assert std.all([std.isArray(r) && std.length(r) == 2 && std.isString(r[0]) && std.isString(r[1]) for r in replacements]) : 'replacements must be an array of arrays of strings';
std.foldl(
function(acc, replacement)
std.strReplace(acc, replacement[0], replacement[1]),
replacements,
str,
),
}