-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocedure.go
286 lines (258 loc) · 7.36 KB
/
procedure.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
package otium
import (
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/alecthomas/kong"
"github.com/google/shlex"
"github.com/peterh/liner"
)
// Procedure is made of a sequence of [Step]. Create it with [NewProcedure],
// fill it with [Procedure.AddStep] and finally start it with
// [Procedure.Execute].
type Procedure struct {
ProcedureOpts
steps []*Step
stepIdx int // Index into the step to execute.
bag Bag
uctx any // The optional user context.
parser *kong.Kong
// Warning: term will be initialized by Execute(), not by NewProcedure().
term *liner.State
}
// ProcedureOpts is used by [NewProcedure] to create a Procedure.
type ProcedureOpts struct {
// Name is the name of the Procedure; by default it is the name of the executable.
Name string
// Title is the title of the Procedure, shown at the beginning of the program.
Title string
// Desc is the summary of what the procedure is about, shown at the beginning of
// the program, just after the Title.
Desc string
// PreFlight is an optional function run after the command-line has been parsed and
// before the first step.
// It is used to perform procedure-specific validations and to initialize the user
// context. Such user context will then be passed as parameter uctx to each call
// of Step.Run(bag Bag, uctx any).
PreFlight func() (any, error)
}
// NewProcedure creates a Procedure.
func NewProcedure(opts ProcedureOpts) *Procedure {
return &Procedure{
ProcedureOpts: opts,
bag: NewBag(),
parser: kong.Must(&topcli{},
kong.Name(""),
kong.Exit(func(int) {}),
kong.ConfigureHelp(kong.HelpOptions{
// Must be disabled because it doesn't make sense in a REPL.
NoAppSummary: true,
WrapUpperBound: 80,
}),
// Must be disabled because it doesn't make sense in a REPL.
kong.NoDefaultHelp(),
),
}
}
// AddStep adds a [Step] to [Procedure].
func (pcd *Procedure) AddStep(step *Step) {
pcd.steps = append(pcd.steps, step)
}
// Execute parses the command-line passed in args, assigns bag variables and
// starts the [Procedure] by putting the user into a REPL.
// If it returns an error, the user program should print it and exit with a
// non-zero status code. See the examples for the suggested usage.
func (pcd *Procedure) Execute(args []string) error {
var errs []error
errs = append(errs, pcd.validate())
for i, step := range pcd.steps {
errs = append(errs, step.validate(i+1))
}
if err := errors.Join(errs...); err != nil {
return err
}
// Fill the bag with all the Vars from all the steps.
// A duplicate variable is considered an error.
for _, step := range pcd.steps {
for _, variable := range step.Vars {
if variable.Fn == nil {
variable.Fn = func(string) error { return nil }
}
// Detect duplicates.
if _, ok := pcd.bag.bag[variable.Name]; ok {
err := fmt.Errorf("step %q: duplicate var %q", step.Title, variable.Name)
errs = append(errs, err)
continue
}
pcd.bag.bag[variable.Name] = variable
}
}
if err := errors.Join(errs...); err != nil {
return err
}
// Setup command-line parsing.
cliFlags := flag.NewFlagSet(args[0], flag.ExitOnError)
// Add the Vars in the bag as CLI flags.
for name, variable := range pcd.bag.bag {
name, variable := name, variable // avoid loop capture :-(
cliFlags.Func(name, variable.Desc,
func(val string) error {
if err := variable.Fn(val); err != nil {
return err
}
pcd.bag.Put(name, val)
return nil
})
}
var docOnly bool
cliFlags.BoolVar(&docOnly, "doc-only", false, "Print documentation only instead of running")
// Parse the command-line.
cliFlags.Usage = func() {
out := cliFlags.Output()
fmt.Fprintf(out, "%s: %s.\n", pcd.Name, pcd.Title)
fmt.Fprintf(out,
"This program is based on otium %s, a simple incremental automation system (https://github.com/marco-m/otium)\n",
version)
fmt.Fprintf(out, "\nUsage of %s:\n", pcd.Name)
cliFlags.PrintDefaults()
}
if err := cliFlags.Parse(args[1:]); err != nil {
// impossible due to flag.ExitOnError
return err
}
if !docOnly && pcd.PreFlight != nil {
var err error
pcd.uctx, err = pcd.PreFlight()
if err != nil {
return fmt.Errorf("PreFlight: %s", err)
}
}
// We cannot initialize liner before (say, in NewProcedure), because
// NewLiner changes the terminal line discipline, so we must do this
// _after_ having parsed the command-line.
pcd.term = liner.NewLiner()
// Restore terminal to previous mode, super important.
defer pcd.term.Close()
pcd.term.SetCtrlCAborts(true)
//
// Configure completer, part 1.
// TODO think how to make it know deeper about the possible completions...
//
pcd.term.SetTabCompletionStyle(liner.TabPrints)
var commands []string
for _, node := range pcd.parser.Model.Children {
commands = append(commands, node.Name)
}
topCompleter := func(line string) []string {
completions := make([]string, 0, len(commands))
line = strings.ToLower(line)
for _, cmd := range commands {
if strings.HasPrefix(cmd, line) {
completions = append(completions, cmd)
}
}
//fmt.Printf("completer: %q, completions: %q\n", line, completions)
return completions
}
fmt.Printf("# %s\n\n", pcd.Title)
fmt.Printf("%s\n", pcd.Desc)
printToc(pcd)
if docOnly {
for pcd.stepIdx != len(pcd.steps) {
if err := visitStep(pcd, nil); err != nil {
return err
}
}
return nil
}
//
// Main loop.
//
var kongCtx *kong.Context
for {
if pcd.stepIdx == len(pcd.steps) {
fmt.Printf("\n(top) Procedure terminated successfully\n")
return nil
}
// We set the completer on each loop because the sub repl in bag.Get
// sets its own.
pcd.term.SetCompleter(topCompleter)
next := pcd.steps[pcd.stepIdx]
fmt.Printf("\n(top) Next step: %d. %s %s\n",
pcd.stepIdx+1, next.Icon(), next.Title)
fmt.Printf("(top) Enter a command or '?' for help\n")
var line string
line, err := pcd.term.Prompt("(top)>> ")
// TODO if we receive EOF, we should return no error if the procedure
// has not started yet, and an error if the procedure has already
// started
if err != nil {
return err
}
//
// Parse user input.
//
var args []string
args, err = shlex.Split(line)
if err != nil {
pcd.parser.Errorf("%s", err)
continue
}
kongCtx, err = pcd.parser.Parse(args)
if err != nil {
pcd.parser.Errorf("%s", err)
continue
}
pcd.term.AppendHistory(line)
//
// Execute user command.
//
err = kongCtx.Run(&bind{pcd: pcd})
if errors.Is(err, io.EOF) || errors.Is(err, ErrUnrecoverable) {
return err
}
if errors.Is(err, errBack) {
continue
}
if err != nil {
pcd.parser.Errorf("%s", err)
continue
}
}
}
func (pcd *Procedure) Put(key, val string) {
pcd.bag.Put(key, val)
}
func (pcd *Procedure) validate() error {
var errs []error
if pcd.Name == "" {
_, pcd.Name = filepath.Split(os.Args[0])
}
pcd.Title = strings.TrimSpace(pcd.Title)
pcd.Desc = strings.TrimSpace(pcd.Desc)
if pcd.Title == "" {
errs = append(errs,
errors.New("procedure has empty title"))
}
if len(pcd.steps) == 0 {
errs = append(errs,
errors.New("procedure has zero steps; want at least one"))
}
return errors.Join(errs...)
}
// Table of contents
func printToc(pcd *Procedure) {
fmt.Printf("\n## Table of contents\n\n")
for i, step := range pcd.steps {
var next string
if i == pcd.stepIdx {
next = "next->"
}
fmt.Printf("%6s %2d. %s %s\n", next, i+1, step.Icon(), step.Title)
}
fmt.Println()
}