diff --git a/cmd/list_environments.go b/cmd/list_environments.go new file mode 100644 index 0000000..488b814 --- /dev/null +++ b/cmd/list_environments.go @@ -0,0 +1,31 @@ +package cmd + +import ( + "github.com/se7entyse7en/pydockenv/internal/environment" + "github.com/se7entyse7en/pydockenv/log" + "github.com/spf13/cobra" +) + +var listEnvironmentsCmd = &cobra.Command{ + Use: "list-environments", + Short: "List all the virtual environments", + Run: func(cmd *cobra.Command, args []string) { + logger := log.Logger + err := log.SetupLogger(cmd) + if err != nil { + logger.WithError(err).Fatal("Cannot setup logger") + } + + logger.Info("Listing virtual environments...") + + if err := environment.ListEnvironments(); err != nil { + logger.WithError(err).Fatal("Cannot list virtual environments") + } + + logger.Info("Virtual environments listed!") + }, +} + +func init() { + rootCmd.AddCommand(listEnvironmentsCmd) +} diff --git a/internal/environment/environment.go b/internal/environment/environment.go index c0a8c84..4efe6c4 100644 --- a/internal/environment/environment.go +++ b/internal/environment/environment.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" @@ -203,6 +204,47 @@ func Deactivate() error { return nil } +func ListEnvironments() error { + logger := log.Logger + + cli, err := client.NewClientWithOpts(client.FromEnv) + if err != nil { + return err + } + + currentEnvName := getCurrentEnv() + containers, err := cli.ContainerList( + context.Background(), types.ContainerListOptions{All: true}) + if err != nil { + return fmt.Errorf("cannot list containers: %w", err) + } + + var msgBuilder strings.Builder + for _, c := range containers { + contName := c.Names[0] + if !strings.HasPrefix(contName, PREFIX) { + continue + } + + envName := contName[len(PREFIX):] + m := fmt.Sprintf("%s\n", envName) + if envName == currentEnvName { + m = fmt.Sprintf("* %s", m) + } + + msgBuilder.WriteString(m) + } + + msg := msgBuilder.String() + if msg == "" { + logger.Info("No environments available") + } else { + logger.Info(msg) + } + + return nil +} + func Remove(envName string) error { logger := log.Logger cli, err := client.NewClientWithOpts(client.FromEnv)