-
Notifications
You must be signed in to change notification settings - Fork 38
/
run.go
635 lines (514 loc) · 15.1 KB
/
run.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
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
package cmd
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/containerd/console"
"github.com/fatih/color"
"github.com/pkg/errors"
"github.com/rwtodd/Go.Sed/sed"
"github.com/spf13/cobra"
"github.com/stateful/runme/v3/internal/project"
"github.com/stateful/runme/v3/internal/runner/client"
"github.com/stateful/runme/v3/internal/tui"
"github.com/stateful/runme/v3/pkg/document"
)
type CommandExportExtractMatch struct {
Key string
Value string
Match string
HasStringValue bool
LineNumber int
}
func runCmd() *cobra.Command {
var (
dryRun bool
runAll bool
skipPrompts bool
skipPromptsExplicitly bool
parallel bool
replaceScripts []string
serverAddr string
cmdCategories []string
getRunnerOpts func() ([]client.RunnerOption, error)
runIndex int
)
cmd := cobra.Command{
Use: "run <commands>",
Aliases: []string{"exec"},
Short: "Run a selected command",
Long: "Run a selected command identified based on its unique parsed name.",
Args: cobra.ArbitraryArgs,
ValidArgsFunction: validCmdNames,
RunE: func(cmd *cobra.Command, args []string) error {
runWithIndex := fFileMode && runIndex >= 0
runMany := runAll || (len(cmdCategories) > 0 && len(args) == 0)
if !runMany && len(args) == 0 && !runWithIndex {
return errors.New("must provide at least one command to run")
}
proj, err := getProject()
if err != nil {
return err
}
var runTasks []project.Task
{
searchBlocks:
tasks, err := getProjectTasks(cmd)
if err != nil {
return err
}
if runWithIndex {
if runIndex >= len(tasks) {
return fmt.Errorf("command index %v out of range", runIndex)
}
runTasks = []project.Task{tasks[runIndex]}
} else if runMany {
for _, task := range tasks {
block := task.CodeBlock
// Check if to run all and if the block should be excluded
if runAll && len(cmdCategories) == 0 && block.ExcludeFromRunAll() {
// Skip the task if it should be excluded from run all
continue
}
// Check if categories are specified and if the block should be excluded
if len(cmdCategories) > 0 && block.ExcludeFromRunAll() {
// Skip the task if it should be excluded based on categories
continue
}
// Check if the block matches any of the specified categories
if len(cmdCategories) > 0 {
blockCategories := block.Categories()
fm, _ := block.Document().Frontmatter()
fmCategories := resolveFrontmatterCategories(fm)
match := false
if len(fmCategories) > 0 && containsCategories(fmCategories, cmdCategories) {
if len(blockCategories) == 0 {
match = true
} else {
match = containsCategories(fmCategories, blockCategories)
}
} else if containsCategories(blockCategories, cmdCategories) {
match = true
}
if !match {
// Skip the task if it doesn't match any specified category
continue
}
}
// If none of the exclusion conditions met, add the task to runTasks
runTasks = append(runTasks, task)
}
if len(runTasks) == 0 && !fAllowUnnamed {
fAllowUnnamed = true
goto searchBlocks
}
} else {
for _, arg := range args {
task, err := lookupTaskWithPrompt(cmd, arg, tasks)
if err != nil {
if isTaskNotFoundError(err) && !fAllowUnnamed {
fAllowUnnamed = true
goto searchBlocks
}
return err
}
if err := replace(replaceScripts, task.CodeBlock.Lines()); err != nil {
return err
}
runTasks = append(runTasks, task)
}
}
}
if len(runTasks) == 0 {
return errors.New("No tasks to execute with the category provided")
}
ctx, cancel := ctxWithSigCancel(cmd.Context())
defer cancel()
runnerOpts, err := getRunnerOpts()
if err != nil {
return err
}
// non-tty fails on linux otherwise
var stdin io.Reader
stdin = bytes.NewBuffer([]byte{})
if isTerminal(os.Stdout.Fd()) {
stdin = cmd.InOrStdin()
}
runnerOpts = append(
runnerOpts,
client.WithinShellMaybe(),
client.WithStdin(stdin),
client.WithStdout(cmd.OutOrStdout()),
client.WithStderr(cmd.ErrOrStderr()),
client.WithProject(proj),
)
preRunOpts := []client.RunnerOption{
client.WrapWithCancelReader(),
}
runner, err := client.New(cmd.Context(), serverAddr, fSkipRunnerFallback, runnerOpts)
if err != nil {
return err
}
for _, task := range runTasks {
fmtr, err := task.CodeBlock.Document().Frontmatter()
if err != nil {
return err
}
if fmtr != nil && fmtr.SkipPrompts {
skipPrompts = true
break
}
}
if (skipPromptsExplicitly || isTerminal(os.Stdout.Fd())) && !skipPrompts {
err = promptEnvVars(cmd, runner, runTasks...)
if err != nil {
return err
}
if runMany {
err := confirmExecution(cmd, len(runTasks), parallel, cmdCategories)
if err != nil {
return err
}
}
}
blockColor := color.New(color.Bold, color.FgYellow)
playColor := color.New(color.BgHiBlue, color.Bold, color.FgWhite)
textColor := color.New()
successColor := color.New(color.FgGreen)
failureColor := color.New(color.FgRed)
infoMsgPrefix := playColor.Sprint(" ► ")
multiRunner := client.MultiRunner{
Runner: runner,
PreRunMsg: func(tasks []project.Task, parallel bool) string {
blockNames := make([]string, len(tasks))
for i, task := range tasks {
blockNames[i] = task.CodeBlock.Name()
blockNames[i] = blockColor.Sprint(blockNames[i])
}
scriptRunText := "Running task"
if runMany && parallel {
scriptRunText = "Running"
blockNames = []string{blockColor.Sprint("all tasks")}
if len(cmdCategories) > 0 {
blockNames = []string{blockColor.Sprintf("tasks for categories %s", cmdCategories)}
}
}
if len(tasks) > 1 && !runMany {
scriptRunText += "s"
}
extraText := ""
if parallel {
extraText = " in parallel"
}
return fmt.Sprintf(
"%s %s %s%s...\n",
infoMsgPrefix,
textColor.Sprint(scriptRunText),
strings.Join(blockNames, ", "),
textColor.Sprint(extraText),
)
},
PostRunMsg: func(task project.Task, exitCode uint) string {
var statusIcon string
if exitCode == 0 {
statusIcon = successColor.Sprint("✓")
} else {
statusIcon = failureColor.Sprint("𐄂")
}
return textColor.Sprintf(
"%s %s %s %s %s %v\n",
infoMsgPrefix,
statusIcon,
textColor.Sprint("Task"),
blockColor.Sprint(task.CodeBlock.Name()),
textColor.Sprint("exited with code"),
exitCode,
)
},
PreRunOpts: preRunOpts,
}
if parallel {
multiRunner.StdoutPrefix = fmt.Sprintf("[%s] ", blockColor.Sprintf("%%s"))
}
defer multiRunner.Cleanup(cmd.Context())
if dryRun {
return runner.DryRunTask(ctx, runTasks[0], cmd.ErrOrStderr()) // #nosec G602; runBlocks is checked
}
err = inRawMode(func() error {
if len(runTasks) > 1 {
return multiRunner.RunBlocks(ctx, runTasks, parallel)
}
if err := client.ApplyOptions(runner, preRunOpts...); err != nil {
return err
}
return runner.RunTask(ctx, runTasks[0]) // #nosec G602; runBlocks comes from the parent scope and is checked
})
if errors.Is(err, io.ErrClosedPipe) {
err = nil
}
return err
},
}
setDefaultFlags(&cmd)
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the final command without executing.")
cmd.Flags().StringArrayVarP(&replaceScripts, "replace", "r", nil, "Replace instructions using sed.")
cmd.Flags().BoolVarP(¶llel, "parallel", "p", false, "Run tasks in parallel.")
cmd.Flags().BoolVarP(&runAll, "all", "a", false, "Run all commands.")
cmd.Flags().BoolVar(&skipPrompts, "skip-prompts", false, "Skip prompting for variables.")
cmd.Flags().StringArrayVarP(&cmdCategories, "category", "c", nil, "Run from a specific category.")
cmd.Flags().IntVarP(&runIndex, "index", "i", -1, "Index of command to run, 0-based. (Ignored in project mode)")
cmd.PreRun = func(cmd *cobra.Command, args []string) {
skipPromptsExplicitly = cmd.Flags().Changed("skip-prompts")
}
getRunnerOpts = setRunnerFlags(&cmd, &serverAddr)
return &cmd
}
func ctxWithSigCancel(ctx context.Context) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
<-sigs
cancel()
}()
return ctx, cancel
}
func replace(scripts []string, lines []string) error {
if len(scripts) == 0 {
return nil
}
for _, script := range scripts {
engine, err := sed.New(strings.NewReader(script))
if err != nil {
return errors.Wrapf(err, "failed to compile sed script %q", script)
}
for idx, line := range lines {
var err error
lines[idx], err = engine.RunString(line)
if err != nil {
return errors.Wrapf(err, "failed to run sed script %q on line %q", script, line)
}
}
}
return nil
}
func inRawMode(cb func() error) error {
if !isTerminal(os.Stdout.Fd()) {
return cb()
}
current := console.Current()
_ = current.SetRaw()
err := cb()
_ = current.Reset()
return err
}
const fileNameSeparator = "/"
func splitRunArgument(name string) (queryFile string, queryName string, err error) {
parts := strings.SplitN(name, fileNameSeparator, 2)
if len(parts) > 1 {
queryFile = parts[0]
queryName = parts[1]
} else {
queryName = name
}
return
}
var (
blockPromptListItemStyle = lipgloss.NewStyle().PaddingLeft(0).Bold(true)
blockPromptAppStyle = lipgloss.NewStyle().Margin(1, 2)
)
type blockPromptItem struct {
task *project.Task
}
func (i blockPromptItem) FilterValue() string {
return i.task.CodeBlock.Name()
}
func (i blockPromptItem) Title() string {
return blockPromptListItemStyle.Render(i.task.CodeBlock.Name())
}
func (i blockPromptItem) Description() string {
return i.task.DocumentPath
}
type RunBlockPrompt struct {
list.Model
selectedBlock list.Item
heading string
}
func (p RunBlockPrompt) Init() tea.Cmd {
return nil
}
func (p RunBlockPrompt) KeyMap() *tui.KeyMap {
kmap := tui.NewKeyMap()
kmap.Set("enter", key.NewBinding(
key.WithKeys("enter"),
key.WithHelp("enter", "select"),
))
return kmap
}
func (p RunBlockPrompt) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
h, v := blockPromptAppStyle.GetFrameSize()
p.SetSize(msg.Width-h, msg.Height-v-len(strings.Split(p.heading, "\n")))
case tea.KeyMsg:
kmap := p.KeyMap()
if kmap.Matches(msg, "enter") {
p.selectedBlock = p.SelectedItem()
return p, tea.Quit
}
}
model, cmd := p.Model.Update(msg)
p.Model = model
return p, cmd
}
func (p RunBlockPrompt) View() string {
content := ""
content += p.heading
content += p.Model.View()
return blockPromptAppStyle.Render(content)
}
type errTaskWithFilenameNotFound struct {
queryFile string
}
func (e errTaskWithFilenameNotFound) Error() string {
return fmt.Sprintf("unable to find file in project matching regex %q", e.queryFile)
}
type errTaskWithNameNotFound struct {
queryName string
}
func (e errTaskWithNameNotFound) Error() string {
return fmt.Sprintf("unable to find any script named %q", e.queryName)
}
func isTaskNotFoundError(err error) bool {
return errors.As(err, &errTaskWithFilenameNotFound{}) || errors.As(err, &errTaskWithNameNotFound{})
}
func filterTasksByFileAndTaskName(tasks []project.Task, queryFile, queryName string) ([]project.Task, error) {
fileMatcher, err := project.CompileRegex(queryFile)
if err != nil {
return nil, err
}
var results []project.Task
foundFile := false
for _, task := range tasks {
if !fileMatcher.MatchString(task.DocumentPath) {
continue
}
foundFile = true
// This is expected that the task name query is
// matched exactly.
if queryName != task.CodeBlock.Name() {
continue
}
results = append(results, task)
}
if len(results) == 0 {
if !foundFile {
return nil, &errTaskWithFilenameNotFound{queryFile: queryFile}
}
return nil, &errTaskWithNameNotFound{queryName: queryName}
}
return results, nil
}
func lookupTaskWithPrompt(cmd *cobra.Command, query string, tasks []project.Task) (task project.Task, err error) {
queryFile, queryName, err := splitRunArgument(query)
if err != nil {
return task, err
}
filteredTasks, err := filterTasksByFileAndTaskName(tasks, queryFile, queryName)
if err != nil {
return task, err
}
if len(filteredTasks) > 1 {
if !isTerminal(os.Stdout.Fd()) {
return task, fmt.Errorf("multiple matches found for code block; please use a file specifier in the form \"{file}%s{task-name}\"", fileNameSeparator)
}
task, err = promptForRun(cmd, filteredTasks)
if err != nil {
return task, err
}
} else {
task = filteredTasks[0]
}
return task, nil
}
func promptForRun(cmd *cobra.Command, tasks []project.Task) (project.Task, error) {
items := make([]list.Item, len(tasks))
for i := range tasks {
items[i] = blockPromptItem{
task: &tasks[i],
}
}
l := list.New(
items,
list.NewDefaultDelegate(),
0,
0,
)
l.SetFilteringEnabled(false)
l.SetShowStatusBar(false)
l.SetShowPagination(false)
l.SetShowTitle(false)
l.Title = "Select Task"
heading := fmt.Sprintf("Found multiple matching tasks. Select from the following.\n\nNote that you can avoid this screen by providing a filename specifier, such as \"{filename}%s{task}\"\n\n\n", fileNameSeparator)
model := RunBlockPrompt{
Model: l,
heading: heading,
}
prog := newProgramWithOutputs(cmd.OutOrStdout(), cmd.InOrStdin(), model, tea.WithAltScreen())
m, err := prog.Run()
if err != nil {
return project.Task{}, err
}
result := m.(RunBlockPrompt).selectedBlock
if result == nil {
return project.Task{}, errors.New("no block selected")
}
return *result.(blockPromptItem).task, nil
}
func confirmExecution(cmd *cobra.Command, numTasks int, parallel bool, categories []string) error {
text := fmt.Sprintf("Run all %d tasks", numTasks)
if categories != nil {
text = fmt.Sprintf("Run %d tasks for categories: %s", numTasks, strings.Join(categories, ", "))
}
if parallel {
text += " (in parallel)"
}
text += "?"
model := tui.NewStandaloneQuestionModel(
text,
tui.MinimalKeyMap,
tui.DefaultStyles,
)
finalModel, err := newProgram(cmd, model).Run()
if err != nil {
return errors.Wrap(err, "cli program failed")
}
confirm := finalModel.(tui.StandaloneQuestionModel).Confirmed()
if !confirm {
return errors.New("operation cancelled")
}
return nil
}
func resolveFrontmatterCategories(fm *document.Frontmatter) []string {
if fm != nil && fm.Category != "" {
return []string{fm.Category}
}
return []string{}
}
func containsCategories(s1 []string, s2 []string) bool {
for _, element := range s2 {
if strings.Contains(strings.Join(s1, ","), element) {
return true
}
}
return false
}