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.

115 lines
2.3 KiB

3 months ago
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) HasTag(CommandTag) bool {
  29. return false
  30. }
  31. func (c *commandFsLs) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  32. var isLongFormat, showHidden bool
  33. for _, arg := range args {
  34. if !strings.HasPrefix(arg, "-") {
  35. break
  36. }
  37. for _, t := range arg {
  38. switch t {
  39. case 'a':
  40. showHidden = true
  41. case 'l':
  42. isLongFormat = true
  43. }
  44. }
  45. }
  46. path, err := commandEnv.parseUrl(findInputDirectory(args))
  47. if err != nil {
  48. return err
  49. }
  50. if commandEnv.isDirectory(path) {
  51. path = path + "/"
  52. }
  53. dir, name := util.FullPath(path).DirAndName()
  54. entryCount := 0
  55. err = filer_pb.ReadDirAllEntries(commandEnv, util.FullPath(dir), name, func(entry *filer_pb.Entry, isLast bool) error {
  56. if !showHidden && strings.HasPrefix(entry.Name, ".") {
  57. return nil
  58. }
  59. entryCount++
  60. if isLongFormat {
  61. fileMode := os.FileMode(entry.Attributes.FileMode)
  62. userName, groupNames := entry.Attributes.UserName, entry.Attributes.GroupName
  63. if userName == "" {
  64. if user, userErr := user.LookupId(strconv.Itoa(int(entry.Attributes.Uid))); userErr == nil {
  65. userName = user.Username
  66. }
  67. }
  68. groupName := ""
  69. if len(groupNames) > 0 {
  70. groupName = groupNames[0]
  71. }
  72. if groupName == "" {
  73. if group, groupErr := user.LookupGroupId(strconv.Itoa(int(entry.Attributes.Gid))); groupErr == nil {
  74. groupName = group.Name
  75. }
  76. }
  77. if strings.HasSuffix(dir, "/") {
  78. // just for printing
  79. dir = dir[:len(dir)-1]
  80. }
  81. fmt.Fprintf(writer, "%s %3d %s %s %6d %s/%s\n",
  82. fileMode, len(entry.GetChunks()),
  83. userName, groupName,
  84. filer.FileSize(entry), dir, entry.Name)
  85. } else {
  86. fmt.Fprintf(writer, "%s\n", entry.Name)
  87. }
  88. return nil
  89. })
  90. if isLongFormat && err == nil {
  91. fmt.Fprintf(writer, "total %d\n", entryCount)
  92. }
  93. return
  94. }