Skip to content

Commit aee068c

Browse files
committed
Update WriteFile support for VFS
1 parent 7de9901 commit aee068c

File tree

1 file changed

+40
-8
lines changed

1 file changed

+40
-8
lines changed

internal/vfs/vfs.go

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package vfs
33
import (
44
"bytes"
55
"encoding/binary"
6-
"errors"
76
"fmt"
87
"io/fs"
98
"os"
@@ -73,11 +72,23 @@ type RealpathFS interface {
7372
Realpath(path string) (string, error)
7473
}
7574

75+
type WriteFileFS interface {
76+
fs.FS
77+
WriteFile(path string, data []byte, perm os.FileMode) error
78+
}
79+
80+
type MkdirAllFS interface {
81+
fs.FS
82+
MkdirAll(path string, perm os.FileMode) error
83+
}
84+
7685
// FromIOFS creates a new FS from an [fs.FS].
7786
//
7887
// For paths like `c:/foo/bar`, fsys will be used as though it's rooted at `/` and the path is `/c:/foo/bar`.
7988
//
8089
// If the provided [fs.FS] implements [RealpathFS], it will be used to implement the Realpath method.
90+
// If the provided [fs.FS] implements [WriteFileFS], it will be used to implement the WriteFile method.
91+
// If the provided [fs.FS] implements [MkdirAllFS], it will be used to implement the MkdirAll method.
8192
//
8293
// Deprecated: FromIOFS does not actually handle case-insensitivity; ensure the passed in [fs.FS]
8394
// respects case-insensitive file names if needed. Consider using [vfstest.FromMapFS] for testing.
@@ -101,6 +112,31 @@ func FromIOFS(fsys fs.FS, useCaseSensitiveFileNames bool) FS {
101112
}
102113
}
103114

115+
var writeFile func(path string, content string, writeByteOrderMark bool) error
116+
if fsys, ok := fsys.(WriteFileFS); ok {
117+
writeFile = func(path string, content string, writeByteOrderMark bool) error {
118+
if writeByteOrderMark {
119+
content = "\uFEFF" + content
120+
}
121+
return fsys.WriteFile(path, []byte(content), 0o666)
122+
}
123+
} else {
124+
writeFile = func(string, string, bool) error {
125+
panic("writeFile not supported")
126+
}
127+
}
128+
129+
var mkdirAll func(path string) error
130+
if fsys, ok := fsys.(MkdirAllFS); ok {
131+
mkdirAll = func(path string) error {
132+
return fsys.MkdirAll(path, 0o777)
133+
}
134+
} else {
135+
mkdirAll = func(string) error {
136+
panic("mkdirAll not supported")
137+
}
138+
}
139+
104140
return &vfs{
105141
useCaseSensitiveFileNames: useCaseSensitiveFileNames,
106142
rootFor: func(root string) fs.FS {
@@ -115,13 +151,9 @@ func FromIOFS(fsys fs.FS, useCaseSensitiveFileNames bool) FS {
115151
}
116152
return sub
117153
},
118-
realpath: realpath,
119-
writeFile: func(string, string, bool) error {
120-
return errors.ErrUnsupported
121-
},
122-
mkdirAll: func(string) error {
123-
return errors.ErrUnsupported
124-
},
154+
realpath: realpath,
155+
writeFile: writeFile,
156+
mkdirAll: mkdirAll,
125157
}
126158
}
127159

0 commit comments

Comments
 (0)