gunk-dev/the-valley

pre_review_prose.go

sourcecfedff357a41main's published tip history
6.1 KiB
1package cmd
2
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "io"
8 "os"
9 "strings"
10 "time"
11
12 "the-valley/flow/internal/backend"
13 "the-valley/flow/internal/config"
14 "the-valley/flow/internal/jobs"
15 "the-valley/flow/internal/prose"
16 "the-valley/flow/internal/run"
17)
18
19// startProsePass runs _pre-review's prose pass, on what HEAD changes in dir
20// since its merge base with base, beside the peer review. The function it
21// returns waits for the pass and prints its report. The pass never fails
22// _pre-review.
23func startProsePass(ctx context.Context, dir, base string, cfg config.Config, author backend.Kind, houseRules string) func(w io.Writer) {
24 pc := cfg.Prose()
25 if !*pc.Enabled {
26 return func(w io.Writer) { fmt.Fprintln(w, "Prose rewrite: off (pre_review.prose.enabled).") }
27 }
28 var out bytes.Buffer
29 done := make(chan struct{})
30 go func() {
31 defer close(done)
32 runProsePass(ctx, &out, dir, base, cfg, pc, author, houseRules)
33 }()
34 return func(w io.Writer) {
35 <-done
36 w.Write(out.Bytes())
37 fmt.Fprintln(w)
38 }
39}
40
41func runProsePass(ctx context.Context, w io.Writer, dir, base string, cfg config.Config, pc config.ProseConfig, author backend.Kind, houseRules string) {
42 // A sandbox host has no session to record the pass in.
43 var store *jobs.Store
44 if os.Getenv(runEventsEnv) != runEventsOutput {
45 if s, err := sessionStore(); err == nil {
46 if hds, ok := s.(*run.HomeDirStore); ok {
47 js := jobs.NewStore(hds.BaseDir())
48 store = &js
49 }
50 }
51 }
52 job := &jobs.Job{ID: eventID("prose"), Kind: jobs.KindProse, Dir: dir, Run: os.Getenv(runIDEnv)}
53 r := prose.Run(ctx, prose.Options{
54 Dir: dir, Base: base, Author: author,
55 Order: pc.Order, Patterns: pc.Paths, MaxInput: pc.MaxInputBytes,
56 Timeout: time.Duration(pc.TimeoutSeconds) * time.Second,
57 HouseRules: houseRules,
58 Writer: func(k backend.Kind) (string, string) { return cfg.ProseWriter(string(k)) },
59 Checker: func(k backend.Kind) (string, string) { return cfg.ProseChecker(string(k)) },
60 Started: func(r *prose.Result) {
61 if store != nil {
62 job.Backend, job.Model = r.Writer, r.WriterModel
63 names := r.Files
64 if len(names) == 0 {
65 names = []string{"commit message"}
66 }
67 job.Prompt = "rewrite " + strings.Join(names, ", ")
68 warnJob(w, job, store.Start(job))
69 }
70 },
71 })
72 fmt.Fprintf(w, "Prose rewrite (writer: %s; fact check: %s; author: %s):\n", orDash(r.Writer), orDash(r.Checker), author)
73 r.PatchFile = saveProse(w, store, job, ".patch", r.Patch)
74 r.MessageFile = saveProse(w, store, job, ".msg", r.Message)
75 if store != nil && job.Backend != "" {
76 job.Prose = r
77 status := jobs.Succeeded
78 if r.Error != "" {
79 status = jobs.Failed
80 }
81 warnJob(w, job, store.Finish(job, status, truncateLine(r.Error, 200)))
82 }
83 printProse(w, r)
84 if r.PatchFile != "" || r.MessageFile != "" || len(r.Failures) > 0 {
85 fmt.Fprintln(w, " Apply the rewrites that keep the meaning; fix or reject the rest. Say in your final report what you applied and why you rejected any.")
86 }
87}
88
89// saveProse writes a pass's patch or commit message beside its job record,
90// else in a temporary file, and returns its path; "" when there is nothing
91// to write.
92func saveProse(w io.Writer, store *jobs.Store, job *jobs.Job, ext, text string) string {
93 if text == "" {
94 return ""
95 }
96 if store != nil && job.Backend != "" {
97 path, err := store.WriteFile(job.ID, ext, []byte(text))
98 if err == nil {
99 return path
100 }
101 warnJob(w, job, err)
102 }
103 f, err := os.CreateTemp("", "klaus-prose-*"+ext)
104 if err != nil {
105 fmt.Fprintf(w, " warning: saving the %s: %v\n", ext[1:], err)
106 return ""
107 }
108 defer f.Close()
109 if _, err := f.WriteString(text); err != nil {
110 fmt.Fprintf(w, " warning: saving the %s: %v\n", ext[1:], err)
111 return ""
112 }
113 return f.Name()
114}
115
116// printProse prints a pass's proposal, for _pre-review and klaus jobs show.
117func printProse(w io.Writer, r *prose.Result) {
118 if len(r.Omitted) > 0 {
119 fmt.Fprintf(w, " Left out, past pre_review.prose.max_input_bytes: %s\n", strings.Join(r.Omitted, ", "))
120 }
121 switch {
122 case r.Skipped != "":
123 fmt.Fprintf(w, " Skipped: %s.\n", r.Skipped)
124 return
125 case r.Error != "":
126 fmt.Fprintf(w, " The rewrite failed: %s\n", r.Error)
127 return
128 case len(r.Edits) == 0:
129 fmt.Fprintln(w, " No rewrites proposed.")
130 return
131 case r.CheckError != "":
132 fmt.Fprintf(w, " The fact check failed: %s\n No rewrite passed it; check their meaning yourself.\n", r.CheckError)
133 }
134 for i, e := range r.Edits {
135 status := "passed"
136 switch {
137 case e.Skipped != "":
138 status = "skipped: " + e.Skipped
139 case r.Failed(i):
140 status = "failed the fact check"
141 case r.CheckError != "":
142 status = "not fact-checked"
143 }
144 if e.Outcome != "" {
145 status += "; " + e.Outcome
146 }
147 where := e.File
148 if where == prose.CommitFile {
149 where = "commit message"
150 }
151 fmt.Fprintf(w, " [%d] %s: %s\n", i+1, where, status)
152 for _, f := range r.Failures {
153 if f.Edit == i+1 {
154 fmt.Fprintf(w, " ✗ %s\n", failureText(f))
155 }
156 }
157 for _, l := range strings.Split(strings.TrimRight(e.Old, "\n"), "\n") {
158 fmt.Fprintf(w, " - %s\n", l)
159 }
160 for _, l := range strings.Split(strings.TrimRight(e.New, "\n"), "\n") {
161 fmt.Fprintf(w, " + %s\n", l)
162 }
163 }
164 for _, f := range r.Failures {
165 if f.Edit < 1 || f.Edit > len(r.Edits) {
166 fmt.Fprintf(w, " ✗ %s\n", failureText(f))
167 }
168 }
169 if r.PatchFile != "" {
170 fmt.Fprintf(w, " Patch of the passing rewrites: git apply %s\n", shellQuote(r.PatchFile))
171 }
172 if r.MessageFile != "" {
173 fmt.Fprintf(w, " Commit message with its passing rewrites: git commit --amend -F %s\n", shellQuote(r.MessageFile))
174 }
175}
176
177func failureText(f prose.Failure) string {
178 if f.Claim != "" {
179 return f.Claim + ": " + f.Problem
180 }
181 return f.Problem
182}
183
184func orDash(s string) string {
185 if s == "" {
186 return "-"
187 }
188 return s
189}
190
191// settleProseJobs records, in run id's prose jobs, which rewrites the
192// worktree took. Finalize calls it before removing the worktree.
193func settleProseJobs(baseDir, id, worktree string) {
194 if baseDir == "" || worktree == "" {
195 return
196 }
197 store := jobs.NewStore(baseDir)
198 list, _ := store.List()
199 for _, j := range list {
200 if j.Kind == jobs.KindProse && j.Run == id && j.Prose != nil && j.Finished() && j.Status != jobs.Died {
201 prose.Settle(worktree, j.Prose)
202 _ = store.Save(j)
203 }
204 }
205}