rename.go 1.2 KB

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