From: Colin P. McCabe Date: Mon, 19 Jun 2023 20:02:17 +0000 (-0700) Subject: pickrand.go: add -n flag X-Git-Url: http://club.cc.cmu.edu/~cmccabe/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=af6e83b9253100d04607d2b41897defad1c0e6f4;p=cmccabe-bin pickrand.go: add -n flag --- diff --git a/pickrand.go b/pickrand.go index 79c4076..e51bf26 100644 --- a/pickrand.go +++ b/pickrand.go @@ -3,22 +3,42 @@ package main import ( "bytes" "crypto/rand" + "flag" "fmt" "math/big" "os" "path/filepath" + "time" ) func main() { - root := "." - if len(os.Args) > 1 { - root = os.Args[1] - } + flag.Usage = func() { + fmt.Fprintf(os.Stdout, "pickrand.go: picks a random file.\n") + fmt.Fprintf(os.Stdout, "\n") + flag.PrintDefaults() + } + prevDays := flag.Int("n", 0, "The number of days back to look.") + flag.Parse() + var maxDuration time.Duration + if (*prevDays != 0) { + maxDuration = time.Duration(int64(*prevDays) * (24 * 60 * 60 * 1e9)) + } + + root := flag.Arg(0) + if (root == "") { + root = "." + } files := make([]string, 0, 32) err := filepath.Walk(root, func(p string, f os.FileInfo, err error) error { if err != nil { return err } + if maxDuration != 0 { + var duration = time.Now().Sub(f.ModTime()) + if duration > maxDuration { + return nil + } + } if !f.IsDir() { files = append(files, p) } @@ -28,6 +48,10 @@ func main() { fmt.Fprintf(os.Stderr, "** Error: %s\n", err.Error()) os.Exit(1) } + if len(files) == 0 { + fmt.Fprintf(os.Stderr, "No matching files found.\n") + os.Exit(1) + } var b [16]byte _, err = rand.Read(b[:]) if err != nil {