forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearcher.go
More file actions
209 lines (192 loc) · 4.62 KB
/
searcher.go
File metadata and controls
209 lines (192 loc) · 4.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package search
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/cli/cli/v2/internal/ghinstance"
)
const (
maxPerPage = 100
orderKey = "order"
sortKey = "sort"
)
var linkRE = regexp.MustCompile(`<([^>]+)>;\s*rel="([^"]+)"`)
var pageRE = regexp.MustCompile(`(\?|&)page=(\d*)`)
var jsonTypeRE = regexp.MustCompile(`[/+]json($|;)`)
//go:generate moq -rm -out searcher_mock.go . Searcher
type Searcher interface {
Repositories(Query) (RepositoriesResult, error)
Issues(Query) (IssuesResult, error)
URL(Query) string
}
type searcher struct {
client *http.Client
host string
}
type httpError struct {
Errors []httpErrorItem
Message string
RequestURL *url.URL
StatusCode int
}
type httpErrorItem struct {
Code string
Field string
Message string
Resource string
}
func NewSearcher(client *http.Client, host string) Searcher {
return &searcher{
client: client,
host: host,
}
}
func (s searcher) Repositories(query Query) (RepositoriesResult, error) {
result := RepositoriesResult{}
toRetrieve := query.Limit
var resp *http.Response
var err error
for toRetrieve > 0 {
query.Limit = min(toRetrieve, maxPerPage)
query.Page = nextPage(resp)
if query.Page == 0 {
break
}
page := RepositoriesResult{}
resp, err = s.search(query, &page)
if err != nil {
return result, err
}
result.IncompleteResults = page.IncompleteResults
result.Total = page.Total
result.Items = append(result.Items, page.Items...)
toRetrieve = toRetrieve - len(page.Items)
}
return result, nil
}
func (s searcher) Issues(query Query) (IssuesResult, error) {
result := IssuesResult{}
toRetrieve := query.Limit
var resp *http.Response
var err error
for toRetrieve > 0 {
query.Limit = min(toRetrieve, maxPerPage)
query.Page = nextPage(resp)
if query.Page == 0 {
break
}
page := IssuesResult{}
resp, err = s.search(query, &page)
if err != nil {
return result, err
}
result.IncompleteResults = page.IncompleteResults
result.Total = page.Total
result.Items = append(result.Items, page.Items...)
toRetrieve = toRetrieve - len(page.Items)
}
return result, nil
}
func (s searcher) search(query Query, result interface{}) (*http.Response, error) {
path := fmt.Sprintf("%ssearch/%s", ghinstance.RESTPrefix(s.host), query.Kind)
qs := url.Values{}
qs.Set("page", strconv.Itoa(query.Page))
qs.Set("per_page", strconv.Itoa(query.Limit))
qs.Set("q", query.String())
if query.Order != "" {
qs.Set(orderKey, query.Order)
}
if query.Sort != "" {
qs.Set(sortKey, query.Sort)
}
url := fmt.Sprintf("%s?%s", path, qs.Encode())
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/vnd.github.v3+json")
resp, err := s.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
success := resp.StatusCode >= 200 && resp.StatusCode < 300
if !success {
return resp, handleHTTPError(resp)
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(result)
if err != nil {
return resp, err
}
return resp, nil
}
func (s searcher) URL(query Query) string {
path := fmt.Sprintf("https://%s/search", s.host)
qs := url.Values{}
qs.Set("type", query.Kind)
qs.Set("q", query.String())
if query.Order != "" {
qs.Set(orderKey, query.Order)
}
if query.Sort != "" {
qs.Set(sortKey, query.Sort)
}
url := fmt.Sprintf("%s?%s", path, qs.Encode())
return url
}
func (err httpError) Error() string {
if err.StatusCode != 422 || len(err.Errors) == 0 {
return fmt.Sprintf("HTTP %d: %s (%s)", err.StatusCode, err.Message, err.RequestURL)
}
query := strings.TrimSpace(err.RequestURL.Query().Get("q"))
return fmt.Sprintf("Invalid search query %q.\n%s", query, err.Errors[0].Message)
}
func handleHTTPError(resp *http.Response) error {
httpError := httpError{
RequestURL: resp.Request.URL,
StatusCode: resp.StatusCode,
}
if !jsonTypeRE.MatchString(resp.Header.Get("Content-Type")) {
httpError.Message = resp.Status
return httpError
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if err := json.Unmarshal(body, &httpError); err != nil {
return err
}
return httpError
}
func nextPage(resp *http.Response) (page int) {
if resp == nil {
return 1
}
for _, m := range linkRE.FindAllStringSubmatch(resp.Header.Get("Link"), -1) {
if !(len(m) > 2 && m[2] == "next") {
continue
}
p := pageRE.FindStringSubmatch(m[1])
if len(p) == 3 {
i, err := strconv.Atoi(p[2])
if err == nil {
return i
}
}
}
return 0
}
func min(a, b int) int {
if a < b {
return a
}
return b
}