forked from tcnksm/ghr
/
client.go
103 lines (81 loc) · 2.46 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
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"fmt"
"net/http"
"net/url"
"code.google.com/p/goauth2/oauth"
"github.com/google/go-github/github"
"strings"
)
// GitHubAPIOpts are the options for GitHub API.
type GitHubAPIOpts struct {
// BaseURL is a GitHub API URL that ghr try to access.
// Default is https://api.github.com/
BaseURL *url.URL
// Token is the GitHub API token
Token string
// ID is release ID. Each release has its unique ID
ID int
// Tag is release tag.
TagName string
// RepoName is repository name.
RepoName string
// OwnerName is repositoy owner name.
OwnerName string
// TargetCommitish specifies the commitish value that determines
// where the Git tag is created from.
TargetCommitish string
// Body describes the contens of the tag.
Body string
// If Draft is true, release would be draft (unpublished).
Draft bool
// If Prerelease is true, release would be prerelease.
Prerelease bool
// UPloadURL is URL to upload artifacts.
UploadURL string
}
// NewOAuthedClient create client with oauth
func NewOAuthedClient(apiOpts *GitHubAPIOpts) *github.Client {
// Create OAuth client
t := &oauth.Transport{
Token: &oauth.Token{AccessToken: apiOpts.Token},
}
// Create GitHub API client with OAuth client
client := github.NewClient(t.Client())
// If other URL is provided, Set it
if apiOpts.BaseURL != nil {
client.BaseURL = apiOpts.BaseURL
}
return client
}
// extractUploadURL extracts uploadURL.
func ExtractUploadURL(apiOpts *GitHubAPIOpts) *url.URL {
bracket := strings.Index(apiOpts.UploadURL, "repos/")
u, _ := url.Parse(apiOpts.UploadURL[0:bracket])
return u
}
// checkStatusOK checks http status returned by API is 200
func CheckStatusOK(res *github.Response) error {
if res.StatusCode != http.StatusOK {
return fmt.Errorf("Github returned %s\n", res.Status)
}
return nil
}
// CheckStatusCreated checks http status returned by API is 201
func CheckStatusCreated(res *github.Response) error {
if res.StatusCode != http.StatusCreated {
if res.StatusCode == 422 {
return fmt.Errorf("Github returned %s (this is probably because the release already exists)\n", res.Status)
}
return fmt.Errorf("Github returned %s\n", res.Status)
}
return nil
}
// checkStatusNoContent checks http status returned by API is 204
// In github API, this means DELETE request is success.
func CheckStatusNoContent(res *github.Response) error {
if res.StatusCode != http.StatusNoContent {
return fmt.Errorf("Github returned %s\n", res.Status)
}
return nil
}