仰望星辰工作室

gitcat

gitcat/ internal/gitx/query.go 4.1 KB · 131 行 原始文件
1package gitx
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "os"
10 "os/exec"
11 "strings"
12 "time"
13)
14
15// 本文件是面向「阅读仓库」的只读检索能力:列文件、检索代码、按行读文件。
16// AI 项目助手靠它们在不把整个仓库读进内存的前提下查看真实代码。
17
18// Paths 返回 tree 下的全部文件路径,最多 limit 条、最多 maxBytes 字节。
19//
20// 第二个返回值为 true 表示结果被截断(体积或条数任一触顶)。
21func Paths(repo, ref string, limit, maxBytes int) ([]string, bool, error) {
22 out, err := runLimit(context.Background(), repo, maxBytes, "ls-tree", "-r", "--name-only", ref)
23 truncated := errors.Is(err, ErrTooLarge)
24 if err != nil && !truncated {
25 return nil, false, err
26 }
27 var paths []string
28 for _, line := range strings.Split(string(out), "\n") {
29 line = strings.TrimRight(line, "\r")
30 if strings.TrimSpace(line) == "" {
31 continue
32 }
33 paths = append(paths, line)
34 }
35 // 截断时最后一行可能是被切断的半截路径,去掉它免得给出不存在的文件。
36 if truncated && len(paths) > 0 {
37 paths = paths[:len(paths)-1]
38 }
39 if limit > 0 && len(paths) > limit {
40 paths = paths[:limit]
41 truncated = true
42 }
43 return paths, truncated, nil
44}
45
46// Grep 在指定 tree 中按字面量检索(忽略大小写),返回「路径:行号:内容」形式的命中行。
47//
48// 关键词通过 -e 传入,因此以 "-" 开头的关键词也不会被 git 当成选项。
49// 命中过多(超过 maxBytes)时返回已读到的部分并把 truncated 置为 true。
50func Grep(repo, ref, pattern string, maxBytes int) (string, bool, error) {
51 out, err := runLimit(context.Background(), repo, maxBytes,
52 "grep", "-n", "-I", "-i", "-F", "--no-color", "-e", pattern, ref)
53 switch {
54 case err == nil:
55 return string(out), false, nil
56 case errors.Is(err, ErrTooLarge):
57 return string(out), true, nil
58 }
59 // git grep 在没有命中时以退出码 1 结束,这是正常结果而非错误。
60 var exitErr *exec.ExitError
61 if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 && strings.TrimSpace(string(out)) == "" {
62 return "", false, nil
63 }
64 return "", false, err
65}
66
67// BlobLines 按行读取文件内容,返回第 start 行到第 end 行(行号从 1 开始,
68// end 为 0 表示一直读到文件末尾),累计输出超过 maxBytes 字节时提前停止。
69//
70// 与 BlobLimited 的区别是流式读取:即使文件有几百 MB,也只读需要的那一段,
71// 不会把整份内容读进内存。
72func BlobLines(repo, ref, path string, start, end, maxBytes int) (lines []string, truncated bool, err error) {
73 if start < 1 {
74 start = 1
75 }
76 ctx, cancel := context.WithTimeout(context.Background(), commandTimeout())
77 defer cancel()
78 cmd := exec.CommandContext(ctx, "git", "cat-file", "blob", blobSpec(ref, path))
79 cmd.Dir = repo
80 cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "LC_ALL=C")
81 // 同 LineCount:下游一旦停止读取,用 WaitDelay 兜底,不让只读操作挂住请求。
82 cmd.WaitDelay = 2 * time.Second
83
84 pipe, err := cmd.StdoutPipe()
85 if err != nil {
86 return nil, false, err
87 }
88 var stderr bytes.Buffer
89 cmd.Stderr = &stderr
90 if err := cmd.Start(); err != nil {
91 return nil, false, err
92 }
93
94 n, used := 0, 0
95 sc := bufio.NewScanner(pipe)
96 sc.Buffer(make([]byte, 0, 64<<10), maxScanToken)
97 for sc.Scan() {
98 n++
99 if n < start {
100 continue
101 }
102 if end > 0 && n > end {
103 break
104 }
105 line := strings.TrimRight(sc.Text(), "\r")
106 if maxBytes > 0 && used+len(line) > maxBytes {
107 truncated = true
108 break
109 }
110 used += len(line) + 1
111 lines = append(lines, line)
112 }
113 scanErr := sc.Err()
114
115 // 提前停止后没人再读管道,git 会阻塞在 write 上;先关读端让它收到 EPIPE。
116 _ = pipe.Close()
117 waitErr := cmd.Wait()
118
119 // 单行超过扫描上限也算截断:这一行读不全,后面的内容更不可靠。
120 if errors.Is(scanErr, bufio.ErrTooLong) {
121 truncated = true
122 }
123 if len(lines) == 0 && waitErr != nil && scanErr == nil {
124 msg := strings.TrimSpace(stderr.String())
125 if msg == "" {
126 msg = waitErr.Error()
127 }
128 return nil, false, fmt.Errorf("git cat-file blob %s: %s", blobSpec(ref, path), msg)
129 }
130 return lines, truncated, nil
131}