Last active
January 15, 2018 18:50
-
-
Save aaronhurt/da397b7c39096f5b014ef8af0628dc06 to your computer and use it in GitHub Desktop.
find and filter files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package find | |
import ( | |
"os" | |
"path/filepath" | |
"regexp" | |
) | |
// File wraps the os.FileInfo struct to include a path reference | |
type File struct { | |
os.FileInfo | |
Path string | |
} | |
// Files represents a slice of File structs | |
type Files []File | |
// Find returns Files under the given root | |
func Find(root string) (Files, error) { | |
var list = Files{} | |
var err error | |
if err = filepath.Walk(root, func(p string, f os.FileInfo, err error) error { | |
if f != nil { | |
list = append(list, File{FileInfo: f, Path: p}) | |
} | |
return nil | |
}); err != nil { | |
return nil, err | |
} | |
return list, nil | |
} | |
// FilterFiles applies the regex filter against all files in the list | |
func (f Files) FilterFiles(regex string) (Files, error) { | |
return f.filter(regex, false, true) | |
} | |
// FilterDirs applies the regex filter against all directories in the list | |
func (f Files) FilterDirs(regex string) (Files, error) { | |
return f.filter(regex, true, false) | |
} | |
// Filter applies the regext against all files and directories in the list | |
func (f Files) Filter(regex string) (Files, error) { | |
return f.filter(regex, true, true) | |
} | |
// filter returns a filtered list of elements | |
func (f Files) filter(regex string, dirs bool, files bool) (Files, error) { | |
var re *regexp.Regexp | |
var out = Files{} | |
var err error | |
if re, err = regexp.Compile(regex); err != nil { | |
return nil, err | |
} | |
for _, file := range f { | |
if !dirs && files && file.IsDir() { | |
// we aren't filtering files | |
out = append(out, file) | |
continue | |
} | |
if !files && dirs && !file.IsDir() { | |
// we aren't filtering directories | |
out = append(out, file) | |
continue | |
} | |
if !re.MatchString(file.Path) { | |
// it's filtered but didn't match | |
out = append(out, file) | |
} | |
} | |
// return filtered output | |
return out, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment