-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.go
327 lines (268 loc) · 6.55 KB
/
cli.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
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
package main
import (
"context"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"golang.org/x/oauth2"
"github.com/github/hub/github"
api "github.com/google/go-github/github"
"github.com/mitchellh/colorstring"
homedir "github.com/mitchellh/go-homedir"
"github.com/skratchdot/open-golang/open"
"gopkg.in/src-d/go-git.v4"
)
const (
// EnvDebug is environmental var to handle debug mode
EnvDebug = "TOSA_DEBUG"
)
// Exit codes are in value that represnet an exit code for a paticular error
const (
ExitCodeOK int = 0
// Errors start at 10
ExitCodeError = 10 + iota
ExitCodeParseFlagsError
ExitCodeBadArgs
ExitCodePullRequestNotFound
)
// Debugf prints debug output when EnvDebug is given
func Debugf(format string, args ...interface{}) {
if env := os.Getenv(EnvDebug); len(env) != 0 {
log.Printf("[DEBUG] "+format+"\n", args...)
}
}
// PrintErrorf prints error message on console
func PrintErrorf(format string, args ...interface{}) {
format = fmt.Sprintf("[red]%s[reset]\n", format)
fmt.Fprint(os.Stderr,
colorstring.Color(fmt.Sprintf(format, args...)))
}
// CLI is the command line object
type CLI struct {
outStream, errStream io.Writer
}
// APIClient is access/operate Github object
type APIClient struct {
client *api.Client
repository *api.Repository
}
// Run invokes the CLI with the given arguments
func (c *CLI) Run(args []string) int {
var (
debug bool
url bool
apiurl bool
newline bool
version bool
)
flags := flag.NewFlagSet(args[0], flag.ContinueOnError)
flags.Usage = func() {
fmt.Fprint(c.errStream, helpText)
}
flags.BoolVar(&debug, "debug", false, "")
flags.BoolVar(&debug, "d", false, "")
flags.BoolVar(&url, "url", false, "")
flags.BoolVar(&url, "u", false, "")
flags.BoolVar(&apiurl, "apiurl", false, "")
flags.BoolVar(&apiurl, "a", false, "")
flags.BoolVar(&newline, "newline", true, "")
flags.BoolVar(&newline, "n", true, "")
flags.BoolVar(&version, "version", false, "")
flags.BoolVar(&version, "v", false, "")
// Parse flag
if err := flags.Parse(args[1:]); err != nil {
return ExitCodeParseFlagsError
}
if debug {
os.Setenv(EnvDebug, "1")
Debugf("Run as DEBUG mode")
}
if version {
fmt.Fprintf(c.outStream, fmt.Sprintf("%s\n", Version))
return ExitCodeOK
}
client, err := NewClient()
if err != nil {
return ExitCodeError
}
sha, err := getSha(flags.Args())
if err != nil {
return ExitCodeError
}
var status int
if url {
status = printURL(client, sha, newline)
} else if apiurl {
status = printAPIUrl(client, sha, newline)
} else {
status = openPr(client, sha)
}
return status
}
func printURL(client *APIClient, sha string, newline bool) int {
Debugf("Print PullRequest URL")
pr, err := client.PullRequest(sha)
if err != nil || pr == nil {
return ExitCodePullRequestNotFound
}
lastc := ""
if newline {
lastc = "\n"
}
format := fmt.Sprintf("%s%s", *pr.HTMLURL, lastc)
fmt.Fprint(os.Stdout, format)
return ExitCodeOK
}
func getSha(args []string) (string, error) {
var sha string
if len(args) == 0 {
wd, _ := os.Getwd()
repo, err := git.PlainOpen(wd)
if err != nil {
return "", err
}
ref, err := repo.Head()
if err != nil {
return "", err
}
sha = ref.Hash().String()
} else {
sha = args[0]
}
Debugf("sha: %s", sha)
return sha, nil
}
func printAPIUrl(client *APIClient, sha string, newline bool) int {
Debugf("Print API URL")
pr, err := client.PullRequest(sha)
if err != nil || pr == nil {
return ExitCodePullRequestNotFound
}
lastc := ""
if newline {
lastc = "\n"
}
format := fmt.Sprintf("%s%s", *pr.URL, lastc)
fmt.Fprint(os.Stdout, format)
return ExitCodeOK
}
func openPr(client *APIClient, sha string) int {
pr, err := client.PullRequest(sha)
if err != nil || pr == nil {
return ExitCodePullRequestNotFound
}
url := *pr.HTMLURL
Debugf("URL: %s", url)
openErr := open.Run(url)
if openErr != nil {
PrintErrorf("Could not open page.")
return ExitCodeError
}
return ExitCodeOK
}
func getAccessTokenFromConf() (string, error) {
homeDir, err := homedir.Dir()
if err != nil {
return "", err
}
confPath := filepath.Join(homeDir, ".config", "tosa")
err = os.Setenv("HUB_CONFIG", confPath)
if err != nil {
return "", err
}
c := github.CurrentConfig()
host, err := c.DefaultHost()
if err != nil {
return "", err
}
return host.AccessToken, nil
}
func getAccessToken() (string, error) {
token := os.Getenv("GITHUB_TOKEN")
if token != "" {
return token, nil
}
token, err := getAccessTokenFromConf()
if err != nil {
return "", err
}
return token, nil
}
// NewClient creates APIClient
func NewClient() (*APIClient, error) {
token, err := getAccessToken()
if err != nil {
return nil, err
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(context.Background(), ts)
client := api.NewClient(tc)
repo, err := Repository(client)
if err != nil {
return nil, err
}
return &APIClient{
client: client,
repository: repo,
}, nil
}
// PullRequest gets pull request object
func (a *APIClient) PullRequest(sha string) (*api.Issue, error) {
opt := &api.SearchOptions{
Sort: "created",
Order: "asc",
}
res, _, err := a.client.Search.Issues(
context.Background(),
fmt.Sprintf("%s is:merged repo:%v", sha, *a.repository.FullName),
opt)
if err != nil {
return nil, err
}
if len(res.Issues) == 0 {
a.repository = a.repository.Parent
if a.repository == nil {
PrintErrorf("Pull Request is not found")
return nil, nil
}
Debugf("Searching parent repository: %s", *a.repository.FullName)
return a.PullRequest(sha)
}
return &res.Issues[0], nil
}
// Repository returns api.Repository
func Repository(client *api.Client) (*api.Repository, error) {
localRepo, err := github.LocalRepo()
if err != nil {
return nil, err
}
prj, err := localRepo.MainProject()
if err != nil {
return nil, err
}
repo, _, err := client.Repositories.Get(context.Background(), prj.Owner, prj.Name)
if err != nil {
PrintErrorf("Repository not found.\n%s", err)
return nil, err
}
return repo, err
}
var helpText = `Usage: tosa [options...] [sha]
tosa is a tool to open the pull request page.
sha is a commit hash you want to know the pull request.
If not specified, get it from HEAD.
Options:
-u, --url Print the pull request url.
-a, --apiurl Print the issue API url.
-n, --newline If -u(--url) or --apiurl option is specified, print
the url with newline character at last.
-d, --debug Enable debug mode.
Print debug log.
-h, --help Show this help message and exit.
-v, --version Print current version.
`