-
Notifications
You must be signed in to change notification settings - Fork 306
/
get_workspace_config.go
215 lines (186 loc) · 5.61 KB
/
get_workspace_config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package helper
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"github.com/loft-sh/devpod/cmd/flags"
"github.com/loft-sh/devpod/pkg/file"
"github.com/loft-sh/devpod/pkg/git"
"github.com/loft-sh/devpod/pkg/image"
"github.com/loft-sh/log"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type GetWorkspaceConfigCommand struct {
*flags.GlobalFlags
timeout time.Duration
maxDepth int
}
type GetWorkspaceConfigCommandResult struct {
IsImage bool `json:"isImage"`
IsGitRepository bool `json:"isGitRepository"`
IsLocal bool `json:"isLocal"`
ConfigPaths []string `json:"configPaths"`
}
// NewGetWorkspaceConfigCommand creates a new command
func NewGetWorkspaceConfigCommand(flags *flags.GlobalFlags) *cobra.Command {
cmd := &GetWorkspaceConfigCommand{
GlobalFlags: flags,
}
shellCmd := &cobra.Command{
Use: "get-workspace-config",
Short: "Retrieves a workspace config",
RunE: func(_ *cobra.Command, args []string) error {
if cmd.maxDepth < 0 {
log.Default.Debugf("--max-depth was %d, setting to 0", cmd.maxDepth)
cmd.maxDepth = 0
}
return cmd.Run(context.Background(), args)
},
}
shellCmd.Flags().DurationVar(&cmd.timeout, "timeout", 10*time.Second, "Timeout for the command, 10 seconds by default")
shellCmd.Flags().IntVar(&cmd.maxDepth, "max-depth", 3, "Maximum depth to search for devcontainer files")
return shellCmd
}
func (cmd *GetWorkspaceConfigCommand) Run(ctx context.Context, args []string) error {
if len(args) != 1 {
return fmt.Errorf("workspace source is missing")
}
rawSource := args[0]
level := log.Default.GetLevel()
if cmd.GlobalFlags.Debug {
level = logrus.DebugLevel
}
logger := log.NewStdoutLogger(os.Stdin, nil, nil, level)
logger.Debugf("Resolving devcontainer config for source: %s", rawSource)
ctx, cancel := context.WithTimeout(context.Background(), cmd.timeout)
defer cancel()
done := make(chan *GetWorkspaceConfigCommandResult, 1)
errChan := make(chan error, 1)
tmpDir, err := os.MkdirTemp("", "devpod")
if err != nil {
return err
}
go func() {
result, err := findDevcontainerFiles(ctx, rawSource, tmpDir, cmd.maxDepth, logger)
if err != nil {
errChan <- err
return
}
done <- result
}()
select {
case err := <-errChan:
_ = os.RemoveAll(tmpDir)
return errors.WithMessage(err, "unable to find devcontainer files")
case <-ctx.Done():
_ = os.RemoveAll(tmpDir)
return errors.WithMessage(ctx.Err(), "timeout while searching for devcontainer files")
case result := <-done:
out, err := json.Marshal(result)
if err != nil {
return err
}
log.Default.Done(string(out))
}
defer close(done)
return nil
}
func findDevcontainerFiles(ctx context.Context, rawSource, tmpDirPath string, maxDepth int, log log.Logger) (*GetWorkspaceConfigCommandResult, error) {
result := &GetWorkspaceConfigCommandResult{ConfigPaths: []string{}}
// local path
isLocalPath, _ := file.IsLocalDir(rawSource)
if isLocalPath {
log.Debug("Local directory detected")
result.IsLocal = true
initialDepth := strings.Count(rawSource, string(filepath.Separator))
err := filepath.WalkDir(rawSource, func(path string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
depth := strings.Count(path, string(filepath.Separator)) - initialDepth
if info.IsDir() && depth > maxDepth {
return filepath.SkipDir
}
if isDevcontainerFilename(path) {
relPath, err := filepath.Rel(rawSource, path)
if err != nil {
log.Warnf("Unable to get relative path for %s: %s", path, err.Error())
return nil
}
result.ConfigPaths = append(result.ConfigPaths, relPath)
}
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
// git repo
gitRepository, gitPRReference, gitBranch, gitCommit, gitSubDir := git.NormalizeRepository(rawSource)
if strings.HasSuffix(rawSource, ".git") || git.PingRepository(gitRepository) {
log.Debug("Git repository detected")
result.IsGitRepository = true
gitInfo := git.NewGitInfo(gitRepository, gitBranch, gitCommit, gitPRReference, gitSubDir)
log.Debugf("Cloning git repository into %s", tmpDirPath)
err := git.CloneRepository(ctx, gitInfo, tmpDirPath, "", true, git.NewCloner(git.ShallowCloneStrategy), log.Writer(logrus.DebugLevel, false), log)
if err != nil {
return nil, err
}
log.Debug("Listing git file tree")
ref := "HEAD"
// checkout on branch if available
if gitBranch != "" {
ref = gitBranch
}
// git ls-tree -r --full-name --name-only $REF
lsArgs := []string{"ls-tree", "-r", "--full-name", "--name-only", ref}
lsCmd := git.CommandContext(ctx, lsArgs...)
lsCmd.Dir = tmpDirPath
stdout, err := lsCmd.StdoutPipe()
if err != nil {
return nil, err
}
err = lsCmd.Start()
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
path := scanner.Text()
depth := strings.Count(path, string(filepath.Separator))
if depth > maxDepth {
continue
}
if isDevcontainerFilename(path) {
result.ConfigPaths = append(result.ConfigPaths, path)
}
}
err = lsCmd.Wait()
if err != nil {
return nil, err
}
return result, nil
}
// container image
_, err := image.GetImage(ctx, rawSource)
if err == nil {
log.Debug("Container image detected")
result.IsImage = true
// Doesn't matter, we just want to know if it's an image
// not going to poke around in the image fs
return result, nil
}
return result, nil
}
func isDevcontainerFilename(path string) bool {
return filepath.Base(path) == ".devcontainer.json" || filepath.Base(path) == "devcontainer.json"
}