-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathrun.go
More file actions
576 lines (489 loc) · 15.2 KB
/
run.go
File metadata and controls
576 lines (489 loc) · 15.2 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package ci
import (
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/depot/cli/pkg/api"
"github.com/depot/cli/pkg/config"
"github.com/depot/cli/pkg/helpers"
civ1 "github.com/depot/cli/pkg/proto/depot/ci/v1"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
const cacheBaseURL = "https://cache.depot.dev"
func NewCmdRun() *cobra.Command {
var (
orgID string
token string
workflowPath string
jobNames []string
sshAfterStep int
)
cmd := &cobra.Command{
Use: "run",
Short: "Run a local CI workflow [beta]",
Long: `Run a local CI workflow YAML via the Depot CI API.
If there are uncommitted changes relative to the default branch, they are automatically
uploaded as a patch and applied during the workflow run.
This command is in beta and subject to change.`,
Example: ` # Run a workflow
depot ci run --workflow .depot/workflows/ci.yml
# Run specific jobs
depot ci run --workflow .depot/workflows/ci.yml --job build --job test
# Debug with SSH after a specific step
depot ci run --workflow .depot/workflows/ci.yml --job build --ssh-after-step 3`,
RunE: func(cmd *cobra.Command, args []string) error {
if workflowPath == "" {
return cmd.Help()
}
ctx := cmd.Context()
if sshAfterStep > 0 && len(jobNames) != 1 {
return fmt.Errorf("--ssh-after-step requires exactly one --job")
}
if orgID == "" {
orgID = config.GetCurrentOrganization()
}
tokenVal, err := helpers.ResolveOrgAuth(ctx, token)
if err != nil {
return err
}
if tokenVal == "" {
return fmt.Errorf("missing API token, please run `depot login`")
}
// Load and parse workflow YAML
workflowBytes, err := os.ReadFile(workflowPath)
if err != nil {
return fmt.Errorf("failed to read workflow file: %w", err)
}
var workflow map[string]interface{}
if err := yaml.Unmarshal(workflowBytes, &workflow); err != nil {
return fmt.Errorf("failed to parse workflow YAML: %w", err)
}
jobsRaw, ok := workflow["jobs"]
if !ok {
return fmt.Errorf("workflow has no 'jobs' key")
}
jobs, ok := jobsRaw.(map[string]interface{})
if !ok {
return fmt.Errorf("workflow 'jobs' is not a map")
}
allJobNames := make([]string, 0, len(jobs))
for name := range jobs {
allJobNames = append(allJobNames, name)
}
// Validate requested jobs exist
for _, name := range jobNames {
if _, exists := jobs[name]; !exists {
return fmt.Errorf("job %q not found in workflow. Available jobs: %s", name, strings.Join(allJobNames, ", "))
}
}
// Determine which jobs to include
selectedJobs := jobNames
if len(selectedJobs) == 0 {
selectedJobs = allJobNames
}
// Pare workflow to selected jobs if a subset was specified
if len(jobNames) > 0 {
paredJobs := make(map[string]interface{})
for _, name := range jobNames {
paredJobs[name] = jobs[name]
}
workflow["jobs"] = paredJobs
jobs = paredJobs
}
// Resolve repo from git remote
workflowDir := filepath.Dir(workflowPath)
if !filepath.IsAbs(workflowDir) {
cwd, _ := os.Getwd()
workflowDir = filepath.Join(cwd, workflowDir)
}
repo, err := resolveRepo(workflowDir)
if err != nil {
return fmt.Errorf("failed to resolve repo: %w", err)
}
// Detect local changes as a patch
patch := detectPatch(workflowDir)
if patch != nil {
fmt.Printf("Default branch: %s\n", patch.defaultBranch)
fmt.Printf("Merge base: %s\n", patch.mergeBase)
fmt.Printf("Patch size: %d bytes\n", len(patch.content))
hash := sha256.Sum256([]byte(patch.content))
patchHash := fmt.Sprintf("%x", hash)[:16]
cacheKey := fmt.Sprintf("patch/%s/%s", patch.mergeBase[:12], patchHash)
fmt.Printf("Cache key: %s\n", cacheKey)
if err := api.UploadCacheEntry(ctx, tokenVal, orgID, cacheKey, []byte(patch.content)); err != nil {
return fmt.Errorf("failed to upload patch: %w", err)
}
fmt.Println("Patch uploaded to Depot Cache")
// Inject patch step into each selected job that has actions/checkout
for _, jobName := range selectedJobs {
injectPatchStep(jobs, jobName, patch.mergeBase, cacheKey)
}
}
// Insert tmate debug step if requested
if sshAfterStep > 0 {
jobName := jobNames[0]
if err := injectTmateStep(jobs, jobName, sshAfterStep, patch != nil); err != nil {
return err
}
}
fmt.Printf("Repo: %s\n", repo)
if len(jobNames) > 0 {
fmt.Printf("Jobs: %s\n", strings.Join(selectedJobs, ", "))
} else {
fmt.Printf("Jobs: (all) %s\n", strings.Join(selectedJobs, ", "))
}
if patch != nil {
fmt.Printf("Checking out commit: %s\n", patch.mergeBase)
}
if sshAfterStep > 0 {
fmt.Printf("Inserting tmate step after step %d\n", sshAfterStep)
}
fmt.Println()
// Serialize workflow back to YAML
yamlBytes, err := yaml.Marshal(workflow)
if err != nil {
return fmt.Errorf("failed to serialize workflow: %w", err)
}
req := &civ1.RunRequest{
Repo: repo,
WorkflowContent: []string{string(yamlBytes)},
}
if len(jobNames) > 0 {
job := jobNames[0]
req.Job = &job
}
resp, err := api.CIRun(ctx, tokenVal, orgID, req)
if err != nil {
return fmt.Errorf("failed to start CI run: %w", err)
}
fmt.Printf("Org: %s\n", resp.OrgId)
fmt.Printf("Run: %s\n", resp.RunId)
fmt.Println()
fmt.Printf("Check status: depot ci status %s\n", resp.RunId)
fmt.Printf("View in Depot: https://depot.dev/orgs/%s/workflows/%s\n", resp.OrgId, resp.RunId)
return nil
},
}
cmd.Flags().StringVar(&orgID, "org", "", "Organization ID (required when user is a member of multiple organizations)")
cmd.Flags().StringVar(&token, "token", "", "Depot API token")
cmd.Flags().StringVar(&workflowPath, "workflow", "", "Path to workflow YAML file")
cmd.Flags().StringSliceVar(&jobNames, "job", nil, "Job name(s) to run (repeatable; omit to run all)")
cmd.Flags().IntVar(&sshAfterStep, "ssh-after-step", 0, "1-based step index to insert a tmate debug step after (requires single --job)")
cmd.AddCommand(NewCmdRunList())
return cmd
}
type patchInfo struct {
defaultBranch string
mergeBase string
content string
}
func detectPatch(workflowDir string) *patchInfo {
defaultBranchOut, err := exec.Command("git", "-C", workflowDir, "symbolic-ref", "refs/remotes/origin/HEAD").Output()
if err != nil {
return nil
}
defaultBranch := strings.TrimSpace(string(defaultBranchOut))
defaultBranch = strings.TrimPrefix(defaultBranch, "refs/remotes/origin/")
mergeBaseOut, err := exec.Command("git", "-C", workflowDir, "merge-base", "HEAD", "origin/"+defaultBranch).Output()
if err != nil {
return nil
}
mergeBase := strings.TrimSpace(string(mergeBaseOut))
diffOut, err := exec.Command("git", "-C", workflowDir, "diff", "--binary", mergeBase).Output()
if err != nil {
return nil
}
content := string(diffOut)
if strings.TrimSpace(content) == "" {
return nil
}
return &patchInfo{
defaultBranch: defaultBranch,
mergeBase: mergeBase,
content: content,
}
}
var repoPattern = regexp.MustCompile(`[/:]([^/:]+/[^/.]+?)(?:\.git)?$`)
func resolveRepo(dir string) (string, error) {
out, err := exec.Command("git", "-C", dir, "remote", "get-url", "origin").Output()
if err != nil {
return "", fmt.Errorf("failed to get git remote URL: %w", err)
}
url := strings.TrimSpace(string(out))
matches := repoPattern.FindStringSubmatch(url)
if matches == nil {
return "", fmt.Errorf("could not parse repo from remote URL: %s", url)
}
return matches[1], nil
}
func injectPatchStep(jobs map[string]interface{}, jobName, mergeBase, cacheKey string) {
jobRaw, ok := jobs[jobName]
if !ok {
return
}
job, ok := jobRaw.(map[string]interface{})
if !ok {
return
}
stepsRaw, ok := job["steps"]
if !ok {
return
}
steps, ok := stepsRaw.([]interface{})
if !ok {
return
}
checkoutIndex := -1
for i, stepRaw := range steps {
step, ok := stepRaw.(map[string]interface{})
if !ok {
continue
}
uses, ok := step["uses"].(string)
if ok && strings.HasPrefix(uses, "actions/checkout") {
checkoutIndex = i
break
}
}
if checkoutIndex == -1 {
fmt.Printf("Job %q: no actions/checkout step, skipping patch injection\n", jobName)
return
}
// Modify checkout step to check out the merge-base commit
checkoutStep := steps[checkoutIndex].(map[string]interface{})
withMap, ok := checkoutStep["with"].(map[string]interface{})
if !ok {
withMap = make(map[string]interface{})
checkoutStep["with"] = withMap
}
withMap["ref"] = mergeBase
// Create patch application step
patchStep := map[string]interface{}{
"name": "Apply local patch from Depot Cache",
"run": fmt.Sprintf(`set -euo pipefail
# Get download URL from Depot Cache service
CACHE_KEY="%s"
echo "Fetching download URL for patch..."
DOWNLOAD_RESPONSE=$(curl -fsSL -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DEPOT_TOKEN" \
"%s/depot.cache.v1.CacheService/GetDownloadURL" \
-d '{"entry_type":"generic","key":"'"$CACHE_KEY"'"}')
PATCH_URL=$(echo "$DOWNLOAD_RESPONSE" | jq -r '.url')
if [ -z "$PATCH_URL" ] || [ "$PATCH_URL" = "null" ]; then
echo "Failed to get download URL: $DOWNLOAD_RESPONSE"
exit 1
fi
echo "Downloading patch..."
curl -fsSL "$PATCH_URL" -o /tmp/local.patch
echo "Applying patch..."
git apply --allow-empty /tmp/local.patch
rm /tmp/local.patch
echo "Patch applied successfully"`, cacheKey, cacheBaseURL),
"env": map[string]interface{}{
"DEPOT_TOKEN": "${{ secrets.DEPOT_TOKEN }}",
},
}
// Insert patch step after checkout
newSteps := make([]interface{}, 0, len(steps)+1)
newSteps = append(newSteps, steps[:checkoutIndex+1]...)
newSteps = append(newSteps, patchStep)
newSteps = append(newSteps, steps[checkoutIndex+1:]...)
job["steps"] = newSteps
}
func injectTmateStep(jobs map[string]interface{}, jobName string, afterStep int, patchInjected bool) error {
jobRaw, ok := jobs[jobName]
if !ok {
return fmt.Errorf("job %q not found", jobName)
}
job, ok := jobRaw.(map[string]interface{})
if !ok {
return fmt.Errorf("job %q is not a map", jobName)
}
stepsRaw, ok := job["steps"]
if !ok {
return fmt.Errorf("job %q has no steps", jobName)
}
steps, ok := stepsRaw.([]interface{})
if !ok {
return fmt.Errorf("job %q steps is not a list", jobName)
}
tmateStep := map[string]interface{}{
"uses": "mxschmitt/action-tmate@v3",
"with": map[string]interface{}{
"limit-access-to-actor": "false",
},
}
insertAt := afterStep
if patchInjected {
// Find checkout index to adjust for the injected patch step
checkoutIndex := -1
for i, stepRaw := range steps {
step, ok := stepRaw.(map[string]interface{})
if !ok {
continue
}
uses, ok := step["uses"].(string)
if ok && strings.HasPrefix(uses, "actions/checkout") {
checkoutIndex = i
break
}
}
if checkoutIndex != -1 && afterStep > checkoutIndex {
insertAt = afterStep + 1
}
}
if insertAt > len(steps) {
return fmt.Errorf("--ssh-after-step %d is out of range (workflow has %d steps)", afterStep, len(steps))
}
newSteps := make([]interface{}, 0, len(steps)+1)
newSteps = append(newSteps, steps[:insertAt]...)
newSteps = append(newSteps, tmateStep)
newSteps = append(newSteps, steps[insertAt:]...)
job["steps"] = newSteps
return nil
}
// validStatuses are the user-facing status names accepted by --status.
var validStatuses = []string{"queued", "running", "finished", "failed", "cancelled"}
func parseStatus(s string) (civ1.CIRunStatus, error) {
switch strings.ToLower(s) {
case "queued":
return civ1.CIRunStatus_CI_RUN_STATUS_QUEUED, nil
case "running":
return civ1.CIRunStatus_CI_RUN_STATUS_RUNNING, nil
case "finished":
return civ1.CIRunStatus_CI_RUN_STATUS_FINISHED, nil
case "failed":
return civ1.CIRunStatus_CI_RUN_STATUS_FAILED, nil
case "cancelled":
return civ1.CIRunStatus_CI_RUN_STATUS_CANCELLED, nil
default:
return 0, fmt.Errorf("invalid status %q, valid values: %s", s, strings.Join(validStatuses, ", "))
}
}
func formatStatus(s civ1.CIRunStatus) string {
switch s {
case civ1.CIRunStatus_CI_RUN_STATUS_QUEUED:
return "queued"
case civ1.CIRunStatus_CI_RUN_STATUS_RUNNING:
return "running"
case civ1.CIRunStatus_CI_RUN_STATUS_FINISHED:
return "finished"
case civ1.CIRunStatus_CI_RUN_STATUS_FAILED:
return "failed"
case civ1.CIRunStatus_CI_RUN_STATUS_CANCELLED:
return "cancelled"
default:
return "unknown"
}
}
func NewCmdRunList() *cobra.Command {
var (
orgID string
token string
statuses []string
n int32
output string
)
cmd := &cobra.Command{
Use: "list",
Short: "List CI runs",
Long: `List CI runs for your organization.`,
Example: ` # List runs (defaults to queued and running)
depot ci run list
# List failed runs
depot ci run list --status failed
# List finished and failed runs
depot ci run list --status finished --status failed
# List the 5 most recent runs
depot ci run list -n 5
# Output as JSON
depot ci run list --output json`,
Aliases: []string{"ls"},
RunE: func(cmd *cobra.Command, args []string) error {
if n <= 0 {
return fmt.Errorf("page size (-n) must be greater than 0")
}
ctx := cmd.Context()
if orgID == "" {
orgID = config.GetCurrentOrganization()
}
tokenVal, err := helpers.ResolveOrgAuth(ctx, token)
if err != nil {
return err
}
if tokenVal == "" {
return fmt.Errorf("missing API token, please run `depot login`")
}
var protoStatuses []civ1.CIRunStatus
for _, s := range statuses {
ps, err := parseStatus(s)
if err != nil {
return err
}
protoStatuses = append(protoStatuses, ps)
}
runs, err := api.CIListRuns(ctx, tokenVal, orgID, protoStatuses, n)
if err != nil {
return fmt.Errorf("failed to list runs: %w", err)
}
if output == "json" {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(runs)
}
if len(runs) == 0 {
if len(statuses) == 0 {
fmt.Println("No queued or active runs found. Use --status to view other runs.")
} else {
fmt.Println("No matching runs found.")
}
return nil
}
fmt.Printf("%-24s %-30s %-12s %-10s %-12s %s\n", "RUN ID", "REPO", "SHA", "STATUS", "TRIGGER", "CREATED")
fmt.Printf("%-24s %-30s %-12s %-10s %-12s %s\n",
strings.Repeat("-", 24),
strings.Repeat("-", 30),
strings.Repeat("-", 12),
strings.Repeat("-", 10),
strings.Repeat("-", 12),
strings.Repeat("-", 20),
)
for _, run := range runs {
repo := run.Repo
if len(repo) > 30 {
repo = repo[:27] + "..."
}
sha := run.Sha
if len(sha) > 12 {
sha = sha[:12]
}
trigger := run.Trigger
if len(trigger) > 12 {
trigger = trigger[:9] + "..."
}
fmt.Printf("%-24s %-30s %-12s %-10s %-12s %s\n",
run.RunId,
repo,
sha,
formatStatus(run.Status),
trigger,
run.CreatedAt,
)
}
return nil
},
}
cmd.Flags().StringVar(&orgID, "org", "", "Organization ID (required when user is a member of multiple organizations)")
cmd.Flags().StringVar(&token, "token", "", "Depot API token")
cmd.Flags().StringSliceVar(&statuses, "status", nil, "Filter by status (repeatable: queued, running, finished, failed, cancelled)")
cmd.Flags().Int32VarP(&n, "n", "n", 50, "Number of runs to return")
cmd.Flags().StringVarP(&output, "output", "o", "", "Output format (json)")
return cmd
}