command_fs_rm.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package shell
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  8. "github.com/seaweedfs/seaweedfs/weed/util"
  9. )
  10. func init() {
  11. Commands = append(Commands, &commandFsRm{})
  12. }
  13. type commandFsRm struct {
  14. }
  15. func (c *commandFsRm) Name() string {
  16. return "fs.rm"
  17. }
  18. func (c *commandFsRm) Help() string {
  19. return `remove file and directory entries
  20. fs.rm [-rf] <entry1> <entry2> ...
  21. fs.rm /dir/file_name1 dir/file_name2
  22. fs.rm /dir
  23. The option "-r" can be recursive.
  24. The option "-f" can be ignored by recursive error.
  25. `
  26. }
  27. func (c *commandFsRm) HasTag(CommandTag) bool {
  28. return false
  29. }
  30. func (c *commandFsRm) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  31. isRecursive := false
  32. ignoreRecursiveError := false
  33. var entries []string
  34. for _, arg := range args {
  35. if !strings.HasPrefix(arg, "-") {
  36. entries = append(entries, arg)
  37. continue
  38. }
  39. for _, t := range arg {
  40. switch t {
  41. case 'r':
  42. isRecursive = true
  43. case 'f':
  44. ignoreRecursiveError = true
  45. }
  46. }
  47. }
  48. if len(entries) < 1 {
  49. return fmt.Errorf("need to have arguments")
  50. }
  51. commandEnv.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  52. for _, entry := range entries {
  53. targetPath, err := commandEnv.parseUrl(entry)
  54. if err != nil {
  55. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
  56. continue
  57. }
  58. targetDir, targetName := util.FullPath(targetPath).DirAndName()
  59. lookupRequest := &filer_pb.LookupDirectoryEntryRequest{
  60. Directory: targetDir,
  61. Name: targetName,
  62. }
  63. _, err = filer_pb.LookupEntry(client, lookupRequest)
  64. if err != nil {
  65. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
  66. continue
  67. }
  68. request := &filer_pb.DeleteEntryRequest{
  69. Directory: targetDir,
  70. Name: targetName,
  71. IgnoreRecursiveError: ignoreRecursiveError,
  72. IsDeleteData: true,
  73. IsRecursive: isRecursive,
  74. IsFromOtherCluster: false,
  75. Signatures: nil,
  76. }
  77. if resp, err := client.DeleteEntry(context.Background(), request); err != nil {
  78. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
  79. } else {
  80. if resp.Error != "" {
  81. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, resp.Error)
  82. }
  83. }
  84. }
  85. return nil
  86. })
  87. return
  88. }