1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
17 // FromFS converts an fs.FS to the FileSystem interface.
18 func FromFS(fsys fs.FS) FileSystem {
19 return &fsysToFileSystem{fsys}
22 type fsysToFileSystem struct {
26 func (f *fsysToFileSystem) fsPath(name string) string {
27 name = path.Clean(name)
31 return strings.TrimPrefix(name, "/")
34 func (f *fsysToFileSystem) Open(name string) (ReadSeekCloser, error) {
35 file, err := f.fsys.Open(f.fsPath(name))
39 if rsc, ok := file.(ReadSeekCloser); ok {
42 return &noSeekFile{f.fsPath(name), file}, nil
45 func (f *fsysToFileSystem) Lstat(name string) (os.FileInfo, error) {
46 return fs.Stat(f.fsys, f.fsPath(name))
49 func (f *fsysToFileSystem) Stat(name string) (os.FileInfo, error) {
50 return fs.Stat(f.fsys, f.fsPath(name))
53 func (f *fsysToFileSystem) RootType(name string) RootType { return "" }
55 func (f *fsysToFileSystem) ReadDir(name string) ([]os.FileInfo, error) {
56 dirs, err := fs.ReadDir(f.fsys, f.fsPath(name))
57 var infos []os.FileInfo
58 for _, d := range dirs {
59 info, err1 := d.Info()
66 infos = append(infos, info)
71 func (f *fsysToFileSystem) String() string { return "io/fs" }
73 type noSeekFile struct {
78 func (f *noSeekFile) Seek(offset int64, whence int) (int64, error) {
79 return 0, &fs.PathError{Op: "seek", Path: f.path, Err: fs.ErrInvalid}