/
github.go
88 lines (78 loc) · 1.88 KB
/
github.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
package github
import (
"context"
"net/http"
"github.com/AlexAkulov/hungryfox"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type Client struct {
Token string
WorkDir string
client *github.Client
}
func (c *Client) connect() {
if c.client == nil {
c.client = github.NewClient(c.getTokenClient())
}
}
func (c *Client) FetchOrgRepos(orgName string) ([]hungryfox.RepoLocation, error) {
opts := &github.RepositoryListByOrgOptions{
ListOptions: github.ListOptions{PerPage: 10},
}
c.connect()
ctx := context.Background()
var repoList []hungryfox.RepoLocation
for {
repo, resp, err := c.client.Repositories.ListByOrg(ctx, orgName, opts)
if err != nil {
return repoList, err
}
if resp.NextPage == 0 {
break
}
repoList = append(repoList, c.convertRepoList(repo)...)
opts.Page = resp.NextPage
}
return repoList, nil
}
func (c *Client) FetchUserRepos(userName string) ([]hungryfox.RepoLocation, error) {
opts := &github.RepositoryListOptions{
ListOptions: github.ListOptions{PerPage: 10},
}
c.connect()
ctx := context.Background()
var repoList []hungryfox.RepoLocation
for {
repo, resp, err := c.client.Repositories.List(ctx, userName, opts)
if err != nil {
return repoList, err
}
if resp.NextPage == 0 {
break
}
repoList = append(repoList, c.convertRepoList(repo)...)
opts.Page = resp.NextPage
}
return repoList, nil
}
func (c *Client) convertRepoList(list []*github.Repository) (hfRepoList []hungryfox.RepoLocation) {
for _, repo := range list {
hfRepoList = append(hfRepoList, hungryfox.RepoLocation{
URL: *repo.HTMLURL,
CloneURL: *repo.CloneURL,
DataPath: c.WorkDir,
RepoPath: *repo.FullName,
})
}
return
}
func (c *Client) getTokenClient() *http.Client {
if c.Token == "" {
return nil
}
return oauth2.NewClient(
context.Background(),
oauth2.StaticTokenSource(&oauth2.Token{AccessToken: c.Token}),
)
}