/
main.go
303 lines (277 loc) · 7.29 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path"
"strconv"
"strings"
"github.com/drone/drone-go/drone"
"github.com/urfave/cli"
"golang.org/x/oauth2"
)
// Version is set at compile time, passing -ldflags "-X main.Version=<build version>"
var Version string
func main() {
app := cli.NewApp()
app.Name = "drone-trigger"
app.Author = "Vaidas Jablonskis <jablonskis@gmail.com>"
app.Version = Version
app.Usage = "trigger drone builds or deployments"
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "verbose",
Usage: "verbose output",
EnvVar: "VERBOSE,PLUGIN_VERBOSE",
},
cli.StringFlag{
Name: "drone-server, s",
Usage: "drone server `URL`",
EnvVar: "DRONE_SERVER,PLUGIN_DRONE_SERVER",
},
cli.StringFlag{
Name: "drone-token, t",
Usage: "drone auth `TOKEN`",
EnvVar: "DRONE_TOKEN,PLUGIN_DRONE_TOKEN",
},
cli.StringFlag{
Name: "repo, r",
Usage: "`REPO`, eg. foo/bar",
EnvVar: "REPO,PLUGIN_REPO",
},
cli.StringFlag{
Name: "commit, c",
Usage: "filter by commit sha",
EnvVar: "FILTER_COMMIT,PLUGIN_COMMIT",
},
cli.StringFlag{
Name: "tag",
Usage: "filter by tag",
EnvVar: "FILTER_TAG,PLUGIN_TAG",
},
cli.StringFlag{
Name: "branch, b",
Usage: "filter by branch",
EnvVar: "FILTER_BRANCH,PLUGIN_BRANCH",
},
cli.StringFlag{
Name: "status",
Usage: "filter by build status",
EnvVar: "FILTER_STATUS,PLUGIN_STATUS",
Value: "success",
},
cli.IntFlag{
Name: "number",
Usage: "filter by build number",
EnvVar: "FILTER_NUMBER,PLUGIN_NUMBER",
},
cli.StringFlag{
Name: "event",
Usage: "filter by trigger event",
EnvVar: "FILTER_EVENT,PLUGIN_EVENT",
},
cli.StringFlag{
Name: "deployed-to",
Usage: "filter by environment deployed to",
EnvVar: "FILTER_DEPLOYED_TO,PLUGIN_DEPLOYED_TO",
},
cli.StringFlag{
Name: "deploy-to, d",
Usage: "environment to deploy to, if set a deployment event will be triggered",
EnvVar: "DEPLOY_TO,PLUGIN_DEPLOY_TO",
},
cli.StringSliceFlag{
Name: "param, p",
Usage: "custom parameters to include in the trigger in KEY=value format",
EnvVar: "PARAMS,PLUGIN_PARAMS",
},
}
app.Action = run
app.Run(os.Args)
}
// Trigger represent drone trigger.
type Trigger struct {
client drone.Client
}
func newTrigger(ctx *cli.Context) *Trigger {
oauthCfg := &oauth2.Config{}
httpClient := oauthCfg.Client(
context.Background(),
&oauth2.Token{
AccessToken: ctx.String("drone-token"),
},
)
return &Trigger{
client: drone.NewClient(ctx.String("drone-server"), httpClient),
}
}
func run(ctx *cli.Context) error {
// Exit if required flags are not set
if !ctx.IsSet("drone-server") && !isAnyEnvSet("DRONE_SERVER", "PLUGIN_DRONE_SERVER") {
if err := cli.ShowAppHelp(ctx); err != nil {
return cli.NewExitError(err, 1)
}
return cli.NewExitError("error: drone server is not set", 3)
}
if !ctx.IsSet("drone-token") && !isAnyEnvSet("DRONE_TOKEN", "PLUGIN_DRONE_TOKEN") {
if err := cli.ShowAppHelp(ctx); err != nil {
return cli.NewExitError(err, 1)
}
return cli.NewExitError("error: drone token is not set", 3)
}
if !ctx.IsSet("repo") && !isAnyEnvSet("REPO", "PLUGIN_REPO") {
if err := cli.ShowAppHelp(ctx); err != nil {
return cli.NewExitError(err, 1)
}
return cli.NewExitError("error: repo is not set", 3)
}
loneFilters := 0
if ctx.IsSet("tag") || isAnyEnvSet("FILTER_TAG", "PLUGIN_TAG") {
loneFilters++
}
if ctx.IsSet("branch") || isAnyEnvSet("FILTER_BRANCH", "PLUGIN_BRANCH") {
loneFilters++
}
if ctx.IsSet("commit") || isAnyEnvSet("FILTER_COMMIT", "PLUGIN_COMMIT") {
loneFilters++
}
if ctx.IsSet("deployed-to") || isAnyEnvSet("FILTER_DEPLOYED_TO", "PLUGIN_DEPLOYED_TO") {
loneFilters++
}
if loneFilters > 1 {
return cli.NewExitError("error: tag, branch, commit or deployed-to cannot be set at the same time, pick one filter", 3)
}
t := newTrigger(ctx)
build, err := t.findBuild(ctx)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
if build == nil {
return cli.NewExitError("No previous builds found", 1)
}
params := parsePairs(ctx.StringSlice("param"))
var newBuild *drone.Build
owner, repo, err := parseRepo(ctx.String("repo"))
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
if ctx.IsSet("deploy-to") || isAnyEnvSet("DEPLOY_TO", "PLUGIN_DEPLOY_TO") {
b, err := t.client.Deploy(owner, repo, build.Number, ctx.String("deploy-to"), params)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
newBuild = b
} else {
b, err := t.client.BuildStart(owner, repo, build.Number, params)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
newBuild = b
}
newBuildURL := path.Join(ctx.String("drone-server"), ctx.String("repo"), strconv.Itoa(newBuild.Number))
fmt.Fprintf(os.Stderr, "Follow new build status at: %s\n", newBuildURL)
if ctx.Bool("verbose") {
j, err := json.MarshalIndent(newBuild, "", " ")
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
fmt.Println(string(j))
}
return nil
}
// findBuild requests an array of previous repo builds from drone API and finds
// the one that matches given filters
func (t *Trigger) findBuild(ctx *cli.Context) (*drone.Build, error) {
user, repo, err := parseRepo(ctx.String("repo"))
if err != nil {
return nil, err
}
builds, err := t.client.BuildList(user, repo)
if err != nil {
return nil, err
}
for _, b := range builds {
if match(ctx, b) {
return b, nil
}
}
return nil, nil
}
// match returns true for the first build that matches cli filter flags.
func match(ctx *cli.Context, build *drone.Build) bool {
if ctx.String("status") != build.Status {
return false
}
if ctx.IsSet("event") && ctx.String("event") != build.Event {
return false
}
// Build number always takes precedence
if ctx.IsSet("number") {
if ctx.Int("number") == build.Number {
return true
}
return false
}
if ctx.IsSet("commit") {
if ctx.String("commit") == build.Commit {
return true
}
return false
}
if ctx.IsSet("tag") {
if "refs/tags/"+ctx.String("tag") == build.Ref {
return true
}
return false
}
if ctx.IsSet("deployed-to") {
if ctx.String("deployed-to") == build.Deploy {
return true
}
return false
}
// Matching on branch does not make sense for pull_request events, because
// the branch for PR events is the base branch.
if ctx.IsSet("branch") {
if ctx.String("branch") == build.Branch && build.Event != "pull_request" {
return true
}
return false
}
// Return latest successful build if no specific filters are set
return true
}
// parseRepo parses a owner/repo string into two parts
func parseRepo(s string) (owner, repo string, err error) {
var parts = strings.Split(s, "/")
if len(parts) != 2 {
err = fmt.Errorf("error: invalid or missing repository. eg octocat/hello-world")
return
}
owner = parts[0]
repo = parts[1]
return
}
// parsePairs parses an array of KEY=VALUE strings into a map
func parsePairs(p []string) map[string]string {
params := map[string]string{}
for _, i := range p {
parts := strings.Split(i, "=")
if len(parts) != 2 {
continue
}
params[parts[0]] = parts[1]
}
return params
}
// isAnyEnvSet checks if any of given environment vars is set and returns a boolean
func isAnyEnvSet(vars ...string) bool {
for _, v := range vars {
_, r := os.LookupEnv(v)
if r {
return r
}
}
return false
}