Skip to content

Commit

Permalink
Merge pull request #1271 from hashicorp/issue-1270-backup-regression
Browse files Browse the repository at this point in the history
fix backup to backup more than once
  • Loading branch information
eikenb authored Aug 31, 2019
2 parents 10fb1e1 + f8b44c8 commit 3957cdf
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
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")
})
}

0 comments on commit 3957cdf

Please sign in to comment.