forked from tillson/git-hound
-
Notifications
You must be signed in to change notification settings - Fork 1
/
search.go
348 lines (332 loc) · 9.97 KB
/
search.go
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package app
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"sync"
"github.com/fatih/color"
)
// RepoSearchResult represents a result in GitHub/Gist code search.
type RepoSearchResult struct {
Repo string
File string
Raw string
Source string
Query string
URL string
searchOptions *SearchOptions
}
type NewSearchPayload struct {
Payload struct {
Results []struct {
RepoName string `json:"repo_nwo"`
Path string `json:"path"`
CommitSha string `json:"commit_sha"`
// Repository struct {
// }
} `json:"results"`
PageCount int `json:"page_count"`
} `json:"payload"`
}
var SearchWaitGroup sync.WaitGroup
// Search Everything
func Search(query string, client *http.Client) (results []RepoSearchResult, err error) {
var languages []string
if GetFlags().LanguageFile != "" {
languages = GetFileLines(GetFlags().LanguageFile)
}
options := SearchOptions{
MaxPages: 100,
}
resultMap := make(map[string]bool)
if !GetFlags().NoRepos {
if len(languages) > 0 {
for _, language := range languages {
options.Language = language
err = SearchGitHub(query, options, client, &results, resultMap)
if err != nil {
color.Red("[!] Error searching GitHub for `" + query + "`")
}
}
}
if !GetFlags().OnlyFiltered {
err = SearchGitHub(query, options, client, &results, resultMap)
if err != nil {
color.Red("[!] Error searching GitHub for `" + query + "`")
}
}
}
if !GetFlags().NoGists {
resultMap = make(map[string]bool)
if len(languages) > 0 {
for _, language := range languages {
options.Language = language
err = SearchGist(query, options, client, &results, resultMap)
if err != nil {
color.Red("[!] Error searching Gist for `" + query + "`")
}
}
}
if !GetFlags().OnlyFiltered {
err = SearchGist(query, options, client, &results, resultMap)
if err != nil {
color.Red("[!] Error searching Gist for `" + query + "`")
}
}
}
return results, err
}
// SearchGitHub searches GitHub code results for the given query
func SearchGitHub(query string, options SearchOptions, client *http.Client, results *[]RepoSearchResult, resultSet map[string]bool) (err error) {
// TODO: A lot of this code is shared between GitHub and Gist searches,
// so we should rework the logic
base := ""
if GetFlags().GithubRepo {
base = "https://github.com/" + query + "/search"
} else {
base = "https://github.com/search"
}
page, pages := 0, 1
var delay = 5
orders := []string{"asc"}
rankings := []string{"indexed"}
for i := 0; i < len(orders); i++ {
for j := 0; j < len(rankings); j++ {
if i == 1 && j == 1 {
continue
}
for page < pages {
str := ConstructSearchURL(base, query, options)
// fmt.Println(str)
response, err := client.Get(str)
if err != nil {
if response != nil {
if response.StatusCode == 403 {
response.Body.Close()
delay += 5
color.Yellow("[!] Rate limited by GitHub. Waiting " + strconv.Itoa(delay) + "s...")
time.Sleep(time.Duration(delay) * time.Second)
} else if response.StatusCode == 503 {
break
}
} else {
fmt.Println(err)
}
continue
}
if delay > 10 {
delay--
}
responseData, err := ioutil.ReadAll(response.Body)
responseStr := string(responseData)
if err != nil {
log.Fatal(err)
}
response.Body.Close()
resultRegex := regexp.MustCompile("href=\"\\/((.*)\\/blob\\/([0-9a-f]{40}\\/([^#\"]+)))\">")
matches := resultRegex.FindAllStringSubmatch(responseStr, -1)
if page == 0 {
if len(matches) == 0 {
resultRegex = regexp.MustCompile("(?s)react-app\\.embeddedData\">(.*?)<\\/script>")
match := resultRegex.FindStringSubmatch(responseStr)
var resultPayload NewSearchPayload
if len(match) == 0 {
page++
continue
}
json.Unmarshal([]byte(match[1]), &resultPayload)
if !GetFlags().ResultsOnly && !GetFlags().JsonOutput {
if pages != resultPayload.Payload.PageCount {
color.Cyan("[*] Searching " + strconv.Itoa(resultPayload.Payload.PageCount) + " pages of results for '" + query + "'...")
}
pages = resultPayload.Payload.PageCount
}
} else {
regex := regexp.MustCompile("\\bdata\\-total\\-pages\\=\"(\\d+)\"")
match := regex.FindStringSubmatch(responseStr)
if err != nil {
log.Fatal(err)
}
if len(match) == 2 {
newPages, err := strconv.Atoi(match[1])
if err == nil {
if newPages > GetFlags().Pages {
newPages = GetFlags().Pages
}
pages = newPages
if pages > 99 && GetFlags().ManyResults {
if !GetFlags().ResultsOnly && !GetFlags().JsonOutput {
color.Cyan("[*] Searching 100+ pages of results for '" + query + "'...")
}
orders = append(orders, "desc")
rankings = append(orders, "")
} else {
if !GetFlags().ResultsOnly && !GetFlags().JsonOutput {
color.Cyan("[*] Searching " + strconv.Itoa(pages) + " pages of results for '" + query + "'...")
}
}
} else {
color.Red("[!] An error occurred while parsing the page count.")
fmt.Println(err)
}
} else {
if strings.Index(responseStr, "Sign in to GitHub") > -1 {
color.Red("[!] Unable to log into GitHub.")
log.Fatal()
} else if len(matches) > 0 {
if !GetFlags().ResultsOnly {
color.Cyan("[*] Searching 1 page of results for '" + query + "'...")
}
}
}
}
}
page++
if len(matches) == 0 {
resultRegex = regexp.MustCompile("(?s)react-app\\.embeddedData\">(.*?)<\\/script>")
match := resultRegex.FindStringSubmatch(responseStr)
var resultPayload NewSearchPayload
if len(match) > 0 {
json.Unmarshal([]byte(match[1]), &resultPayload)
for _, result := range resultPayload.Payload.Results {
if resultSet[(result.RepoName+result.Path)] == true {
continue
}
resultSet[(result.RepoName + result.Path)] = true
SearchWaitGroup.Add(1)
// fmt.Println(result.RepoName + "/" + result.DefaultBranch + "/" + result.Path)
go ScanAndPrintResult(client, RepoSearchResult{
Repo: result.RepoName,
File: result.Path,
Raw: result.RepoName + "/" + result.CommitSha + "/" + result.Path,
Source: "repo",
Query: query,
URL: "https://github.com/" + result.RepoName + "/blob/" + result.CommitSha + "/" + result.Path,
})
}
}
} else {
for _, element := range matches {
if len(element) == 5 {
if resultSet[(element[2]+"/"+element[3])] == true {
continue
}
resultSet[(element[2] + "/" + element[3])] = true
SearchWaitGroup.Add(1)
go ScanAndPrintResult(client, RepoSearchResult{
Repo: element[2],
File: element[4],
Raw: element[2] + "/" + element[3],
Source: "repo",
Query: query,
URL: "https://github.com/" + element[2] + "/blob/" + element[3],
})
}
}
time.Sleep(time.Duration(delay) * time.Second)
}
options.Page = (page + 1)
}
}
}
return nil
}
// SearchGist searches Gist results for the given query
func SearchGist(query string, options SearchOptions, client *http.Client, results *[]RepoSearchResult, resultSet map[string]bool) (err error) {
// TODO: A lot of this code is shared between GitHub and Gist searches,
// so we should rework the logic
base := "https://gist.github.com/search"
page, pages := 0, 1
var delay = 5
for page < pages {
options.Page = (page + 1)
response, err := client.Get(ConstructSearchURL(base, query, options))
if err != nil {
if response != nil {
if response.StatusCode == 403 {
delay += 5
color.Yellow("[!] Rate limited by GitHub. Waiting " + strconv.Itoa(delay) + "s...")
time.Sleep(time.Duration(delay) * time.Second)
} else if response.StatusCode == 503 {
break
}
} else {
fmt.Println(err)
}
continue
}
if delay > 10 {
delay--
}
responseData, err := ioutil.ReadAll(response.Body)
responseStr := string(responseData)
if err != nil {
log.Fatal(err)
}
if page == 0 {
regex := regexp.MustCompile("\\bdata\\-total\\-pages\\=\"(\\d+)\"")
match := regex.FindStringSubmatch(responseStr)
if err != nil {
log.Fatal(err)
}
if len(match) == 2 {
newPages, err := strconv.Atoi(match[1])
if err == nil {
if newPages > GetFlags().Pages {
newPages = GetFlags().Pages
}
pages = newPages
if pages > 99 {
if !GetFlags().ResultsOnly && !GetFlags().JsonOutput {
color.Cyan("[*] Searching 100+ pages of Gist results for '" + query + "'...")
}
} else {
if !GetFlags().ResultsOnly && !GetFlags().JsonOutput {
color.Cyan("[*] Searching " + strconv.Itoa(pages) + " pages of results for '" + query + "'...")
}
}
} else {
color.Red("[!] An error occurred while parsing the Gist page count.")
fmt.Println(err)
}
} else {
if strings.Index(responseStr, "Sign in to GitHub") > -1 {
color.Red("[!] Unable to log into GitHub.")
log.Fatal()
} else {
if !GetFlags().ResultsOnly {
color.Cyan("[*] Searching 1 page of Gist results for '" + query + "'...")
}
}
}
}
page++
resultRegex := regexp.MustCompile("href=\"\\/(\\w+\\/[0-9a-z]{5,})\">")
matches := resultRegex.FindAllStringSubmatch(responseStr, -1)
for _, element := range matches {
if len(element) == 2 {
if resultSet[element[1]] == true {
continue
}
resultSet[element[1]] = true
SearchWaitGroup.Add(1)
go ScanAndPrintResult(client, RepoSearchResult{
Repo: element[1],
File: element[1],
Raw: GetRawGistPage(client, element[1]),
Source: "gist",
Query: query,
URL: "https://gist.github.com/" + element[1],
})
}
}
time.Sleep(time.Duration(delay) * time.Second)
}
return nil
}