ut/utio/dir.go

69 lines
1.5 KiB
Go

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()
}
// PathExists tests if the supplied path exists.
func PathExists(path string) bool {
var _, err = os.Stat(path)
return err == nil
}
// PathDoesNotExist tests if the supplied does not exist.
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)
}