Skip to content

Commit adb6c90

Browse files
committed
fileio: create parent dirs before writing file
1 parent 424f899 commit adb6c90

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

internal/fileio/fileio.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,18 @@ func ReadJson[T any](path string) (T, error) {
7171
}
7272

7373
// WriteFile writes the file to disk.
74+
// If the path directories do not exist, creates them.
7475
// The content can be text or binary (encoded as a data URL),
7576
// e.g. data:application/octet-stream;base64,MTIz
7677
func WriteFile(path, content string, perm fs.FileMode) (err error) {
78+
// create parent directories if needed
79+
dir := filepath.Dir(path)
80+
err = os.MkdirAll(dir, 0755)
81+
if err != nil {
82+
return err
83+
}
84+
85+
// write file content
7786
var data []byte
7887
if !strings.HasPrefix(content, "data:") {
7988
// text file

internal/fileio/fileio_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,16 @@ func TestWriteFile(t *testing.T) {
114114
be.Err(t, err, nil)
115115
defer func() { _ = os.RemoveAll(dir) }()
116116

117+
t.Run("create nested dirs", func(t *testing.T) {
118+
path := filepath.Join(dir, "a/b/c/file.txt")
119+
err = WriteFile(path, "hello", 0444)
120+
be.Err(t, err, nil)
121+
got, err := os.ReadFile(path)
122+
be.Err(t, err, nil)
123+
want := []byte("hello")
124+
be.Equal(t, got, want)
125+
})
126+
117127
t.Run("text", func(t *testing.T) {
118128
path := filepath.Join(dir, "data.txt")
119129
err = WriteFile(path, "hello", 0444)

0 commit comments

Comments
 (0)