Skip to content

Commit

Permalink
fix: Construct templateDataMap manually
Browse files Browse the repository at this point in the history
Closes twpayne#2502

Round-tripping the template data via JSON caused a data regression such
that values that were `map[string]any{nil}` (the default value) are
turned into `null` in JSON and therefore `nil` in a template.
Previously, the value of `map[string]any{nil}` would be rendered as
`{}`.

Manual construction of the map restores the old functionality. For
chezmoi version 3, we may want to consider *restoring* the behaviour
from `v2.25.0` (`null`), but this is a regression version version 2.

```console
# before this fix
$ go run . execute-template '{{ .chezmoi.osRelease | toJson }}'
null%
$ go run . execute-template '{{ .chezmoi.osRelease | toJson }}'
{}%
```
  • Loading branch information
halostatue committed Oct 28, 2022
1 parent 3b95c7e commit 9a0a90a
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions pkg/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1239,17 +1239,29 @@ func (c *Config) getTemplateData() *templateData {
// getTemplateDataMao returns the template data as a map.
func (c *Config) getTemplateDataMap() map[string]any {
templateData := c.getTemplateData()
// FIXME round-tripping via JSON is a horrible hack
data, err := json.Marshal(templateData)
if err != nil {
panic(err)
}
var templateDataMap map[string]any
if err := json.Unmarshal(data, &templateDataMap); err != nil {
panic(err)
}

return map[string]any{
"chezmoi": templateDataMap,
"chezmoi": map[string]any{
"arch": templateData.Arch,
"args": templateData.Args,
"cacheDir": templateData.CacheDir.String(),
"configFile": templateData.ConfigFile.String(),
"executable": templateData.Executable.String(),
"fqdnHostname": templateData.FQDNHostname,
"gid": templateData.GID,
"group": templateData.Group,
"homeDir": templateData.HomeDir.String(),
"hostname": templateData.Hostname,
"kernel": templateData.Kernel,
"os": templateData.OS,
"osRelease": templateData.OSRelease,
"sourceDir": templateData.SourceDir.String(),
"uid": templateData.UID,
"username": templateData.Username,
"version": templateData.Version,
"windowsVersion": templateData.WindowsVersion,
"workingTree": templateData.WorkingTree.String(),
},
}
}

Expand Down

0 comments on commit 9a0a90a

Please sign in to comment.