Repository navigation
Expand file tree
/
Copy pathsessionparse.go
More file actions
594 lines (575 loc) · 21.1 KB
/
Copy pathsessionparse.go
File metadata and controls
594 lines (575 loc) · 21.1 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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
package main
import (
"fmt"
"path"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/dcadolph/kibble/internal/docblock"
kplan "github.com/dcadolph/kibble/internal/plan"
"github.com/dcadolph/kibble/internal/shell"
"github.com/dcadolph/kibble/internal/util"
)
// Reading the session's output back into per-line outcomes. The marker
// protocol is fragile by nature, since documented commands print whatever
// they like, so the parsing is deliberately tolerant about where a marker sits
// and strict about what counts as one.
// lineOutcome is one parsed KIBBLE-LINE marker with the output that
// preceded it.
type lineOutcome struct {
// code is the exit code, or -1 for a planned skip marker.
code int
// output is the text the line printed before its marker.
output string
// background marks a line still running when its step was judged, so it
// never produced an exit code and ready carries what is known instead.
background bool
// ready reports whether the step reached its documented readiness signal.
ready bool
// logged marks a line whose step redirected its output to a file, which a
// background step does for the whole block. Kibble records such a line's
// exit code and never sees its words, so an empty output here means the
// output went somewhere else and not that the command was quiet.
logged bool
// cwd is the directory the line ran in, empty when the marker carried none.
cwd string
// inherited marks a line that ran in a directory an earlier section of its
// document entered, which its own section never did.
inherited bool
// ownProject marks a line that invoked a project manager, whose commands
// read the project in the directory they run in.
ownProject bool
// resolver marks a line that invoked a package resolver, a project manager or
// an installer such as pipx, whose nonzero exit is never a query that ran and
// found nothing.
resolver bool
// roots holds the names at the top of the checkout, from the plan.
roots map[string]bool
// missing marks a line whose needed file did not exist just before it ran.
missing bool
// notFound marks a line that invoked a documented binary and exited with a
// code the documents say means nothing was found.
notFound bool
// member marks a line that ran in a directory an earlier line's own words
// declared a member of the checkout's workspace.
member bool
// truncated marks a line that printed more than the session keeps, so the
// end of output is not the end of what the line said.
truncated bool
// creators maps each path an earlier line of the same document was to
// create, and did not pass, to that line's command.
creators map[string]string
// toolGone marks a line after which the documented binary it ran failed
// its `--version` probe, though the probe passed when the session began.
toolGone bool
}
// sessionRepoDir is the directory every document's shell starts in.
const sessionRepoDir = "/work/repo"
var (
// reWorkspaceMember matches the line uv prints when a new project joins a
// workspace, capturing the project name and the workspace root.
reWorkspaceMember = regexp.MustCompile("Adding `([^`]+)` as member of workspace `([^`]+)`")
// reInitializedAt matches the line uv prints for a new project, capturing
// the project name and the directory it was created in.
reInitializedAt = regexp.MustCompile("Initialized project `([^`]+)` at `([^`]+)`")
// reProbeMarker parses a KIBBLE-PROBE marker into step ID, line index, and
// the exit code of the `--version` probe that followed the line.
reProbeMarker = regexp.MustCompile(`KIBBLE-PROBE (\S+):(\d+) CODE=(-?\d+)$`)
)
// markerTail splits a line on a session marker, returning the output that
// preceded the marker, the text that followed it, and whether the marker is
// present. Markers are found anywhere in a line rather than only at its
// start, so a documented command whose output ends without a newline cannot
// hide the marker the session printed next.
func markerTail(line, marker string) (before, after string, ok bool) {
i := strings.Index(line, marker)
if i < 0 {
return "", "", false
}
return line[:i], line[i+len(marker):], true
}
// sessionEnd records how the session's container stopped, which the output
// alone cannot say. A session that ends early with budget left was ended by
// the container rather than by a document, since the outer script only stops
// at its done marker.
type sessionEnd struct {
// expired reports whether the session's budget ran out.
expired bool
// err is the container client's exit error, nil when it exited cleanly.
err error
}
// classifyExample parses session output into a Result: per-line outcomes
// feed step results, and the worst outcome names the repo's example status.
func classifyExample(step InstallStep, plan *kplan.Plan, out string, wrapped map[string]bool,
dur, lineBudget time.Duration, end sessionEnd) Result {
res := Result{Step: step, Duration: dur}
outcomes := map[string]lineOutcome{}
have := map[string]bool{}
// absent holds the lines whose needed file did not exist when they started.
absent := map[string]bool{}
var chunk []string
aborted, done, noBin := false, false, false
pkgCode, buildCode := 0, 0
var buildTail []string
cut := false
keep := func(s string) {
switch {
case strings.TrimSpace(s) == "":
case len(chunk) < 200:
chunk = append(chunk, s)
default:
cut = true
}
}
for _, line := range strings.Split(out, "\n") {
switch pre, rest, ok := markerTail(line, "KIBBLE-HAVE "); {
case strings.Contains(line, "KIBBLE-NOBIN"):
noBin = true
case ok:
keep(pre)
have[strings.TrimSpace(rest)] = true
case strings.Contains(line, "KIBBLE-NEED "):
pre, rest, _ := markerTail(line, "KIBBLE-NEED ")
keep(pre)
if f := strings.Fields(rest); len(f) == 2 && f[1] == "0" {
absent[f[0]] = true
}
case strings.Contains(line, "KIBBLE-PKGS CODE="):
_, code, _ := markerTail(line, "KIBBLE-PKGS CODE=")
pkgCode, _ = strconv.Atoi(strings.TrimSpace(code))
chunk, cut = nil, false
case strings.Contains(line, "KIBBLE-BUILD CODE="):
_, code, _ := markerTail(line, "KIBBLE-BUILD CODE=")
buildCode, _ = strconv.Atoi(strings.TrimSpace(code))
chunk, cut = nil, false
case strings.Contains(line, "KIBBLE-ABORT"):
aborted = true
buildTail = chunk
case strings.Contains(line, "KIBBLE-STEP "):
chunk, cut = nil, false
case strings.Contains(line, "KIBBLE-DONE"):
done = true
case reProbeMarker.MatchString(line):
m := reProbeMarker.FindStringSubmatch(line)
keep(line[:len(line)-len(m[0])])
if o, ok := outcomes[m[1]+":"+m[2]]; ok {
o.toolGone = m[3] != "0"
outcomes[m[1]+":"+m[2]] = o
}
chunk, cut = nil, false
case reLineMarker.MatchString(line):
m := reLineMarker.FindStringSubmatch(line)
keep(line[:len(line)-len(m[0])])
o := lineOutcome{code: -1, output: strings.Join(chunk, "\n"), missing: absent[m[1]+":"+m[2]]}
o.truncated = cut
switch {
case m[3] != "":
o.code, _ = strconv.Atoi(m[3])
o.cwd = m[4]
case m[5] != "":
ready, _ := strconv.Atoi(m[5])
o.background = true
o.ready = ready == 0
}
outcomes[m[1]+":"+m[2]] = o
chunk, cut = nil, false
default:
keep(line)
}
}
built := fromCheckout(plan)
asset := releaseAsset(plan)
switch {
case aborted && built:
// The build is kibble's stand-in for an install the docs never let it
// run, so its failure says nothing about the document.
res.Status = StatusBlocked
res.Reason = ReasonMissingDependency
res.Detail = "building the tool from the checkout failed, so the examples did not run; " + checkoutNote
switch {
case buildCode == 124:
res.Detail += ": the build timed out"
case len(buildTail) > 0:
res.Detail += ": " + util.Truncate(buildFailLine(buildTail), 160)
}
return res
case aborted && asset != "":
res.Status = StatusSkipped
res.Detail = "documented release download failed in the session; examples not run; " +
releaseNote(asset)
return res
case aborted:
res.Status = StatusSkipped
res.Detail = "documented install failed in the session; examples not run"
return res
case noBin && built:
res.Status = StatusSkipped
res.Detail = "the tool built from the checkout is not on PATH under the expected name; examples not run"
return res
case noBin:
res.Status = StatusSkipped
res.Detail = "installed tool is not on PATH under any documented name; examples not run"
return res
}
run, worst, detail := buildOutcomes(plan, outcomes, wrapped, done, end.expired, have, lineBudget)
res.example = run
res.Status = worst
res.Detail = detail
if pkgCode != 0 && res.Status == StatusVerified {
res.Detail += "; package install failed"
}
if !done && !end.expired && unsettled(plan, outcomes) {
// The lines still carry what ran, for the triage listing, but the
// session as a whole has no verdict: a container that dies with budget
// left says nothing about the document it was running.
res.Status = StatusError
res.Detail = "the container ended before the session finished, so the examples have no verdict"
if end.err != nil {
first, _, _ := strings.Cut(end.err.Error(), "\n")
res.Detail += ": " + util.Truncate(first, 120)
}
}
if built && res.Status != StatusError {
res.Detail = strings.TrimSuffix(checkoutNote+"; "+res.Detail, "; ")
}
if asset != "" && res.Status != StatusError {
res.Detail = strings.TrimSuffix(releaseNote(asset)+"; "+res.Detail, "; ")
}
return res
}
// unsettled reports whether any runnable plan line printed no marker.
func unsettled(plan *kplan.Plan, outcomes map[string]lineOutcome) bool {
for _, s := range plan.Steps {
for i, l := range s.Lines {
if _, seen := outcomes[fmt.Sprintf("%s:%d", s.ID, i)]; l.Skip == "" && !seen {
return true
}
}
}
return false
}
// buildOutcomes walks the plan against the recorded markers, resolves
// failures that only depend on skipped lines, and returns the per-step
// outcomes with the aggregate status and its summary detail.
func buildOutcomes(plan *kplan.Plan, outcomes map[string]lineOutcome, wrapped map[string]bool,
done, expired bool, have map[string]bool, lineBudget time.Duration) (*exampleRun, Status, string) {
run := &exampleRun{}
documented := documentedSettings(plan)
ended := false
bins := map[string]bool{}
for _, b := range plan.Binaries {
bins[b] = true
}
// entered holds the sections, by document, heading, and details element,
// that ran a cd. A document keeps one shell, so a directory one section
// enters is where every later section of that document runs. Collapsed
// details under one heading are sections of their own: glance's README
// offers a template setup that enters a directory and a manual setup
// beside it, and the manual one then ran inside the template's.
entered := map[string]bool{}
// pending holds, per document, the paths earlier lines were to create and
// did not, each with the first such line's command.
pending := map[string]map[string]string{}
// members holds the directories earlier lines declared members of the
// checkout's workspace.
members := map[string]bool{}
roots := map[string]bool{}
for _, r := range plan.Roots {
roots[r] = true
}
for _, s := range plan.Steps {
es := exampleStep{ID: s.ID, Doc: s.Doc, Heading: s.Heading}
section := fmt.Sprintf("%s\x00%s\x00%d", s.Doc, s.Heading, s.Details)
for i, l := range s.Lines {
key := fmt.Sprintf("%s:%d", s.ID, i)
lr := lineResult{Cmd: docblock.Flatten(l.Cmd), Code: -1, Line: l.Line, Synthetic: l.Synthetic,
Setup: l.File != "" || shell.SetupOnly(l.Cmd)}
o, seen := outcomes[key]
o.roots = roots
switch {
case l.Skip != "":
lr.Status = StatusSkipped
if l.Gap {
lr.Status = StatusGap
}
lr.Reason = l.SkipReason
lr.Detail = l.Skip
case !seen && (ended || done):
// The session stopped before reaching this line. Kibble chose
// nothing here, so the line is unestablished rather than
// skipped: a run that spent its budget early must not report
// the lines it never reached as deliberate.
lr.Status = StatusBlocked
lr.Reason = ReasonDependsOnSkipped
lr.Detail = "not run: the session ended before reaching it"
if !ended {
// The session finished, so the shell that stopped short
// was this document's own, ended by this line or one
// before it, and later documents still ran.
lr.Detail = "not established: the document's shell exited at or before this line"
}
case !seen && expired:
lr.Status = StatusTimeout
lr.Detail = "session ended while this line ran"
ended = true
case l.Need != "" && o.missing && o.code != 0 && !o.background:
// The file was absent when the line started and the line did not
// pass. Whether that is the document's gap depends on whether
// everything before it in the document ran: a line kibble did
// not run may be what creates the file. A line that passed
// without the file never needed it, so it is classified as usual.
blocker, unplanned := earlierNotPassed(run, es, s.Doc, l.Unplanned)
lr = settleNeed(lr, l, o, blocker, unplanned)
case !seen:
// The session stopped with budget left, so the container ended
// rather than this line hanging. What the line would have done
// is not known.
lr.Status = StatusBlocked
lr.Reason = ReasonNotExecuted
lr.Detail = "not established: the container ended before this line settled"
ended = true
default:
// A background step sends the whole block's output to a log, so
// silence from one of its lines is kibble's blind spot rather
// than the command's.
o.logged = s.Background
o.inherited = o.cwd != "" && o.cwd != sessionRepoDir && !entered[section]
o.creators = pending[s.Doc]
if bin, _ := kplan.InvokedBinary(docblock.Flatten(l.Cmd), bins); bin != "" {
o.ownProject = kplan.CommandEcosystem[bin] != ""
o.resolver = o.ownProject || resolverTools[bin]
o.notFound = slices.Contains(plan.NotFoundCodes, o.code)
}
o.member = members[o.cwd]
recordMembers(members, o)
lr = classifyLineResult(lr, l, o, wrapped[key], documented, lineBudget)
}
if changesDir(l.Cmd) {
entered[section] = true
}
trackCreators(pending, s.Doc, l, lr)
es.Lines = append(es.Lines, lr)
}
run.Steps = append(run.Steps, es)
}
resolveMissingBinaries(run, plan, have)
resolveDependentFailures(run, plan)
status, detail := summarize(run)
return run, status, detail
}
// recordMembers adds to members each directory the line's output declared a
// member of the checkout's workspace, or of a workspace rooted in a directory
// already recorded as a member. The directory is the path uv reports
// initializing, or the project name under the line's directory when it
// reports none.
func recordMembers(members map[string]bool, o lineOutcome) {
initialized := map[string]string{}
for _, m := range reInitializedAt.FindAllStringSubmatch(o.output, -1) {
initialized[m[1]] = m[2]
}
for _, m := range reWorkspaceMember.FindAllStringSubmatch(o.output, -1) {
if m[2] != sessionRepoDir && !members[m[2]] {
continue
}
dir, ok := initialized[m[1]]
if !ok {
dir = path.Join(o.cwd, m[1])
}
members[dir] = true
}
}
// trackCreators records the paths a line was to create under its document. A
// line that passed made them, so they are dropped. A line that did not pass
// may not have, and the first such line stays the one named.
func trackCreators(pending map[string]map[string]string, doc string, l kplan.PlanLine, lr lineResult) {
names := l.Creates
if l.File != "" {
names = append(append([]string(nil), names...), l.File)
}
if len(names) == 0 {
return
}
if pending[doc] == nil {
pending[doc] = map[string]string{}
}
for _, name := range names {
name = normName(name)
switch {
case lr.Status == StatusVerified:
delete(pending[doc], name)
case pending[doc][name] == "":
pending[doc][name] = lr.Cmd
}
}
}
// settleNeed settles a line that started without a file it reads and did not
// pass. With every earlier line of the document passed, the document never
// creates the file and the line is its gap. Otherwise blocker names the first
// earlier line that did not pass, which may be the one meant to create it, or
// when unplanned is set the code block kibble did not run.
func settleNeed(lr lineResult, l kplan.PlanLine, o lineOutcome, blocker string, unplanned bool) lineResult {
lr.Code = o.code
lr.output, lr.cwd = o.output, o.cwd
if blocker == "" && readerSupplied(l.Need, o.cwd, o.roots) {
return readerSuppliedResult(lr, l.Need, "")
}
if blocker == "" {
lr.Status = StatusGap
lr.Reason = ReasonMissingFixture
lr.Detail = fmt.Sprintf("references %s, which no documented step creates", l.Need)
return lr
}
lr.Status = StatusBlocked
lr.Reason = ReasonDependsOnSkipped
if unplanned {
lr.Detail = fmt.Sprintf("references %s, which an earlier code block kibble did not run may create: %s",
l.Need, blocker)
return lr
}
lr.Detail = fmt.Sprintf("references %s, which an earlier line that did not pass may create: %s",
l.Need, blocker)
return lr
}
// earlierNotPassed returns the first earlier line of the document that did not
// pass, or empty when every one did. unplanned is the location of a block the
// plan left out of the document, which never ran and so comes first; the second
// result reports that the blocker is such a block.
func earlierNotPassed(run *exampleRun, current exampleStep, doc, unplanned string) (string, bool) {
if unplanned != "" {
return unplanned, true
}
steps := append(append([]exampleStep(nil), run.Steps...), current)
for _, s := range steps {
if s.Doc != doc {
continue
}
for _, l := range s.Lines {
if l.Status != StatusVerified {
return l.Cmd, false
}
}
}
return "", false
}
// changesDir reports whether a line moves the shell to another directory.
func changesDir(cmd string) bool {
line, ok := shell.Parse(docblock.Flatten(cmd))
if !ok {
return false
}
for _, c := range line.Cmds {
switch c.Name() {
case "cd", "pushd", "popd":
return true
}
}
return false
}
// summarize reduces per-line outcomes to the aggregate status and detail:
// the first failure names the broken line, a timeout names the hang, a pass
// counts coverage, and a run with nothing to do says why. Blocked lines are
// counted and reported but do not outrank a pass, since a session that
// verified lines did verify them; what they must never do is disappear, so
// the count travels with every summary that has one.
func summarize(run *exampleRun) (Status, string) {
ran, skipped, gaps, blocked, synthetic, setup := 0, 0, 0, 0, 0, 0
var firstFail, firstTimeout, firstSkip, firstGap, firstBlocked string
for _, s := range run.Steps {
for _, l := range s.Lines {
switch l.Status {
case StatusVerified:
if l.Setup {
// A cd or a written file passing proves nothing about the
// document's claims, so it is counted apart from them.
setup++
continue
}
ran++
if len(l.Synthetic) > 0 {
synthetic++
}
case StatusSkipped:
skipped++
if firstSkip == "" {
firstSkip = l.Detail
}
case StatusBlocked:
blocked++
if firstBlocked == "" {
firstBlocked = fmt.Sprintf("%s %q %s", stepName(s), l.Cmd, l.Detail)
}
case StatusGap:
gaps++
if firstGap == "" {
firstGap = fmt.Sprintf("%s %q %s", stepName(s), l.Cmd, l.Detail)
}
case StatusTimeout:
if firstTimeout == "" {
firstTimeout = fmt.Sprintf("%s %q %s", stepName(s), l.Cmd, l.Detail)
}
case StatusFail:
if firstFail == "" {
firstFail = fmt.Sprintf("%s %q %s", stepName(s), l.Cmd, l.Detail)
}
}
}
}
tally := fmt.Sprintf("%d lines ran, %d skipped", ran, skipped)
if blocked > 0 {
tally += fmt.Sprintf(", %d blocked", blocked)
}
if setup > 0 {
tally += fmt.Sprintf(", %d only set up the session", setup)
}
if synthetic > 0 {
// Named on the summary line rather than only in the JSON, since the
// summary is what a reader actually reads before believing the green.
tally += fmt.Sprintf(" (%d against fabricated files)", synthetic)
}
switch {
case firstFail != "":
return StatusFail, firstFail
case firstTimeout != "":
return StatusTimeout, firstTimeout
case gaps > 0:
return StatusGap, fmt.Sprintf("%d %s, first: %s",
gaps, plural(gaps, "documentation gap", "documentation gaps"), firstGap)
case ran > 0:
return StatusVerified, tally
case blocked > 0:
// Nothing was verified and something was tried without settling. The
// session has no verdict on this document and must not imply one.
return StatusBlocked, fmt.Sprintf("%s, first: %s", tally, firstBlocked)
case setup > 0:
detail := fmt.Sprintf("%s, and no line tested a claim", tally)
if firstSkip != "" {
detail += ": " + firstSkip
}
return StatusSkipped, detail
default:
detail := "no lines runnable"
if firstSkip != "" {
detail += ": " + firstSkip
}
return StatusSkipped, detail
}
}
// plural picks the singular or plural word for n.
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
// stepName identifies a step to a reader. A session now replays every document
// a repository has, so a bare block identifier no longer says where to look:
// b41 is a different block in every document. The document leads when the step
// carries one.
func stepName(s exampleStep) string {
if s.Doc == "" {
return s.ID
}
return s.Doc + " " + s.ID
}