Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

restore: Add --replace option to automatically overwrite existing container of the same name #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (
)

var (
optStart = false
optStart = false
optReplace = false

restoreCmd = &cobra.Command{
Use: "restore <backup file>",
Expand Down Expand Up @@ -171,7 +172,23 @@ func createContainer(backup Backup) (string, error) {
if err != nil {
return "", err
}
// io.Copy(os.Stdout, reader)

_, err = cli.ContainerInspect(ctx, name)
if err == nil {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my comment on #23: try to keep the happy path on the left edge. Check for an error and bail out immediately, then keep the rest of the code on the left edge.

Related: what happens in case of an error here? Shouldn't we return it?

if optReplace {
fmt.Println("Removing existing Container with name:", name)
err = cli.ContainerStop(ctx, name, nil)
if err != nil {
return "", err
}
err = cli.ContainerRemove(ctx, name, types.ContainerRemoveOptions{})
if err != nil {
return "", err
}
} else {
return "", fmt.Errorf("The container name '" + name + "' is already in use, rename existing container or run restore with --replace to overwrite")
}
}

resp, err := cli.ContainerCreate(ctx, backup.Config, &container.HostConfig{
PortBindings: backup.PortMap,
Expand Down Expand Up @@ -226,5 +243,6 @@ func startContainer(id string) error {

func init() {
restoreCmd.Flags().BoolVarP(&optStart, "start", "s", false, "start restored container")
restoreCmd.Flags().BoolVarP(&optReplace, "replace", "r", false, "replace existing container with same name")
RootCmd.AddCommand(restoreCmd)
}