tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/engine/fs/localfs/localfs.go (about) 1 package localfs 2 3 import ( 4 "os" 5 "path/filepath" 6 "time" 7 8 "tractor.dev/toolkit-go/engine/fs" 9 ) 10 11 type FS struct{} 12 13 func New() *FS { 14 return &FS{} 15 } 16 17 func (FS) Create(name string) (fs.File, error) { 18 f, e := os.Create(fsToUnixPath(name)) 19 if f == nil { 20 // while this looks strange, we need to return a bare nil (of type nil) not 21 // a nil value of type *os.File or nil won't be nil 22 return nil, e 23 } 24 return f, e 25 } 26 27 func (FS) Mkdir(name string, perm fs.FileMode) error { 28 return os.Mkdir(fsToUnixPath(name), perm) 29 } 30 31 func (FS) MkdirAll(path string, perm fs.FileMode) error { 32 return os.MkdirAll(path, perm) 33 } 34 35 func (FS) Open(name string) (fs.File, error) { 36 f, e := os.Open(fsToUnixPath(name)) 37 if f == nil { 38 // while this looks strange, we need to return a bare nil (of type nil) not 39 // a nil value of type *os.File or nil won't be nil 40 return nil, e 41 } 42 return f, e 43 } 44 45 func (FS) OpenFile(name string, flag int, perm fs.FileMode) (fs.File, error) { 46 f, e := os.OpenFile(fsToUnixPath(name), flag, perm) 47 if f == nil { 48 // while this looks strange, we need to return a bare nil (of type nil) not 49 // a nil value of type *os.File or nil won't be nil 50 return nil, e 51 } 52 return f, e 53 } 54 55 func (FS) Remove(name string) error { 56 return os.Remove(fsToUnixPath(name)) 57 } 58 59 func (FS) RemoveAll(path string) error { 60 return os.RemoveAll(fsToUnixPath(path)) 61 } 62 63 func (FS) Rename(oldname, newname string) error { 64 return os.Rename(fsToUnixPath(oldname), fsToUnixPath(newname)) 65 } 66 67 func (FS) Stat(name string) (fs.FileInfo, error) { 68 return os.Stat(fsToUnixPath(name)) 69 } 70 71 func (FS) Chmod(name string, mode fs.FileMode) error { 72 return os.Chmod(fsToUnixPath(name), mode) 73 } 74 75 func (FS) Chown(name string, uid, gid int) error { 76 return os.Chown(fsToUnixPath(name), uid, gid) 77 } 78 79 func (FS) Chtimes(name string, atime time.Time, mtime time.Time) error { 80 return os.Chtimes(fsToUnixPath(name), atime, mtime) 81 } 82 83 // Converts an `io/fs` path to a Unix path. 84 // Assumes path is absolute already 85 func fsToUnixPath(path string) string { 86 if !filepath.IsAbs(path) { 87 path = "/" + path 88 } 89 return filepath.Clean(path) 90 }