gunk-dev/the-valley

forbidden_terms.go

source4cbb5ec9c5dbmain's published tip history
10.7 KiB
1package cmd
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os/exec"
10 "path/filepath"
11 "regexp"
12 "sort"
13 "strconv"
14 "strings"
15
16 "the-valley/flow/internal/config"
17 "the-valley/flow/internal/git"
18 "the-valley/flow/internal/project"
19 "github.com/spf13/cobra"
20)
21
22var forbiddenTermsCmd = &cobra.Command{
23 Use: "_forbidden-terms [<base>] [<head>]",
24 Short: "Check a range for the repo's forbidden terms",
25 Long: `Checks what <base>...<head> adds to the current checkout's repo for the
26terms forbidden_terms in ~/.klaus/config.json forbids there, the scan
27_pre-review runs before an agent pushes: the lines the range adds, the
28names of files it adds or renames, and the messages of the commits in
29<base>..<head>. Each term matches case-insensitively as a literal substring;
30files under the entry's allow_paths are skipped.
31
32<head> defaults to HEAD and <base> to the default branch (origin's when it
33exists), so the range is the change since its merge base. --repo picks the
34entry, by registered project name or owner/repo, when the checkout's own
35origin or registration doesn't.
36
37Prints file:line: term for each hit (commit <sha>: term for a message) and
38exits 1 when there is one; never prints the term list itself.`,
39 Hidden: true,
40 Args: cobra.MaximumNArgs(2),
41 RunE: func(cmd *cobra.Command, args []string) error {
42 cmd.SilenceUsage = true
43 repoRef, _ := cmd.Flags().GetString("repo")
44 dir, err := git.RepoRoot()
45 if err != nil {
46 return fmt.Errorf("finding the checkout: %w", err)
47 }
48 cfg, err := config.Load(dir)
49 if err != nil {
50 return fmt.Errorf("loading config: %w", err)
51 }
52 out := cmd.OutOrStdout()
53 entries, err := forbiddenTermsFor(cfg, dir, repoRef)
54 if err != nil {
55 return err
56 }
57 if len(entries) == 0 {
58 fmt.Fprintln(out, "No forbidden terms are configured for this repo.")
59 return nil
60 }
61 base, head := defaultBranchRef(dir, cfg.DefaultBranch), "HEAD"
62 if len(args) > 0 {
63 base = args[0]
64 }
65 if len(args) > 1 {
66 head = args[1]
67 }
68 hits, err := scanForbiddenTerms(dir, base, head, entries)
69 if err != nil {
70 return err
71 }
72 printForbiddenTerms(out, hits)
73 if len(hits) > 0 {
74 return errors.New("forbidden terms found")
75 }
76 return nil
77 },
78}
79
80// forbiddenHit is one forbidden term in what a change adds: on Line of File,
81// in File's name (Line 0), or in the message of Commit.
82type forbiddenHit struct {
83 File string
84 Line int
85 Commit string
86 Term string
87}
88
89func (h forbiddenHit) String() string {
90 switch {
91 case h.Commit != "":
92 return fmt.Sprintf("commit %s: %s", h.Commit, h.Term)
93 case h.Line == 0:
94 return fmt.Sprintf("%s: %s (file name)", h.File, h.Term)
95 }
96 return fmt.Sprintf("%s:%d: %s", h.File, h.Line, h.Term)
97}
98
99// printForbiddenTerms reports hits the way _pre-review reports its other
100// checks. It names only the terms that hit, never the configured list.
101func printForbiddenTerms(w io.Writer, hits []forbiddenHit) {
102 if len(hits) == 0 {
103 fmt.Fprintln(w, " โœ“ no forbidden terms added")
104 return
105 }
106 label := "term"
107 if len(hits) > 1 {
108 label = "terms"
109 }
110 fmt.Fprintf(w, " โœ— %d forbidden %s added โ€” replace each with a neutral name:\n", len(hits), label)
111 for _, h := range hits {
112 fmt.Fprintf(w, " %s\n", h)
113 }
114}
115
116// forbiddenTermsFor returns the forbidden_terms entries for the repo checked
117// out in dir, or for repoRef when it is set. A key is a registered project
118// name or owner/repo; it names the repo when it is repoRef itself, when it is
119// owner/repo and the repo's origin is that GitHub repo, or when it is a
120// registered project that shares the repo's git directory or origin. Every
121// entry that names the repo applies, each with its own allow_paths. A
122// registry at both its names is an error: it would leave out the entries
123// that name a project.
124func forbiddenTermsFor(cfg config.Config, dir, repoRef string) ([]config.ForbiddenTermsConfig, error) {
125 if len(cfg.ForbiddenTerms) == 0 {
126 return nil, nil
127 }
128 reg, err := registryUnlessConflict()
129 if err != nil {
130 return nil, err
131 }
132 slug, common := repoSlugForDir(dir), gitCommonDir(dir)
133 if repoRef != "" {
134 slug, common = repoSlug(repoRef), ""
135 if reg != nil {
136 if p, ok := reg.Get(repoRef); ok {
137 slug, common = repoSlugForDir(p), gitCommonDir(p)
138 }
139 }
140 }
141 keys := make([]string, 0, len(cfg.ForbiddenTerms))
142 for k := range cfg.ForbiddenTerms {
143 keys = append(keys, k)
144 }
145 sort.Strings(keys)
146 var entries []config.ForbiddenTermsConfig
147 for _, key := range keys {
148 if repoRef != "" && strings.EqualFold(key, repoRef) || forbiddenKeyNames(key, slug, common, reg) {
149 entries = append(entries, cfg.ForbiddenTerms[key])
150 }
151 }
152 return entries, nil
153}
154
155// forbiddenKeyNames reports whether key names the repo with origin slug and
156// git common directory common (either may be "").
157func forbiddenKeyNames(key, slug, common string, reg *project.Registry) bool {
158 if strings.Contains(key, "/") {
159 return slug != "" && strings.EqualFold(repoSlug(key), slug)
160 }
161 if reg == nil {
162 return false
163 }
164 p, ok := reg.Get(key)
165 if !ok {
166 return false
167 }
168 if common != "" && gitCommonDir(p) == common {
169 return true
170 }
171 return slug != "" && strings.EqualFold(repoSlugForDir(p), slug)
172}
173
174// gitCommonDir returns the absolute git common directory of the checkout at
175// dir, the same for all its worktrees, or "" when dir is not a checkout.
176func gitCommonDir(dir string) string {
177 if dir == "" {
178 return ""
179 }
180 out, err := exec.Command("git", "-C", dir, "rev-parse", "--path-format=absolute", "--git-common-dir").Output()
181 if err != nil {
182 return ""
183 }
184 p := strings.TrimSpace(string(out))
185 if resolved, err := filepath.EvalSymlinks(p); err == nil {
186 p = resolved
187 }
188 return p
189}
190
191// defaultBranchRef returns the ref of the default branch to diff a change
192// against: origin's, which worktrees start from, when dir has it, else the
193// local branch.
194func defaultBranchRef(dir, branch string) string {
195 if branch == "" {
196 branch = "main"
197 }
198 if git.RefExists(context.Background(), dir, "refs/remotes/origin/"+branch) {
199 return "origin/" + branch
200 }
201 return branch
202}
203
204// scanForbiddenTerms returns the forbidden terms of entries in what
205// base...head adds in dir: added lines and added or renamed file names,
206// outside each entry's allow_paths, and the messages of base..head's
207// commits. Deleted lines don't count.
208func scanForbiddenTerms(dir, base, head string, entries []config.ForbiddenTermsConfig) ([]forbiddenHit, error) {
209 termsFor := func(path string) []string {
210 var terms []string
211 for _, e := range entries {
212 if !allowedPath(path, e.AllowPaths) {
213 terms = append(terms, e.Terms...)
214 }
215 }
216 return terms
217 }
218 var hits []forbiddenHit
219
220 names, err := gitForbiddenScan(dir, "diff", "--name-only", "-z", "--diff-filter=AR", "--no-relative", base+"..."+head)
221 if err != nil {
222 return nil, err
223 }
224 for _, name := range strings.Split(strings.TrimRight(names, "\x00"), "\x00") {
225 for _, t := range matchTerms(name, termsFor(name)) {
226 hits = append(hits, forbiddenHit{File: name, Term: t})
227 }
228 }
229
230 // --text: a file git takes for binary, or one .gitattributes marks -diff,
231 // still has its lines scanned. --no-renames: a file moved out of
232 // allow_paths adds all its lines at its new path.
233 diff, err := gitForbiddenScan(dir, "diff", "--unified=0", "--text", "--no-renames", "--no-color", "--no-ext-diff", "--no-textconv", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", base+"..."+head)
234 if err != nil {
235 return nil, err
236 }
237 for _, l := range addedLines(diff) {
238 for _, t := range matchTerms(l.text, termsFor(l.file)) {
239 hits = append(hits, forbiddenHit{File: l.file, Line: l.line, Term: t})
240 }
241 }
242
243 var all []string
244 for _, e := range entries {
245 all = append(all, e.Terms...)
246 }
247 log, err := gitForbiddenScan(dir, "log", "-z", "--format=%h%n%B", base+".."+head)
248 if err != nil {
249 return nil, err
250 }
251 for _, c := range strings.Split(strings.TrimRight(log, "\x00"), "\x00") {
252 sha, msg, _ := strings.Cut(c, "\n")
253 for _, t := range matchTerms(msg, all) {
254 hits = append(hits, forbiddenHit{Commit: sha, Term: t})
255 }
256 }
257 return hits, nil
258}
259
260func gitForbiddenScan(dir string, args ...string) (string, error) {
261 c := exec.Command("git", append([]string{"-C", dir}, args...)...)
262 var stdout, stderr bytes.Buffer
263 c.Stdout, c.Stderr = &stdout, &stderr
264 if err := c.Run(); err != nil {
265 return "", fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(stderr.String()))
266 }
267 return stdout.String(), nil
268}
269
270// matchTerms returns the terms s contains, ignoring case. A term is a
271// literal: its dots are dots.
272func matchTerms(s string, terms []string) []string {
273 var found []string
274 lower := strings.ToLower(s)
275 for _, t := range terms {
276 if strings.TrimSpace(t) != "" && strings.Contains(lower, strings.ToLower(t)) {
277 found = append(found, t)
278 }
279 }
280 return found
281}
282
283// allowedPath reports whether path is one of allow, or under one that is a
284// directory.
285func allowedPath(path string, allow []string) bool {
286 for _, a := range allow {
287 a = strings.TrimSuffix(strings.TrimPrefix(a, "./"), "/")
288 if a != "" && (path == a || strings.HasPrefix(path, a+"/")) {
289 return true
290 }
291 }
292 return false
293}
294
295type addedLine struct {
296 file string
297 line int
298 text string
299}
300
301var zeroContextHunk = regexp.MustCompile(`^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@`)
302
303// addedLines returns the lines a unified diff adds, with their new-side line
304// numbers. Hunk counts, not prefixes, mark a hunk's end, so an added line
305// that begins "++ " isn't taken for a file header.
306func addedLines(diff string) []addedLine {
307 var lines []addedLine
308 var file string
309 var line, oldLeft, newLeft int
310 for _, l := range strings.Split(diff, "\n") {
311 if oldLeft > 0 || newLeft > 0 {
312 switch {
313 case strings.HasPrefix(l, "-"):
314 oldLeft--
315 case strings.HasPrefix(l, "+"):
316 if file != "" {
317 lines = append(lines, addedLine{file: file, line: line, text: l[1:]})
318 }
319 line++
320 newLeft--
321 case strings.HasPrefix(l, `\`): // "\ No newline at end of file"
322 default:
323 line++
324 oldLeft--
325 newLeft--
326 }
327 continue
328 }
329 switch {
330 case strings.HasPrefix(l, "diff --git "):
331 file = ""
332 case strings.HasPrefix(l, "+++ "):
333 // git ends an unquoted path that has a space with a tab.
334 path := strings.TrimSuffix(strings.TrimPrefix(l, "+++ "), "\t")
335 if path == "/dev/null" {
336 file = ""
337 continue
338 }
339 if uq, err := strconv.Unquote(path); err == nil {
340 path = uq
341 }
342 file = strings.TrimPrefix(path, "b/")
343 default:
344 if m := zeroContextHunk.FindStringSubmatch(l); m != nil {
345 oldLeft, newLeft = hunkLen(m[1]), hunkLen(m[3])
346 line, _ = strconv.Atoi(m[2])
347 }
348 }
349 }
350 return lines
351}
352
353// hunkLen reads a hunk header's line count, which is 1 when omitted.
354func hunkLen(s string) int {
355 if s == "" {
356 return 1
357 }
358 n, _ := strconv.Atoi(s)
359 return n
360}
361
362func init() {
363 forbiddenTermsCmd.Flags().String("repo", "", "Repo whose forbidden_terms entry applies: a registered project name or owner/repo (default: the checkout's)")
364 rootCmd.AddCommand(forbiddenTermsCmd)
365}