From 304f720c79fb63ac53e1a8ec26c7b87e38c33e12 Mon Sep 17 00:00:00 2001 From: rmanach Date: Tue, 12 Apr 2022 12:47:41 +0200 Subject: [PATCH] walk into directory and filter filename with regex --- main.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 4a7cdde..a3d2826 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,14 @@ +// packer - a simple CLI tool to find and zip file corresponding to a given regex +// find + zip linux CLI works too package main import ( + "fmt" "github.com/akamensky/argparse" "log" "os" - "fmt" + fp "path/filepath" + re "regexp" ) // parseArguments - get needed arguments to launch the `packer` @@ -25,17 +29,60 @@ func parseArguments() (string, string, string, error) { err = fmt.Errorf("parsing error: %s", parseError) } - return *regex, *outputPath, *directory, err + return *regex, *directory, *outputPath, err +} + +// buildRegex - build POSIX regex from a string +// WARN: lookahead and lookbehind are not supported +func buildRegex(regex string) (*re.Regexp, error) { + rc, err := re.CompilePOSIX(regex) + return rc, err +} + +// walkFilteredDir - walk into a directory and its subdirectories and find files that match a regex +func walkDirFiltered(directory string, regex re.Regexp) ([]string, error) { + var files []string + err := fp.Walk(directory, + func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if !info.IsDir() && regex.MatchString(path) { + fmt.Println(path) + files = append(files, path) + } + return err + }) + return files, err +} + +// getFilesFromDirectoryPath - wrapper calling `walkDirFiltered()` +func getFilesFromDirectoryPath(directory string, regex re.Regexp) ([]string, error) { + files, err := walkDirFiltered(directory, regex) + return files, err } func main() { + // parse arguments regex, directory, outputPath, err := parseArguments() - if err != nil { log.Fatal("error while parsing args : ", err) } - log.Printf("looking for file '%s' in '%s' ...", regex, directory) + // build regex from string + rc, err := buildRegex(regex) + if err != nil { + log.Fatal("error while compiling regex : '", regex, "'\nWARN: lookahead and lookbehind not implemented") + } + + // deferencing Regexp pointer + rd := *rc + + // walk into directory + log.Printf("looking for file '%s' in '%s' ...", rd.String(), directory) + files, err := getFilesFromDirectoryPath(directory, rd) + + log.Printf("files found : %d", len(files)) log.Printf("files zipped in %s", outputPath) }