Skip to content

Commit

Permalink
✨ feat: fs - add more make dir util func
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jan 28, 2023
1 parent 030676d commit c4447cb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
6 changes: 6 additions & 0 deletions fsutil/fsutil.go
Expand Up @@ -5,6 +5,7 @@ import (
"io"
"net/http"
"os"
"path/filepath"
)

const (
Expand Down Expand Up @@ -77,3 +78,8 @@ func ReaderMimeType(r io.Reader) (mime string) {

return http.DetectContentType(buf[:n])
}

// JoinPaths elements, alias of filepath.Join()
func JoinPaths(elem ...string) string {
return filepath.Join(elem...)
}
34 changes: 29 additions & 5 deletions fsutil/operate.go
Expand Up @@ -15,6 +15,27 @@ func Mkdir(dirPath string, perm os.FileMode) error {
return os.MkdirAll(dirPath, perm)
}

// MkDirs batch make multi dirs at once
func MkDirs(perm os.FileMode, dirPaths ...string) error {
for _, dirPath := range dirPaths {
if err := os.MkdirAll(dirPath, perm); err != nil {
return err
}
}
return nil
}

// MkSubDirs batch make multi sub-dirs at once
func MkSubDirs(perm os.FileMode, parentDir string, subDirs ...string) error {
for _, dirName := range subDirs {
dirPath := parentDir + "/" + dirName
if err := os.MkdirAll(dirPath, perm); err != nil {
return err
}
}
return nil
}

// MkParentDir quick create parent dir
func MkParentDir(fpath string) error {
dirPath := filepath.Dir(fpath)
Expand All @@ -36,6 +57,13 @@ const (
FsRFlags = os.O_RDONLY // read-only
)

func fsFlagsOr(fileFlags []int, fileFlag int) int {
if len(fileFlags) > 0 {
return fileFlags[0]
}
return fileFlag
}

// OpenFile like os.OpenFile, but will auto create dir.
func OpenFile(filepath string, flag int, perm os.FileMode) (*os.File, error) {
fileDir := path.Dir(filepath)
Expand All @@ -56,11 +84,7 @@ func OpenFile(filepath string, flag int, perm os.FileMode) (*os.File, error) {
//
// Tip: file flag default is FsCWAFlags
func QuickOpenFile(filepath string, fileFlag ...int) (*os.File, error) {
flag := FsCWAFlags
if len(fileFlag) > 0 {
flag = fileFlag[0]
}

flag := fsFlagsOr(fileFlag, FsCWAFlags)
return OpenFile(filepath, flag, DefaultFilePerm)
}

Expand Down

0 comments on commit c4447cb

Please sign in to comment.