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