105 lines
2.2 KiB
Go
105 lines
2.2 KiB
Go
|
package ifs
|
||
|
|
||
|
import (
|
||
|
"io/fs"
|
||
|
"os"
|
||
|
"runtime"
|
||
|
)
|
||
|
|
||
|
type FS interface {
|
||
|
Mkdir(name string, perm fs.FileMode) error
|
||
|
MkdirAll(name string, perm fs.FileMode) error
|
||
|
Open(name string) (fs.File, error)
|
||
|
OpenFile(name string, flag int, perm fs.FileMode) (File, error)
|
||
|
Remove(name string) error
|
||
|
RemoveAll(name string) error
|
||
|
}
|
||
|
|
||
|
func DirFS(dir string) FS {
|
||
|
return dirFS(dir)
|
||
|
}
|
||
|
|
||
|
type File interface {
|
||
|
Stat() (fs.FileInfo, error)
|
||
|
Read([]byte) (int, error)
|
||
|
Write([]byte) (int, error)
|
||
|
Close() error
|
||
|
}
|
||
|
|
||
|
type dirFS string
|
||
|
|
||
|
func (dir dirFS) validPath(name, op string) error {
|
||
|
if !fs.ValidPath(name) || runtime.GOOS == "windows" && containsAny(name, `\:`) {
|
||
|
return &os.PathError{Op: op, Path: name, Err: os.ErrInvalid}
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (dir dirFS) Mkdir(name string, perm fs.FileMode) error {
|
||
|
if err := dir.validPath(name, "mkdir"); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return os.Mkdir(string(dir)+"/"+name, perm)
|
||
|
}
|
||
|
|
||
|
func (dir dirFS) MkdirAll(name string, perm fs.FileMode) error {
|
||
|
if err := dir.validPath(name, "mkdirAll"); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return os.MkdirAll(string(dir)+"/"+name, perm)
|
||
|
}
|
||
|
|
||
|
func (dir dirFS) Open(name string) (fs.File, error) {
|
||
|
if err := dir.validPath(name, "open"); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return os.Open(string(dir) + "/" + name)
|
||
|
}
|
||
|
|
||
|
func (dir dirFS) OpenFile(name string, flag int, perm fs.FileMode) (File, error) {
|
||
|
if err := dir.validPath(name, "openFile"); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
f, err := os.OpenFile(string(dir)+"/"+name, flag, perm)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return f, nil
|
||
|
}
|
||
|
|
||
|
func (dir dirFS) Remove(name string) error {
|
||
|
if err := dir.validPath(name, "remove"); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return os.Remove(string(dir) + "/" + name)
|
||
|
}
|
||
|
|
||
|
func (dir dirFS) RemoveAll(name string) error {
|
||
|
if err := dir.validPath(name, "removeAll"); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return os.RemoveAll(string(dir) + "/" + name)
|
||
|
}
|
||
|
|
||
|
func (dir dirFS) Stat(name string) (fs.FileInfo, error) {
|
||
|
if err := dir.validPath(name, "stat"); err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
f, err := os.Stat(string(dir) + "/" + name)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return f, nil
|
||
|
}
|
||
|
|
||
|
func containsAny(s, chars string) bool {
|
||
|
for i := 0; i < len(s); i++ {
|
||
|
for j := 0; j < len(chars); j++ {
|
||
|
if s[i] == chars[j] {
|
||
|
return true
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return false
|
||
|
}
|