Repository navigation
Expand file tree
/
Copy pathrun.go
More file actions
454 lines (423 loc) · 12.5 KB
/
Copy pathrun.go
File metadata and controls
454 lines (423 loc) · 12.5 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
// Code generated by litgo from litgo.lit.md; DO NOT EDIT.
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/tlehman/litgo/internal/lit"
"github.com/tlehman/litgo/internal/vego"
)
// reporter carries the run's progress to a person (plain text) or to an
// editor (one JSON event per line). It belongs to one goroutine.
type reporter struct {
json bool
seen map[string]bool
}
func (r *reporter) emit(event string, fields map[string]any) {
if !r.json {
return
}
fields["event"] = event
b, _ := json.Marshal(fields)
fmt.Println(string(b))
}
func (r *reporter) diag(d lit.Diag) {
key := fmt.Sprintf("%s:%d:%d:%s", d.File, d.Line, d.Col, d.Message)
if r.seen[key] {
return
}
r.seen[key] = true
if r.json {
b, _ := json.Marshal(d)
var fields map[string]any
json.Unmarshal(b, &fields)
r.emit("diagnostic", fields)
return
}
sev := map[int]string{lit.SevError: "error", lit.SevWarning: "warning", lit.SevInfo: "note"}[d.Severity]
fmt.Fprintf(os.Stderr, "%s:%d:%d: %s: %s\n", relPath(d.File), d.Line+1, d.Col+1, sev, d.Message)
}
func (r *reporter) output(stream, text string) {
if r.json {
r.emit("output", map[string]any{"stream": stream, "text": text})
return
}
if stream == "stderr" {
fmt.Fprintln(os.Stderr, text)
} else {
fmt.Println(text)
}
}
func (r *reporter) status(format string, args ...any) {
if !r.json {
fmt.Fprintf(os.Stderr, "litgo: "+format+"\n", args...)
}
}
func relPath(p string) string {
if wd, err := os.Getwd(); err == nil {
if rel, err := filepath.Rel(wd, p); err == nil && !strings.HasPrefix(rel, "..") {
return rel
}
}
return p
}
// remapper rewrites positions in tangled files back to the literate source.
type remapper struct {
dir string
outputs map[string]*mapped // by absolute output path
}
// mapped is a tangled file together with the document it came from.
type mapped struct {
*lit.Output
doc *lit.Doc
}
var posRe = regexp.MustCompile(`((?:[A-Za-z]:)?[\w./\\-]*\.go):(\d+)(?::(\d+))?`)
// lookup finds the tangled file a tool is talking about. Compilers name
// files relative to where they ran; `go test` names them relative to the
// package, so a bare file name is matched if it is unambiguous.
func (m *remapper) lookup(path string) *mapped {
abs := path
if !filepath.IsAbs(abs) {
abs = filepath.Join(m.dir, abs)
}
if o := m.outputs[filepath.Clean(abs)]; o != nil || filepath.Base(path) != path {
return o
}
var found *mapped
for p, o := range m.outputs {
if filepath.Base(p) == path {
if found != nil {
return nil
}
found = o
}
}
return found
}
// line rewrites every `file.go:line:col` in a line of tool output and returns
// the first position it translated.
func (m *remapper) line(s string) (string, *lit.Diag) {
var first *lit.Diag
out := posRe.ReplaceAllStringFunc(s, func(match string) string {
g := posRe.FindStringSubmatch(match)
res := m.lookup(g[1])
if res == nil {
return match
}
ln, _ := strconv.Atoi(g[2])
col := 1
if g[3] != "" {
col, _ = strconv.Atoi(g[3])
}
srcLine, srcCol, _, ok := res.Map(ln-1, col-1)
if !ok {
return match
}
if first == nil {
first = &lit.Diag{File: res.doc.Path, Line: srcLine, Col: srcCol}
}
if g[3] == "" {
return fmt.Sprintf("%s:%d", relPath(res.doc.Path), srcLine+1)
}
return fmt.Sprintf("%s:%d:%d", relPath(res.doc.Path), srcLine+1, srcCol+1)
})
return out, first
}
var compilerLineRe = regexp.MustCompile(`^(?:\./)?([^\s:]+\.go):(\d+)(?::(\d+))?:\s+(.*)$`)
// toolOutput turns compiler or vet output into diagnostics, and reports
// whatever it could not place (linker errors, package-level complaints).
func (m *remapper) toolOutput(out []byte, sev int, source string, r *reporter) {
var last *lit.Diag
flush := func() {
if last != nil {
r.diag(*last)
last = nil
}
}
for _, raw := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
if raw == "" || strings.HasPrefix(raw, "# ") {
continue
}
if g := compilerLineRe.FindStringSubmatch(raw); g != nil {
flush()
if _, pos := m.line(g[1] + ":" + g[2] + ":" + firstNonEmpty(g[3], "1")); pos != nil {
msg, _ := m.line(g[4])
pos.Severity, pos.Message, pos.Source = sev, msg, source
last = pos
continue
}
}
if last != nil && (strings.HasPrefix(raw, "\t") || strings.HasPrefix(raw, " ")) {
cont, _ := m.line(strings.TrimSpace(raw))
last.Message += "\n" + cont
continue
}
flush()
text, _ := m.line(raw)
r.output("stderr", text)
}
flush()
}
func firstNonEmpty(a, b string) string {
if a != "" {
return a
}
return b
}
// writeTangled writes a file unless that would clobber a hand-written one.
func writeTangled(o *lit.Output, force bool) error {
if old, err := os.ReadFile(o.Path); err == nil {
if bytes.Equal(old, o.Bytes()) {
return nil // leave the timestamp alone so builds stay cached
}
if !force && !lit.Generated(old) && len(bytes.TrimSpace(old)) > 0 && lit.CommentsFor(o.File.Lang).Line != "" {
return fmt.Errorf("%s exists and was not generated by litgo; use --force to overwrite it, or tangle to another <!-- file: ... -->", relPath(o.Path))
}
}
if err := os.MkdirAll(filepath.Dir(o.Path), 0o755); err != nil {
return err
}
return os.WriteFile(o.Path, o.Bytes(), 0o644)
}
type runOptions struct {
json bool
force bool
vet bool
noProve bool
timeout time.Duration
args []string
}
// runFile is the feedback loop: tangle, compile, run, with every position in
// every message pointing at the .lit.md source.
func runFile(path string, o runOptions) int {
r := &reporter{json: o.json, seen: map[string]bool{}}
abs, err := filepath.Abs(path)
if err != nil {
return fail(r, err)
}
dir := filepath.Dir(abs)
src, err := os.ReadFile(abs)
if err != nil {
return fail(r, err)
}
doc := lit.Parse(abs, src)
// A custom run command may build a whole package, so tangle the siblings too.
docs := []*lit.Doc{doc}
if doc.Run != "" {
siblings, _ := filepath.Glob(filepath.Join(dir, "*.lit.md"))
for _, s := range siblings {
if s == abs {
continue
}
if b, err := os.ReadFile(s); err == nil {
docs = append(docs, lit.Parse(s, b))
}
}
}
m := &remapper{dir: dir, outputs: map[string]*mapped{}}
ok, unproved := true, false
for _, d := range docs {
res := d.Tangle()
for _, dg := range res.Diags {
r.diag(dg)
}
if res.HasErrors() {
ok = false
continue
}
for _, out := range res.Files {
if err := writeTangled(out, o.force); err != nil {
r.diag(lit.Diag{File: d.Path, Line: max(out.File.Line, 0), Severity: lit.SevError, Message: err.Error(), Source: "litgo"})
ok = false
continue
}
m.outputs[filepath.Clean(out.Path)] = &mapped{out, d}
}
if n := len(res.Files); n == 1 {
r.emit("tangle", map[string]any{"file": d.Path, "out": res.Files[0].Path})
r.status("tangled %s → %s", relPath(d.Path), relPath(res.Files[0].Path))
} else if n > 1 {
r.emit("tangle", map[string]any{"file": d.Path, "out": fmt.Sprintf("%d files", n)})
r.status("tangled %s → %d files", relPath(d.Path), n)
}
if !o.noProve {
start := time.Now()
proofs, sum := vego.Prove(res)
for _, dg := range proofs {
r.diag(dg)
if dg.Severity == lit.SevError {
ok, unproved = false, true
}
}
if sum.Functions > 0 {
r.emit("prove", map[string]any{"file": d.Path, "functions": sum.Functions, "proved": sum.Proved,
"obligations": sum.Obligations, "ms": time.Since(start).Milliseconds()})
r.status("proved %d of %d annotated functions in %s (%d obligations, %d ms)", sum.Proved, sum.Functions,
relPath(d.Path), sum.Obligations, time.Since(start).Milliseconds())
}
}
}
if !ok {
stage := "tangle"
if unproved {
stage = "prove"
r.status("not proved, so not run (--no-prove runs it anyway)")
}
r.emit("build", map[string]any{"ok": false, "ms": 0, "stage": stage})
return 1
}
// A document that writes several files is a package or a module, and
// only it knows how it is built
command := doc.Run
if command == "" && len(doc.Files) > 1 {
command = "go build ./..."
}
if command != "" {
r.status("$ %s", command)
return execute(r, m, exec.Command("sh", "-c", command), dir, o.timeout, true)
}
def := doc.Files[0]
main := m.outputs[filepath.Clean(doc.OutPath(def))]
if def.Lang != "go" || main == nil {
r.status("no run step for tangler %q; add <!-- run: command -->", def.Lang)
r.emit("build", map[string]any{"ok": true, "ms": 0})
return 0
}
tmp, err := os.MkdirTemp("", "litgo-run")
if err != nil {
return fail(r, err)
}
defer os.RemoveAll(tmp)
bin := filepath.Join(tmp, "prog")
start := time.Now()
build := exec.Command("go", "build", "-gcflags=-e", "-o", bin, filepath.Base(main.Path))
build.Dir = dir
out, err := build.CombinedOutput()
ms := time.Since(start).Milliseconds()
m.toolOutput(out, lit.SevError, "go build", r)
if err != nil {
r.emit("build", map[string]any{"ok": false, "ms": ms, "stage": "compile"})
r.status("build failed (%d ms)", ms)
return 1
}
r.emit("build", map[string]any{"ok": true, "ms": ms})
r.status("built in %d ms", ms)
if o.vet {
vet := exec.Command("go", "vet", filepath.Base(main.Path))
vet.Dir = dir
out, _ := vet.CombinedOutput()
m.toolOutput(out, lit.SevWarning, "go vet", r)
}
if def.Package != "main" && def.Package != "" {
r.status("package %s compiles; nothing to run", def.Package)
r.emit("exit", map[string]any{"code": 0, "ms": 0, "ran": false})
return 0
}
return execute(r, m, exec.Command(bin, o.args...), dir, o.timeout, false)
}
func fail(r *reporter, err error) int {
r.diag(lit.Diag{Severity: lit.SevError, Message: err.Error(), Source: "litgo"})
return 1
}
var (
frameRe = regexp.MustCompile(`^\s+(\S+\.go):(\d+)`)
// reportRe is looser than compilerLineRe: `go test` indents its failures.
reportRe = regexp.MustCompile(`^\s*(?:\./)?[^\s:]+\.go:\d+(?::\d+)?:\s+(.*)$`)
)
// outputLine is one line of a program's output, or the end of a stream.
type outputLine struct {
stream, text string
eof bool
}
// pump sends the lines of one of a program's streams, and then its end.
func pump(stream string, rd io.Reader, lines chan<- outputLine) {
sc := bufio.NewScanner(rd)
sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
for sc.Scan() {
lines <- outputLine{stream: stream, text: sc.Text()}
}
lines <- outputLine{stream: stream, eof: true}
}
// execute streams a program's output, translating positions as it goes. A
// panic becomes a diagnostic on the innermost frame that lives in the
// literate source.
func execute(r *reporter, m *remapper, cmd *exec.Cmd, dir string, timeout time.Duration, parseTools bool) int {
cmd.Dir = dir
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
ownGroup(cmd)
start := time.Now()
if err := cmd.Start(); err != nil {
return fail(r, err)
}
defer killOnSignal(cmd)()
var timeUp <-chan time.Time // stays nil, which never delivers, without a timeout
if timeout > 0 {
timer := time.NewTimer(timeout)
defer timer.Stop()
timeUp = timer.C
}
lines := make(chan outputLine)
go pump("stdout", stdout, lines)
go pump("stderr", stderr, lines)
timedOut := false
var panicMsg string
panicPlaced := false
for open := 2; open > 0; {
select {
case <-timeUp:
timedOut = true
killGroup(cmd)
case l := <-lines:
if l.eof {
open--
continue
}
raw := l.text
text, pos := m.line(raw)
if l.stream == "stderr" {
switch {
case strings.HasPrefix(raw, "panic: ") || strings.HasPrefix(raw, "fatal error: "):
panicMsg, panicPlaced = raw, false
case panicMsg != "" && !panicPlaced && pos != nil && frameRe.MatchString(raw):
pos.Severity, pos.Message, pos.Source = lit.SevError, panicMsg, "runtime"
r.diag(*pos)
panicPlaced = true
case parseTools && pos != nil && reportRe.MatchString(raw):
msg, _ := m.line(reportRe.FindStringSubmatch(raw)[1])
pos.Severity, pos.Message, pos.Source = lit.SevError, msg, "run"
r.diag(*pos)
}
} else if parseTools && pos != nil && reportRe.MatchString(raw) {
msg, _ := m.line(reportRe.FindStringSubmatch(raw)[1])
pos.Severity, pos.Message, pos.Source = lit.SevError, msg, "run"
r.diag(*pos)
}
r.output(l.stream, text)
}
}
err := cmd.Wait()
code := 0
if err != nil {
code = 1
if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() >= 0 {
code = ee.ExitCode()
}
}
ms := time.Since(start).Milliseconds()
if timedOut {
r.output("stderr", fmt.Sprintf("litgo: killed after %s", timeout))
}
r.emit("exit", map[string]any{"code": code, "ms": ms, "ran": true, "timed_out": timedOut})
r.status("exit %d (%d ms)", code, ms)
return code
}