diff --git a/cmd/remove.go b/cmd/remove.go new file mode 100644 index 0000000..a8f1c21 --- /dev/null +++ b/cmd/remove.go @@ -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) +} diff --git a/internal/environment/environment.go b/internal/environment/environment.go index d487850..c0a8c84 100644 --- a/internal/environment/environment.go +++ b/internal/environment/environment.go @@ -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") }