From 1d681358ffb9c054a3576cff87a828c6d2cd5053 Mon Sep 17 00:00:00 2001 From: Andrew Leech Date: Tue, 27 Apr 2021 11:17:59 +1000 Subject: [PATCH] restore: Add --replace option to automatically overwrite existing container of the same name --- restore.go | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/restore.go b/restore.go index b32aece..68daffb 100644 --- a/restore.go +++ b/restore.go @@ -15,7 +15,8 @@ import ( ) var ( - optStart = false + optStart = false + optReplace = false restoreCmd = &cobra.Command{ Use: "restore ", @@ -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 { + 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, @@ -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) }