-
Notifications
You must be signed in to change notification settings - Fork 0
/
harness.go
84 lines (68 loc) · 2.05 KB
/
harness.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
package harness
import (
"context"
"fmt"
"time"
"github.com/fatih/color"
)
// Harness is a support structure that runs tasks, the harness can be customized with
// pre- and post- execution hook functions, where common functionality to all tasks
// can be defined.
type Harness struct {
PreExecHook Task
PostExecHook Task
}
// New constructs a harness.
func New(opts ...Option) *Harness {
h := Harness{
PreExecHook: func(_ context.Context) error { return nil },
PostExecHook: func(_ context.Context) error { return nil },
}
for _, opt := range opts {
opt(&h)
}
return &h
}
// Execute a list of tasks inside the harness.
// Every task inside the harness is run sequentially, showing a consistent output where
// the task status and timing info are clearly visible.
func (h *Harness) Execute(ctx context.Context, tasks ...Task) error {
var errs []string
start := time.Now()
if err := h.PreExecHook(ctx); err != nil {
return fmt.Errorf("failed to initialize ci harness: %s", err.Error())
}
for i := range tasks {
task := tasks[i]
if err := task(ctx); err != nil {
errs = append(errs, err.Error())
}
}
if err := h.PostExecHook(ctx); err != nil {
return fmt.Errorf("failed to run post exec hook: %s", err.Error())
}
elapsed := time.Since(start).Round(time.Millisecond)
fmt.Printf("\n------------------------\n\n")
if len(errs) > 0 {
color.Red(" ✘ finished with errors after %s", elapsed)
for _, errmsg := range errs {
color.Red(" • %s", errmsg)
}
fmt.Printf("\n")
return fmt.Errorf("task finished with errors")
}
color.Green("✔ all good after %s\n\n", elapsed)
return nil
}
// Task defines the basic function that the harness executes.
// Additional configuration and tweaks can be done by using clojures which return
// Tasks.
type Task func(ctx context.Context) error
type Option func(h *Harness)
// WithPreExecFunc allows specifying a task that will be run every execution, before the
// specific execution tasks are run.
func WithPreExecFunc(hook Task) Option {
return func(h *Harness) {
h.PreExecHook = hook
}
}