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

Method gitGrep

internal/tool/code_search.go:147–265  ·  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 if usePerlRegexp && exitCode == 128 && isPerlRegexpCompileError(trimmedErr) {
188 trimmedErr += `; fix the regular expression (e.g. use \( for a literal opening parenthesis), or set use_perl_regexp=false to search for the entire text literally`
189 }
190 return "", fmt.Errorf("git grep failed: %w: %s", err, trimmedErr)
191 }
192 }
193
194 lines := strings.Split(strings.TrimRight(outStr, "\n"), "\n")
195
196 type match struct {
197 lineNum int
198 content string
199 }
200 fileMatches := make(map[string][]match)
201 var fileOrder []string
202 seen := make(map[string]bool)
203
204 hasRef := p.FileReader.Ref != ""

Calls 6

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