Skip to content

Commit

Permalink
✨ feat: fsutil - add new func Glob() for quick list files by pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 16, 2023
1 parent 68df21b commit b3ce62f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
30 changes: 29 additions & 1 deletion fsutil/find.go
Expand Up @@ -3,9 +3,11 @@ package fsutil
import (
"io/fs"
"os"
"path"
"path/filepath"

"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/strutil"
)

Expand Down Expand Up @@ -43,11 +45,37 @@ func SearchNameUpx(dirPath, name string) (string, bool) {

// 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.
func WalkDir(dir string, fn fs.WalkDirFunc) error {
return filepath.WalkDir(dir, fn)
}

// GlobWithFunc handle matched file
// 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 Glob(pattern string, fls ...comdef.StringMatchFunc) []string {
files, _ := filepath.Glob(pattern)
if len(fls) == 0 || len(files) == 0 {
return files
}

var matched []string
for _, file := range files {
for _, fn := range fls {
if fn(path.Base(file)) {
matched = append(matched, file)
break
}
}
}
return matched
}

// GlobWithFunc find files by glob path pattern, then handle matched file
//
// - TIP: will be not find in subdir.
func GlobWithFunc(pattern string, fn func(filePath string) error) (err error) {
Expand Down
5 changes: 5 additions & 0 deletions fsutil/find_test.go
Expand Up @@ -30,6 +30,11 @@ func TestSearchNameUp(t *testing.T) {
}

func TestGlobWithFunc(t *testing.T) {
assert.NotEmpty(t, fsutil.Glob("testdata/*"))
assert.NotEmpty(t, fsutil.Glob("testdata/*", func(s string) bool {
return s[0] != '.'
}))

var paths []string
err := fsutil.GlobWithFunc("testdata/*", func(fpath string) error {
paths = append(paths, fpath)
Expand Down

0 comments on commit b3ce62f

Please sign in to comment.