Skip to content

Commit

Permalink
Add list-environments 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 3667602 commit ec70ddc
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
31 changes: 31 additions & 0 deletions cmd/list_environments.go
Original file line number Diff line number Diff line change
@@ -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)
}
42 changes: 42 additions & 0 deletions internal/environment/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit ec70ddc

Please sign in to comment.