package gitx import ( "bufio" "bytes" "context" "errors" "fmt" "os" "os/exec" "strings" "time" ) // 本文件是面向「阅读仓库」的只读检索能力:列文件、检索代码、按行读文件。 // AI 项目助手靠它们在不把整个仓库读进内存的前提下查看真实代码。 // Paths 返回 tree 下的全部文件路径,最多 limit 条、最多 maxBytes 字节。 // // 第二个返回值为 true 表示结果被截断(体积或条数任一触顶)。 func Paths(repo, ref string, limit, maxBytes int) ([]string, bool, error) { out, err := runLimit(context.Background(), repo, maxBytes, "ls-tree", "-r", "--name-only", ref) truncated := errors.Is(err, ErrTooLarge) if err != nil && !truncated { return nil, false, err } var paths []string for _, line := range strings.Split(string(out), "\n") { line = strings.TrimRight(line, "\r") if strings.TrimSpace(line) == "" { continue } paths = append(paths, line) } // 截断时最后一行可能是被切断的半截路径,去掉它免得给出不存在的文件。 if truncated && len(paths) > 0 { paths = paths[:len(paths)-1] } if limit > 0 && len(paths) > limit { paths = paths[:limit] truncated = true } return paths, truncated, nil } // Grep 在指定 tree 中按字面量检索(忽略大小写),返回「路径:行号:内容」形式的命中行。 // // 关键词通过 -e 传入,因此以 "-" 开头的关键词也不会被 git 当成选项。 // 命中过多(超过 maxBytes)时返回已读到的部分并把 truncated 置为 true。 func Grep(repo, ref, pattern string, maxBytes int) (string, bool, error) { out, err := runLimit(context.Background(), repo, maxBytes, "grep", "-n", "-I", "-i", "-F", "--no-color", "-e", pattern, ref) switch { case err == nil: return string(out), false, nil case errors.Is(err, ErrTooLarge): return string(out), true, nil } // git grep 在没有命中时以退出码 1 结束,这是正常结果而非错误。 var exitErr *exec.ExitError if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 && strings.TrimSpace(string(out)) == "" { return "", false, nil } return "", false, err } // BlobLines 按行读取文件内容,返回第 start 行到第 end 行(行号从 1 开始, // end 为 0 表示一直读到文件末尾),累计输出超过 maxBytes 字节时提前停止。 // // 与 BlobLimited 的区别是流式读取:即使文件有几百 MB,也只读需要的那一段, // 不会把整份内容读进内存。 func BlobLines(repo, ref, path string, start, end, maxBytes int) (lines []string, truncated bool, err error) { if start < 1 { start = 1 } ctx, cancel := context.WithTimeout(context.Background(), commandTimeout()) defer cancel() cmd := exec.CommandContext(ctx, "git", "cat-file", "blob", blobSpec(ref, path)) cmd.Dir = repo cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "LC_ALL=C") // 同 LineCount:下游一旦停止读取,用 WaitDelay 兜底,不让只读操作挂住请求。 cmd.WaitDelay = 2 * time.Second pipe, err := cmd.StdoutPipe() if err != nil { return nil, false, err } var stderr bytes.Buffer cmd.Stderr = &stderr if err := cmd.Start(); err != nil { return nil, false, err } n, used := 0, 0 sc := bufio.NewScanner(pipe) sc.Buffer(make([]byte, 0, 64<<10), maxScanToken) for sc.Scan() { n++ if n < start { continue } if end > 0 && n > end { break } line := strings.TrimRight(sc.Text(), "\r") if maxBytes > 0 && used+len(line) > maxBytes { truncated = true break } used += len(line) + 1 lines = append(lines, line) } scanErr := sc.Err() // 提前停止后没人再读管道,git 会阻塞在 write 上;先关读端让它收到 EPIPE。 _ = pipe.Close() waitErr := cmd.Wait() // 单行超过扫描上限也算截断:这一行读不全,后面的内容更不可靠。 if errors.Is(scanErr, bufio.ErrTooLong) { truncated = true } if len(lines) == 0 && waitErr != nil && scanErr == nil { msg := strings.TrimSpace(stderr.String()) if msg == "" { msg = waitErr.Error() } return nil, false, fmt.Errorf("git cat-file blob %s: %s", blobSpec(ref, path), msg) } return lines, truncated, nil }