github.com/kunnos/engine@v1.13.1/cli/command/container/rename.go (about)

     1  package container
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"golang.org/x/net/context"
     8  
     9  	"github.com/docker/docker/cli"
    10  	"github.com/docker/docker/cli/command"
    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.DockerCli) *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.DockerCli, 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 fmt.Errorf("Error: Neither old nor new names may be empty")
    44  	}
    45  
    46  	if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil {
    47  		fmt.Fprintf(dockerCli.Err(), "%s\n", err)
    48  		return fmt.Errorf("Error: failed to rename container named %s", oldName)
    49  	}
    50  	return nil
    51  }