-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_selector.go
More file actions
353 lines (287 loc) · 7.7 KB
/
github_selector.go
File metadata and controls
353 lines (287 loc) · 7.7 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
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
package main
import (
"bufio"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"os/user"
"strings"
"github.com/google/go-github/github"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"gopkg.in/mattes/go-expand-tilde.v1"
"gopkg.in/src-d/go-git.v4"
"log"
)
type GithubSelector struct {
GithubToken string
CloneDir string
OrgNames []string
UserNames []string
}
const configDir = ".config/github_selector"
const cacheFile = "cache.json"
const configFile = "config.json"
var homeDir string
func main() {
refresh := flag.Bool("refresh",false, "will refresh the list of github packages")
function := flag.Bool("function", false, "print a bash function used to setup")
flag.Parse()
if *function {
fmt.Println("gs() { cd $($GOPATH/bin/github_selector) }")
os.Exit(0)
}
g := GithubSelector{}
g.Run(*refresh)
}
func (g *GithubSelector) Run(refresh bool) {
// Just initialize the config, this asks the user for config input
// or reads from disk
g.createOrLoadConfig()
// If we refresh, load github repositories
// else read the local cache and use that as the repository list
var repos []github.Repository
_, err := os.Stat(buildCachePath())
if os.IsNotExist(err) || refresh {
for _, orgName := range g.OrgNames {
ptrRepos := g.listOrgRepos(orgName, g.GithubToken)
for _, r := range ptrRepos {
repos = append(repos, *r)
}
}
for _, userName := range g.UserNames {
ptrRepos := g.listUserRepos(userName, g.GithubToken)
for _, r := range ptrRepos {
repos = append(repos, *r)
}
}
g.writeRepoCache(repos)
} else {
repos = g.readRepoCache()
}
// spawn fzf and then allow the user to pick which repository they want
filtered := g.withFilter("fzf -m", func(in io.WriteCloser) {
for _, repo := range repos {
fmt.Fprintln(in, *repo.FullName)
}
})
// take the output from fzf and then use that to pick the repository from our repo list
var selectedRepo github.Repository
for _, repo := range repos {
if *repo.FullName == filtered[0] {
selectedRepo = repo
}
}
// clone the repository
g.cloneRepo(selectedRepo)
// write out the repository name so that it can be used to cd by an external function
fmt.Printf("%s/%s\n", g.CloneDir, *selectedRepo.Name)
}
func (g *GithubSelector) cloneRepo(githubRepo github.Repository) {
basePath := g.CloneDir
repoPath := basePath + "/" + *githubRepo.Name
repo, err := git.PlainClone(repoPath, false, &git.CloneOptions{
URL: fmt.Sprintf("git@github.com:%s.git", *githubRepo.FullName),
Progress: os.Stderr,
})
if err == git.ErrRepositoryAlreadyExists {
return
}
if err != nil {
log.Fatal(err)
}
config, err := repo.Config()
if err != nil {
log.Fatal(err)
}
defaultBranch := githubRepo.GetDefaultBranch()
config.Branches[defaultBranch].Remote = "origin"
}
func (g *GithubSelector) withFilter(command string, input func(in io.WriteCloser)) []string {
shell := os.Getenv("SHELL")
if len(shell) == 0 {
shell = "sh"
}
cmd := exec.Command(shell, "-c", command)
cmd.Stderr = os.Stderr
in, _ := cmd.StdinPipe()
go func() {
input(in)
in.Close()
}()
result, _ := cmd.Output()
return strings.Split(string(result), "\n")
}
func (g *GithubSelector) listOrgRepos(organizationName string, githubToken string) []*github.Repository {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: githubToken},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
opt := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 1000},
}
// get all pages of results
var allRepos []*github.Repository
for {
repos, resp, err := client.Repositories.ListByOrg(ctx, organizationName, opt)
if err != nil {
fmt.Println(err)
}
allRepos = append(allRepos, repos...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return allRepos
}
func (g *GithubSelector) listUserRepos(userName string, githubToken string) []*github.Repository {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: githubToken},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
opt := &github.RepositoryListOptions{
ListOptions: github.ListOptions{
PerPage: 1000,
},
}
// get all pages of results
var allRepos []*github.Repository
for {
repos, resp, err := client.Repositories.List(ctx, userName, opt)
if err != nil {
fmt.Println(err)
}
allRepos = append(allRepos, repos...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return allRepos
}
/*
* Config
*/
func (g *GithubSelector) createOrLoadConfig() error {
configPath := buildConfigPath()
// Ensure directory exists
if _, err := os.Stat(buildConfigDirPath()); os.IsNotExist(err) {
os.MkdirAll(buildConfigDirPath(), 0755)
}
// Ensure config exists and if not write the defaults and return them
if _, err := os.Stat(buildConfigPath()); os.IsNotExist(err) {
fmt.Fprintln(os.Stderr, "no config found, creating new config...")
g.promptUserForConfig()
data, err := json.Marshal(g)
if err != nil {
return errors.Wrap(err, "unable to create config")
}
err = ioutil.WriteFile(configPath, data, 0644)
if err != nil {
return errors.Wrap(err, "unable to write default config")
}
return nil
}
return g.loadConfig(buildConfigPath())
}
func (g *GithubSelector) promptUserForConfig() {
var err error
g.GithubToken, err = readString("Whats your github access token?")
rawCloneDir, err := readString("Whats your git clone directory?")
g.CloneDir, err = tilde.Expand(rawCloneDir)
orgNames, err := readString("What organizations do you want to search? (comma separated)")
if err != nil {
panic("Failed to parse input")
}
orgs := strings.Split(orgNames, ",")
for _, org := range orgs {
org = strings.TrimSpace(org)
}
userNames, err := readString("What user names do you want to search? (comma separated)")
if err != nil {
panic("Failed to parse input")
}
users := strings.Split(userNames, ",")
for _, u := range users {
u = strings.TrimSpace(u)
}
g.OrgNames = orgs
g.UserNames = users
}
func (g *GithubSelector) loadConfig(path string) error {
b, err := ioutil.ReadFile(path)
if err != nil {
return errors.Wrap(err, "unable to load config")
}
var config GithubSelector
err = json.Unmarshal(b, &config)
if err != nil {
return errors.Wrap(err, "unable to unmarshal config")
}
*g = config
return nil
}
/*
* Cache Management
*/
func (g *GithubSelector) writeRepoCache(repos []github.Repository) error {
jsonRepos, err := json.Marshal(repos)
if err != nil {
return errors.Wrap(err, "unable to marshall repo JSON")
}
err = ioutil.WriteFile(buildCachePath(), jsonRepos, 0644)
if err != nil {
return errors.Wrap(err, "Unable to write cache to disk")
}
return nil
}
func (g *GithubSelector) readRepoCache() ([]github.Repository) {
jsonRepos, err := ioutil.ReadFile(buildCachePath())
if err != nil {
panic(errors.Wrap(err, "Unable to read cache"))
}
var repos []github.Repository
err = json.Unmarshal(jsonRepos, &repos)
if err != nil {
panic(errors.Wrap(err, "Unable to read cache"))
}
return repos
}
/*
* Helpers
*/
func readString(message string) (string, error) {
reader := bufio.NewReader(os.Stdin)
fmt.Fprintf(os.Stderr, "%s : ", message)
in, err := reader.ReadString('\n')
return strings.TrimSpace(in), err
}
func getHomeDir() string {
if homeDir != "" {
return homeDir
}
usr, err := user.Current()
if err != nil {
panic(err)
}
return usr.HomeDir
}
func buildConfigDirPath() string {
return fmt.Sprintf("%s/%s", getHomeDir(), configDir)
}
func buildConfigPath() string {
return fmt.Sprintf("%s/%s/%s", getHomeDir(), configDir, configFile)
}
func buildCachePath() string {
return fmt.Sprintf("%s/%s/%s", getHomeDir(), configDir, cacheFile)
}