command_fs_mv.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package shell
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "path/filepath"
  7. "github.com/chrislusf/seaweedfs/weed/filer2"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. )
  10. func init() {
  11. Commands = append(Commands, &commandFsMv{})
  12. }
  13. type commandFsMv struct {
  14. }
  15. func (c *commandFsMv) Name() string {
  16. return "fs.mv"
  17. }
  18. func (c *commandFsMv) Help() string {
  19. return `move or rename a file or a folder
  20. fs.mv <source entry> <destination entry>
  21. fs.mv /dir/file_name /dir2/filename2
  22. fs.mv /dir/file_name /dir2
  23. fs.mv /dir/dir2 /dir3/dir4/
  24. fs.mv /dir/dir2 /dir3/new_dir
  25. `
  26. }
  27. func (c *commandFsMv) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {
  28. filerServer, filerPort, sourcePath, err := commandEnv.parseUrl(args[0])
  29. if err != nil {
  30. return err
  31. }
  32. _, _, destinationPath, err := commandEnv.parseUrl(args[1])
  33. if err != nil {
  34. return err
  35. }
  36. ctx := context.Background()
  37. sourceDir, sourceName := filer2.FullPath(sourcePath).DirAndName()
  38. destinationDir, destinationName := filer2.FullPath(destinationPath).DirAndName()
  39. return commandEnv.withFilerClient(ctx, filerServer, filerPort, func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
  40. // collect destination entry info
  41. destinationRequest := &filer_pb.LookupDirectoryEntryRequest{
  42. Name: destinationDir,
  43. Directory: destinationName,
  44. }
  45. respDestinationLookupEntry, err := client.LookupDirectoryEntry(ctx, destinationRequest)
  46. var targetDir, targetName string
  47. // moving a file or folder
  48. if err == nil && respDestinationLookupEntry.Entry.IsDirectory {
  49. // to a directory
  50. targetDir = filepath.ToSlash(filepath.Join(destinationDir, destinationName))
  51. targetName = sourceName
  52. } else {
  53. // to a file or folder
  54. targetDir = destinationDir
  55. targetName = destinationName
  56. }
  57. request := &filer_pb.AtomicRenameEntryRequest{
  58. OldDirectory: sourceDir,
  59. OldName: sourceName,
  60. NewDirectory: targetDir,
  61. NewName: targetName,
  62. }
  63. _, err = client.AtomicRenameEntry(ctx, request)
  64. fmt.Fprintf(writer, "move: %s => %s\n", sourcePath, filer2.NewFullPath(targetDir, targetName))
  65. return err
  66. })
  67. }