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