-
Notifications
You must be signed in to change notification settings - Fork 19
/
run.go
344 lines (298 loc) · 7.17 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
package demo
import (
"bufio"
"errors"
"fmt"
"io"
"math/rand"
"os"
"os/exec"
"strings"
"time"
"github.com/gookit/color"
"github.com/urfave/cli/v2"
)
// errOutputNil is the error returned if no output has been set.
var errOutputNil = errors.New("provided output is nil")
// Run is an abstraction for one part of the Demo. A demo can contain multiple
// runs.
type Run struct {
title string
description []string
steps []step
out io.Writer
options *Options
setup func() error
cleanup func() error
}
type step struct {
r *Run
text, command []string
canFail, isBreakPoint bool
}
// Options specify the run options.
type Options struct {
AutoTimeout time.Duration
Auto bool
BreakPoint bool
ContinueOnError bool
HideDescriptions bool
DryRun bool
NoColor bool
Immediate bool
SkipSteps int
Shell string
}
func emptyFn() error { return nil }
// NewRun creates a new run for the provided description string.
func NewRun(title string, description ...string) *Run {
return &Run{
title: title,
description: description,
steps: nil,
out: os.Stdout,
options: nil,
setup: emptyFn,
cleanup: emptyFn,
}
}
// optionsFrom creates a new set of options from the provided context.
func optionsFrom(ctx *cli.Context) Options {
return Options{
AutoTimeout: ctx.Duration(FlagAutoTimeout),
Auto: ctx.Bool(FlagAuto),
BreakPoint: ctx.Bool(FlagBreakPoint),
ContinueOnError: ctx.Bool(FlagContinueOnError),
HideDescriptions: ctx.Bool(FlagHideDescriptions),
DryRun: ctx.Bool(FlagDryRun),
NoColor: ctx.Bool(FlagNoColor),
Immediate: ctx.Bool(FlagImmediate),
SkipSteps: ctx.Int(FlagSkipSteps),
Shell: ctx.String(FlagShell),
}
}
// S is a short-hand for converting string slice syntaxes.
func S(s ...string) []string {
return s
}
// SetOutput can be used to replace the default output for the Run.
func (r *Run) SetOutput(output io.Writer) error {
if output == nil {
return errOutputNil
}
r.out = output
return nil
}
// Setup sets the cleanup function called before this run.
func (r *Run) Setup(setupFn func() error) {
r.setup = setupFn
}
// Cleanup sets the cleanup function called after this run.
func (r *Run) Cleanup(cleanupFn func() error) {
r.cleanup = cleanupFn
}
// Step creates a new step on the provided run.
func (r *Run) Step(text, command []string) {
r.steps = append(r.steps, step{r, text, command, false, false})
}
// StepCanFail creates a new step which can fail on execution.
func (r *Run) StepCanFail(text, command []string) {
r.steps = append(r.steps, step{r, text, command, true, false})
}
// BreakPoint creates a new step which can fail on execution.
func (r *Run) BreakPoint() {
r.steps = append(r.steps, step{r, nil, nil, true, true})
}
// Run executes the run in the provided CLI context.
func (r *Run) Run(ctx *cli.Context) error {
return r.RunWithOptions(optionsFrom(ctx))
}
// RunWithOptions executes the run with the provided Options.
func (r *Run) RunWithOptions(opts Options) error {
if opts.Shell == "" {
opts.Shell = "bash"
}
if err := r.setup(); err != nil {
return err
}
r.options = &opts
if err := r.printTitleAndDescription(); err != nil {
return err
}
for i, step := range r.steps {
if r.options.SkipSteps > i {
continue
}
if r.options.ContinueOnError {
step.canFail = true
}
if err := step.run(i+1, len(r.steps)); err != nil {
return err
}
}
return r.cleanup()
}
func (r *Run) printTitleAndDescription() error {
p := color.Cyan.Sprintf
if r.options.NoColor {
p = fmt.Sprintf
}
if err := write(r.out, p("%s\n", r.title)); err != nil {
return err
}
for range r.title {
if err := write(r.out, p("=")); err != nil {
return err
}
}
if err := write(r.out, "\n"); err != nil {
return err
}
if !r.options.HideDescriptions {
p = color.White.Darken().Sprintf
if r.options.NoColor {
p = fmt.Sprintf
}
for _, d := range r.description {
if err := write(
r.out, p("%s\n", d),
); err != nil {
return err
}
}
if err := write(r.out, "\n"); err != nil {
return err
}
}
return nil
}
func write(w io.Writer, str string) error {
_, err := w.Write([]byte(str))
if err != nil {
return fmt.Errorf("write: %w", err)
}
return nil
}
func (s *step) run(current, maximum int) error {
if err := s.waitOrSleep(); err != nil {
return fmt.Errorf("unable to run step: %v: %w", s, err)
}
if len(s.text) > 0 && !s.r.options.HideDescriptions {
s.echo(current, maximum)
}
if s.isBreakPoint {
return s.wait()
}
if len(s.command) > 0 {
return s.execute()
}
return nil
}
func (s *step) echo(current, maximum int) {
p := color.White.Darken().Sprintf
if s.r.options.NoColor {
p = fmt.Sprintf
}
prepared := []string{}
for i, x := range s.text {
if i == len(s.text)-1 {
colon := ":"
if s.command == nil {
// Do not set the expectation that there is more if no command
// provided.
colon = ""
}
prepared = append(
prepared,
p(
"# %s [%d/%d]%s\n",
x, current, maximum, colon,
),
)
} else {
m := p("# %s", x)
prepared = append(prepared, m)
}
}
s.print(prepared...)
}
func (s *step) execute() error {
joinedCommand := strings.Join(s.command, " ")
cmd := exec.Command(s.r.options.Shell, "-c", joinedCommand) //nolint:gosec // we purposefully run user-provided code
cmd.Stderr = s.r.out
cmd.Stdout = s.r.out
p := color.Green.Sprintf
if s.r.options.NoColor {
p = fmt.Sprintf
}
cmdString := p("> %s", strings.Join(s.command, " \\\n "))
s.print(cmdString)
if err := s.waitOrSleep(); err != nil {
return fmt.Errorf("unable to execute step: %v: %w", s, err)
}
if s.r.options.DryRun {
return nil
}
err := cmd.Run()
if s.canFail {
return nil
}
s.print("")
if err != nil {
return fmt.Errorf("step command failed: %w", err)
}
return nil
}
func (s *step) print(msg ...string) error {
for _, m := range msg {
for _, c := range m {
if !s.r.options.Immediate {
const maximum = 40
//nolint:gosec,gomnd // the sleep has no security implications and is randomly chosen
time.Sleep(time.Duration(rand.Intn(maximum)) * time.Millisecond)
}
if err := write(s.r.out, fmt.Sprintf("%c", c)); err != nil {
return err
}
}
if err := write(s.r.out, "\n"); err != nil {
return err
}
}
return nil
}
func (s *step) waitOrSleep() error {
if s.r.options.Auto {
time.Sleep(s.r.options.AutoTimeout)
} else {
if err := write(s.r.out, "…"); err != nil {
return err
}
_, err := bufio.NewReader(os.Stdin).ReadBytes('\n')
if err != nil {
return fmt.Errorf("unable to read newline: %w", err)
}
// Move cursor up again
if err := write(s.r.out, "\x1b[1A"); err != nil {
return err
}
}
return nil
}
func (s *step) wait() error {
if !s.r.options.BreakPoint {
return nil
}
if err := write(s.r.out, "bp"); err != nil {
return err
}
_, err := bufio.NewReader(os.Stdin).ReadBytes('\n')
if err != nil {
return fmt.Errorf("unable to read newline: %w", err)
}
// Move cursor up again
if err := write(s.r.out, "\x1b[1A"); err != nil {
return err
}
return nil
}