rename.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package container
  2. import (
  3. "fmt"
  4. "strings"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/client"
  7. "github.com/docker/docker/cli"
  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 *client.DockerCli) *cobra.Command {
  16. var opts renameOptions
  17. cmd := &cobra.Command{
  18. Use: "rename OLD_NAME 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. cmd.SetFlagErrorFunc(flagErrorFunc)
  28. return cmd
  29. }
  30. func runRename(dockerCli *client.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 fmt.Errorf("Error: Neither old nor new names may be empty")
  36. }
  37. if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil {
  38. fmt.Fprintf(dockerCli.Err(), "%s\n", err)
  39. return fmt.Errorf("Error: failed to rename container named %s", oldName)
  40. }
  41. return nil
  42. }