/
editcmd.go
241 lines (217 loc) · 7.78 KB
/
editcmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package cmd
import (
"log/slog"
"os"
"runtime"
"time"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
"github.com/twpayne/chezmoi/v2/internal/chezmoi"
"github.com/twpayne/chezmoi/v2/internal/chezmoilog"
)
type editCmdConfig struct {
Command string `json:"command" mapstructure:"command" yaml:"command"`
Args []string `json:"args" mapstructure:"args" yaml:"args"`
Hardlink bool `json:"hardlink" mapstructure:"hardlink" yaml:"hardlink"`
MinDuration time.Duration `json:"minDuration" mapstructure:"minDuration" yaml:"minDuration"`
Watch bool `json:"watch" mapstructure:"watch" yaml:"watch"`
Apply bool `json:"apply" mapstructure:"apply" yaml:"apply"`
filter *chezmoi.EntryTypeFilter
init bool
}
func (c *Config) newEditCmd() *cobra.Command {
editCmd := &cobra.Command{
Use: "edit targets...",
Short: "Edit the source state of a target",
Long: mustLongHelp("edit"),
Example: example("edit"),
ValidArgsFunction: c.targetValidArgs,
RunE: c.runEditCmd,
Annotations: newAnnotations(
modifiesDestinationDirectory,
modifiesSourceDirectory,
persistentStateModeReadWrite,
requiresSourceDirectory,
runsCommands,
),
}
editCmd.Flags().BoolVarP(&c.Edit.Apply, "apply", "a", c.Edit.Apply, "Apply after editing")
editCmd.Flags().VarP(c.Edit.filter.Exclude, "exclude", "x", "Exclude entry types")
editCmd.Flags().BoolVar(&c.Edit.Hardlink, "hardlink", c.Edit.Hardlink, "Invoke editor with a hardlink to the source file")
editCmd.Flags().VarP(c.Edit.filter.Include, "include", "i", "Include entry types")
editCmd.Flags().BoolVar(&c.Edit.init, "init", c.Edit.init, "Recreate config file from template")
editCmd.Flags().BoolVar(&c.Edit.Watch, "watch", c.Edit.Watch, "Apply on save")
return editCmd
}
func (c *Config) runEditCmd(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
if err := c.runEditor([]string{c.WorkingTreeAbsPath.String()}); err != nil {
return err
}
if c.Edit.Apply {
if err := c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, noArgs, applyArgsOptions{
cmd: cmd,
filter: c.Edit.filter,
init: c.Edit.init,
recursive: true,
umask: c.Umask,
preApplyFunc: c.defaultPreApplyFunc,
}); err != nil {
return err
}
}
return nil
}
sourceState, err := c.newSourceState(cmd.Context(), cmd)
if err != nil {
return err
}
targetRelPaths, err := c.targetRelPaths(sourceState, args, &targetRelPathsOptions{
mustBeInSourceState: true,
})
if err != nil {
return err
}
editorArgs := make([]string, 0, len(targetRelPaths))
type transparentlyDecryptedFile struct {
sourceAbsPath chezmoi.AbsPath
decryptedAbsPath chezmoi.AbsPath
}
var transparentlyDecryptedFiles []transparentlyDecryptedFile
TARGET_REL_PATH:
for _, targetRelPath := range targetRelPaths {
sourceStateEntry := sourceState.MustEntry(targetRelPath)
sourceRelPath := sourceStateEntry.SourceRelPath()
switch sourceStateFile, ok := sourceStateEntry.(*chezmoi.SourceStateFile); {
case ok && sourceStateFile.Attr.Encrypted:
// FIXME in the case that the file is an encrypted template then we
// should first decrypt the file to a temporary directory and
// secondly add a hardlink from the edit directory to the temporary
// directory.
tempDirAbsPath, err := c.tempDir("chezmoi-encrypted")
if err != nil {
return err
}
// FIXME use RawContents and DecryptFile
decryptedAbsPath := tempDirAbsPath.Join(sourceRelPath.TargetRelPath(c.encryption.EncryptedSuffix()))
contents, err := sourceStateFile.Contents()
if err != nil {
return err
}
if err := os.MkdirAll(decryptedAbsPath.Dir().String(), 0o700); err != nil {
return err
}
if err := c.baseSystem.WriteFile(decryptedAbsPath, contents, 0o600); err != nil {
return err
}
transparentlyDecryptedFile := transparentlyDecryptedFile{
sourceAbsPath: c.SourceDirAbsPath.Join(sourceRelPath.RelPath()),
decryptedAbsPath: decryptedAbsPath,
}
transparentlyDecryptedFiles = append(transparentlyDecryptedFiles, transparentlyDecryptedFile)
editorArgs = append(editorArgs, decryptedAbsPath.String())
case ok && c.Edit.Hardlink && runtime.GOOS != "windows":
// If the operating system supports hard links and the file is not
// encrypted, then create a hard link to the file in the source
// directory in the temporary edit directory. This means that the
// editor will see the target filename while simultaneously updating
// the file in the source directory.
// Compute the hard link path from the target path. If the file is a
// template then preserve the .tmpl suffix as a clue to the editor.
targetRelPath := sourceRelPath.TargetRelPath(c.encryption.EncryptedSuffix())
if sourceStateFile.Attr.Template {
targetRelPath = targetRelPath.AppendString(chezmoi.TemplateSuffix)
}
tempDirAbsPath, err := c.tempDir("chezmoi-edit")
if err != nil {
return err
}
hardlinkAbsPath := tempDirAbsPath.Join(targetRelPath)
// Attempt to create the hard link. If this succeeds, continue to
// the next target. Hardlinking will fail if the temporary directory
// is on a different filesystem to the source directory, which is
// not the case for most users.
//
// FIXME create a temporary directory on the same filesystem as the
// source directory if needed.
if err := os.MkdirAll(hardlinkAbsPath.Dir().String(), 0o700); err != nil {
return err
}
if err := c.baseSystem.Link(c.SourceDirAbsPath.Join(sourceRelPath.RelPath()), hardlinkAbsPath); err == nil {
editorArgs = append(editorArgs, hardlinkAbsPath.String())
continue TARGET_REL_PATH
}
// Otherwise, fall through to the default option of editing the
// source file in the source state.
fallthrough
default:
sourceAbsPath := c.SourceDirAbsPath.Join(sourceRelPath.RelPath())
editorArgs = append(editorArgs, sourceAbsPath.String())
}
}
postEditFunc := func() error {
for _, transparentlyDecryptedFile := range transparentlyDecryptedFiles {
contents, err := c.encryption.EncryptFile(transparentlyDecryptedFile.decryptedAbsPath)
if err != nil {
return err
}
if err := c.baseSystem.WriteFile(transparentlyDecryptedFile.sourceAbsPath, contents, 0o666); err != nil {
return err
}
}
if c.Edit.Apply || c.Edit.Watch {
// Reset the cached source state to ensure that we re-read any
// changed files.
//
// FIXME Be more precise in what we invalidate. Only the changed
// files need to be re-read, not the entire source state.
c.resetSourceState()
if err := c.applyArgs(cmd.Context(), c.destSystem, c.DestDirAbsPath, args, applyArgsOptions{
cmd: cmd,
filter: c.Edit.filter,
init: c.Edit.init,
recursive: true,
umask: c.Umask,
preApplyFunc: c.defaultPreApplyFunc,
}); err != nil {
return err
}
}
return nil
}
if c.Edit.Watch {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
for _, editorArg := range editorArgs {
// FIXME watch directories recursively
if err := watcher.Add(editorArg); err != nil {
return err
}
}
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
c.logger.Debug("watcher.Events", slog.String("Name", event.Name), chezmoilog.Stringer("Op", event.Op))
err := postEditFunc()
chezmoilog.InfoOrError(c.logger, "postEditFunc", err)
case _, ok := <-watcher.Errors:
if !ok {
return
}
chezmoilog.InfoOrError(c.logger, "watcher.Errors", err)
}
}
}()
}
if err := c.runEditor(editorArgs); err != nil {
return err
}
return postEditFunc()
}