You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.2 KiB

5 years ago
5 years ago
5 years ago
  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.Chunks),
  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. }