forked from mercari/tfnotify
/
client.go
91 lines (75 loc) · 1.65 KB
/
client.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
package github
import (
"errors"
"os"
"strings"
"github.com/google/go-github/github"
"github.com/mercari/tfnotify/terraform"
"golang.org/x/oauth2"
)
// EnvToken is GitHub API Token
const EnvToken = "GITHUB_TOKEN"
// Client is a API client for GitHub
type Client struct {
*github.Client
Debug bool
Config Config
common service
Comment *CommentService
Commits *CommitsService
Notify *NotifyService
API API
}
// Config is a configuration for GitHub client
type Config struct {
Token string
Owner string
Repo string
PR PullRequest
CI string
Parser terraform.Parser
Template terraform.Template
}
// PullRequest represents GitHub Pull Request metadata
type PullRequest struct {
Revision string
Message string
Number int
}
type service struct {
client *Client
}
// NewClient returns Client initialized with Config
func NewClient(cfg Config) (*Client, error) {
token := cfg.Token
token = strings.TrimPrefix(token, "$")
if token == EnvToken {
token = os.Getenv(EnvToken)
}
if token == "" {
return &Client{}, errors.New("github token is missing")
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(oauth2.NoContext, ts)
client := github.NewClient(tc)
c := &Client{
Config: cfg,
Client: client,
}
c.common.client = c
c.Comment = (*CommentService)(&c.common)
c.Commits = (*CommitsService)(&c.common)
c.Notify = (*NotifyService)(&c.common)
c.API = &GitHub{
Client: client,
owner: cfg.Owner,
repo: cfg.Repo,
}
return c, nil
}
// IsNumber returns true if PullRequest is Pull Request build
func (pr *PullRequest) IsNumber() bool {
return pr.Number != 0
}