rename.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/cli"
  7. "github.com/docker/docker/cli/command"
  8. "github.com/spf13/cobra"
  9. )
  10. type renameOptions struct {
  11. oldName string
  12. newName string
  13. }
  14. // NewRenameCommand creates a new cobra.Command for `docker rename`
  15. func NewRenameCommand(dockerCli *command.DockerCli) *cobra.Command {
  16. var opts renameOptions
  17. cmd := &cobra.Command{
  18. Use: "rename CONTAINER NEW_NAME",
  19. Short: "Rename a container",
  20. Args: cli.ExactArgs(2),
  21. RunE: func(cmd *cobra.Command, args []string) error {
  22. opts.oldName = args[0]
  23. opts.newName = args[1]
  24. return runRename(dockerCli, &opts)
  25. },
  26. }
  27. return cmd
  28. }
  29. func runRename(dockerCli *command.DockerCli, opts *renameOptions) error {
  30. ctx := context.Background()
  31. oldName := strings.TrimSpace(opts.oldName)
  32. newName := strings.TrimSpace(opts.newName)
  33. if oldName == "" || newName == "" {
  34. return fmt.Errorf("Error: Neither old nor new names may be empty")
  35. }
  36. if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil {
  37. fmt.Fprintf(dockerCli.Err(), "%s\n", err)
  38. return fmt.Errorf("Error: failed to rename container named %s", oldName)
  39. }
  40. return nil
  41. }