Skip to content

Commit 0443108

Browse files
fix/search: print partial results when there are graphql errors
src search discarded every result and exited non-zero when the GraphQL response carried errors for individual results, such as "repository does not exist" on one result's file.content. Treat errors that arrive alongside results as warnings (printed to stderr, in full with -v) and only fail hard when no results came back, matching the behaviour src repos list got in #1282. Fixes #1150 Amp-Thread-ID: https://ampcode.com/threads/T-01a18b53-40bb-7118-975d-9c1b224f5602 Co-authored-by: Amp <amp@ampcode.com>
1 parent 99c43e8 commit 0443108

5 files changed

Lines changed: 190 additions & 54 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ All notable changes to `src-cli` are documented in this file.
2222

2323
### Fixed
2424

25+
- `src search` no longer discards all results when the GraphQL response contains errors for some of them (for example, `repository does not exist` for a repository deleted mid-search). The results are printed, and the errors are reported as warnings; rerun with `-v` to inspect them. [#1150](https://github.com/sourcegraph/src-cli/issues/1150)
2526
- `src doc` now generates reference pages for the `search-jobs`, `debug`, and `snapshot` subcommands, and the root `index.md` again lists legacy commands (`batch`, `repos`, `search`, ...) alongside the `urfave/cli` ones.
2627

2728
### Removed

‎cmd/src/repos_list.go‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,11 @@ func gqlWarningMessage(graphQLError *api.GraphQlError) string {
137137
return message
138138
}
139139

140-
func formatRepositoryListWarnings(warnings api.GraphQlErrors) string {
140+
// formatGraphQLWarnings renders GraphQL errors that came back alongside
141+
// data. activity names the operation, e.g. "listing" or "search".
142+
func formatGraphQLWarnings(activity string, warnings api.GraphQlErrors) string {
141143
var b strings.Builder
142-
fmt.Fprintf(&b, "warnings: %d errors during listing\n", len(warnings))
144+
fmt.Fprintf(&b, "warnings: %d errors during %s\n", len(warnings), activity)
143145
for _, warning := range warnings {
144146
path := gqlWarningPath(warning)
145147
message := gqlWarningMessage(warning)
@@ -242,7 +244,7 @@ Examples:
242244
}
243245
if len(warnings) > 0 {
244246
if *verbose {
245-
fmt.Fprint(flagSet.Output(), formatRepositoryListWarnings(warnings))
247+
fmt.Fprint(flagSet.Output(), formatGraphQLWarnings("listing", warnings))
246248
} else {
247249
fmt.Fprintf(flagSet.Output(), "warning: %d errors during listing; rerun with -v to inspect them\n", len(warnings))
248250
}

‎cmd/src/repos_list_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ func TestListRepositoriesHandlesGraphQLErrors(t *testing.T) {
9090
}
9191
}
9292

93-
func TestFormatRepositoryListWarnings(t *testing.T) {
93+
func TestFormatGraphQLWarnings(t *testing.T) {
9494
t.Parallel()
9595

9696
tests := []struct {
@@ -133,7 +133,7 @@ listing timed out
133133
for _, test := range tests {
134134
t.Run(test.name, func(t *testing.T) {
135135
t.Parallel()
136-
require.Equal(t, test.want, formatRepositoryListWarnings(test.warnings))
136+
require.Equal(t, test.want, formatGraphQLWarnings("listing", test.warnings))
137137
})
138138
}
139139
}

‎cmd/src/search.go‎

Lines changed: 88 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"bytes"
55
"context"
6+
"encoding/json"
67
"flag"
78
"fmt"
89
"html"
@@ -131,7 +132,79 @@ Other tips:
131132

132133
client := cfg.apiClient(apiFlags, flagSet.Output())
133134

134-
query := `fragment FileMatchFields on FileMatch {
135+
// Errors returned alongside results (for example, a single repository
136+
// that no longer exists) are treated as warnings, and the data as
137+
// partially complete.
138+
result, warnings, err := runSearch(context.Background(), client, queryString)
139+
if err != nil {
140+
return err
141+
}
142+
143+
improved := searchResultsImproved{
144+
SourcegraphEndpoint: cfg.endpointURL.String(),
145+
Query: queryString,
146+
Site: result.Site,
147+
searchResults: result.Search.Results,
148+
}
149+
150+
if len(warnings) > 0 {
151+
if *verbose {
152+
fmt.Fprint(flagSet.Output(), formatGraphQLWarnings("search", warnings))
153+
} else {
154+
fmt.Fprintf(flagSet.Output(), "warning: %d errors during search; rerun with -v to inspect them\n", len(warnings))
155+
}
156+
}
157+
158+
if *jsonFlag {
159+
// Print the formatted JSON.
160+
f, err := marshalIndent(improved)
161+
if err != nil {
162+
return err
163+
}
164+
fmt.Println(string(f))
165+
return nil
166+
}
167+
168+
tmpl, err := parseTemplate(searchResultsTemplate)
169+
if err != nil {
170+
return err
171+
}
172+
return execTemplate(tmpl, improved)
173+
}
174+
175+
// Register the command.
176+
commands = append(commands, &command{
177+
flagSet: flagSet,
178+
description: "search for results on Sourcegraph",
179+
handler: handler,
180+
usageFunc: func() {
181+
fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src %s':\n", flagSet.Name())
182+
flagSet.PrintDefaults()
183+
fmt.Println(usage)
184+
},
185+
})
186+
}
187+
188+
// searchQueryData is the data portion of the GraphQL search response.
189+
type searchQueryData struct {
190+
Site struct{ BuildVersion string }
191+
Search struct {
192+
Results searchResults
193+
}
194+
}
195+
196+
// searchQueryResult is the raw GraphQL search response, including any errors
197+
// returned alongside the data.
198+
type searchQueryResult struct {
199+
Data searchQueryData `json:"data"`
200+
Errors []json.RawMessage `json:"errors,omitempty"`
201+
}
202+
203+
// runSearch returns the search results, any GraphQL errors returned alongside
204+
// results (should be treated as warnings), and a hard error when the query
205+
// fails without usable results.
206+
func runSearch(ctx context.Context, client api.Client, queryString string) (searchQueryData, api.GraphQlErrors, error) {
207+
query := `fragment FileMatchFields on FileMatch {
135208
repository {
136209
name
137210
url
@@ -250,56 +323,22 @@ Other tips:
250323
}
251324
` + searchResultsAlertFragment
252325

253-
var result struct {
254-
Site struct {
255-
BuildVersion string
256-
}
257-
Search struct {
258-
Results searchResults
259-
}
260-
}
261-
262-
if ok, err := client.NewRequest(query, map[string]any{
263-
"query": api.NullString(queryString),
264-
}).Do(context.Background(), &result); err != nil || !ok {
265-
return err
266-
}
267-
268-
improved := searchResultsImproved{
269-
SourcegraphEndpoint: cfg.endpointURL.String(),
270-
Query: queryString,
271-
Site: result.Site,
272-
searchResults: result.Search.Results,
273-
}
274-
275-
if *jsonFlag {
276-
// Print the formatted JSON.
277-
f, err := marshalIndent(improved)
278-
if err != nil {
279-
return err
280-
}
281-
fmt.Println(string(f))
282-
return nil
283-
}
284-
285-
tmpl, err := parseTemplate(searchResultsTemplate)
286-
if err != nil {
287-
return err
288-
}
289-
return execTemplate(tmpl, improved)
326+
var result searchQueryResult
327+
ok, err := client.NewRequest(query, map[string]any{
328+
"query": api.NullString(queryString),
329+
}).DoRaw(ctx, &result)
330+
if err != nil || !ok {
331+
return searchQueryData{}, nil, err
332+
}
333+
if len(result.Errors) == 0 {
334+
return result.Data, nil, nil
290335
}
291336

292-
// Register the command.
293-
commands = append(commands, &command{
294-
flagSet: flagSet,
295-
description: "search for results on Sourcegraph",
296-
handler: handler,
297-
usageFunc: func() {
298-
fmt.Fprintf(flag.CommandLine.Output(), "Usage of 'src %s':\n", flagSet.Name())
299-
flagSet.PrintDefaults()
300-
fmt.Println(usage)
301-
},
302-
})
337+
graphQLErrors := api.NewGraphQlErrors(result.Errors)
338+
if len(result.Data.Search.Results.Results) > 0 {
339+
return result.Data, graphQLErrors, nil
340+
}
341+
return searchQueryData{}, nil, graphQLErrors
303342
}
304343

305344
// searchResults represents the data we get back from the GraphQL search request.

‎cmd/src/search_test.go‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"bytes"
5+
"context"
56
"encoding/json"
67
"os"
78
"os/exec"
@@ -10,6 +11,10 @@ import (
1011
"testing"
1112

1213
"github.com/grafana/regexp"
14+
"github.com/stretchr/testify/mock"
15+
"github.com/stretchr/testify/require"
16+
17+
mockapi "github.com/sourcegraph/src-cli/internal/api/mock"
1318
)
1419

1520
var _ = func() bool {
@@ -131,3 +136,92 @@ func TestBuildVersionHasNewSearchInterface(t *testing.T) {
131136
t.Errorf("Build version is after the new generic search interface was merged. Expected true, but got false.")
132137
}
133138
}
139+
140+
func TestRunSearchHandlesGraphQLErrors(t *testing.T) {
141+
t.Parallel()
142+
143+
fileMatch := func(repoName string) map[string]any {
144+
return map[string]any{
145+
"__typename": "FileMatch",
146+
"repository": map[string]any{"name": repoName},
147+
"file": map[string]any{"path": "package.json"},
148+
}
149+
}
150+
searchResponse := func(results []map[string]any, graphqlErrors ...map[string]any) map[string]any {
151+
response := map[string]any{
152+
"data": map[string]any{
153+
"site": map[string]any{"buildVersion": "6.0.0"},
154+
"search": map[string]any{
155+
"results": map[string]any{
156+
"results": results,
157+
"resultCount": len(results),
158+
},
159+
},
160+
},
161+
}
162+
if len(graphqlErrors) > 0 {
163+
response["errors"] = graphqlErrors
164+
}
165+
return response
166+
}
167+
168+
tests := []struct {
169+
name string
170+
response map[string]any
171+
wantRepos []string
172+
wantWarnings []string
173+
wantErr string
174+
}{
175+
{
176+
name: "missing repository content keeps the other results",
177+
response: searchResponse(
178+
[]map[string]any{fileMatch("github.com/sourcegraph/ok"), fileMatch("github.com/sourcegraph/deleted")},
179+
graphqlError("repository does not exist: github.com/sourcegraph/deleted", "search", "results", "results", 1, "file", "content"),
180+
),
181+
wantRepos: []string{"github.com/sourcegraph/ok", "github.com/sourcegraph/deleted"},
182+
wantWarnings: []string{"repository does not exist: github.com/sourcegraph/deleted"},
183+
},
184+
{
185+
name: "errors without results are hard errors",
186+
response: searchResponse(
187+
nil,
188+
graphqlError("search timed out", "search"),
189+
),
190+
wantErr: "search timed out",
191+
},
192+
}
193+
194+
for _, test := range tests {
195+
t.Run(test.name, func(t *testing.T) {
196+
t.Parallel()
197+
198+
client := new(mockapi.Client)
199+
request := &mockapi.Request{Response: mustJSON(t, test.response)}
200+
client.On("NewRequest", mock.Anything, mock.Anything).Return(request).Once()
201+
request.On("DoRaw", context.Background(), mock.Anything).Return(true, nil).Once()
202+
203+
result, warnings, err := runSearch(context.Background(), client, "package.json")
204+
client.AssertExpectations(t)
205+
request.AssertExpectations(t)
206+
207+
if test.wantErr != "" {
208+
require.ErrorContains(t, err, test.wantErr)
209+
require.Empty(t, result.Search.Results.Results)
210+
require.Nil(t, warnings)
211+
return
212+
}
213+
214+
require.NoError(t, err)
215+
require.Equal(t, "6.0.0", result.Site.BuildVersion)
216+
require.Len(t, result.Search.Results.Results, len(test.wantRepos))
217+
for i, want := range test.wantRepos {
218+
repository := result.Search.Results.Results[i]["repository"].(map[string]any)
219+
require.Equal(t, want, repository["name"])
220+
}
221+
require.Len(t, warnings, len(test.wantWarnings))
222+
for i, want := range test.wantWarnings {
223+
require.ErrorContains(t, warnings[i], want)
224+
}
225+
})
226+
}
227+
}

0 commit comments

Comments
 (0)