Debian Codegraph @

util/sprig/strings.go

raw
1 package sprig
2
3 import (
4 "encoding/base32"
5 "encoding/base64"
6 "fmt"
7 "golang.org/x/text/cases"
8 "golang.org/x/text/language"
9 "reflect"
10 "strconv"
11 "strings"
12 )
13
14 // base64encode encodes a string to base64 using standard encoding.
15 //
16 // Parameters:
17 // - v: The string to encode
18 //
19 // Returns:
20 // - string: The base64 encoded string
21 func base64encode(v string) string {
22 return base64.StdEncoding.EncodeToString([]byte(v))
23 }
24
25 // base64decode decodes a base64 encoded string.
26 // If the input is not valid base64, it returns the error message as a string.
27 //
28 // Parameters:
29 // - v: The base64 encoded string to decode
30 //
31 // Returns:
32 // - string: The decoded string, or an error message if decoding fails
33 func base64decode(v string) string {
34 data, err := base64.StdEncoding.DecodeString(v)
35 if err != nil {
36 return err.Error()
37 }
38 return string(data)
39 }
40
41 // base32encode encodes a string to base32 using standard encoding.
42 //
43 // Parameters:
44 // - v: The string to encode
45 //
46 // Returns:
47 // - string: The base32 encoded string
48 func base32encode(v string) string {
49 return base32.StdEncoding.EncodeToString([]byte(v))
50 }
51
52 // base32decode decodes a base32 encoded string.
53 // If the input is not valid base32, it returns the error message as a string.
54 //
55 // Parameters:
56 // - v: The base32 encoded string to decode
57 //
58 // Returns:
59 // - string: The decoded string, or an error message if decoding fails
60 func base32decode(v string) string {
61 data, err := base32.StdEncoding.DecodeString(v)
62 if err != nil {
63 return err.Error()
64 }
65 return string(data)
66 }
67
68 // quote adds double quotes around each non-nil string in the input and joins them with spaces.
69 // This uses Go's %q formatter which handles escaping special characters.
70 //
71 // Parameters:
72 // - str: A variadic list of values to quote
73 //
74 // Returns:
75 // - string: The quoted strings joined with spaces
76 func quote(str ...any) string {
77 out := make([]string, 0, len(str))
78 for _, s := range str {
79 if s != nil {
80 out = append(out, fmt.Sprintf("%q", strval(s)))
81 }
82 }
83 return strings.Join(out, " ")
84 }
85
86 // squote adds single quotes around each non-nil value in the input and joins them with spaces.
87 // Unlike quote, this doesn't escape special characters.
88 //
89 // Parameters:
90 // - str: A variadic list of values to quote
91 //
92 // Returns:
93 // - string: The single-quoted values joined with spaces
94 func squote(str ...any) string {
95 out := make([]string, 0, len(str))
96 for _, s := range str {
97 if s != nil {
98 out = append(out, fmt.Sprintf("'%v'", s))
99 }
100 }
101 return strings.Join(out, " ")
102 }
103
104 // cat concatenates all non-nil values into a single string.
105 // Nil values are removed before concatenation.
106 //
107 // Parameters:
108 // - v: A variadic list of values to concatenate
109 //
110 // Returns:
111 // - string: The concatenated string
112 func cat(v ...any) string {
113 v = removeNilElements(v)
114 r := strings.TrimSpace(strings.Repeat("%v ", len(v)))
115 return fmt.Sprintf(r, v...)
116 }
117
118 // indent adds a specified number of spaces at the beginning of each line in a string.
119 // It has a safety limit to prevent excessive memory usage.
120 //
121 // Parameters:
122 // - spaces: The number of spaces to add
123 // - v: The string to indent
124 //
125 // Returns:
126 // - string: The indented string
127 //
128 // Panics:
129 // - If spaces exceeds indentSpacesLimit
130 func indent(spaces int, v string) string {
131 if spaces > indentSpacesLimit {
132 panic(fmt.Sprintf("indent %d exceeds limit of %d", spaces, indentSpacesLimit))
133 }
134 pad := strings.Repeat(" ", spaces)
135 return pad + strings.Replace(v, "\n", "\n"+pad, -1)
136 }
137
138 // nindent adds a newline followed by an indented string.
139 // It's a shorthand for "\n" + indent(spaces, v).
140 //
141 // Parameters:
142 // - spaces: The number of spaces to add
143 // - v: The string to indent
144 //
145 // Returns:
146 // - string: A newline followed by the indented string
147 func nindent(spaces int, v string) string {
148 return "\n" + indent(spaces, v)
149 }
150
151 // replace replaces all occurrences of a substring with another substring.
152 //
153 // Parameters:
154 // - old: The substring to replace
155 // - new: The replacement substring
156 // - src: The source string
157 //
158 // Returns:
159 // - string: The resulting string after all replacements
160 func replace(old, new, src string) string {
161 return strings.Replace(src, old, new, -1)
162 }
163
164 // plural returns the singular or plural form of a word based on the count.
165 // If count is 1, it returns the singular form, otherwise it returns the plural form.
166 //
167 // Parameters:
168 // - one: The singular form of the word
169 // - many: The plural form of the word
170 // - count: The count to determine which form to use
171 //
172 // Returns:
173 // - string: Either the singular or plural form based on the count
174 func plural(one, many string, count int) string {
175 if count == 1 {
176 return one
177 }
178 return many
179 }
180
181 // strslice converts a value to a slice of strings.
182 // It handles various input types:
183 // - []string: returned as is
184 // - []any: converted to []string, skipping nil values
185 // - arrays and slices: converted to []string, skipping nil values
186 // - nil: returns an empty slice
187 // - anything else: returns a single-element slice with the string representation
188 //
189 // Parameters:
190 // - v: The value to convert to a string slice
191 //
192 // Returns:
193 // - []string: A slice of strings
194 func strslice(v any) []string {
195 switch v := v.(type) {
196 case []string:
197 return v
198 case []any:
199 b := make([]string, 0, len(v))
200 for _, s := range v {
201 if s != nil {
202 b = append(b, strval(s))
203 }
204 }
205 return b
206 default:
207 val := reflect.ValueOf(v)
208 switch val.Kind() {
209 case reflect.Array, reflect.Slice:
210 l := val.Len()
211 b := make([]string, 0, l)
212 for i := 0; i < l; i++ {
213 value := val.Index(i).Interface()
214 if value != nil {
215 b = append(b, strval(value))
216 }
217 }
218 return b
219 default:
220 if v == nil {
221 return []string{}
222 }
223
224 return []string{strval(v)}
225 }
226 }
227 }
228
229 // removeNilElements creates a new slice with all nil elements removed.
230 // This is a helper function used by other functions like cat.
231 //
232 // Parameters:
233 // - v: The slice to process
234 //
235 // Returns:
236 // - []any: A new slice with all nil elements removed
237 func removeNilElements(v []any) []any {
238 newSlice := make([]any, 0, len(v))
239 for _, i := range v {
240 if i != nil {
241 newSlice = append(newSlice, i)
242 }
243 }
244 return newSlice
245 }
246
247 // strval converts any value to a string.
248 // It handles various types:
249 // - string: returned as is
250 // - []byte: converted to string
251 // - error: returns the error message
252 // - fmt.Stringer: calls the String() method
253 // - anything else: uses fmt.Sprintf("%v", v)
254 //
255 // Parameters:
256 // - v: The value to convert to a string
257 //
258 // Returns:
259 // - string: The string representation of the value
260 func strval(v any) string {
261 switch v := v.(type) {
262 case string:
263 return v
264 case []byte:
265 return string(v)
266 case error:
267 return v.Error()
268 case fmt.Stringer:
269 return v.String()
270 default:
271 return fmt.Sprintf("%v", v)
272 }
273 }
274
275 // trunc truncates a string to a specified length.
276 // If c is positive, it returns the first c characters.
277 // If c is negative, it returns the last |c| characters.
278 // If the string is shorter than the requested length, it returns the original string.
279 //
280 // Parameters:
281 // - c: The number of characters to keep (positive from start, negative from end)
282 // - s: The string to truncate
283 //
284 // Returns:
285 // - string: The truncated string
286 func trunc(c int, s string) string {
287 if c < 0 && len(s)+c > 0 {
288 return s[len(s)+c:]
289 }
290 if c >= 0 && len(s) > c {
291 return s[:c]
292 }
293 return s
294 }
295
296 // title converts a string to title case.
297 // This uses the English language rules for capitalization.
298 //
299 // Parameters:
300 // - s: The string to convert
301 //
302 // Returns:
303 // - string: The string in title case
304 func title(s string) string {
305 return cases.Title(language.English).String(s)
306 }
307
308 // join concatenates the elements of a slice with a separator.
309 // The input is first converted to a string slice using strslice.
310 //
311 // Parameters:
312 // - sep: The separator to use between elements
313 // - v: The value to join (will be converted to a string slice)
314 //
315 // Returns:
316 // - string: The joined string
317 func join(sep string, v any) string {
318 return strings.Join(strslice(v), sep)
319 }
320
321 // split splits a string by a separator and returns a map.
322 // The keys in the map are "_0", "_1", etc., corresponding to the position of each part.
323 //
324 // Parameters:
325 // - sep: The separator to split on
326 // - orig: The string to split
327 //
328 // Returns:
329 // - map[string]string: A map with keys "_0", "_1", etc. and values being the split parts
330 func split(sep, orig string) map[string]string {
331 parts := strings.Split(orig, sep)
332 res := make(map[string]string, len(parts))
333 for i, v := range parts {
334 res["_"+strconv.Itoa(i)] = v
335 }
336 return res
337 }
338
339 // splitList splits a string by a separator and returns a slice.
340 // This is a simple wrapper around strings.Split.
341 //
342 // Parameters:
343 // - sep: The separator to split on
344 // - orig: The string to split
345 //
346 // Returns:
347 // - []string: A slice containing the split parts
348 func splitList(sep, orig string) []string {
349 return strings.Split(orig, sep)
350 }
351
352 // splitn splits a string by a separator with a limit and returns a map.
353 // The keys in the map are "_0", "_1", etc., corresponding to the position of each part.
354 // It will split the string into at most n parts.
355 //
356 // Parameters:
357 // - sep: The separator to split on
358 // - n: The maximum number of parts to return
359 // - orig: The string to split
360 //
361 // Returns:
362 // - map[string]string: A map with keys "_0", "_1", etc. and values being the split parts
363 func splitn(sep string, n int, orig string) map[string]string {
364 parts := strings.SplitN(orig, sep, n)
365 res := make(map[string]string, len(parts))
366 for i, v := range parts {
367 res["_"+strconv.Itoa(i)] = v
368 }
369 return res
370 }
371
372 // substring creates a substring of the given string.
373 // It extracts a portion of a string based on start and end indices.
374 //
375 // Parameters:
376 // - start: The starting index (inclusive)
377 // - end: The ending index (exclusive)
378 // - s: The source string
379 //
380 // Behavior:
381 // - If start < 0, returns s[:end]
382 // - If start >= 0 and end < 0 or end > len(s), returns s[start:]
383 // - Otherwise, returns s[start:end]
384 //
385 // Returns:
386 // - string: The extracted substring
387 func substring(start, end int, s string) string {
388 if start < 0 {
389 return s[:end]
390 }
391 if end < 0 || end > len(s) {
392 return s[start:]
393 }
394 return s[start:end]
395 }
396
397 // repeat creates a new string by repeating the input string a specified number of times.
398 // It has safety limits to prevent excessive memory usage or infinite loops.
399 //
400 // Parameters:
401 // - count: The number of times to repeat the string
402 // - str: The string to repeat
403 //
404 // Returns:
405 // - string: The repeated string
406 //
407 // Panics:
408 // - If count exceeds loopExecutionLimit
409 // - If the resulting string length would exceed stringLengthLimit
410 func repeat(count int, str string) string {
411 if count > loopExecutionLimit {
412 panic(fmt.Sprintf("repeat count %d exceeds limit of %d", count, loopExecutionLimit))
413 } else if count*len(str) >= stringLengthLimit {
414 panic(fmt.Sprintf("repeat count %d with string length %d exceeds limit of %d", count, len(str), stringLengthLimit))
415 }
416 return strings.Repeat(str, count)
417 }
418
419 // trimAll removes all leading and trailing characters contained in the cutset.
420 // Note that the parameter order is reversed from the standard strings.Trim function.
421 //
422 // Parameters:
423 // - a: The cutset of characters to remove
424 // - b: The string to trim
425 //
426 // Returns:
427 // - string: The trimmed string
428 func trimAll(a, b string) string {
429 return strings.Trim(b, a)
430 }
431
432 // trimPrefix removes the specified prefix from a string.
433 // If the string doesn't start with the prefix, it returns the original string.
434 // Note that the parameter order is reversed from the standard strings.TrimPrefix function.
435 //
436 // Parameters:
437 // - a: The prefix to remove
438 // - b: The string to trim
439 //
440 // Returns:
441 // - string: The string with the prefix removed, or the original string if it doesn't start with the prefix
442 func trimPrefix(a, b string) string {
443 return strings.TrimPrefix(b, a)
444 }
445
446 // trimSuffix removes the specified suffix from a string.
447 // If the string doesn't end with the suffix, it returns the original string.
448 // Note that the parameter order is reversed from the standard strings.TrimSuffix function.
449 //
450 // Parameters:
451 // - a: The suffix to remove
452 // - b: The string to trim
453 //
454 // Returns:
455 // - string: The string with the suffix removed, or the original string if it doesn't end with the suffix
456 func trimSuffix(a, b string) string {
457 return strings.TrimSuffix(b, a)
458 }
459
460 // contains checks if a string contains a substring.
461 //
462 // Parameters:
463 // - substr: The substring to search for
464 // - str: The string to search in
465 //
466 // Returns:
467 // - bool: True if str contains substr, false otherwise
468 func contains(substr string, str string) bool {
469 return strings.Contains(str, substr)
470 }
471
472 // hasPrefix checks if a string starts with a specified prefix.
473 //
474 // Parameters:
475 // - substr: The prefix to check for
476 // - str: The string to check
477 //
478 // Returns:
479 // - bool: True if str starts with substr, false otherwise
480 func hasPrefix(substr string, str string) bool {
481 return strings.HasPrefix(str, substr)
482 }
483
484 // hasSuffix checks if a string ends with a specified suffix.
485 //
486 // Parameters:
487 // - substr: The suffix to check for
488 // - str: The string to check
489 //
490 // Returns:
491 // - bool: True if str ends with substr, false otherwise
492 func hasSuffix(substr string, str string) bool {
493 return strings.HasSuffix(str, substr)
494 }