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