Debian Codegraph @

util/sprig/list.go

raw
1 package sprig
2
3 import (
4 "fmt"
5 "math"
6 "reflect"
7 "sort"
8 )
9
10 // Reflection is used in these functions so that slices and arrays of strings,
11 // ints, and other types not implementing []any can be worked with.
12 // For example, this is useful if you need to work on the output of regexs.
13
14 // list creates a new list (slice) containing the provided arguments.
15 // It accepts any number of arguments of any type and returns them as a slice.
16 func list(v ...any) []any {
17 return v
18 }
19
20 // push appends an element to the end of a list (slice or array).
21 // It takes a list and a value, and returns a new list with the value appended.
22 // This function will panic if the first argument is not a slice or array.
23 func push(list any, v any) []any {
24 l, err := mustPush(list, v)
25 if err != nil {
26 panic(err)
27 }
28 return l
29 }
30
31 // mustPush is the implementation of push that returns an error instead of panicking.
32 // It converts the input list to a slice of any type, then appends the value.
33 func mustPush(list any, v any) ([]any, error) {
34 tp := reflect.TypeOf(list).Kind()
35 switch tp {
36 case reflect.Slice, reflect.Array:
37 l2 := reflect.ValueOf(list)
38 l := l2.Len()
39 nl := make([]any, l)
40 for i := 0; i < l; i++ {
41 nl[i] = l2.Index(i).Interface()
42 }
43 return append(nl, v), nil
44 default:
45 return nil, fmt.Errorf("cannot push on type %s", tp)
46 }
47 }
48
49 // prepend adds an element to the beginning of a list (slice or array).
50 // It takes a list and a value, and returns a new list with the value at the start.
51 // This function will panic if the first argument is not a slice or array.
52 func prepend(list any, v any) []any {
53 l, err := mustPrepend(list, v)
54 if err != nil {
55 panic(err)
56 }
57 return l
58 }
59
60 // mustPrepend is the implementation of prepend that returns an error instead of panicking.
61 // It converts the input list to a slice of any type, then prepends the value.
62 func mustPrepend(list any, v any) ([]any, error) {
63 tp := reflect.TypeOf(list).Kind()
64 switch tp {
65 case reflect.Slice, reflect.Array:
66 l2 := reflect.ValueOf(list)
67 l := l2.Len()
68 nl := make([]any, l)
69 for i := 0; i < l; i++ {
70 nl[i] = l2.Index(i).Interface()
71 }
72 return append([]any{v}, nl...), nil
73 default:
74 return nil, fmt.Errorf("cannot prepend on type %s", tp)
75 }
76 }
77
78 // chunk divides a list into sub-lists of the specified size.
79 // It takes a size and a list, and returns a list of lists, each containing
80 // up to 'size' elements from the original list.
81 // This function will panic if the second argument is not a slice or array.
82 func chunk(size int, list any) [][]any {
83 l, err := mustChunk(size, list)
84 if err != nil {
85 panic(err)
86 }
87 return l
88 }
89
90 // mustChunk is the implementation of chunk that returns an error instead of panicking.
91 // It divides the input list into chunks of the specified size.
92 func mustChunk(size int, list any) ([][]any, error) {
93 tp := reflect.TypeOf(list).Kind()
94 switch tp {
95 case reflect.Slice, reflect.Array:
96 l2 := reflect.ValueOf(list)
97 l := l2.Len()
98 numChunks := int(math.Floor(float64(l-1)/float64(size)) + 1)
99 if numChunks > sliceSizeLimit {
100 return nil, fmt.Errorf("number of chunks %d exceeds maximum limit of %d", numChunks, sliceSizeLimit)
101 }
102 result := make([][]any, numChunks)
103 for i := 0; i < numChunks; i++ {
104 clen := size
105 // Handle the last chunk which might be smaller
106 if i == numChunks-1 {
107 clen = int(math.Floor(math.Mod(float64(l), float64(size))))
108 if clen == 0 {
109 clen = size
110 }
111 }
112 result[i] = make([]any, clen)
113 for j := 0; j < clen; j++ {
114 ix := i*size + j
115 result[i][j] = l2.Index(ix).Interface()
116 }
117 }
118 return result, nil
119
120 default:
121 return nil, fmt.Errorf("cannot chunk type %s", tp)
122 }
123 }
124
125 // last returns the last element of a list (slice or array).
126 // If the list is empty, it returns nil.
127 // This function will panic if the argument is not a slice or array.
128 func last(list any) any {
129 l, err := mustLast(list)
130 if err != nil {
131 panic(err)
132 }
133
134 return l
135 }
136
137 // mustLast is the implementation of last that returns an error instead of panicking.
138 // It returns the last element of the list or nil if the list is empty.
139 func mustLast(list any) (any, error) {
140 tp := reflect.TypeOf(list).Kind()
141 switch tp {
142 case reflect.Slice, reflect.Array:
143 l2 := reflect.ValueOf(list)
144
145 l := l2.Len()
146 if l == 0 {
147 return nil, nil
148 }
149
150 return l2.Index(l - 1).Interface(), nil
151 default:
152 return nil, fmt.Errorf("cannot find last on type %s", tp)
153 }
154 }
155
156 // first returns the first element of a list (slice or array).
157 // If the list is empty, it returns nil.
158 // This function will panic if the argument is not a slice or array.
159 func first(list any) any {
160 l, err := mustFirst(list)
161 if err != nil {
162 panic(err)
163 }
164
165 return l
166 }
167
168 // mustFirst is the implementation of first that returns an error instead of panicking.
169 // It returns the first element of the list or nil if the list is empty.
170 func mustFirst(list any) (any, error) {
171 tp := reflect.TypeOf(list).Kind()
172 switch tp {
173 case reflect.Slice, reflect.Array:
174 l2 := reflect.ValueOf(list)
175
176 l := l2.Len()
177 if l == 0 {
178 return nil, nil
179 }
180
181 return l2.Index(0).Interface(), nil
182 default:
183 return nil, fmt.Errorf("cannot find first on type %s", tp)
184 }
185 }
186
187 // rest returns all elements of a list except the first one.
188 // If the list is empty, it returns nil.
189 // This function will panic if the argument is not a slice or array.
190 func rest(list any) []any {
191 l, err := mustRest(list)
192 if err != nil {
193 panic(err)
194 }
195
196 return l
197 }
198
199 // mustRest is the implementation of rest that returns an error instead of panicking.
200 // It returns all elements of the list except the first one, or nil if the list is empty.
201 func mustRest(list any) ([]any, error) {
202 tp := reflect.TypeOf(list).Kind()
203 switch tp {
204 case reflect.Slice, reflect.Array:
205 l2 := reflect.ValueOf(list)
206 l := l2.Len()
207 if l == 0 {
208 return nil, nil
209 }
210 nl := make([]any, l-1)
211 for i := 1; i < l; i++ {
212 nl[i-1] = l2.Index(i).Interface()
213 }
214 return nl, nil
215 default:
216 return nil, fmt.Errorf("cannot find rest on type %s", tp)
217 }
218 }
219
220 // initial returns all elements of a list except the last one.
221 // If the list is empty, it returns nil.
222 // This function will panic if the argument is not a slice or array.
223 func initial(list any) []any {
224 l, err := mustInitial(list)
225 if err != nil {
226 panic(err)
227 }
228
229 return l
230 }
231
232 // mustInitial is the implementation of initial that returns an error instead of panicking.
233 // It returns all elements of the list except the last one, or nil if the list is empty.
234 func mustInitial(list any) ([]any, error) {
235 tp := reflect.TypeOf(list).Kind()
236 switch tp {
237 case reflect.Slice, reflect.Array:
238 l2 := reflect.ValueOf(list)
239 l := l2.Len()
240 if l == 0 {
241 return nil, nil
242 }
243 nl := make([]any, l-1)
244 for i := 0; i < l-1; i++ {
245 nl[i] = l2.Index(i).Interface()
246 }
247 return nl, nil
248 default:
249 return nil, fmt.Errorf("cannot find initial on type %s", tp)
250 }
251 }
252
253 // sortAlpha sorts a list of strings alphabetically.
254 // If the input is not a slice or array, it returns a single-element slice
255 // containing the string representation of the input.
256 func sortAlpha(list any) []string {
257 k := reflect.Indirect(reflect.ValueOf(list)).Kind()
258 switch k {
259 case reflect.Slice, reflect.Array:
260 a := strslice(list)
261 s := sort.StringSlice(a)
262 s.Sort()
263 return s
264 }
265 return []string{strval(list)}
266 }
267
268 // reverse returns a new list with the elements in reverse order.
269 // This function will panic if the argument is not a slice or array.
270 func reverse(v any) []any {
271 l, err := mustReverse(v)
272 if err != nil {
273 panic(err)
274 }
275
276 return l
277 }
278
279 // mustReverse is the implementation of reverse that returns an error instead of panicking.
280 // It returns a new list with the elements in reverse order.
281 func mustReverse(v any) ([]any, error) {
282 tp := reflect.TypeOf(v).Kind()
283 switch tp {
284 case reflect.Slice, reflect.Array:
285 l2 := reflect.ValueOf(v)
286 l := l2.Len()
287 // We do not sort in place because the incoming array should not be altered.
288 nl := make([]any, l)
289 for i := 0; i < l; i++ {
290 nl[l-i-1] = l2.Index(i).Interface()
291 }
292 return nl, nil
293 default:
294 return nil, fmt.Errorf("cannot find reverse on type %s", tp)
295 }
296 }
297
298 // compact returns a new list with all "empty" elements removed.
299 // An element is considered empty if it's nil, zero, an empty string, or an empty collection.
300 // This function will panic if the argument is not a slice or array.
301 func compact(list any) []any {
302 l, err := mustCompact(list)
303 if err != nil {
304 panic(err)
305 }
306 return l
307 }
308
309 // mustCompact is the implementation of compact that returns an error instead of panicking.
310 // It returns a new list with all "empty" elements removed.
311 func mustCompact(list any) ([]any, error) {
312 tp := reflect.TypeOf(list).Kind()
313 switch tp {
314 case reflect.Slice, reflect.Array:
315 l2 := reflect.ValueOf(list)
316 l := l2.Len()
317 var nl []any
318 var item any
319 for i := 0; i < l; i++ {
320 item = l2.Index(i).Interface()
321 if !empty(item) {
322 nl = append(nl, item)
323 }
324 }
325 return nl, nil
326 default:
327 return nil, fmt.Errorf("cannot compact on type %s", tp)
328 }
329 }
330
331 // uniq returns a new list with duplicate elements removed.
332 // The first occurrence of each element is kept.
333 // This function will panic if the argument is not a slice or array.
334 func uniq(list any) []any {
335 l, err := mustUniq(list)
336 if err != nil {
337 panic(err)
338 }
339 return l
340 }
341
342 // mustUniq is the implementation of uniq that returns an error instead of panicking.
343 // It returns a new list with duplicate elements removed.
344 func mustUniq(list any) ([]any, error) {
345 tp := reflect.TypeOf(list).Kind()
346 switch tp {
347 case reflect.Slice, reflect.Array:
348 l2 := reflect.ValueOf(list)
349 l := l2.Len()
350 var dest []any
351 var item any
352 for i := 0; i < l; i++ {
353 item = l2.Index(i).Interface()
354 if !inList(dest, item) {
355 dest = append(dest, item)
356 }
357 }
358 return dest, nil
359 default:
360 return nil, fmt.Errorf("cannot find uniq on type %s", tp)
361 }
362 }
363
364 // inList checks if a value is present in a list.
365 // It uses deep equality comparison to check for matches.
366 // Returns true if the value is found, false otherwise.
367 func inList(haystack []any, needle any) bool {
368 for _, h := range haystack {
369 if reflect.DeepEqual(needle, h) {
370 return true
371 }
372 }
373 return false
374 }
375
376 // without returns a new list with all occurrences of the specified values removed.
377 // This function will panic if the first argument is not a slice or array.
378 func without(list any, omit ...any) []any {
379 l, err := mustWithout(list, omit...)
380 if err != nil {
381 panic(err)
382 }
383 return l
384 }
385
386 // mustWithout is the implementation of without that returns an error instead of panicking.
387 // It returns a new list with all occurrences of the specified values removed.
388 func mustWithout(list any, omit ...any) ([]any, error) {
389 tp := reflect.TypeOf(list).Kind()
390 switch tp {
391 case reflect.Slice, reflect.Array:
392 l2 := reflect.ValueOf(list)
393 l := l2.Len()
394 res := []any{}
395 var item any
396 for i := 0; i < l; i++ {
397 item = l2.Index(i).Interface()
398 if !inList(omit, item) {
399 res = append(res, item)
400 }
401 }
402 return res, nil
403 default:
404 return nil, fmt.Errorf("cannot find without on type %s", tp)
405 }
406 }
407
408 // has checks if a value is present in a list.
409 // Returns true if the value is found, false otherwise.
410 // This function will panic if the second argument is not a slice or array.
411 func has(needle any, haystack any) bool {
412 l, err := mustHas(needle, haystack)
413 if err != nil {
414 panic(err)
415 }
416 return l
417 }
418
419 // mustHas is the implementation of has that returns an error instead of panicking.
420 // It checks if a value is present in a list.
421 func mustHas(needle any, haystack any) (bool, error) {
422 if haystack == nil {
423 return false, nil
424 }
425 tp := reflect.TypeOf(haystack).Kind()
426 switch tp {
427 case reflect.Slice, reflect.Array:
428 l2 := reflect.ValueOf(haystack)
429 var item any
430 l := l2.Len()
431 for i := 0; i < l; i++ {
432 item = l2.Index(i).Interface()
433 if reflect.DeepEqual(needle, item) {
434 return true, nil
435 }
436 }
437 return false, nil
438 default:
439 return false, fmt.Errorf("cannot find has on type %s", tp)
440 }
441 }
442
443 // slice extracts a portion of a list based on the provided indices.
444 // Usage examples:
445 // $list := [1, 2, 3, 4, 5]
446 // slice $list -> list[0:5] = list[:]
447 // slice $list 0 3 -> list[0:3] = list[:3]
448 // slice $list 3 5 -> list[3:5]
449 // slice $list 3 -> list[3:5] = list[3:]
450 //
451 // This function will panic if the first argument is not a slice or array.
452 func slice(list any, indices ...any) any {
453 l, err := mustSlice(list, indices...)
454 if err != nil {
455 panic(err)
456 }
457 return l
458 }
459
460 // mustSlice is the implementation of slice that returns an error instead of panicking.
461 // It extracts a portion of a list based on the provided indices.
462 func mustSlice(list any, indices ...any) (any, error) {
463 tp := reflect.TypeOf(list).Kind()
464 switch tp {
465 case reflect.Slice, reflect.Array:
466 l2 := reflect.ValueOf(list)
467 l := l2.Len()
468 if l == 0 {
469 return nil, nil
470 }
471 // Determine start and end indices
472 var start, end int
473 if len(indices) > 0 {
474 start = toInt(indices[0])
475 }
476 if len(indices) < 2 {
477 end = l
478 } else {
479 end = toInt(indices[1])
480 }
481 return l2.Slice(start, end).Interface(), nil
482 default:
483 return nil, fmt.Errorf("list should be type of slice or array but %s", tp)
484 }
485 }
486
487 // concat combines multiple lists into a single list.
488 // It takes any number of lists and returns a new list containing all elements.
489 // This function will panic if any argument is not a slice or array.
490 func concat(lists ...any) any {
491 var res []any
492 for _, list := range lists {
493 tp := reflect.TypeOf(list).Kind()
494 switch tp {
495 case reflect.Slice, reflect.Array:
496 l2 := reflect.ValueOf(list)
497 for i := 0; i < l2.Len(); i++ {
498 res = append(res, l2.Index(i).Interface())
499 }
500 default:
501 panic(fmt.Sprintf("cannot concat type %s as list", tp))
502 }
503 }
504 return res
505 }