X-Git-Url: http://club.cc.cmu.edu/~cmccabe/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=pickrand.go;h=e51bf26fbf295bf5ebf246fb6d10ad4beccea485;hb=master;hp=1bf4844c67599735c972cc6287d49b4e6b0a99b9;hpb=235c8f2e5692d8c89145085057609de827dc0aee;p=cmccabe-bin diff --git a/pickrand.go b/pickrand.go index 1bf4844..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,7 +48,11 @@ func main() { fmt.Fprintf(os.Stderr, "** Error: %s\n", err.Error()) os.Exit(1) } - var b [8]byte + 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 { fmt.Fprintf(os.Stderr, "Failed to access cryptographic randomness. " + @@ -42,5 +66,5 @@ func main() { } j := int(i.Uint64()) - fmt.Printf("%s\n", root + "/" + files[j]) + fmt.Printf("%s\n", files[j]) }