Path: blob/main/dev/preview/previewctl/cmd/workspaces.go
2500 views
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package cmd56import (7"context"8"fmt"9"os/exec"10"time"1112"github.com/cockroachdb/errors"13"github.com/hashicorp/terraform-exec/tfexec"14"github.com/sirupsen/logrus"15"github.com/spf13/cobra"16)1718type listWorkspaceOpts struct {19TFDir string2021logger *logrus.Logger22timeout time.Duration23}2425func newListWorkspacesCmd(logger *logrus.Logger) *cobra.Command {26ctx := context.Background()27opts := &listWorkspaceOpts{28logger: logger,29}3031cmd := &cobra.Command{32Use: "workspaces",33Short: "List all existing workspaces in the directory",34RunE: func(cmd *cobra.Command, args []string) error {35list, err := opts.getWorkspaces(ctx)36if err != nil {37return err38}3940for _, ws := range list {41fmt.Println(ws)42}4344return nil45},46}4748cmd.PersistentFlags().StringVar(&opts.TFDir, "tf-dir", "dev/preview/infrastructure", "TF working directory")4950return cmd51}5253func (o *listWorkspaceOpts) getWorkspaces(ctx context.Context) ([]string, error) {54execPath, err := exec.LookPath("terraform")55if err != nil {56return nil, errors.Wrap(err, "error getting Terraform executable path")57}5859tf, err := tfexec.NewTerraform(o.TFDir, execPath)60if err != nil {61return nil, errors.Wrap(err, "error running NewTerraform")62}6364if d, err := tf.WorkspaceShow(ctx); err == nil && d != "default" {65_ = tf.WorkspaceSelect(ctx, "default")66}6768err = tf.Init(ctx, tfexec.Upgrade(true))69if err != nil {70return nil, errors.Wrap(err, "error running Init")71}7273list, _, err := tf.WorkspaceList(ctx)74if err != nil {75return nil, errors.Wrap(err, "error running list")76}7778filtered := []string{}79for i := range list {80if list[i] != "default" {81filtered = append(filtered, list[i])82}83}8485return filtered, nil86}878889