[feature:5023] Add '--replace' option into container creation command

This commit is contained in:
Ioannis Deligiannis 2024-04-27 14:23:47 +03:00
parent 865190615b
commit 39c54e5a7f
No known key found for this signature in database
GPG Key ID: 38CCDB3A4B0A4742
1 changed files with 14 additions and 0 deletions

View File

@ -39,6 +39,7 @@ type createOptions struct {
untrusted bool untrusted bool
pull string // always, missing, never pull string // always, missing, never
quiet bool quiet bool
replace bool
} }
// NewCreateCommand creates a new cobra.Command for `docker create` // NewCreateCommand creates a new cobra.Command for `docker create`
@ -69,6 +70,7 @@ func NewCreateCommand(dockerCli command.Cli) *cobra.Command {
flags.StringVar(&options.name, "name", "", "Assign a name to the container") flags.StringVar(&options.name, "name", "", "Assign a name to the container")
flags.StringVar(&options.pull, "pull", PullImageMissing, `Pull image before creating ("`+PullImageAlways+`", "|`+PullImageMissing+`", "`+PullImageNever+`")`) flags.StringVar(&options.pull, "pull", PullImageMissing, `Pull image before creating ("`+PullImageAlways+`", "|`+PullImageMissing+`", "`+PullImageNever+`")`)
flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the pull output") flags.BoolVarP(&options.quiet, "quiet", "q", false, "Suppress the pull output")
flags.BoolVarP(&options.replace, "replace", "", false, "If a container with the same name exists, replace it")
// Add an explicit help that doesn't have a `-h` to prevent the conflict // Add an explicit help that doesn't have a `-h` to prevent the conflict
// with hostname // with hostname
@ -250,6 +252,18 @@ func createContainer(ctx context.Context, dockerCli command.Cli, containerCfg *c
} }
} }
if options.replace {
if len(options.name) != 0 {
dockerCli.Client().ContainerRemove(ctx, options.name, container.RemoveOptions{
RemoveVolumes: false,
RemoveLinks: false,
Force: true,
})
} else {
return "", errors.Errorf("Error: cannot replace container without --name being set")
}
}
hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.Out().GetTtySize() hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.Out().GetTtySize()
response, err := dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, platform, options.name) response, err := dockerCli.Client().ContainerCreate(ctx, config, hostConfig, networkingConfig, platform, options.name)