/lsr/lsr.go

https://code.google.com/p/rbits/ · Go · 88 lines · 63 code · 10 blank · 15 comment · 14 complexity · e5c243f494ca89daddaa74df5b9e001c MD5 · raw file

  1. // Permission to use, copy, modify, and/or distribute this software for
  2. // any purpose is hereby granted, provided this notice appear in all copies.
  3. /*
  4. Lsr: list recursively.
  5. lsr [-d | -fd] [name ...]
  6. For each directory argument, lsr recursively lists the contents of the
  7. directory; for each file argument, lsr repeats its name. When no argument
  8. is given, the current directory is listed.
  9. Options:
  10. -d only print directories
  11. -fd print both files and directories
  12. -l list in long format; name mode mtime size
  13. */
  14. package main
  15. import (
  16. "flag"
  17. "fmt"
  18. "log"
  19. "os"
  20. "path/filepath"
  21. _ "code.google.com/p/rbits/log"
  22. )
  23. var (
  24. flagD = flag.Bool("d", false, "only print directories")
  25. flagFD = flag.Bool("fd", false, "print both files and directories")
  26. flagL = flag.Bool("l", false, "long format")
  27. )
  28. var usageString = `usage: lsr [-d | -fd | -l] [name ...]
  29. Options:
  30. `
  31. func usage() {
  32. fmt.Fprint(os.Stderr, usageString)
  33. flag.PrintDefaults()
  34. os.Exit(1)
  35. }
  36. func prname(path string, f os.FileInfo) error {
  37. if f.IsDir() && path[len(path)-1] != '/' {
  38. path = path + "/"
  39. }
  40. if *flagL {
  41. mode := f.Mode() & 0x1FF
  42. size := f.Size()
  43. mtime := f.ModTime().Unix()
  44. fmt.Printf("%s %o %v %v\n", path, mode, mtime, size)
  45. return nil
  46. }
  47. fmt.Println(path)
  48. return nil
  49. }
  50. func pr(path string, f os.FileInfo, err error) error {
  51. if err != nil {
  52. log.Println(err)
  53. return nil
  54. }
  55. if *flagFD {
  56. return prname(path, f)
  57. }
  58. if *flagD && f.IsDir() {
  59. return prname(path, f)
  60. }
  61. if !*flagD && !f.IsDir() {
  62. return prname(path, f)
  63. }
  64. return nil
  65. }
  66. func main() {
  67. flag.Usage = usage
  68. flag.Parse()
  69. if flag.NArg() == 0 {
  70. filepath.Walk(".", pr)
  71. return
  72. }
  73. for _, v := range flag.Args() {
  74. filepath.Walk(v, pr)
  75. }
  76. }