From: qydysky Date: Sun, 6 Apr 2025 18:07:20 +0000 (+0800) Subject: 1 (#42) X-Git-Tag: v0.28.20250406180726 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=c321a3c20e1c567177b0230d738b389cf91c2a77;p=part%2F.git 1 (#42) --- diff --git a/file/FileWR.go b/file/FileWR.go index 88ae50f..4c82e38 100644 --- a/file/FileWR.go +++ b/file/FileWR.go @@ -108,6 +108,48 @@ type Config struct { Coder encoder.Encoding } +type FS interface { + fs.FS + OpenFile(name string) (*File, error) +} + +type dirFS string + +func (dir dirFS) Open(name string) (fs.File, error) { + return dir.OpenFile(name) +} + +func (dir dirFS) OpenFile(name string) (*File, error) { + fullname, err := dir.join(name) + if err != nil { + return nil, &fs.PathError{Op: "open", Path: name, Err: err} + } + return Open(fullname).CheckRoot(string(dir)), nil +} + +// join returns the path for name in dir. +func (dir dirFS) join(name string) (string, error) { + if dir == "" { + return "", errors.New("os: DirFS with empty root") + } + name, err := filepath.Localize(name) + if err != nil { + return "", fs.ErrInvalid + } + if os.IsPathSeparator(dir[len(dir)-1]) { + return string(dir) + name, nil + } + return string(dir) + string(os.PathSeparator) + name, nil +} + +func DirFS(dir string) FS { + return dirFS(dir) +} + +func Open(filePath string) *File { + return New(filePath, 0, false) +} + func New(filePath string, curIndex int64, autoClose bool) *File { return &File{ Config: Config{ @@ -125,6 +167,16 @@ func (t *File) CheckRoot(root string) *File { } else { t.Config.FilePath = rel } + newPath(dos{ + create: os.Create, + lstat: os.Lstat, + mkdir: os.Mkdir, + open: os.Open, + openFile: os.OpenFile, + remove: os.Remove, + removeAll: os.RemoveAll, + stat: os.Stat, + }, t.Config.root+"/.t", fs.ModeDir) return t } @@ -650,6 +702,10 @@ func (t *File) IsExist() bool { return err == nil } +func IsExist(path string) bool { + return Open(path).IsExist() +} + func (t *File) IsDir() bool { info, err := t.Stat() if err != nil { diff --git a/file/FileWR_test.go b/file/FileWR_test.go index 452af23..3d1dc13 100644 --- a/file/FileWR_test.go +++ b/file/FileWR_test.go @@ -16,6 +16,23 @@ import ( "golang.org/x/text/encoding/unicode" ) +func TestDir(t *testing.T) { + Open("test2").Delete() + if Open("test2").IsExist() { + t.Fatal() + } + if f, e := DirFS("test2").Open("FileWR.go"); e != nil { + t.Fatal(e) + } else if _, e := f.(*File).Write([]byte{'1'}, false); e != nil { + t.Fatal(e) + } else { + f.(*File).Delete() + } + if !Open("test2").IsExist() { + t.Fatal() + } +} + func TestMain(t *testing.T) { if runtime.GOOS == `windows` { if filepath.Join(`c:\`, "s/as") != `c:\s\as` {