Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix backup to backup more than once #1271

Merged
merged 1 commit into from
Aug 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion renderer/renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,12 @@ func AtomicWrite(path string, createDestDirs bool, contents []byte, perms os.Fil
// If we got this far, it means we are about to save the file. Copy the
// current file so we have a backup. Note that os.Link preserves the Mode.
if backup {
if err := os.Link(path, path+".bak"); err != nil {
bak, old := path+".bak", path+".old.bak"
os.Rename(bak, old) // ignore error
if err := os.Link(path, bak); err != nil {
log.Printf("[WARN] (runner) could not backup %q: %v", path, err)
} else {
os.Remove(old) // ignore error
}
}

Expand Down
37 changes: 37 additions & 0 deletions renderer/renderer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,41 @@ func TestAtomicWrite(t *testing.T) {
}
}
})

t.Run("backup_backup", func(t *testing.T) {
outDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(outDir)
outFile, err := ioutil.TempFile(outDir, "")
if err != nil {
t.Fatal(err)
}
if _, err := outFile.Write([]byte("first")); err != nil {
t.Fatal(err)
}

contains := func(filename, content string) {
f, err := ioutil.ReadFile(filename + ".bak")
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(f, []byte(content)) {
t.Fatalf("expected %q to be %q", f, []byte(content))
}
}

err = AtomicWrite(outFile.Name(), true, []byte("second"), 0644, true)
if err != nil {
t.Fatal(err)
}
contains(outFile.Name(), "first")

err = AtomicWrite(outFile.Name(), true, []byte("third"), 0644, true)
if err != nil {
t.Fatal(err)
}
contains(outFile.Name(), "second")
})
}