Documentation ¶
Overview ¶
Package fsutil Filesystem util functions, quick create, read and write file. eg: file and dir check, operate
Index ¶
- Constants
- Variables
- func ApplyFilters(fPath string, ent fs.DirEntry, filters []FilterFunc) bool
- func CopyFile(srcPath, dstPath string) error
- func CreateFile(fpath string, filePerm, dirPerm os.FileMode, fileFlag ...int) (*os.File, error)
- func DeleteIfExist(fPath string) error
- func DeleteIfFileExist(fPath string) error
- func DetectMime(path string) string
- func Dir(fpath string) string
- func DirPath(fpath string) string
- func DiscardReader(src io.Reader)
- func ExcludeDotFile(_ string, ent fs.DirEntry) bool
- func Expand(pathStr string) string
- func ExpandPath(pathStr string) string
- func Extname(fpath string) string
- func FileExists(path string) bool
- func FileExt(fpath string) string
- func FilePathInDirs(file string, dirs ...string) string
- func FindInDir(dir string, handleFn HandleFunc, filters ...FilterFunc) (e error)
- func FirstExists(paths ...string) string
- func FirstExistsDir(paths ...string) string
- func FirstExistsFile(paths ...string) string
- func GetContents(in any) []byte
- func Glob(pattern string, fls ...NameMatchFunc) []string
- func GlobWithFunc(pattern string, fn func(filePath string) error) (err error)
- func IsAbsPath(aPath string) bool
- func IsDir(path string) bool
- func IsEmptyDir(dirPath string) bool
- func IsFile(path string) bool
- func IsImageFile(path string) bool
- func IsZipFile(filepath string) bool
- func JoinPaths(elem ...string) string
- func JoinPaths3(basePath, secPath string, elems ...string) string
- func JoinSubPaths(basePath string, elems ...string) string
- func LineScanner(in any) *bufio.Scanner
- func MatchFirst(paths []string, matcher PathMatchFunc, defaultPath string) string
- func MatchPaths(paths []string, matcher PathMatchFunc) []string
- func MimeType(path string) (mime string)
- func MkDirs(perm os.FileMode, dirPaths ...string) error
- func MkParentDir(fpath string) error
- func MkSubDirs(perm os.FileMode, parentDir string, subDirs ...string) error
- func Mkdir(dirPath string, perm os.FileMode) error
- func Must2(_ any, err error)
- func MustCopyFile(srcPath, dstPath string)
- func MustCreateFile(filePath string, filePerm, dirPerm os.FileMode) *os.File
- func MustOpenFile(filePath string, flag int, perm os.FileMode) *os.File
- func MustRead(in any) []byte
- func MustReadFile(filePath string) []byte
- func MustReadReader(r io.Reader) []byte
- func MustRemove(fPath string)
- func MustSave(filePath string, data any, optFns ...OpenOptionFunc)
- func Name(fpath string) string
- func NewIOReader(in any) (r io.Reader, err error)
- func OSTempDir(pattern string) (string, error)
- func OSTempFile(pattern string) (*os.File, error)
- func OnlyFindDir(_ string, ent fs.DirEntry) bool
- func OnlyFindFile(_ string, ent fs.DirEntry) bool
- func OpenAppendFile(filepath string, filePerm ...os.FileMode) (*os.File, error)
- func OpenFile(filePath string, flag int, perm os.FileMode) (*os.File, error)
- func OpenReadFile(filepath string) (*os.File, error)
- func OpenTruncFile(filepath string, filePerm ...os.FileMode) (*os.File, error)
- func PathExists(path string) bool
- func PathMatch(pattern, s string) bool
- func PathName(fpath string) string
- func PutContents(filePath string, data any, fileFlag ...int) (int, error)
- func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error)
- func QuietRemove(fPath string)
- func ReadAll(in any) []byte
- func ReadExistFile(filePath string) []byte
- func ReadFile(filePath string) []byte
- func ReadOrErr(in any) ([]byte, error)
- func ReadReader(r io.Reader) []byte
- func ReadString(in any) string
- func ReadStringOrErr(in any) (string, error)
- func ReaderMimeType(r io.Reader) (mime string)
- func Realpath(pathStr string) string
- func Remove(fPath string) error
- func RemoveSub(dirPath string, fns ...FilterFunc) error
- func ResolvePath(pathStr string) string
- func RmFileIfExist(fPath string) error
- func RmIfExist(fPath string) error
- func SafeRemoveAll(path string)
- func SaveFile(filePath string, data any, optFns ...OpenOptionFunc) error
- func SearchNameUp(dirPath, name string) string
- func SearchNameUpx(dirPath, name string) (string, bool)
- func SlashPath(path string) string
- func SplitPath(pathStr string) (dir, name string)
- func Suffix(fpath string) string
- func TempDir(dir, pattern string) (string, error)
- func TempFile(dir, pattern string) (*os.File, error)
- func TextScanner(in any) *scanner.Scanner
- func ToAbsPath(p string) string
- func UnixPath(path string) string
- func Unzip(archive, targetDir string) (err error)
- func UpdateContents(filePath string, handleFn func(bs []byte) []byte) error
- func WalkDir(dir string, fn fs.WalkDirFunc) error
- func WriteFile(filePath string, data any, perm os.FileMode, fileFlag ...int) error
- func WriteOSFile(f *os.File, data any) (n int, err error)
- type Entry
- type FileInfo
- type FileInfos
- type FilterFunc
- type HandleFunc
- type NameMatchFunc
- type OpenOption
- type OpenOptionFunc
- type PathMatchFunc
Constants ¶
const ( FsCWAFlags = os.O_CREATE | os.O_WRONLY | os.O_APPEND // create, append write-only FsCWTFlags = os.O_CREATE | os.O_WRONLY | os.O_TRUNC // create, override write-only FsCWFlags = os.O_CREATE | os.O_WRONLY // create, write-only FsRWFlags = os.O_RDWR // read-write, dont create. FsRFlags = os.O_RDONLY // read-only )
some commonly flag consts for open file.
const (
// MimeSniffLen sniff Length, use for detect file mime type
MimeSniffLen = 512
)
const PathSep = os.PathSeparator
PathSep alias of os.PathSeparator
Variables ¶
var ( DefaultDirPerm os.FileMode = 0775 DefaultFilePerm os.FileMode = 0665 OnlyReadFilePerm os.FileMode = 0444 )
perm for create dir or file
var ( // DefaultFileFlags for create and write DefaultFileFlags = os.O_CREATE | os.O_WRONLY | os.O_APPEND // OnlyReadFileFlags open file for read OnlyReadFileFlags = os.O_RDONLY )
var ( DirExist = IsDir FileExist = IsFile PathExist = PathExists )
alias methods
var ( // MustRm removes the named file or (empty) directory. MustRm = MustRemove // QuietRm removes the named file or (empty) directory. QuietRm = QuietRemove )
alias methods
var ImageMimeTypes = map[string]string{
"bmp": "image/bmp",
"gif": "image/gif",
"ief": "image/ief",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"svg": "image/svg+xml",
"ico": "image/x-icon",
"webp": "image/webp",
}
ImageMimeTypes refer net/http package
Functions ¶
func ApplyFilters ¶
func ApplyFilters(fPath string, ent fs.DirEntry, filters []FilterFunc) bool
ApplyFilters handle
func CreateFile ¶
CreateFile create file if not exists
Usage:
CreateFile("path/to/file.txt", 0664, 0666)
func DeleteIfExist ¶
DeleteIfExist removes the named file or (empty) directory on exists.
func DeleteIfFileExist ¶
DeleteIfFileExist removes the named file on exists.
func DetectMime ¶
DetectMime detect file mime type. alias of MimeType()
func ExpandPath ¶
ExpandPath will parse `~` as user home dir path.
func FileExists ¶
FileExists reports whether the named file or directory exists.
func FilePathInDirs ¶
FilePathInDirs get full file path in dirs.
Params:
- file: can be relative path, file name, full path.
- dirs: dir paths
func FindInDir ¶
func FindInDir(dir string, handleFn HandleFunc, filters ...FilterFunc) (e error)
FindInDir code refer the go pkg: path/filepath.glob()
- TIP: will be not find in subdir.
filters: return false will skip the file.
func FirstExists ¶
FirstExists check multi paths and return first exists path.
func FirstExistsDir ¶
FirstExistsDir check multi paths and return first exists dir.
func FirstExistsFile ¶
FirstExistsFile check multi paths and return first exists file.
func GetContents ¶
GetContents read contents from path or io.Reader, will panic on in type error
func Glob ¶
func Glob(pattern string, fls ...NameMatchFunc) []string
Glob find files by glob path pattern. alias of filepath.Glob() and support filter matched files by name.
Usage:
files := fsutil.Glob("/path/to/dir/*.go")
func GlobWithFunc ¶
GlobWithFunc find files by glob path pattern, then handle matched file
- TIP: will be not find in subdir.
func IsEmptyDir ¶
IsEmptyDir reports whether the named directory is empty.
func IsZipFile ¶
IsZipFile check is zip file. from https://blog.csdn.net/wangshubo1989/article/details/71743374
func JoinPaths3 ¶
JoinPaths3 elements, like the filepath.Join()
func JoinSubPaths ¶
JoinSubPaths elements, like the filepath.Join()
func LineScanner ¶
LineScanner create from filepath or io.Reader, will panic on in type error. Will scan and parse text to lines.
s := fsutil.LineScanner("/path/to/file") for s.Scan() { fmt.Println(s.Text()) }
func MatchFirst ¶
func MatchFirst(paths []string, matcher PathMatchFunc, defaultPath string) string
MatchFirst filter paths by filter func and return first match path.
func MatchPaths ¶
func MatchPaths(paths []string, matcher PathMatchFunc) []string
MatchPaths given paths by custom mather func.
func MkParentDir ¶
MkParentDir quick create parent dir for given path.
func MustCopyFile ¶
func MustCopyFile(srcPath, dstPath string)
MustCopyFile copy file to another path.
func MustCreateFile ¶
MustCreateFile create file, will panic on error
func MustOpenFile ¶
MustOpenFile like os.OpenFile, but will auto create dir.
Usage:
file := MustOpenFile("path/to/file.txt", FsCWFlags, 0666)
func MustReadFile ¶
MustReadFile read file contents, will panic on error
func MustReadReader ¶
MustReadReader read contents from io.Reader, will panic on error
func MustRemove ¶
func MustRemove(fPath string)
MustRemove removes the named file or (empty) directory. NOTICE: will panic on error
func MustSave ¶
func MustSave(filePath string, data any, optFns ...OpenOptionFunc)
MustSave create file and write contents to file, panic on error.
- data type allow: string, []byte, io.Reader
default option see NewOpenOption()
func NewIOReader ¶
NewIOReader instance by input file path or io.Reader
func OSTempDir ¶
OSTempDir creates a new temp dir on os.TempDir and return the temp dir path
Usage:
fsutil.OSTempDir("example.*")
func OSTempFile ¶
OSTempFile create a temp file on os.TempDir()
Usage:
fsutil.OSTempFile("example.*.txt")
func OpenAppendFile ¶
OpenAppendFile like os.OpenFile, open for append write. if not exists, will create it.
func OpenFile ¶
OpenFile like os.OpenFile, but will auto create dir.
Usage:
file, err := OpenFile("path/to/file.txt", FsCWFlags, 0666)
func OpenReadFile ¶
OpenReadFile like os.OpenFile, open file for read contents
func OpenTruncFile ¶
OpenTruncFile like os.OpenFile, open for override write. if not exists, will create it.
func PathExists ¶
PathExists reports whether the named file or directory exists.
func PutContents ¶
PutContents create file and write contents to file at once.
data type allow: string, []byte, io.Reader. will auto create dir.
Tip: file flag default is FsCWTFlags (override write)
Usage:
fsutil.PutContents(filePath, contents, fsutil.FsCWAFlags) // append write fsutil.Must2(fsutil.PutContents(filePath, contents)) // panic on error
func QuickOpenFile ¶
QuickOpenFile like os.OpenFile, open for append write. if not exists, will create it.
Alias of OpenAppendFile()
func QuietRemove ¶
func QuietRemove(fPath string)
QuietRemove removes the named file or (empty) directory.
NOTICE: will ignore error
func ReadExistFile ¶
ReadExistFile read file contents if existed, will panic on error
func ReadReader ¶
ReadReader read contents from io.Reader, will panic on error
func ReadString ¶
ReadString read contents from path or io.Reader, will panic on in type error
func ReadStringOrErr ¶
ReadStringOrErr read contents from path or io.Reader, will panic on in type error
func ReaderMimeType ¶
ReaderMimeType get the io.Reader mimeType
Usage:
file, err := os.Open(filepath) if err != nil { return } mime := ReaderMimeType(file)
func Realpath ¶
Realpath returns the shortest path name equivalent to path by purely lexical processing. Will expand ~ to home dir, and join with workdir if path is relative path.
func RemoveSub ¶
func RemoveSub(dirPath string, fns ...FilterFunc) error
RemoveSub removes all sub files and dirs of dirPath, but not remove dirPath.
func ResolvePath ¶
ResolvePath will parse `~` and env var in path
func RmFileIfExist ¶
RmFileIfExist removes the named file on exists.
func SafeRemoveAll ¶
func SafeRemoveAll(path string)
SafeRemoveAll removes path and any children it contains. will ignore error
func SaveFile ¶
func SaveFile(filePath string, data any, optFns ...OpenOptionFunc) error
SaveFile create file and write contents to file. will auto create dir.
- data type allow: string, []byte, io.Reader
default option see NewOpenOption()
func SearchNameUp ¶
SearchNameUp find file/dir name in dirPath or parent dirs, return the name of directory path
Usage:
repoDir := fsutil.SearchNameUp("/path/to/dir", ".git")
func SearchNameUpx ¶
SearchNameUpx find file/dir name in dirPath or parent dirs, return the name of directory path and dir is changed.
func SplitPath ¶
SplitPath splits path immediately following the final Separator, separating it into a directory and file name component
func TempDir ¶
TempDir creates a new temp dir and return the temp dir path
Usage:
fsutil.TempDir("", "example.*") fsutil.TempDir("testdata", "example.*")
func TempFile ¶
TempFile is like os.CreateTemp, but can custom temp dir.
Usage:
// create temp file on os.TempDir() fsutil.TempFile("", "example.*.txt") // create temp file on "testdata" dir fsutil.TempFile("testdata", "example.*.txt")
func TextScanner ¶
TextScanner from filepath or io.Reader, will panic on in type error. Will scan parse text to tokens: Ident, Int, Float, Char, String, RawString, Comment, etc.
Usage:
s := fsutil.TextScanner("/path/to/file") for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() { fmt.Printf("%s: %s\n", s.Position, s.TokenText()) }
func ToAbsPath ¶
ToAbsPath convert path to absolute path. Will expand home dir, if empty will return current work dir
TIP: will don't check path is really exists
func Unzip ¶
Unzip a zip archive from https://blog.csdn.net/wangshubo1989/article/details/71743374
func UpdateContents ¶
UpdateContents read file contents, call handleFn(contents) handle, then write updated contents to file
func WalkDir ¶
func WalkDir(dir string, fn fs.WalkDirFunc) error
WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.
TIP: will recursively find in sub dirs.
Types ¶
type Entry ¶
type Entry interface { fs.DirEntry // Path get file/dir full path. eg: "/path/to/file.go" Path() string // Info get file info. like fs.DirEntry.Info(), but will cache result. Info() (fs.FileInfo, error) }
Entry extends fs.DirEntry, add some useful methods
type FileInfo ¶
type FileInfo interface { fs.FileInfo // Path get file full path. eg: "/path/to/file.go" Path() string }
FileInfo extends fs.FileInfo, add some useful methods
type FileInfos ¶
type FileInfos []FileInfo
FileInfos type for FileInfo slice
implements sort.Interface:
sorts by oldest time modified in the file info. eg: [old_220211, old_220212, old_220213]
type HandleFunc ¶
HandleFunc type for FindInDir
type NameMatchFunc ¶
type NameMatchFunc = comdef.StringMatchFunc
NameMatchFunc name match func, alias of comdef.StringMatchFunc
type OpenOption ¶
type OpenOption struct { // file open flag. see FsCWTFlags Flag int // file perm. see DefaultFilePerm Perm os.FileMode }
OpenOption for open file
func NewOpenOption ¶
func NewOpenOption(optFns ...OpenOptionFunc) *OpenOption
NewOpenOption create a new OpenOption instance
Defaults:
- open flags: FsCWTFlags (override write)
- file Perm: DefaultFilePerm
func OpenOptOrNew ¶
func OpenOptOrNew(opt *OpenOption) *OpenOption
OpenOptOrNew create a new OpenOption instance if opt is nil
type PathMatchFunc ¶
type PathMatchFunc = comdef.StringMatchFunc
PathMatchFunc path match func. alias of comdef.StringMatchFunc