Added methods to retrieve all file paths in a directory.
This commit is contained in:
parent
bf8c3172c3
commit
491d976677
46
utio/dir.go
46
utio/dir.go
@ -2,8 +2,45 @@ package utio
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Files gives back all the files in the specified directory
|
||||
func Files(root string) ([]string, error) {
|
||||
var files []string
|
||||
if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
files = append(files, path)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// Files gives back all the files in the specified directory that match the specified glob pattern.
|
||||
func FilesFilter(dir, glob string) ([]string, error) {
|
||||
files, err := Files(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var filtered []string
|
||||
globRE := globToRE(glob)
|
||||
for _, f := range files {
|
||||
if globRE.MatchString(f) {
|
||||
filtered = append(filtered, f)
|
||||
}
|
||||
}
|
||||
return filtered, nil
|
||||
}
|
||||
|
||||
// Home gives back the home directory for the current user.
|
||||
func Home() (string, error) {
|
||||
return os.UserHomeDir()
|
||||
@ -20,3 +57,12 @@ func PathDoesNotExist(path string) bool {
|
||||
var _, err = os.Stat(path)
|
||||
return os.IsNotExist(err)
|
||||
}
|
||||
|
||||
func globToRE(glob string) *regexp.Regexp {
|
||||
pattern := glob
|
||||
pattern = strings.ReplaceAll(pattern, "\\", "\\\\")
|
||||
pattern = strings.ReplaceAll(pattern, ".", "\\.")
|
||||
pattern = strings.ReplaceAll(pattern, "*", ".*")
|
||||
pattern = strings.ReplaceAll(pattern, "?", ".")
|
||||
return regexp.MustCompile(pattern)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user