-
Notifications
You must be signed in to change notification settings - Fork 13
/
github.go
101 lines (92 loc) · 2.47 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
89
90
91
92
93
94
95
96
97
98
99
100
101
package git
import (
"fmt"
"strings"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
// GithubConfig is the configuration for the github client
type GithubConfig struct {
Token string
Owner string
Repo string
}
type githubService struct {
config *GithubConfig
client *github.Client
}
// InitGithub initializes the github git service with the given config
func InitGithub(config *GithubConfig) {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: config.Token},
)
tc := oauth2.NewClient(oauth2.NoContext, ts)
service = &githubService{
config: config,
client: github.NewClient(tc),
}
}
func (s *githubService) getContents(branch, path string) (*github.RepositoryContent, []*github.RepositoryContent, *github.Response, error) {
var opts *github.RepositoryContentGetOptions
if branch != "" {
opts = &github.RepositoryContentGetOptions{Ref: branch}
}
return s.client.Repositories.GetContents(s.config.Owner, s.config.Repo, path, opts)
}
// Branches returns a list of branches for the repository
func (s *githubService) Branches() ([]string, error) {
var opts *github.ListOptions
var ret []string
for {
branches, resp, err := s.client.Repositories.ListBranches(s.config.Owner, s.config.Repo, opts)
if err != nil {
return nil, err
}
for _, branch := range branches {
ret = append(ret, *branch.Name)
}
if resp.NextPage > 0 {
opts = &github.ListOptions{
Page: resp.NextPage,
}
} else {
return ret, nil
}
}
}
// Contents returns the contents of the file at the given path
func (s *githubService) Contents(branch, path string) ([]byte, error) {
file, _, _, err := s.getContents(branch, path)
if err != nil {
if errResp, ok := err.(*github.ErrorResponse); ok {
if errResp.Response.StatusCode == 404 {
return nil, nil
}
}
return nil, err
}
if file == nil {
return nil, fmt.Errorf("%s is a directory", path)
}
return file.Decode()
}
// List returns a list of subpaths of the given directory path
func (s *githubService) List(branch, path string) ([]string, error) {
_, directory, _, err := s.getContents(branch, path)
if err != nil {
if errResp, ok := err.(*github.ErrorResponse); ok {
if errResp.Response.StatusCode == 404 {
return nil, nil
}
}
return nil, err
}
if directory == nil {
return nil, fmt.Errorf("%s is a file", path)
}
var paths []string
for _, file := range directory {
paths = append(paths, strings.TrimPrefix(strings.TrimPrefix(*file.Path, path), "/"))
}
return paths, nil
}