Last active
March 7, 2016 14:35
-
-
Save damiankloip/f518c81d49aef8b71765 to your computer and use it in GitHub Desktop.
This file contains 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 main | |
import ( | |
"os" | |
"fmt" | |
"regexp" | |
"path/filepath" | |
"github.com/codegangsta/cli" | |
) | |
func main() { | |
app := cli.NewApp() | |
app.Name = "FindNG" | |
app.Usage = "Find for the 21st century!" | |
app.Version = "0.0.1" | |
app.Flags = []cli.Flag { | |
cli.BoolFlag { | |
Name: "count, c", | |
Usage: "Return a count of matches", | |
}, | |
cli.BoolFlag { | |
Name: "ext, e", | |
Usage: "Use extended regex patterns", | |
}, | |
} | |
app.Action = func(c *cli.Context) { | |
var root, pattern string | |
args := c.Args() | |
length := len(args); | |
switch { | |
case length == 0: | |
fmt.Println("No arguments provided") | |
os.Exit(1) | |
case length == 1: | |
var err error | |
// Assume the single argument is a pattern. Default root to cwd. | |
root, err = os.Getwd() | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
pattern = args.First() | |
case length > 1: | |
// Assume path will be the first arg, and pattern the second. | |
root = args.First() | |
pattern = args.Get(1) | |
} | |
count_matches := c.Bool("count") | |
extended := c.Bool("ext") | |
if count_matches { | |
countResults(root, pattern, extended) | |
} else { | |
printResults(root, pattern, extended) | |
} | |
} | |
app.Run(os.Args) | |
} | |
func printResults(root string, pattern string, extended bool) { | |
err := filepath.Walk(root, func (path string, fileInfo os.FileInfo, _ error) error { | |
var matched bool | |
if extended { | |
matched, _ = regexp.MatchString(pattern, filepath.Base(path)) | |
} else { | |
matched, _ = filepath.Match(pattern, filepath.Base(path)) | |
} | |
if matched { | |
fmt.Println(path) | |
} | |
return nil | |
}) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} | |
func countResults(root string, pattern string, extended bool) { | |
count := 0; | |
err := filepath.Walk(root, func (path string, fileInfo os.FileInfo, _ error) error { | |
var matched bool | |
if extended { | |
matched, _ = regexp.MatchString(pattern, filepath.Base(path)) | |
} else { | |
matched, _ = filepath.Match(pattern, filepath.Base(path)) | |
} | |
if matched { | |
count += 1 | |
} | |
return nil | |
}) | |
fmt.Println(count) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment