feat: merge template func should support variadic list of maps (#1464)

This commit is contained in:
Pete Davison
2024-01-11 16:00:52 +00:00
committed by GitHub
parent 40b6150030
commit 94aaea390f
3 changed files with 18 additions and 11 deletions

View File

@@ -1292,8 +1292,8 @@ Task also adds the following functions:
based on a base path (first argument). The same as Go's based on a base path (first argument). The same as Go's
[filepath.Rel](https://pkg.go.dev/path/filepath#Rel). [filepath.Rel](https://pkg.go.dev/path/filepath#Rel).
- `merge`: Creates a new map that is a copy of the first map with the keys of - `merge`: Creates a new map that is a copy of the first map with the keys of
the second map merged into it. If there are duplicate keys, the value of the each subsequent map merged into it. If there is a duplicate key, the value of
second map is used. the last map with that key is used.
- `spew`: Returns the Go representation of a specific variable. Useful for - `spew`: Returns the Go representation of a specific variable. Useful for
debugging. Uses the [davecgh/go-spew](https://github.com/davecgh/go-spew) debugging. Uses the [davecgh/go-spew](https://github.com/davecgh/go-spew)
package. package.

View File

@@ -53,15 +53,21 @@ func init() {
"relPath": func(basePath, targetPath string) (string, error) { "relPath": func(basePath, targetPath string) (string, error) {
return filepath.Rel(basePath, targetPath) return filepath.Rel(basePath, targetPath)
}, },
"merge": func(a, b map[string]any) map[string]any { "merge": func(base map[string]any, v ...map[string]any) map[string]any {
m := make(map[string]any, len(a)+len(b)) cap := len(v)
for k, v := range a { for _, m := range v {
m[k] = v cap += len(m)
} }
for k, v := range b { result := make(map[string]any, cap)
m[k] = v for k, v := range base {
result[k] = v
} }
return m for _, m := range v {
for k, v := range m {
result[k] = v
}
}
return result
}, },
"spew": func(v any) string { "spew": func(v any) string {
return spew.Sdump(v) return spew.Sdump(v)

View File

@@ -61,9 +61,10 @@ tasks:
map: map:
vars: vars:
MAP_1: {A: 1, B: 2, C: 3} MAP_1: {A: 1, B: 2, C: 3}
MAP_2: {D: 4, E: 5, F: 6} MAP_2: {B: 4, C: 5, D: 6}
MAP_3: {C: 7, D: 8, E: 9}
cmds: cmds:
- echo '{{merge .MAP_1 .MAP_2}}' - echo '{{merge .MAP_1 .MAP_2 .MAP_3}}'
for-string: for-string:
vars: vars: