-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.go
357 lines (292 loc) · 8.84 KB
/
main.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
349
350
351
352
353
354
355
356
357
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"net/http"
"os"
"regexp"
"strings"
"github.com/google/go-github/v38/github"
"github.com/xanzy/go-gitlab"
"golang.org/x/oauth2"
"golang.org/x/time/rate"
)
type config struct {
orgFlag bool
repoFlag bool
userFlag bool
maxFlag int
cleanFlag bool
ghOnlyFlag bool
glOnlyFlag bool
simpleFlag bool
verboseFlag bool
}
var (
flags = config{}
urlRegexp = regexp.MustCompile(`^https?://(?:www\.)?([^/]+)`)
spaceRegexp = regexp.MustCompile(`\s+`)
)
func init() {
flag.BoolVar(&flags.orgFlag, "o", false, "search for organization names")
flag.BoolVar(&flags.repoFlag, "r", false, "search for repository names")
flag.BoolVar(&flags.userFlag, "u", false, "search for username matches")
flag.IntVar(&flags.maxFlag, "max", 10, "maximum search results per category")
flag.BoolVar(&flags.cleanFlag, "c", false, "clean input URLs")
flag.BoolVar(&flags.ghOnlyFlag, "gh", false, "search only GitHub")
flag.BoolVar(&flags.glOnlyFlag, "gl", false, "search only GitLab")
flag.BoolVar(&flags.simpleFlag, "s", false, "simple output style for piping to another tool")
flag.BoolVar(&flags.verboseFlag, "v", false, "enable verbose mode")
}
func main() {
flag.Parse()
validateFlags(flags)
verbosePrint("Reading and cleaning words...\n")
words := readAndCleanWords(flags, flag.Args())
verbosePrint("Words cleaned.\n")
verbosePrint("Searching platforms...\n")
searchPlatforms(words, flags)
verbosePrint("Platform search completed.\n")
}
func validateFlags(cfg config) {
if !(cfg.orgFlag || cfg.repoFlag || cfg.userFlag) {
fmt.Println("At least one search flag (-o, -r, or -u) must be specified")
os.Exit(1)
}
verbosePrint("Flags validated.\n")
}
func verbosePrint(format string, a ...interface{}) {
if flags.verboseFlag {
fmt.Printf(format, a...)
}
}
func readAndCleanWords(cfg config, args []string) map[string]struct{} {
words := make(map[string]struct{})
if len(args) > 0 {
for _, word := range args {
processWord(word, words, cfg)
}
} else {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
word := strings.TrimSpace(scanner.Text())
processWord(word, words, cfg)
}
checkScannerError(scanner)
}
return words
}
func processWord(word string, words map[string]struct{}, cfg config) {
if cfg.cleanFlag {
word = cleanWord(word)
}
addWordToMap(words, word)
word = removeWhitespace(word)
wordLines := strings.Split(word, "\n")
for _, w := range wordLines {
addWordToMap(words, w)
}
}
func addWordToMap(words map[string]struct{}, word string) {
if _, exists := words[word]; !exists {
words[word] = struct{}{}
}
}
func checkScannerError(scanner *bufio.Scanner) {
if err := scanner.Err(); err != nil {
fmt.Printf("Error reading stdin: %s\n", err)
os.Exit(1)
}
}
func searchPlatforms(words map[string]struct{}, cfg config) {
ghClient, ghErr := createGitHubClient()
glClient, glErr := createGitLabClient()
if ghErr != nil {
fmt.Printf("Error creating GitHub client: %s\n", ghErr)
}
if glErr != nil {
fmt.Printf("Error creating GitLab client: %s\n", glErr)
}
for word := range words {
if !cfg.glOnlyFlag && ghErr == nil {
verbosePrint("Searching GitHub for word: %s\n", word)
searchGitHub(ghClient, word, cfg)
}
if !cfg.ghOnlyFlag && glErr == nil {
verbosePrint("Searching GitLab for word: %s\n", word)
searchGitLab(glClient, word, cfg)
}
}
}
func cleanWord(word string) string {
match := urlRegexp.FindStringSubmatch(word)
if len(match) > 1 {
return match[1]
}
return word
}
func removeWhitespace(word string) string {
removedSpaces := spaceRegexp.ReplaceAllString(word, "")
withHyphens := spaceRegexp.ReplaceAllString(word, "-")
return removedSpaces + "\n" + withHyphens
}
func searchGitHub(client *github.Client, query string, cfg config) {
if client == nil {
return
}
if cfg.orgFlag {
searchGitHubOrganizations(client, query, cfg.maxFlag)
}
if cfg.repoFlag {
searchGitHubRepositories(client, query, cfg.maxFlag)
}
if cfg.userFlag {
searchGitHubUsers(client, query, cfg.maxFlag)
}
}
func searchGitLab(client *gitlab.Client, query string, cfg config) {
if client == nil {
return
}
if cfg.orgFlag || cfg.userFlag {
searchGitLabGroupsAndUsers(client, query, cfg.maxFlag)
}
if cfg.repoFlag {
searchGitLabProjects(client, query, cfg.maxFlag)
}
}
func searchGitHubOrganizations(client *github.Client, query string, maxResults int) {
ctx := context.Background()
opt := &github.SearchOptions{ListOptions: github.ListOptions{PerPage: maxResults}}
results, _, err := client.Search.Users(ctx, "type:org "+query, opt)
if err != nil {
fmt.Printf("Error searching organizations: %s\n", err)
return
}
orgLogins := make([]string, len(results.Users))
for i, org := range results.Users {
orgLogins[i] = *org.Login
}
printResults(fmt.Sprintf("GitHub organizations matching '%s'", query), orgLogins)
}
func searchGitHubRepositories(client *github.Client, query string, maxResults int) {
ctx := context.Background()
opt := &github.SearchOptions{ListOptions: github.ListOptions{PerPage: maxResults}}
results, _, err := client.Search.Repositories(ctx, query, opt)
if err != nil {
fmt.Printf("Error searching repositories: %s\n", err)
return
}
repoNames := make([]string, len(results.Repositories))
for i, repo := range results.Repositories {
repoNames[i] = *repo.FullName
}
printResults(fmt.Sprintf("GitHub repositories matching '%s'", query), repoNames)
}
func searchGitHubUsers(client *github.Client, query string, maxResults int) {
ctx := context.Background()
opt := &github.SearchOptions{ListOptions: github.ListOptions{PerPage: maxResults}}
results, _, err := client.Search.Users(ctx, "type:user "+query, opt)
if err != nil {
fmt.Printf("Error searching users: %s\n", err)
return
}
userLogins := make([]string, len(results.Users))
for i, user := range results.Users {
userLogins[i] = *user.Login
}
printResults(fmt.Sprintf("GitHub users matching '%s'", query), userLogins)
}
func createGitHubClient() (*github.Client, error) {
ctx := context.Background()
token := os.Getenv("GITHUB_ACCESS_TOKEN")
if token == "" {
return nil, errors.New("GITHUB_ACCESS_TOKEN environment variable is not set")
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
tc.Transport = &rateLimitedTransport{
transport: tc.Transport,
limiter: rate.NewLimiter(rate.Every(10), 10),
}
client := github.NewClient(tc)
return client, nil
}
type rateLimitedTransport struct {
transport http.RoundTripper
limiter *rate.Limiter
}
func (t *rateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if err := t.limiter.Wait(context.Background()); err != nil {
return nil, err
}
return t.transport.RoundTrip(req)
}
func searchGitLabGroupsAndUsers(client *gitlab.Client, query string, maxResults int) {
opt := &gitlab.ListGroupsOptions{Search: gitlab.String(query), ListOptions: gitlab.ListOptions{PerPage: maxResults}}
groups, _, err := client.Groups.ListGroups(opt)
if err != nil {
fmt.Printf("Error searching GitLab groups: %s\n", err)
return
}
if flags.orgFlag {
groupFullPaths := make([]string, len(groups))
for i, group := range groups {
groupFullPaths[i] = group.FullPath
}
printResults(fmt.Sprintf("GitLab groups matching '%s'", query), groupFullPaths)
}
users, _, err := client.Users.ListUsers(&gitlab.ListUsersOptions{Search: gitlab.String(query), ListOptions: gitlab.ListOptions{PerPage: maxResults}})
if err != nil {
fmt.Printf("Error searching GitLab users: %s\n", err)
return
}
if flags.userFlag {
userUsernames := make([]string, len(users))
for i, user := range users {
userUsernames[i] = user.Username
}
printResults(fmt.Sprintf("GitLab users matching '%s'", query), userUsernames)
}
}
func searchGitLabProjects(client *gitlab.Client, query string, maxResults int) {
opt := &gitlab.ListProjectsOptions{Search: gitlab.String(query), ListOptions: gitlab.ListOptions{PerPage: maxResults}}
projects, _, err := client.Projects.ListProjects(opt)
if err != nil {
fmt.Printf("Error searching GitLab projects: %s\n", err)
return
}
projectFullPaths := make([]string, len(projects))
for i, project := range projects {
projectFullPaths[i] = project.PathWithNamespace
}
printResults(fmt.Sprintf("GitLab projects matching '%s'", query), projectFullPaths)
}
func createGitLabClient() (*gitlab.Client, error) {
token := os.Getenv("GITLAB_ACCESS_TOKEN")
if token == "" {
return nil, errors.New("GITLAB_ACCESS_TOKEN environment variable is not set")
}
client, err := gitlab.NewClient(token)
if err != nil {
return nil, err
}
return client, nil
}
func printResults(header string, results []string) {
if flags.simpleFlag {
for _, result := range results {
fmt.Println(result)
}
} else {
fmt.Printf("\n%s:\n", header)
for _, result := range results {
fmt.Printf("- %s\n", result)
}
}
}