Skip to content

Commit

Permalink
Merge pull request #18 from chezmoi/replace-all
Browse files Browse the repository at this point in the history
feat: Add replaceAll
  • Loading branch information
twpayne authored May 18, 2024
2 parents 9907d6a + bdba638 commit 7bbc981
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions docs/templatefuncs.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,16 @@ with *replacement* in *string*.
far
```

## `replaceAll` *old* *new* *string*

`replaceAll` replaces all instances of *old* with *new* in *string*.

```text
{{ "abcba" | replaceAll "b" "d" }}
adcda
```

## `stat` *path*

`stat` returns a map representation of executing
Expand Down
8 changes: 8 additions & 0 deletions templatefuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func NewFuncMap() template.FuncMap {
"prefixLines": prefixLinesTemplateFunc,
"quote": eachString(strconv.Quote),
"regexpReplaceAll": regexpReplaceAllTemplateFunc,
"replaceAll": replaceAllTemplateFunc,
"stat": eachString(statTemplateFunc),
"toJSON": toJSONTemplateFunc,
"toLower": eachString(strings.ToLower),
Expand Down Expand Up @@ -145,6 +146,13 @@ func prefixLinesTemplateFunc(prefix, s string) string {
return builder.String()
}

// replaceAllTemplateFunc is the `replaceAll` template function.
func replaceAllTemplateFunc(old, new string, v any) any { //nolint:predeclared
return eachString(func(s string) any {
return strings.ReplaceAll(s, old, new)
})(v)
}

// regexpReplaceAllTemplateFunc is the core implementation of the
// `regexpReplaceAll` template function.
func regexpReplaceAllTemplateFunc(expr, repl, s string) string {
Expand Down
8 changes: 8 additions & 0 deletions templatefuncs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,14 @@ func TestFuncMap(t *testing.T) {
"# b",
),
},
{
template: `{{ "abcba" | replaceAll "b" "d" }}`,
expected: `adcda`,
},
{
template: `{{ list "abc" "cba" | replaceAll "b" "d" }}`,
expected: "[adc cda]",
},
{
template: `{{ quote "a" }}`,
expected: `"a"`,
Expand Down

0 comments on commit 7bbc981

Please sign in to comment.