forked from drone-plugins/drone-bintray
/
main.go
288 lines (251 loc) · 8 KB
/
main.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
/*
Drone plugin to upload one or more packages to Bintray.
See DOCS.md for usage.
Author: David Tootill November 2015 (GitHub tooda02)
*/
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
"path"
"strings"
"github.com/drone/drone-go/drone"
"github.com/drone/drone-go/plugin"
)
const defaultHost = "https://api.bintray.com"
type Bintray struct {
Username string `json:"username"`
APIKey string `json:"api_key"`
Branch string `json:"branch"`
Host string `json:"host"`
Debug bool `json:"debug"`
Insecure bool `json:"insecure"`
Artifacts []Artifact `json:"artifacts"`
}
type Artifact struct {
File string `json:"file"`
Type string `json:"type"`
Owner string `json:"owner"`
Repository string `json:"repository"`
Artifact string `json:"package"`
Target string `json:"target"`
Distr string `json:"distr,omitempty"`
Component string `json:"component,omitempty"`
Arch []string `json:"arch,omitempty"`
Publish bool `json:"publish,omitempty"`
Override bool `json:"override,omitempty"`
Versioni interface{} `json:"version"`
Version string
}
var (
version string = "1.0"
buildDate string // Filled from build
bintray Bintray
)
type MessageText struct {
Message string `json:"message"`
}
func main() {
fmt.Printf("\nDrone Bintray plugin version %s %s\n", version, buildDate)
var workspace = drone.Workspace{}
plugin.Param("workspace", &workspace)
plugin.Param("vargs", &bintray)
if err := plugin.Parse(); err != nil {
fmt.Printf("ERROR Can't parse yaml config: %s", err.Error())
os.Exit(1)
}
if bintray.Host == "" {
bintray.Host = defaultHost
}
if bintray.Debug {
saveApikey := bintray.APIKey
bintray.APIKey = "******"
fmt.Printf("DEBUG plugin input:\n%#v\n%#v\n", workspace, bintray)
bintray.APIKey = saveApikey
}
if len(bintray.Branch) == 0 || bintray.Branch == "master" {
fmt.Printf("\nPublishing %d artifacts to Bintray for user %s\n", len(bintray.Artifacts), bintray.Username)
} else {
fmt.Printf("\nPublishing %d artifacts on branch %s to Bintray for user %s\n", len(bintray.Artifacts), bintray.Branch, bintray.Username)
}
for i, artifact := range bintray.Artifacts {
artifact.Version = fmt.Sprintf("%v", artifact.Versioni)
fmt.Printf("\nUploading file %d %s to %s\n", i+1,
artifact.File, artifact.getEndpoint())
artifact.Upload(workspace.Path)
}
}
// Upload a package to Bintray
func (this *Artifact) Upload(filename string) {
// Build file upload request
filepath := path.Join(filename, this.File)
file, err := os.Open(filepath)
if err != nil {
fmt.Printf("Unable to open input file %s: %s\n", filepath, err.Error())
os.Exit(1)
}
req, err := http.NewRequest("PUT", this.getEndpoint(), file)
if err != nil {
fmt.Printf("Unable to build REST request: %s\n", err.Error())
os.Exit(1)
}
req.SetBasicAuth(bintray.Username, bintray.APIKey)
req.Header.Add("X-Bintray-Override", boolToString(this.Override))
req.Header.Add("X-Bintray-Publish", boolToString(this.Publish))
if this.Type == "Debian" {
this.addDebianHeaders(req)
}
// Set up an HTTP client with a bundled root CA certificate (borrowed from Ubuntu 14.04)
// This is necessary because the required certificate is missing from the root image and
// without it the upload fails with "x509: failed to load system roots and no roots provided"
client := http.Client{}
pool := x509.NewCertPool()
if pemCerts, err := ioutil.ReadFile("/etc/ssl/certs/ca-certificates.crt"); err != nil {
fmt.Printf("Unable to read ca-certificates.crt: %s\n", err.Error())
os.Exit(1)
} else {
pool.AppendCertsFromPEM(pemCerts)
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
InsecureSkipVerify: bintray.Insecure,
},
}
}
if bintray.Debug {
dumpRequest("DEBUG HTTP Request", req)
}
// Execute the upload request and format the response
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Upload request failed: %s\n", err.Error())
dumpRequest("Failing request", req)
os.Exit(1)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Unable to read request response: %s\n", err.Error())
dumpRequest("Failing request", req)
os.Exit(1)
}
messageText := new(MessageText)
if len(respBody) > 0 {
json.Unmarshal(respBody, messageText)
}
if resp.StatusCode > 299 {
errorText := fmt.Sprintf("Error %d", resp.StatusCode)
httpErrorText := http.StatusText(resp.StatusCode)
if len(httpErrorText) > 0 {
errorText += " " + httpErrorText
}
if len(messageText.Message) > 0 {
errorText += " - " + messageText.Message
}
fmt.Printf("%s\n", errorText)
dumpRequest("Failing request", req)
os.Exit(1)
}
if len(messageText.Message) == 0 && len(respBody) > 0 {
messageText.Message = string(respBody)
}
fmt.Printf("Result: %s\n", messageText.Message)
if messageText.Message != "success" {
if this.Override || !strings.Contains(messageText.Message, "already exists") {
dumpRequest("\nRequest was:", req)
os.Exit(1)
}
}
}
// Add headers required to upload a Debian package
func (this *Artifact) addDebianHeaders(req *http.Request) {
if len(this.Distr) == 0 || len(this.Component) == 0 || len(this.Arch) == 0 {
fmt.Printf("ERROR Cannot process package %s - Missing Debian argument(s):\n", this.Artifact)
if len(this.Distr) == 0 {
fmt.Printf(" distr not defined in yaml config\n")
}
if len(this.Component) == 0 {
fmt.Printf(" component not defined in yaml config\n")
}
if len(this.Arch) == 0 {
fmt.Printf(" arch not defined in yaml config\n")
}
os.Exit(1)
}
req.Header.Add("X-Bintray-Debian-Distribution: %s", this.Distr)
req.Header.Add("X-Bintray-Debian-Component: %s", this.Component)
req.Header.Add("X-Bintray-Debian-Architecture: %s", strings.Join(this.Arch, ","))
}
// Get the Bintray endpoint corresponding to this package and version
func (this *Artifact) getEndpoint() string {
if len(this.File) == 0 ||
len(this.Owner) == 0 ||
len(this.Repository) == 0 ||
len(this.Artifact) == 0 ||
(len(this.Version) == 0 && this.Type != "Maven") ||
len(this.Target) == 0 {
fmt.Printf("ERROR Cannot process package %s - Missing argument(s):\n", this.Artifact)
if len(this.Artifact) == 0 {
fmt.Printf(" package not defined in yaml config\n")
}
if len(this.File) == 0 {
fmt.Printf(" file not defined in yaml config\n")
}
if len(this.Owner) == 0 {
fmt.Printf(" owner not defined in yaml config\n")
}
if len(this.Repository) == 0 {
fmt.Printf(" repository not defined in yaml config\n")
}
if len(this.Version) == 0 && this.Type != "Maven" {
fmt.Printf(" version not defined in yaml config\n")
}
if len(this.Target) == 0 {
fmt.Printf(" target not defined in yaml config\n")
}
os.Exit(1)
}
contentType := "content"
if this.Type == "Maven" {
contentType = "maven"
}
endpoint := fmt.Sprintf("%s/%s/%s/%s/%s/", bintray.Host, contentType, this.Owner, this.Repository, this.Artifact)
if len(this.Version) > 0 && this.Type != "Maven" {
endpoint = fmt.Sprintf("%s%s/", endpoint, this.Version)
}
if len(bintray.Branch) == 0 || bintray.Branch == "master" {
return endpoint + this.Target
}
return fmt.Sprintf("%stest/%s/%s", endpoint, bintray.Branch, this.Target)
}
// Dump an HTTP request to stdout, hiding the authorization tag
func dumpRequest(prefix string, req *http.Request) {
fmt.Printf("%s:\n", prefix)
if dumpedRequest, err := httputil.DumpRequestOut(req, false); err != nil {
fmt.Printf(" %s\n", err.Error())
} else {
for _, line := range strings.Split(string(dumpedRequest), "\n") {
line = strings.TrimSpace(line)
if len(line) > 0 {
if strings.HasPrefix(line, "Authorization:") {
line = "Authorization: Basic xxxxxxxxxx"
}
fmt.Printf(" %s\n", line)
}
}
}
}
// Convert a boolean value to string "1" or "0"
func boolToString(val bool) string {
if val {
return "1"
} else {
return "0"
}
}