github.1git.de/docker/cli@v26.1.3+incompatible/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/docker/cli/cli/command/completion"
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  )
    14  
    15  type renameOptions struct {
    16  	oldName string
    17  	newName string
    18  }
    19  
    20  // NewRenameCommand creates a new cobra.Command for `docker rename`
    21  func NewRenameCommand(dockerCli command.Cli) *cobra.Command {
    22  	var opts renameOptions
    23  
    24  	cmd := &cobra.Command{
    25  		Use:   "rename CONTAINER NEW_NAME",
    26  		Short: "Rename a container",
    27  		Args:  cli.ExactArgs(2),
    28  		RunE: func(cmd *cobra.Command, args []string) error {
    29  			opts.oldName = args[0]
    30  			opts.newName = args[1]
    31  			return runRename(cmd.Context(), dockerCli, &opts)
    32  		},
    33  		Annotations: map[string]string{
    34  			"aliases": "docker container rename, docker rename",
    35  		},
    36  		ValidArgsFunction: completion.ContainerNames(dockerCli, true),
    37  	}
    38  	return cmd
    39  }
    40  
    41  func runRename(ctx context.Context, dockerCli command.Cli, opts *renameOptions) error {
    42  	oldName := strings.TrimSpace(opts.oldName)
    43  	newName := strings.TrimSpace(opts.newName)
    44  
    45  	if oldName == "" || newName == "" {
    46  		return errors.New("Error: Neither old nor new names may be empty")
    47  	}
    48  
    49  	if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil {
    50  		fmt.Fprintln(dockerCli.Err(), err)
    51  		return errors.Errorf("Error: failed to rename container named %s", oldName)
    52  	}
    53  	return nil
    54  }