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.

91 lines
2.1 KiB

  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. sourceDir, sourceName := filer2.FullPath(sourcePath).DirAndName()
  37. destinationDir, destinationName := filer2.FullPath(destinationPath).DirAndName()
  38. return commandEnv.withFilerClient(filerServer, filerPort, func(client filer_pb.SeaweedFilerClient) error {
  39. // collect destination entry info
  40. destinationRequest := &filer_pb.LookupDirectoryEntryRequest{
  41. Name: destinationDir,
  42. Directory: destinationName,
  43. }
  44. respDestinationLookupEntry, err := filer_pb.LookupEntry(client, destinationRequest)
  45. var targetDir, targetName string
  46. // moving a file or folder
  47. if err == nil && respDestinationLookupEntry.Entry.IsDirectory {
  48. // to a directory
  49. targetDir = filepath.ToSlash(filepath.Join(destinationDir, destinationName))
  50. targetName = sourceName
  51. } else {
  52. // to a file or folder
  53. targetDir = destinationDir
  54. targetName = destinationName
  55. }
  56. request := &filer_pb.AtomicRenameEntryRequest{
  57. OldDirectory: sourceDir,
  58. OldName: sourceName,
  59. NewDirectory: targetDir,
  60. NewName: targetName,
  61. }
  62. _, err = client.AtomicRenameEntry(context.Background(), request)
  63. fmt.Fprintf(writer, "move: %s => %s\n", sourcePath, filer2.NewFullPath(targetDir, targetName))
  64. return err
  65. })
  66. }