2018-01-13 16:14:54 +00:00
|
|
|
package utio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
2021-02-11 20:07:12 +00:00
|
|
|
"path/filepath"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
2018-01-13 16:14:54 +00:00
|
|
|
)
|
|
|
|
|
2021-02-11 20:07:12 +00:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2018-01-13 16:14:54 +00:00
|
|
|
// Home gives back the home directory for the current user.
|
|
|
|
func Home() (string, error) {
|
2021-02-11 19:35:32 +00:00
|
|
|
return os.UserHomeDir()
|
2018-01-13 16:14:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|
2021-02-11 20:07:12 +00:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|