Skip to content

Commit

Permalink
feat: Add toYaml template function
Browse files Browse the repository at this point in the history
  • Loading branch information
twpayne committed Nov 22, 2021
1 parent 10dbbcd commit da41e0f
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ Manage your dotfiles across multiple machines, securely.
* [`secretJSON` [*arg*...]](#secretjson-arg)
* [`stat` *name*](#stat-name)
* [`stdinIsATTY`](#stdinisatty)
* [`toYaml` *value*](#toyaml-value)
* [`vault` *key*](#vault-key)
* [`writeToStdout` *string*...](#writetostdout-string)

Expand Down Expand Up @@ -2593,6 +2594,18 @@ used.

---

### `toYaml` *value*

`toYaml` returns the YAML representation of *value*.

#### `toYaml` examples

```
{{ dict "key" "value" | toYaml }}
```

---

### `vault` *key*

`vault` returns structured data from [Vault](https://www.vaultproject.io/) using
Expand Down
1 change: 1 addition & 0 deletions internal/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,7 @@ func newConfig(options ...configOption) (*Config, error) {
"secret": c.secretTemplateFunc,
"secretJSON": c.secretJSONTemplateFunc,
"stat": c.statTemplateFunc,
"toYaml": c.toYamlTemplateFunc,
"vault": c.vaultTemplateFunc,
} {
c.addTemplateFunc(key, value)
Expand Down
9 changes: 9 additions & 0 deletions internal/cmd/templatefuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,15 @@ func (c *Config) statTemplateFunc(name string) interface{} {
}
}

func (c *Config) toYamlTemplateFunc(data interface{}) string {
yaml, err := chezmoi.FormatYAML.Marshal(data)
if err != nil {
returnTemplateError(err)
return ""
}
return string(yaml)
}

func returnTemplateError(err error) {
panic(err)
}
4 changes: 4 additions & 0 deletions internal/cmd/testdata/scripts/templatefuncs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ stdout arg
# test that the output template function fails if the command fails
! chezmoi execute-template '{{ output "false" }}'

# test toYaml
chezmoi execute-template '{{ dict "key" "value" | toYaml }}'
stdout '^key: value$'

# test writeToStdout
chezmoi execute-template --init '{{ writeToStdout "string" }}'
stdout string
Expand Down

0 comments on commit da41e0f

Please sign in to comment.