command_fs_ls.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. package shell
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "os/user"
  7. "strconv"
  8. "strings"
  9. "github.com/seaweedfs/seaweedfs/weed/filer"
  10. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  11. "github.com/seaweedfs/seaweedfs/weed/util"
  12. )
  13. func init() {
  14. Commands = append(Commands, &commandFsLs{})
  15. }
  16. type commandFsLs struct {
  17. }
  18. func (c *commandFsLs) Name() string {
  19. return "fs.ls"
  20. }
  21. func (c *commandFsLs) Help() string {
  22. return `list all files under a directory
  23. fs.ls [-l] [-a] /dir/
  24. fs.ls [-l] [-a] /dir/file_name
  25. fs.ls [-l] [-a] /dir/file_prefix
  26. `
  27. }
  28. func (c *commandFsLs) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  29. var isLongFormat, showHidden bool
  30. for _, arg := range args {
  31. if !strings.HasPrefix(arg, "-") {
  32. break
  33. }
  34. for _, t := range arg {
  35. switch t {
  36. case 'a':
  37. showHidden = true
  38. case 'l':
  39. isLongFormat = true
  40. }
  41. }
  42. }
  43. path, err := commandEnv.parseUrl(findInputDirectory(args))
  44. if err != nil {
  45. return err
  46. }
  47. if commandEnv.isDirectory(path) {
  48. path = path + "/"
  49. }
  50. dir, name := util.FullPath(path).DirAndName()
  51. entryCount := 0
  52. err = filer_pb.ReadDirAllEntries(commandEnv, util.FullPath(dir), name, func(entry *filer_pb.Entry, isLast bool) error {
  53. if !showHidden && strings.HasPrefix(entry.Name, ".") {
  54. return nil
  55. }
  56. entryCount++
  57. if isLongFormat {
  58. fileMode := os.FileMode(entry.Attributes.FileMode)
  59. userName, groupNames := entry.Attributes.UserName, entry.Attributes.GroupName
  60. if userName == "" {
  61. if user, userErr := user.LookupId(strconv.Itoa(int(entry.Attributes.Uid))); userErr == nil {
  62. userName = user.Username
  63. }
  64. }
  65. groupName := ""
  66. if len(groupNames) > 0 {
  67. groupName = groupNames[0]
  68. }
  69. if groupName == "" {
  70. if group, groupErr := user.LookupGroupId(strconv.Itoa(int(entry.Attributes.Gid))); groupErr == nil {
  71. groupName = group.Name
  72. }
  73. }
  74. if strings.HasSuffix(dir, "/") {
  75. // just for printing
  76. dir = dir[:len(dir)-1]
  77. }
  78. fmt.Fprintf(writer, "%s %3d %s %s %6d %s/%s\n",
  79. fileMode, len(entry.GetChunks()),
  80. userName, groupName,
  81. filer.FileSize(entry), dir, entry.Name)
  82. } else {
  83. fmt.Fprintf(writer, "%s\n", entry.Name)
  84. }
  85. return nil
  86. })
  87. if isLongFormat && err == nil {
  88. fmt.Fprintf(writer, "total %d\n", entryCount)
  89. }
  90. return
  91. }