Skip to content

Commit b785f26

Browse files
committed
Teach updateFile to delete files
We might want to ensure a possibly pre-existing file does not exist in some cases. updateFile could have been called with nil content, but that would only ensure the file was empty not that it was deleted which may not always be good enough. Signed-off-by: Manuel Mendez <[email protected]>
1 parent 3b2bdee commit b785f26

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

lint-install.go

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,12 +149,13 @@ func updateMakefile(root string, cfg Config, dryRun bool) (string, error) {
149149
}
150150

151151
// updateFile updates a configuration file within a project.
152+
// If the content is nil the file is removed.
152153
func updateFile(root string, basename string, content []byte, dryRun bool) (string, error) {
153154
dest := filepath.Join(root, basename)
154155
var existing []byte
155-
var err error
156156

157-
if _, err = os.Stat(dest); err == nil {
157+
f, err := os.Stat(dest)
158+
if err == nil {
158159
klog.Infof("Found existing %s", dest)
159160
existing, err = os.ReadFile(dest)
160161
if err != nil {
@@ -167,7 +168,18 @@ func updateFile(root string, basename string, content []byte, dryRun bool) (stri
167168
change := gotextdiff.ToUnified(basename, basename, string(existing), edits)
168169

169170
if !dryRun {
170-
if err := os.WriteFile(dest, content, 0o600); err != nil {
171+
var err error
172+
if content == nil {
173+
// must be broken up, can't be conten == nil && f != nil because then
174+
// the else branch will be taken if the file does *not* exist and
175+
// an empty file will be written
176+
if f != nil {
177+
err = os.Remove(dest)
178+
}
179+
} else {
180+
err = os.WriteFile(dest, content, 0o600)
181+
}
182+
if err != nil {
171183
return "", err
172184
}
173185
}

0 commit comments

Comments
 (0)