Skip to content
This repository has been archived by the owner on Jun 29, 2022. It is now read-only.

Commit

Permalink
pkg/util/walkers: truncate file when writing
Browse files Browse the repository at this point in the history
To avoid leaving old content untouched when updating files, which may
happen if new content is smaller than the old one.

Closes #40

Signed-off-by: Mateusz Gozdek <mateusz@kinvolk.io>
  • Loading branch information
invidian authored and iaguis committed Feb 27, 2020
1 parent 9887328 commit b8231dd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/util/walkers/copying.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func CopyingWalker(path string, newDirPerms os.FileMode) assets.WalkFunc {
// this is the only content stored in the file.
func writeFile(p string, r io.Reader) error {
// TODO: If we start packing binaries, make sure they have executable bit set.
f, err := os.OpenFile(p, os.O_RDWR|os.O_CREATE, 0644)
f, err := os.OpenFile(p, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("failed to open target file %s: %w", p, err)
}
Expand Down
26 changes: 26 additions & 0 deletions pkg/util/walkers/copying_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,29 @@ func TestWriteFile(t *testing.T) {
t.Fatalf("Expected: '%s', got '%s'", testData, string(d))
}
}

func TestWriteFileTruncate(t *testing.T) {
f, err := ioutil.TempFile("", tmpPattern)
if err != nil {
t.Fatalf("Creating temp file should succeed, got: %v", err)
}

defer os.Remove(f.Name())

if err := writeFile(f.Name(), strings.NewReader("111111")); err != nil {
t.Fatalf("Writing to file should succeed, got: %v", err)
}

if err := writeFile(f.Name(), strings.NewReader(testData)); err != nil {
t.Fatalf("Updating file should succeed, got: %v", err)
}

d, err := ioutil.ReadFile(f.Name())
if err != nil {
t.Fatalf("Reading tmp file should succeed, got: %v", err)
}

if !reflect.DeepEqual(testData, string(d)) {
t.Fatalf("Expected: '%s', got '%s'", testData, string(d))
}
}

0 comments on commit b8231dd

Please sign in to comment.