-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
68 lines (55 loc) · 1.52 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
package main
import (
"context"
"fmt"
"os"
"github.com/google/go-github/v48/github"
"golang.org/x/oauth2"
)
type GithubClient struct {
gh *github.Client
}
func NewGithubClient() (*GithubClient, error) {
key := "GITHUB_TOKEN"
val, ok := os.LookupEnv(key)
if !ok {
fmt.Printf("%s not set\n", key)
return nil, fmt.Errorf("%s not set", key)
}
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: val},
)
tc := oauth2.NewClient(ctx, ts)
gh := github.NewClient(tc)
return &GithubClient{
gh: gh,
}, nil
}
func (gc *GithubClient) Client() *github.Client {
return gc.gh
}
func (gc *GithubClient) SearchCommit(hash string) (*github.Commit, error) {
commits, _, err := gc.Client().Search.Commits(context.Background(), "hash:"+hash, &github.SearchOptions{})
if err != nil {
//fmt.Println("Search error: ", err)
return nil, err
}
if commits.GetTotal() == 0 {
return nil, fmt.Errorf("error getting commit: no data found for %s", hash)
}
if commits.GetTotal() != 1 {
return nil, fmt.Errorf("error getting commit: not unique data returned for %s", hash)
}
commit := commits.Commits[0].Commit
return commit, nil
}
func (gc *GithubClient) GetCommitFromOrgAndRepo(org string, repo string, hash string) (*github.Commit, error) {
commits, _, err := gc.Client().Repositories.GetCommit(context.Background(), org, repo, hash, &github.ListOptions{})
if err != nil {
//fmt.Println("Can't get ", hash, " use search instead")
return nil, err
}
commit := commits.Commit
return commit, nil
}