Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/dev/preview/previewctl/cmd/workspaces.go
2500 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cmd
6
7
import (
8
"context"
9
"fmt"
10
"os/exec"
11
"time"
12
13
"github.com/cockroachdb/errors"
14
"github.com/hashicorp/terraform-exec/tfexec"
15
"github.com/sirupsen/logrus"
16
"github.com/spf13/cobra"
17
)
18
19
type listWorkspaceOpts struct {
20
TFDir string
21
22
logger *logrus.Logger
23
timeout time.Duration
24
}
25
26
func newListWorkspacesCmd(logger *logrus.Logger) *cobra.Command {
27
ctx := context.Background()
28
opts := &listWorkspaceOpts{
29
logger: logger,
30
}
31
32
cmd := &cobra.Command{
33
Use: "workspaces",
34
Short: "List all existing workspaces in the directory",
35
RunE: func(cmd *cobra.Command, args []string) error {
36
list, err := opts.getWorkspaces(ctx)
37
if err != nil {
38
return err
39
}
40
41
for _, ws := range list {
42
fmt.Println(ws)
43
}
44
45
return nil
46
},
47
}
48
49
cmd.PersistentFlags().StringVar(&opts.TFDir, "tf-dir", "dev/preview/infrastructure", "TF working directory")
50
51
return cmd
52
}
53
54
func (o *listWorkspaceOpts) getWorkspaces(ctx context.Context) ([]string, error) {
55
execPath, err := exec.LookPath("terraform")
56
if err != nil {
57
return nil, errors.Wrap(err, "error getting Terraform executable path")
58
}
59
60
tf, err := tfexec.NewTerraform(o.TFDir, execPath)
61
if err != nil {
62
return nil, errors.Wrap(err, "error running NewTerraform")
63
}
64
65
if d, err := tf.WorkspaceShow(ctx); err == nil && d != "default" {
66
_ = tf.WorkspaceSelect(ctx, "default")
67
}
68
69
err = tf.Init(ctx, tfexec.Upgrade(true))
70
if err != nil {
71
return nil, errors.Wrap(err, "error running Init")
72
}
73
74
list, _, err := tf.WorkspaceList(ctx)
75
if err != nil {
76
return nil, errors.Wrap(err, "error running list")
77
}
78
79
filtered := []string{}
80
for i := range list {
81
if list[i] != "default" {
82
filtered = append(filtered, list[i])
83
}
84
}
85
86
return filtered, nil
87
}
88
89