command_fs_tree.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package shell
  2. import (
  3. "fmt"
  4. "io"
  5. "strings"
  6. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  7. "github.com/seaweedfs/seaweedfs/weed/util"
  8. )
  9. func init() {
  10. Commands = append(Commands, &commandFsTree{})
  11. }
  12. type commandFsTree struct {
  13. }
  14. func (c *commandFsTree) Name() string {
  15. return "fs.tree"
  16. }
  17. func (c *commandFsTree) Help() string {
  18. return `recursively list all files under a directory
  19. fs.tree /some/dir
  20. `
  21. }
  22. func (c *commandFsTree) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  23. path, err := commandEnv.parseUrl(findInputDirectory(args))
  24. if err != nil {
  25. return err
  26. }
  27. dir, name := util.FullPath(path).DirAndName()
  28. dirCount, fCount, terr := treeTraverseDirectory(writer, commandEnv, util.FullPath(dir), name, newPrefix(), -1)
  29. if terr == nil {
  30. fmt.Fprintf(writer, "%d directories, %d files\n", dirCount, fCount)
  31. }
  32. return terr
  33. }
  34. func treeTraverseDirectory(writer io.Writer, filerClient filer_pb.FilerClient, dir util.FullPath, name string, prefix *Prefix, level int) (directoryCount, fileCount int64, err error) {
  35. prefix.addMarker(level)
  36. err = filer_pb.ReadDirAllEntries(filerClient, dir, name, func(entry *filer_pb.Entry, isLast bool) error {
  37. if level < 0 && name != "" {
  38. if entry.Name != name {
  39. return nil
  40. }
  41. }
  42. fmt.Fprintf(writer, "%s%s\n", prefix.getPrefix(level, isLast), entry.Name)
  43. if entry.IsDirectory {
  44. directoryCount++
  45. subDir := dir.Child(entry.Name)
  46. dirCount, fCount, terr := treeTraverseDirectory(writer, filerClient, subDir, "", prefix, level+1)
  47. directoryCount += dirCount
  48. fileCount += fCount
  49. err = terr
  50. } else {
  51. fileCount++
  52. }
  53. return nil
  54. })
  55. return
  56. }
  57. type Prefix struct {
  58. markers map[int]bool
  59. }
  60. func newPrefix() *Prefix {
  61. return &Prefix{
  62. markers: make(map[int]bool),
  63. }
  64. }
  65. func (p *Prefix) addMarker(marker int) {
  66. p.markers[marker] = true
  67. }
  68. func (p *Prefix) removeMarker(marker int) {
  69. delete(p.markers, marker)
  70. }
  71. func (p *Prefix) getPrefix(level int, isLastChild bool) string {
  72. var sb strings.Builder
  73. if level < 0 {
  74. return ""
  75. }
  76. for i := 0; i < level; i++ {
  77. if _, ok := p.markers[i]; ok {
  78. sb.WriteString("│")
  79. } else {
  80. sb.WriteString(" ")
  81. }
  82. sb.WriteString(" ")
  83. }
  84. if isLastChild {
  85. sb.WriteString("└──")
  86. p.removeMarker(level)
  87. } else {
  88. sb.WriteString("├──")
  89. }
  90. return sb.String()
  91. }