File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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
7677func 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
Original file line number Diff line number Diff 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 )
You can’t perform that action at this time.
0 commit comments