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

Method gitGrep

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

Source from the content-addressed store, hash-verified

134}
135
136func (p *CodeSearchProvider) gitGrep(ctx context.Context, searchText string, caseSensitive bool, usePerlRegexp bool, pathspec []string) (string, error) {
137 cmdArgs := p.buildGrepArgs(searchText, caseSensitive, usePerlRegexp, false, pathspec)
138 if cmdArgs == nil {
139 return "Error: ref must not start with '-'", nil
140 }
141
142 outStr, errStr, err := p.runGitGrep(ctx, cmdArgs)
143
144 // Non-git directory: `git grep` exits 128 with "not a git repository".
145 // `ocr scan` supports plain directories, so retry in --no-index mode, which
146 // searches the working tree directly while still honoring .gitignore.
147 // Ref-based search needs a real repo, so it is not retried.
148 if err != nil && p.FileReader.Ref == "" && isNotGitRepoError(err, errStr) {
149 cmdArgs = p.buildGrepArgs(searchText, caseSensitive, usePerlRegexp, true, pathspec)
150 outStr, errStr, err = p.runGitGrep(ctx, cmdArgs)
151 }
152
153 if err != nil {
154 if errors.Is(err, context.DeadlineExceeded) {
155 return "code_search timed out. Try narrowing file_patterns to a more specific path.", nil
156 }
157 if errors.Is(err, context.Canceled) {
158 return "", err
159 }
160 if outStr == "" {
161 if errStr == "" {
162 return "No matches found", nil
163 }
164 return fmt.Sprintf("Error: %s", strings.TrimSpace(errStr)), nil
165 }
166 }
167
168 lines := strings.Split(strings.TrimRight(outStr, "\n"), "\n")
169 truncated := len(lines) >= gitGrepMaxCount
170
171 type match struct {
172 lineNum int
173 content string
174 }
175 fileMatches := make(map[string][]match)
176 var fileOrder []string
177 seen := make(map[string]bool)
178
179 hasRef := p.FileReader.Ref != ""
180 splitN := 3
181 offset := 0
182 if hasRef {
183 splitN = 4
184 offset = 1
185 }
186
187 var sb strings.Builder
188 if truncated {
189 sb.WriteString(fmt.Sprintf("Note: The results have been truncated. Only showing first %d results.\n", gitGrepMaxCount))
190 }
191
192 for _, line := range lines {
193 if line == "" {

Calls 4

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