Skip to content

Commit

Permalink
Add remove command
Browse files Browse the repository at this point in the history
Signed-off-by: Lou Marvin Caraig <[email protected]>
  • Loading branch information
se7entyse7en committed Jun 6, 2020
1 parent 1e65df0 commit 3667602
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
50 changes: 50 additions & 0 deletions cmd/remove.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package cmd

import (
"github.com/se7entyse7en/pydockenv/internal/environment"
"github.com/se7entyse7en/pydockenv/log"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

var removeCmd = &cobra.Command{
Use: "remove [environment-name]",
Short: "Remove a virtual environment",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
logger := log.Logger
err := log.SetupLogger(cmd)
if err != nil {
logger.WithError(err).Fatal("Cannot setup logger")
}

cmdArgs, err := parseRemoveArgs(cmd, args)
if err != nil {
logger.WithError(err).Fatal("Cannot parse arguments")
}

ctxLogger := logger.WithFields(logrus.Fields{
"name": cmdArgs.Name,
})
ctxLogger.Info("Removing virtual environment...")

if err := environment.Remove(cmdArgs.Name); err != nil {
logger.WithError(err).Fatal("Cannot remove virtual environment")
}

ctxLogger.Info("Virtual environment removed!")
},
}

func parseRemoveArgs(cmd *cobra.Command, args []string) (*removeArgs, error) {
name := args[0]
return &removeArgs{Name: name}, nil
}

type removeArgs struct {
Name string
}

func init() {
rootCmd.AddCommand(removeCmd)
}
40 changes: 40 additions & 0 deletions internal/environment/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,46 @@ func Deactivate() error {
return nil
}

func Remove(envName string) error {
logger := log.Logger
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return err
}

contName := fmt.Sprintf("%s_%s", PREFIX, envName)

ctxLogger := logger.WithFields(logrus.Fields{
"container-name": contName,
})
ctxLogger.Debug("Removing container...")

err = cli.ContainerRemove(context.Background(), contName,
types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
})
if err != nil {
return fmt.Errorf("cannot remove container: %w", err)
}

ctxLogger.Debug("Container removed!")

netName := fmt.Sprintf("%s_%s_network", PREFIX, envName)
ctxLogger = logger.WithFields(logrus.Fields{
"network-name": netName,
})

ctxLogger.Debug("Removing network...")
err = cli.NetworkRemove(context.Background(), netName)
if err != nil {
return fmt.Errorf("cannot remove network: %w", err)
}

ctxLogger.Debug("Network Removed!")
return nil
}

func getCurrentEnv() string {
return os.Getenv("PYDOCKENV")
}
Expand Down

0 comments on commit 3667602

Please sign in to comment.