Skip to content

Commit b37ae73

Browse files
committed
output: truncate file when creating
1 parent ea047dc commit b37ae73

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

internal/output/output.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func NewOutput(path string, verbose bool) (o *Output, err error) {
3838
}
3939

4040
if path != "" {
41-
o.receivedDataFile, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0o644)
41+
o.receivedDataFile, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
4242
}
4343

4444
return o, err

internal/output/output_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package output
2+
3+
import (
4+
"os"
5+
"testing"
6+
)
7+
8+
// TestNewOutput_truncatesFile ensures that creating a new Output with an existing file truncates it.
9+
func TestNewOutput_truncatesFile(t *testing.T) {
10+
path := "test_output.txt"
11+
// Create file with some data
12+
err := os.WriteFile(path, []byte("old-data"), 0o644)
13+
if err != nil {
14+
t.Fatalf("failed to prepare test file: %v", err)
15+
}
16+
17+
o, err := NewOutput(path, false)
18+
if err != nil {
19+
t.Fatalf("failed to create output: %v", err)
20+
}
21+
defer func() {
22+
_ = o.receivedDataFile.Close()
23+
_ = os.Remove(path)
24+
}()
25+
26+
// Write new content
27+
_, err = o.receivedDataFile.WriteString("new")
28+
if err != nil {
29+
t.Fatalf("failed to write: %v", err)
30+
}
31+
_ = o.receivedDataFile.Close()
32+
33+
b, err := os.ReadFile(path)
34+
if err != nil {
35+
t.Fatalf("failed to read: %v", err)
36+
}
37+
if string(b) != "new" {
38+
t.Fatalf("file not truncated, got: %q", string(b))
39+
}
40+
}

0 commit comments

Comments
 (0)