github.com/DaoCloud/dao@v0.0.0-20161212064103-c3dbfd13ee36/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 CONTAINER NEW_NAME", 25 Short: "重命名一个容器", 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 34 return cmd 35 } 36 37 func runRename(dockerCli *client.DockerCli, opts *renameOptions) error { 38 ctx := context.Background() 39 40 oldName := strings.TrimSpace(opts.oldName) 41 newName := strings.TrimSpace(opts.newName) 42 43 if oldName == "" || newName == "" { 44 return fmt.Errorf("错误: 新名称和旧名称均不能为空") 45 } 46 47 if err := dockerCli.Client().ContainerRename(ctx, oldName, newName); err != nil { 48 fmt.Fprintf(dockerCli.Err(), "%s\n", err) 49 return fmt.Errorf("错误: 重命名容器名称到 %s 失败", oldName) 50 } 51 return nil 52 }