MCPcopy Create free account
hub / github.com/alibaba/open-code-review / gitGrep

Method gitGrep

internal/tool/code_search.go:147–262  ·  view source on GitHub ↗
(ctx context.Context, searchText string, caseSensitive bool, usePerlRegexp bool, pathspec []string)

Source from the content-addressed store, hash-verified

145}
146
147func (p *CodeSearchProvider) gitGrep(ctx context.Context, searchText string, caseSensitive bool, usePerlRegexp bool, pathspec []string) (string, error) {
148 if p.FileReader.Mode == ModeEmpty {
149 return "No matches found", nil
150 }
151 cmdArgs := p.buildGrepArgs(searchText, caseSensitive, usePerlRegexp, false, pathspec)
152 if cmdArgs == nil {
153 return "Error: ref must not start with '-'", nil
154 }
155
156 outStr, errStr, err := p.runGitGrep(ctx, cmdArgs)
157
158 // Non-git directory: `git grep` exits 128 with "not a git repository".
159 // `ocr scan` supports plain directories, so retry in --no-index mode, which
160 // searches the working tree directly while still honoring .gitignore.
161 // Ref-based search needs a real repo, so it is not retried.
162 if err != nil && p.FileReader.Ref == "" && isNotGitRepoError(err, errStr) {
163 cmdArgs = p.buildGrepArgs(searchText, caseSensitive, usePerlRegexp, true, pathspec)
164 outStr, errStr, err = p.runGitGrep(ctx, cmdArgs)
165 }
166
167 if err != nil {
168 if errors.Is(err, context.DeadlineExceeded) {
169 return "", fmt.Errorf("git grep timed out; try narrowing file_patterns to a more specific path: %w", err)
170 }
171 if errors.Is(err, context.Canceled) {
172 return "", err
173 }
174 if outStr == "" {
175 var exitErr *exec.ExitError
176 exitCode := -1
177 if errors.As(err, &exitErr) {
178 exitCode = exitErr.ExitCode()
179 }
180 if errStr == "" && exitCode == 1 {
181 return "No matches found", nil
182 }
183 trimmedErr := trimGitUsage(errStr, exitCode)
184 if trimmedErr == "" {
185 return "", fmt.Errorf("git grep failed: %w", err)
186 }
187 return "", fmt.Errorf("git grep failed: %w: %s", err, trimmedErr)
188 }
189 }
190
191 lines := strings.Split(strings.TrimRight(outStr, "\n"), "\n")
192
193 type match struct {
194 lineNum int
195 content string
196 }
197 fileMatches := make(map[string][]match)
198 var fileOrder []string
199 seen := make(map[string]bool)
200
201 hasRef := p.FileReader.Ref != ""
202 splitN := 3
203 offset := 0
204 if hasRef {

Calls 5

buildGrepArgsMethod · 0.95
runGitGrepMethod · 0.95
isNotGitRepoErrorFunction · 0.85
trimGitUsageFunction · 0.85
StringMethod · 0.45