github.com/portworx/docker@v1.12.1/api/client/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/api/client"
    10  	"github.com/docker/docker/cli"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  type renameOptions struct {
    15  	oldName string
    16  	newName string
    17  }
    18  
    19  // NewRenameCommand creats a new cobra.Command for `docker rename`
    20  func NewRenameCommand(dockerCli *client.DockerCli) *cobra.Command {
    21  	var opts renameOptions
    22  
    23  	cmd := &cobra.Command{
    24  		Use:   "rename OLD_NAME 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  	cmd.SetFlagErrorFunc(flagErrorFunc)
    34  
    35  	return cmd
    36  }
    37  
    38  func runRename(dockerCli *client.DockerCli, opts *renameOptions) error {
    39  	ctx := context.Background()
    40  
    41  	oldName := strings.TrimSpace(opts.oldName)
    42  	newName := strings.TrimSpace(opts.newName)
    43  
    44  	if oldName == "" || newName == "" {
    45  		return fmt.Errorf("Error: Neither old nor new names may be empty")
    46  	}
    47  
    48  	if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil {
    49  		fmt.Fprintf(dockerCli.Err(), "%s\n", err)
    50  		return fmt.Errorf("Error: failed to rename container named %s", oldName)
    51  	}
    52  	return nil
    53  }