| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path" |
| 13 | "path/filepath" |
| 14 | "regexp" |
| 15 | "runtime" |
| 16 | "slices" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "time" |
| 21 | "unicode" |
| 22 | "unicode/utf8" |
| 23 | |
| 24 | "amadan.net/oficina/equipo/internal/runner/checks" |
| 25 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 26 | "amadan.net/oficina/equipo/internal/wire" |
| 27 | ) |
| 28 | |
| 29 | // Read tool bounds: the model gets enough to answer, never a whole repo. |
| 30 | const ( |
| 31 | maxSearchLines = 60 |
| 32 | maxReadLines = 300 |
| 33 | maxToolOutput = 16 << 10 |
| 34 | indexEvery = time.Hour |
| 35 | ) |
| 36 | |
| 37 | // Index is the runner's context catalog: for every repository the agent |
| 38 | // can reach, what it is called and what it is, from a shallow clone of |
| 39 | // its default branch. Only names and short summaries leave the runner. |
| 40 | type Index struct { |
| 41 | Forge Forge |
| 42 | Clones *Clones |
| 43 | Path string |
| 44 | Logger *slog.Logger |
| 45 | // Changed is called after a refresh changed the catalog. |
| 46 | Changed func() |
| 47 | // Refreshed is called after every completed refresh. |
| 48 | Refreshed func() |
| 49 | // Pace spaces fetches: the hub rate-limits one agent's git requests, |
| 50 | // and the production runner shares that agent. |
| 51 | Pace time.Duration |
| 52 | |
| 53 | mu sync.Mutex |
| 54 | catalog []wire.RepoInfo |
| 55 | settled bool |
| 56 | kick chan struct{} |
| 57 | } |
| 58 | |
| 59 | func (x *Index) kicks() chan struct{} { |
| 60 | x.mu.Lock() |
| 61 | defer x.mu.Unlock() |
| 62 | if x.kick == nil { |
| 63 | x.kick = make(chan struct{}, 1) |
| 64 | } |
| 65 | return x.kick |
| 66 | } |
| 67 | |
| 68 | // Kick asks the loop for a delta refresh now: what the agent reaches |
| 69 | // changed, so only new repositories are fetched. |
| 70 | func (x *Index) Kick() { |
| 71 | select { |
| 72 | case x.kicks() <- struct{}{}: |
| 73 | default: |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | // Ready reports whether a refresh completed in this process: before it, |
| 78 | // a fresh runner's catalog may be empty or out of date. |
| 79 | func (x *Index) Ready() bool { |
| 80 | x.mu.Lock() |
| 81 | defer x.mu.Unlock() |
| 82 | return x.settled |
| 83 | } |
| 84 | |
| 85 | // Catalog is the current catalog, newest refresh. |
| 86 | func (x *Index) Catalog() []wire.RepoInfo { |
| 87 | x.mu.Lock() |
| 88 | defer x.mu.Unlock() |
| 89 | if x.catalog == nil && x.Path != "" { |
| 90 | raw, err := os.ReadFile(x.Path) |
| 91 | if err == nil { |
| 92 | _ = json.Unmarshal(raw, &x.catalog) |
| 93 | } |
| 94 | } |
| 95 | return slices.Clone(x.catalog) |
| 96 | } |
| 97 | |
| 98 | // Loop refreshes the catalog now and hourly, and a delta when kicked. |
| 99 | func (x *Index) Loop(ctx context.Context) { |
| 100 | kick := x.kicks() |
| 101 | for { |
| 102 | x.Refresh(ctx) |
| 103 | full := time.After(indexEvery) |
| 104 | wait: |
| 105 | for { |
| 106 | select { |
| 107 | case <-ctx.Done(): |
| 108 | return |
| 109 | case <-full: |
| 110 | break wait |
| 111 | case <-kick: |
| 112 | x.Delta(ctx) |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | // Delta drops what the agent no longer reaches and fetches only what is |
| 119 | // new, or was empty (its first commit may have arrived), keeping every |
| 120 | // other entry as it is. |
| 121 | func (x *Index) Delta(ctx context.Context) { |
| 122 | repos := x.Forge.Reachable(ctx) |
| 123 | if len(repos) > wire.MaxCatalog { |
| 124 | repos = repos[:wire.MaxCatalog] |
| 125 | } |
| 126 | have := map[string]bool{} |
| 127 | empty := map[string]wire.RepoInfo{} |
| 128 | var out []wire.RepoInfo |
| 129 | for _, e := range x.Catalog() { |
| 130 | switch { |
| 131 | case !slices.Contains(repos, e.Repo): |
| 132 | case e.Empty: |
| 133 | empty[e.Repo] = e |
| 134 | default: |
| 135 | out = append(out, e) |
| 136 | have[e.Repo] = true |
| 137 | } |
| 138 | } |
| 139 | first := true |
| 140 | for _, repo := range repos { |
| 141 | if have[repo] { |
| 142 | continue |
| 143 | } |
| 144 | if !first && x.Pace > 0 { |
| 145 | select { |
| 146 | case <-ctx.Done(): |
| 147 | case <-time.After(x.Pace): |
| 148 | } |
| 149 | } |
| 150 | first = false |
| 151 | if ctx.Err() != nil { |
| 152 | return |
| 153 | } |
| 154 | e, err := x.entry(ctx, repo) |
| 155 | if err != nil { |
| 156 | if x.Logger != nil { |
| 157 | x.Logger.Warn("index", "repo", repo, "err", sanitize(err)) |
| 158 | } |
| 159 | if prev, ok := empty[repo]; ok { |
| 160 | out = append(out, prev) |
| 161 | } |
| 162 | continue |
| 163 | } |
| 164 | out = append(out, e) |
| 165 | } |
| 166 | slices.SortFunc(out, func(a, b wire.RepoInfo) int { return strings.Compare(a.Repo, b.Repo) }) |
| 167 | x.publish(out) |
| 168 | } |
| 169 | |
| 170 | // Refresh fetches each reachable repository's tip and rebuilds its entry. |
| 171 | // A repository that cannot be fetched keeps its previous entry. |
| 172 | func (x *Index) Refresh(ctx context.Context) { |
| 173 | old := map[string]wire.RepoInfo{} |
| 174 | for _, e := range x.Catalog() { |
| 175 | old[e.Repo] = e |
| 176 | } |
| 177 | repos := x.Forge.Reachable(ctx) |
| 178 | if len(repos) > wire.MaxCatalog { |
| 179 | repos = repos[:wire.MaxCatalog] |
| 180 | } |
| 181 | out := make([]wire.RepoInfo, 0, len(repos)) |
| 182 | for i, repo := range repos { |
| 183 | if i > 0 && x.Pace > 0 { |
| 184 | select { |
| 185 | case <-ctx.Done(): |
| 186 | case <-time.After(x.Pace): |
| 187 | } |
| 188 | } |
| 189 | if ctx.Err() != nil { |
| 190 | return |
| 191 | } |
| 192 | e, err := x.entry(ctx, repo) |
| 193 | if err != nil { |
| 194 | if x.Logger != nil { |
| 195 | x.Logger.Warn("index", "repo", repo, "err", sanitize(err)) |
| 196 | } |
| 197 | if prev, ok := old[repo]; ok { |
| 198 | out = append(out, prev) |
| 199 | } |
| 200 | continue |
| 201 | } |
| 202 | out = append(out, e) |
| 203 | } |
| 204 | x.publish(out) |
| 205 | } |
| 206 | |
| 207 | // publish installs a new catalog and tells the runner. |
| 208 | func (x *Index) publish(out []wire.RepoInfo) { |
| 209 | if out == nil { |
| 210 | out = []wire.RepoInfo{} |
| 211 | } |
| 212 | x.mu.Lock() |
| 213 | changed := !sameCatalog(x.catalog, out) |
| 214 | x.catalog, x.settled = out, true |
| 215 | x.mu.Unlock() |
| 216 | if x.Path != "" { |
| 217 | raw, _ := json.Marshal(out) |
| 218 | if os.WriteFile(x.Path+".tmp", raw, 0600) == nil { |
| 219 | _ = os.Rename(x.Path+".tmp", x.Path) |
| 220 | } |
| 221 | } |
| 222 | if changed && x.Changed != nil { |
| 223 | x.Changed() |
| 224 | } |
| 225 | if x.Refreshed != nil { |
| 226 | x.Refreshed() |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | func sameCatalog(a, b []wire.RepoInfo) bool { |
| 231 | x, _ := json.Marshal(a) |
| 232 | y, _ := json.Marshal(b) |
| 233 | return bytes.Equal(x, y) |
| 234 | } |
| 235 | |
| 236 | func (x *Index) entry(ctx context.Context, repo string) (wire.RepoInfo, error) { |
| 237 | fctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| 238 | defer cancel() |
| 239 | branch, err := x.Clones.DefaultBranch(fctx, repo) |
| 240 | if errors.Is(err, ErrEmptyRepo) { |
| 241 | // Reachable, nothing pushed yet: listed by name, so the |
| 242 | // coordinator can say it is empty rather than out of reach. |
| 243 | return wire.RepoInfo{Repo: repo, Names: bounded([]string{path.Base(repo)}, wire.MaxRepoNames), Hints: []string{}, Empty: true}, nil |
| 244 | } |
| 245 | if err != nil { |
| 246 | return wire.RepoInfo{}, err |
| 247 | } |
| 248 | if err = x.Clones.Shallow(fctx, repo, branch); err != nil { |
| 249 | return wire.RepoInfo{}, err |
| 250 | } |
| 251 | return x.describe(ctx, repo, branch, x.Clones.Path(repo)), nil |
| 252 | } |
| 253 | |
| 254 | // describe reads one clone's default branch: its newest commit, names, |
| 255 | // hints, the checks gate and whether this runner can run it. |
| 256 | func (x *Index) describe(ctx context.Context, repo, branch, dir string) wire.RepoInfo { |
| 257 | e := wire.RepoInfo{Repo: repo, DefaultBranch: branch, Names: []string{}, Hints: []string{}} |
| 258 | if out, err := x.git(ctx, dir, "log", "-1", "--format=%ct%x00%H%x00%s", "HEAD"); err == nil { |
| 259 | if f := strings.SplitN(strings.TrimSpace(string(out)), "\x00", 3); len(f) == 3 { |
| 260 | if sec, err := strconv.ParseInt(f[0], 10, 64); err == nil { |
| 261 | e.UpdatedAt = time.Unix(sec, 0).UTC() |
| 262 | } |
| 263 | if objectName.MatchString(f[1]) { |
| 264 | e.HeadSHA = f[1] |
| 265 | } |
| 266 | e.HeadSubject = clip(strings.ToValidUTF8(f[2], ""), wire.MaxRepoString) |
| 267 | } |
| 268 | } |
| 269 | files, _ := x.git(ctx, dir, "ls-tree", "-r", "--name-only", "HEAD") |
| 270 | list := strings.Split(string(files), "\n") |
| 271 | read := func(name string) string { |
| 272 | if !slices.Contains(list, name) { |
| 273 | return "" |
| 274 | } |
| 275 | out, err := x.git(ctx, dir, "cat-file", "blob", "HEAD:"+name) |
| 276 | if err != nil || len(out) > 256<<10 { |
| 277 | return "" |
| 278 | } |
| 279 | return string(out) |
| 280 | } |
| 281 | readme, agents := read("README.md"), read("AGENTS.md") |
| 282 | e.Summary = summary(readme) |
| 283 | if e.Summary == "" { |
| 284 | e.Summary = summary(agents) |
| 285 | } |
| 286 | names := []string{path.Base(repo)} |
| 287 | names = append(names, headings(readme)...) |
| 288 | names = append(names, headings(agents)...) |
| 289 | names = append(names, manifestNames(read)...) |
| 290 | names = append(names, productNames(readme+"\n"+agents)...) |
| 291 | names = append(names, appNames(list)...) |
| 292 | e.Names = bounded(names, wire.MaxRepoNames) |
| 293 | e.Hints = bounded(hints(list, read), wire.MaxRepoHints) |
| 294 | var gateText string |
| 295 | e.Gate, gateText = listedGate(list, read) |
| 296 | if runtime.GOOS != "darwin" && checks.NeedsMacOS(list, gateText) { |
| 297 | e.ChecksReason = "needs_macos" |
| 298 | } |
| 299 | // Protocol 2: what the instance places checks by. |
| 300 | e.NeedsMacOS, e.Simulator = checks.NeedsMacOS(nil, gateText), sharedScheme(list) |
| 301 | return e |
| 302 | } |
| 303 | |
| 304 | // listedGate is the checks gate a tree holds, in Amadan's order (as |
| 305 | // findGate finds it in a checked-out tree), and the text of its files. |
| 306 | func listedGate(list []string, read func(string) string) (name, text string) { |
| 307 | var ciD strings.Builder |
| 308 | for _, f := range list { |
| 309 | if rest, ok := strings.CutPrefix(f, ".amadan/ci.d/"); ok && rest != "" && !strings.Contains(rest, "/") { |
| 310 | ciD.WriteString(read(f) + "\n") |
| 311 | name = ".amadan/ci.d" |
| 312 | } |
| 313 | } |
| 314 | if name != "" { |
| 315 | return name, ciD.String() |
| 316 | } |
| 317 | if slices.Contains(list, ".amadan/ci") { |
| 318 | return ".amadan/ci", read(".amadan/ci") |
| 319 | } |
| 320 | for _, f := range []string{"GNUmakefile", "makefile", "Makefile"} { |
| 321 | if s := read(f); s != "" && makeCI.MatchString(s) { |
| 322 | return "make ci", s |
| 323 | } |
| 324 | } |
| 325 | return "", "" |
| 326 | } |
| 327 | |
| 328 | // sharedScheme reports whether a tree has a shared Xcode scheme: its |
| 329 | // checks need the iOS simulator. |
| 330 | func sharedScheme(list []string) bool { |
| 331 | for _, f := range list { |
| 332 | if strings.Contains(f, "/xcshareddata/xcschemes/") && strings.HasSuffix(f, ".xcscheme") { |
| 333 | return true |
| 334 | } |
| 335 | } |
| 336 | return false |
| 337 | } |
| 338 | |
| 339 | func (x *Index) git(ctx context.Context, dir string, args ...string) ([]byte, error) { |
| 340 | return readGit(ctx, x.Clones.Git, dir, args...) |
| 341 | } |
| 342 | |
| 343 | // Read limits for git on a clone: time per command and bytes of output. |
| 344 | const ( |
| 345 | readTimeout = 20 * time.Second |
| 346 | readLimit = 1 << 20 |
| 347 | ) |
| 348 | |
| 349 | // readOnly are the overrides every read runs with. Command-line config |
| 350 | // outranks the clone's own config, so nothing in a hostile repository's |
| 351 | // config, attributes or hooks can run: no hooks, no fsmonitor, no |
| 352 | // textconv or external diff, no attribute files, no network protocol. |
| 353 | var readOnly = []string{ |
| 354 | "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "diff.external=", |
| 355 | "-c", "core.attributesFile=/dev/null", "-c", "protocol.allow=never", "-c", "core.sshCommand=/bin/false", |
| 356 | "-c", "core.askPass=/bin/false", "-c", "credential.helper=", "-c", "maintenance.auto=false", "-c", "gc.auto=0", |
| 357 | "-c", "core.untrackedCache=false", "-c", "safe.directory=*", |
| 358 | } |
| 359 | |
| 360 | // readGit runs one read-only plumbing command (grep, cat-file, ls-tree, |
| 361 | // rev-parse, log) on a bare clone, with a clean environment, a time limit |
| 362 | // and bounded output. |
| 363 | func readGit(ctx context.Context, git, dir string, args ...string) ([]byte, error) { |
| 364 | ctx, cancel := context.WithTimeout(ctx, readTimeout) |
| 365 | defer cancel() |
| 366 | cmd := exec.CommandContext(ctx, git, append(append(append([]string{}, readOnly...), "-C", dir), args...)...) |
| 367 | env := workspace.GitEnvironment() |
| 368 | env["HOME"] = "/nonexistent" |
| 369 | env["GIT_TERMINAL_PROMPT"] = "0" |
| 370 | env["GIT_NO_LAZY_FETCH"] = "1" |
| 371 | env["GIT_OPTIONAL_LOCKS"] = "0" |
| 372 | env["GIT_CEILING_DIRECTORIES"] = filepath.Dir(dir) |
| 373 | env["GIT_DIR"] = dir |
| 374 | for k, v := range env { |
| 375 | cmd.Env = append(cmd.Env, k+"="+v) |
| 376 | } |
| 377 | cmd.Dir = dir |
| 378 | cmd.Stderr = io.Discard |
| 379 | out, err := cmd.StdoutPipe() |
| 380 | if err != nil { |
| 381 | return nil, err |
| 382 | } |
| 383 | if err = cmd.Start(); err != nil { |
| 384 | return nil, err |
| 385 | } |
| 386 | raw, _ := io.ReadAll(io.LimitReader(out, readLimit+1)) |
| 387 | if len(raw) > readLimit { |
| 388 | _ = cmd.Process.Kill() |
| 389 | _ = cmd.Wait() |
| 390 | return nil, errReadPath |
| 391 | } |
| 392 | return raw, cmd.Wait() |
| 393 | } |
| 394 | |
| 395 | // tip is the commit the read tools look at, resolved once per call so |
| 396 | // every read in it sees one fixed tree. |
| 397 | func (x *Index) tip(ctx context.Context, dir string) (string, error) { |
| 398 | out, err := x.git(ctx, dir, "rev-parse", "--verify", "--end-of-options", "HEAD^{commit}") |
| 399 | sha := strings.TrimSpace(string(out)) |
| 400 | if err != nil || !objectName.MatchString(sha) { |
| 401 | return "", errReadPath |
| 402 | } |
| 403 | return sha, nil |
| 404 | } |
| 405 | |
| 406 | var objectName = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`) |
| 407 | |
| 408 | // summary is the first prose paragraph, without markdown decoration. |
| 409 | func summary(md string) string { |
| 410 | for _, para := range strings.Split(md, "\n\n") { |
| 411 | p := strings.TrimSpace(para) |
| 412 | if p == "" || strings.HasPrefix(p, "#") || strings.HasPrefix(p, "<") || strings.HasPrefix(p, "```") || strings.HasPrefix(p, "|") { |
| 413 | continue |
| 414 | } |
| 415 | p = mdImage.ReplaceAllString(p, "") |
| 416 | p = mdLink.ReplaceAllString(p, "$1") |
| 417 | p = strings.Join(strings.Fields(strings.NewReplacer("*", "", "`", "", "_", " ").Replace(p)), " ") |
| 418 | if p == "" { |
| 419 | continue |
| 420 | } |
| 421 | return clip(p, wire.MaxRepoString) |
| 422 | } |
| 423 | return "" |
| 424 | } |
| 425 | |
| 426 | var ( |
| 427 | mdImage = regexp.MustCompile(`\[?!\[[^\]]*\]\([^)]*\)(?:\]\([^)]*\))?`) |
| 428 | mdLink = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) |
| 429 | ) |
| 430 | |
| 431 | func clip(s string, n int) string { |
| 432 | if len(s) <= n { |
| 433 | return s |
| 434 | } |
| 435 | s = s[:n] |
| 436 | for !utf8.ValidString(s) { |
| 437 | s = s[:len(s)-1] |
| 438 | } |
| 439 | return s |
| 440 | } |
| 441 | |
| 442 | // heading is a top-level title: section titles are not names. |
| 443 | var heading = regexp.MustCompile(`(?m)^#\s+(.+)$`) |
| 444 | |
| 445 | func headings(md string) []string { |
| 446 | var out []string |
| 447 | for _, m := range heading.FindAllStringSubmatch(md, 6) { |
| 448 | h := strings.TrimSpace(strings.Trim(m[1], "#*` ")) |
| 449 | if len(h) > 1 && len(h) < 40 { |
| 450 | out = append(out, h) |
| 451 | } |
| 452 | } |
| 453 | return out |
| 454 | } |
| 455 | |
| 456 | var ( |
| 457 | jsonName = regexp.MustCompile(`"name"\s*:\s*"([^"]{2,40})"`) |
| 458 | tomlName = regexp.MustCompile(`(?m)^name\s*=\s*"([^"]{2,40})"`) |
| 459 | goModule = regexp.MustCompile(`(?m)^module\s+(\S+)`) |
| 460 | capWord = regexp.MustCompile(`\b[A-Z][a-z]+(?:[A-Z][a-z]+)*\b`) |
| 461 | appBundle = regexp.MustCompile(`(?:^|/)([A-Za-z0-9 _-]{2,40})\.(?:xcodeproj|xcworkspace)(?:/|$)`) |
| 462 | ) |
| 463 | |
| 464 | func manifestNames(read func(string) string) []string { |
| 465 | var out []string |
| 466 | if m := jsonName.FindStringSubmatch(read("package.json")); m != nil { |
| 467 | out = append(out, m[1]) |
| 468 | } |
| 469 | if m := tomlName.FindStringSubmatch(read("Cargo.toml")); m != nil { |
| 470 | out = append(out, m[1]) |
| 471 | } |
| 472 | if m := goModule.FindStringSubmatch(read("go.mod")); m != nil { |
| 473 | out = append(out, path.Base(m[1])) |
| 474 | } |
| 475 | return out |
| 476 | } |
| 477 | |
| 478 | func appNames(files []string) []string { |
| 479 | var out []string |
| 480 | for _, f := range files { |
| 481 | if m := appBundle.FindStringSubmatch(f); m != nil { |
| 482 | out = append(out, m[1]) |
| 483 | } |
| 484 | } |
| 485 | return out |
| 486 | } |
| 487 | |
| 488 | // common capitalised words that are not product names. |
| 489 | var common = map[string]bool{"The": true, "This": true, "You": true, "Use": true, "Run": true, "See": true, "For": true, "When": true, "If": true, "It": true, "Read": true, "Keep": true, "Never": true, "Do": true, "Each": true, "All": true, "And": true, "Go": true, "Make": true, "Only": true, "Every": true, "With": true, "From": true, "One": true, "No": true, "Not": true, "What": true, "Where": true, "How": true, "Use_": true, "Note": true, "Plan": true, "Task": true, "Write": true, "Test": true, "Tests": true, "Build": true} |
| 490 | |
| 491 | // productNames are capitalised words used at least twice: app and product |
| 492 | // names like Woodstar tend to repeat. |
| 493 | func productNames(text string) []string { |
| 494 | counts := map[string]int{} |
| 495 | var order []string |
| 496 | for _, w := range capWord.FindAllString(text, -1) { |
| 497 | if common[w] || len(w) < 4 { |
| 498 | continue |
| 499 | } |
| 500 | if counts[w] == 0 { |
| 501 | order = append(order, w) |
| 502 | } |
| 503 | counts[w]++ |
| 504 | } |
| 505 | var out []string |
| 506 | for _, w := range order { |
| 507 | if counts[w] >= 2 { |
| 508 | out = append(out, w) |
| 509 | } |
| 510 | } |
| 511 | return out |
| 512 | } |
| 513 | |
| 514 | func hints(files []string, read func(string) string) []string { |
| 515 | var out []string |
| 516 | has := func(name string) bool { return slices.Contains(files, name) } |
| 517 | if has("go.mod") { |
| 518 | out = append(out, "go") |
| 519 | } |
| 520 | if has("Package.swift") || slices.ContainsFunc(files, func(f string) bool { return strings.HasSuffix(f, ".swift") }) { |
| 521 | out = append(out, "swift") |
| 522 | if strings.Contains(strings.Join(files, "\n"), "View.swift") { |
| 523 | out = append(out, "swiftui") |
| 524 | } |
| 525 | } |
| 526 | if pkg := read("package.json"); pkg != "" { |
| 527 | out = append(out, "javascript") |
| 528 | for _, fw := range []string{"react", "vue", "svelte", "next", "vite"} { |
| 529 | if strings.Contains(pkg, `"`+fw+`"`) { |
| 530 | out = append(out, fw) |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | if has("Cargo.toml") { |
| 535 | out = append(out, "rust") |
| 536 | } |
| 537 | if has("pyproject.toml") || has("requirements.txt") { |
| 538 | out = append(out, "python") |
| 539 | } |
| 540 | if slices.ContainsFunc(files, func(f string) bool { return strings.HasSuffix(f, ".kt") || strings.HasSuffix(f, ".gradle.kts") }) { |
| 541 | out = append(out, "android") |
| 542 | } |
| 543 | return out |
| 544 | } |
| 545 | |
| 546 | func bounded(in []string, n int) []string { |
| 547 | out := []string{} |
| 548 | for _, s := range in { |
| 549 | s = strings.TrimSpace(s) |
| 550 | if s == "" || len(s) > 40 || !isPrintableName(s) || slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, s) }) { |
| 551 | continue |
| 552 | } |
| 553 | out = append(out, s) |
| 554 | if len(out) == n { |
| 555 | break |
| 556 | } |
| 557 | } |
| 558 | return out |
| 559 | } |
| 560 | |
| 561 | // errReadPath refuses paths that leave the tree or name git internals. |
| 562 | var errReadPath = errors.New("path refused") |
| 563 | |
| 564 | func cleanPath(p string) (string, error) { |
| 565 | p = strings.TrimPrefix(strings.TrimSpace(p), "/") |
| 566 | if p == "" || p == "." { |
| 567 | return "", nil |
| 568 | } |
| 569 | c := path.Clean(p) |
| 570 | if c != p || strings.HasPrefix(c, "..") || strings.ContainsAny(c, "\x00\n:") || strings.HasPrefix(c, "-") { |
| 571 | return "", errReadPath |
| 572 | } |
| 573 | return c, nil |
| 574 | } |
| 575 | |
| 576 | // SearchCode is git grep over the default branch tip: fixed string, case |
| 577 | // insensitive, bounded. Git reads objects only; no checkout, no hooks. |
| 578 | func (x *Index) SearchCode(ctx context.Context, repo, query string) (string, error) { |
| 579 | query = strings.TrimSpace(query) |
| 580 | if query == "" || len(query) > 200 || strings.ContainsAny(query, "\x00\n") { |
| 581 | return "", errReadPath |
| 582 | } |
| 583 | dir, err := x.ready(ctx, repo) |
| 584 | if err != nil { |
| 585 | return "", err |
| 586 | } |
| 587 | sha, err := x.tip(ctx, dir) |
| 588 | if err != nil { |
| 589 | return "", err |
| 590 | } |
| 591 | out, err := x.git(ctx, dir, "grep", "--no-textconv", "--no-ext-grep", "-n", "-I", "-i", "-F", "--max-count=5", "-e", query, sha, "--") |
| 592 | var exit *exec.ExitError |
| 593 | if errors.As(err, &exit) && exit.ExitCode() == 1 { |
| 594 | return "No matches.", nil |
| 595 | } |
| 596 | if err != nil { |
| 597 | return "", err |
| 598 | } |
| 599 | lines := strings.Split(strings.TrimSpace(strings.ReplaceAll(string(out), sha+":", "")), "\n") |
| 600 | more := "" |
| 601 | if len(lines) > maxSearchLines { |
| 602 | more = "\n(" + strconv.Itoa(len(lines)-maxSearchLines) + " more lines; search for something narrower.)" |
| 603 | lines = lines[:maxSearchLines] |
| 604 | } |
| 605 | for i, l := range lines { |
| 606 | lines[i] = clip(l, 240) |
| 607 | } |
| 608 | return clip(strings.Join(lines, "\n"), maxToolOutput) + more, nil |
| 609 | } |
| 610 | |
| 611 | // ReadFile shows a file from the default branch tip with line numbers, |
| 612 | // or lists a directory. Bounded to maxReadLines from start. |
| 613 | func (x *Index) ReadFile(ctx context.Context, repo, file string, start int) (string, error) { |
| 614 | p, err := cleanPath(file) |
| 615 | if err != nil { |
| 616 | return "", err |
| 617 | } |
| 618 | dir, err := x.ready(ctx, repo) |
| 619 | if err != nil { |
| 620 | return "", err |
| 621 | } |
| 622 | sha, err := x.tip(ctx, dir) |
| 623 | if err != nil { |
| 624 | return "", err |
| 625 | } |
| 626 | // The entry's mode says what it is; a symlink is shown as its target |
| 627 | // text and never followed, a submodule is not read. |
| 628 | object := sha + "^{tree}" |
| 629 | if p != "" { |
| 630 | entry, err := x.git(ctx, dir, "ls-tree", "--full-tree", sha, "--", p) |
| 631 | fields := strings.Fields(string(entry)) |
| 632 | if err != nil || len(fields) < 4 { |
| 633 | return "No such file.", nil |
| 634 | } |
| 635 | switch fields[0] { |
| 636 | case "040000": |
| 637 | case "120000": |
| 638 | return "A symbolic link (not followed).", nil |
| 639 | case "160000": |
| 640 | return "A submodule (not read).", nil |
| 641 | } |
| 642 | object = fields[2] |
| 643 | } |
| 644 | kind, err := x.git(ctx, dir, "cat-file", "-t", object) |
| 645 | if err != nil { |
| 646 | return "No such file.", nil |
| 647 | } |
| 648 | if strings.TrimSpace(string(kind)) == "tree" { |
| 649 | out, err := x.git(ctx, dir, "ls-tree", "--name-only", object) |
| 650 | if err != nil { |
| 651 | return "", err |
| 652 | } |
| 653 | return clip(string(out), maxToolOutput), nil |
| 654 | } |
| 655 | size, err := x.git(ctx, dir, "cat-file", "-s", object) |
| 656 | if n, _ := strconv.Atoi(strings.TrimSpace(string(size))); err != nil || n > readLimit { |
| 657 | return "The file is too large to read here.", nil |
| 658 | } |
| 659 | // cat-file blob: raw object bytes, no textconv or filters. |
| 660 | out, err := x.git(ctx, dir, "cat-file", "blob", object) |
| 661 | if err != nil { |
| 662 | return "", err |
| 663 | } |
| 664 | if bytes.IndexByte(out[:min(len(out), 8000)], 0) >= 0 { |
| 665 | return "Binary file.", nil |
| 666 | } |
| 667 | return numberedLines(out, start), nil |
| 668 | } |
| 669 | |
| 670 | // numberedLines is a read: up to maxReadLines lines from start (1-based), |
| 671 | // each numbered and clipped, and how to read on. |
| 672 | func numberedLines(out []byte, start int) string { |
| 673 | lines := strings.Split(string(out), "\n") |
| 674 | start = max(start, 1) |
| 675 | if start > len(lines) { |
| 676 | return "The file has " + strconv.Itoa(len(lines)) + " lines." |
| 677 | } |
| 678 | end := min(len(lines), start-1+maxReadLines) |
| 679 | var b strings.Builder |
| 680 | for i := start - 1; i < end; i++ { |
| 681 | b.WriteString(strconv.Itoa(i+1) + "\t" + clip(lines[i], 400) + "\n") |
| 682 | } |
| 683 | if end < len(lines) { |
| 684 | b.WriteString("(" + strconv.Itoa(len(lines)-end) + " more lines; read again with start " + strconv.Itoa(end+1) + ".)\n") |
| 685 | } |
| 686 | return clip(b.String(), maxToolOutput) |
| 687 | } |
| 688 | |
| 689 | // ready makes sure the index has a clone of repo to read. An empty |
| 690 | // repository has nothing to read (ErrEmptyRepo). |
| 691 | func (x *Index) ready(ctx context.Context, repo string) (string, error) { |
| 692 | catalog := x.Catalog() |
| 693 | if slices.ContainsFunc(catalog, func(e wire.RepoInfo) bool { return e.Repo == repo && e.Empty }) { |
| 694 | return "", ErrEmptyRepo |
| 695 | } |
| 696 | dir := x.Clones.Path(repo) |
| 697 | if _, err := os.Stat(dir); err == nil { |
| 698 | return dir, nil |
| 699 | } |
| 700 | for _, e := range catalog { |
| 701 | if e.Repo == repo { |
| 702 | return dir, x.Clones.Shallow(ctx, repo, e.DefaultBranch) |
| 703 | } |
| 704 | } |
| 705 | return "", errReadPath |
| 706 | } |
| 707 | |
| 708 | // isPrintableName keeps only names a person would type. |
| 709 | func isPrintableName(s string) bool { |
| 710 | for _, r := range s { |
| 711 | if !unicode.IsPrint(r) { |
| 712 | return false |
| 713 | } |
| 714 | } |
| 715 | return true |
| 716 | } |
| 717 | |