github.com/AliyunContainerService/cli@v0.0.0-20181009023821-814ced4b30d0/cli/command/container/rename.go (about)

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