command_fs_rm.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package shell
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  8. "github.com/chrislusf/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) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  28. isRecursive := false
  29. ignoreRecursiveError := false
  30. var entiries []string
  31. for _, arg := range args {
  32. if !strings.HasPrefix(arg, "-") {
  33. entiries = append(entiries, arg)
  34. continue
  35. }
  36. for _, t := range arg {
  37. switch t {
  38. case 'r':
  39. isRecursive = true
  40. case 'f':
  41. ignoreRecursiveError = true
  42. }
  43. }
  44. }
  45. if len(entiries) < 1 {
  46. return fmt.Errorf("need to have arguments")
  47. }
  48. commandEnv.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  49. for _, entry := range entiries {
  50. targetPath, err := commandEnv.parseUrl(entry)
  51. if err != nil {
  52. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
  53. continue
  54. }
  55. targetDir, targetName := util.FullPath(targetPath).DirAndName()
  56. lookupRequest := &filer_pb.LookupDirectoryEntryRequest{
  57. Directory: targetDir,
  58. Name: targetName,
  59. }
  60. _, err = filer_pb.LookupEntry(client, lookupRequest)
  61. if err != nil {
  62. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
  63. continue
  64. }
  65. request := &filer_pb.DeleteEntryRequest{
  66. Directory: targetDir,
  67. Name: targetName,
  68. IgnoreRecursiveError: ignoreRecursiveError,
  69. IsDeleteData: true,
  70. IsRecursive: isRecursive,
  71. IsFromOtherCluster: false,
  72. Signatures: nil,
  73. }
  74. if resp, err := client.DeleteEntry(context.Background(), request); err != nil {
  75. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, err)
  76. } else {
  77. if resp.Error != "" {
  78. fmt.Fprintf(writer, "rm: %s: %v\n", targetPath, resp.Error)
  79. }
  80. }
  81. }
  82. return nil
  83. })
  84. return
  85. }