Skip to content

Commit

Permalink
fix: Set CHEZMOI_ environment variables for modify_ scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
twpayne committed Apr 18, 2023
1 parent 9e3b204 commit ee3793a
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pkg/chezmoi/sourcestate.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ type SourceState struct {
readTemplateData bool
userTemplateData map[string]any
priorityTemplateData map[string]any
scriptEnv []string
templateData map[string]any
templateFuncs template.FuncMap
templateOptions []string
Expand Down Expand Up @@ -199,6 +200,13 @@ func WithReadTemplateData(readTemplateData bool) SourceStateOption {
}
}

// WithScriptEnv sets the script environment variables.
func WithScriptEnv(scriptEnv []string) SourceStateOption {
return func(s *SourceState) {
s.scriptEnv = scriptEnv
}
}

// WithSourceDir sets the source directory.
func WithSourceDir(sourceDirAbsPath AbsPath) SourceStateOption {
return func(s *SourceState) {
Expand Down Expand Up @@ -1673,6 +1681,7 @@ func (s *SourceState) newModifyTargetStateEntryFunc(

// Run the modifier on the current contents.
cmd := interpreter.ExecCommand(tempFile.Name())
cmd.Env = s.scriptEnv
cmd.Stdin = bytes.NewReader(currentContents)
cmd.Stderr = os.Stderr
contents, err = chezmoilog.LogCmdOutput(cmd)
Expand Down
1 change: 1 addition & 0 deletions pkg/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1537,6 +1537,7 @@ func (c *Config) newSourceState(
chezmoi.WithLogger(&sourceStateLogger),
chezmoi.WithMode(c.Mode),
chezmoi.WithPriorityTemplateData(c.Data),
chezmoi.WithScriptEnv(c.runEnv),
chezmoi.WithSourceDir(c.SourceDirAbsPath),
chezmoi.WithSystem(c.sourceSystem),
chezmoi.WithTemplateFuncs(c.templateFuncs),
Expand Down
8 changes: 8 additions & 0 deletions pkg/cmd/testdata/scripts/issue2934.txtar
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# test that chezmoi sets environment variables for modify_ scripts
exec chezmoi apply
grep ^${CHEZMOISOURCEDIR@R}$ $HOME/.modify

-- home/user/.local/share/chezmoi/modify_dot_modify --
#!/bin/sh

echo ${CHEZMOI_SOURCE_DIR}

0 comments on commit ee3793a

Please sign in to comment.