forked from drone/drone-yaml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
410 lines (368 loc) · 11.9 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright the Drone Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/drone/drone-runtime/engine"
"github.com/drone/drone-yaml/yaml"
"github.com/drone/drone-yaml/yaml/compiler"
"github.com/drone/drone-yaml/yaml/compiler/transform"
"github.com/drone/drone-yaml/yaml/converter"
"github.com/drone/drone-yaml/yaml/linter"
"github.com/drone/drone-yaml/yaml/pretty"
"github.com/drone/drone-yaml/yaml/signer"
"github.com/fatih/color"
"github.com/google/go-jsonnet"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
format = kingpin.Command("fmt", "format the yaml file")
formatPriv = format.Flag("privileged", "privileged mode").Short('p').Bool()
formatSave = format.Flag("save", "save result to source").Short('s').Bool()
formatFile = format.Arg("source", "source file location").Default(".drone.yml").File()
convert = kingpin.Command("convert", "convert the yaml file")
convertSave = convert.Flag("save", "save result to source").Short('s').Bool()
convertFile = convert.Arg("source", "source file location").Default(".drone.yml").File()
convertAddr = convert.Flag("addr", "remote repository address").String()
lint = kingpin.Command("lint", "lint the yaml file")
lintPriv = lint.Flag("privileged", "privileged mode").Short('p').Bool()
lintFile = lint.Arg("source", "source file location").Default(".drone.yml").File()
sign = kingpin.Command("sign", "sign the yaml file")
signKey = sign.Arg("key", "secret key").Required().String()
signFile = sign.Arg("source", "source file location").Default(".drone.yml").File()
signSave = sign.Flag("save", "save result to source").Short('s').Bool()
verify = kingpin.Command("verify", "verify the yaml signature")
verifyKey = verify.Arg("key", "secret key").Required().String()
verifyFile = verify.Arg("source", "source file location").Default(".drone.yml").File()
compile = kingpin.Command("compile", "compile the yaml file")
compileIn = compile.Arg("source", "source file location").Default(".drone.yml").File()
compileName = compile.Flag("name", "pipeline name").String()
parse = kingpin.Command("jsonnet", "parse the jsonnet file to a yaml")
parseSource = parse.Flag("source", "source file location").Default(".drone.jsonnet").String()
parseTarget = parse.Flag("target", "target file location").Default(".drone.yml").String()
parseStream = parse.Flag("stream", "Write output as a YAML stream").Default("false").Bool()
parseFormat = parse.Flag("format", "Write output as formatted YAML").Default("true").Bool()
parseStdout = parse.Flag("stdout", "Write output to stdout").Default("false").Bool()
parseString = parse.Flag("string", "Expect a string, manifest as plain text").Default("false").Bool()
)
func main() {
switch kingpin.Parse() {
case format.FullCommand():
kingpin.FatalIfError(runFormat(), "")
case convert.FullCommand():
kingpin.FatalIfError(runConvert(), "")
case lint.FullCommand():
kingpin.FatalIfError(runLint(), "")
case sign.FullCommand():
kingpin.FatalIfError(runSign(), "")
case verify.FullCommand():
kingpin.FatalIfError(runVerify(), "")
case compile.FullCommand():
kingpin.FatalIfError(runCompile(), "")
case parse.FullCommand():
kingpin.FatalIfError(runParse(), "")
}
}
// Code referenced from https://github.com/drone/drone-cli/blob/master/drone/jsonnet/jsonnet.go#L57
func runParse() error {
source := *parseSource
target := *parseTarget
data, err := ioutil.ReadFile(source)
if err != nil {
return err
}
vm := jsonnet.MakeVM()
vm.MaxStack = 500
vm.StringOutput = *parseString
vm.ErrorFormatter.SetMaxStackTraceSize(20)
vm.ErrorFormatter.SetColorFormatter(
color.New(color.FgRed).Fprintf,
)
buf := new(bytes.Buffer)
if *parseStream {
docs, err := vm.EvaluateSnippetStream(source, string(data))
if err != nil {
return err
}
for _, doc := range docs {
buf.WriteString("---")
buf.WriteString("\n")
buf.WriteString(doc)
}
} else {
result, err := vm.EvaluateSnippet(source, string(data))
if err != nil {
return err
}
buf.WriteString(result)
}
// the yaml file is parsed and formatted by default. This
// can be disabled for --format=false.
if *parseFormat {
manifest, err := yaml.Parse(buf)
if err != nil {
return err
}
buf.Reset()
pretty.Print(buf, manifest)
}
// the user can optionally write the yaml to stdout. This
// is useful for debugging purposes without mutating an
// existing file.
if *parseStdout {
io.Copy(os.Stdout, buf)
return nil
}
return ioutil.WriteFile(target, buf.Bytes(), 0644)
}
func runFormat() error {
f := *formatFile
m, err := yaml.Parse(f)
if err != nil {
return err
}
b := new(bytes.Buffer)
pretty.Print(b, m)
if *formatSave {
return ioutil.WriteFile(f.Name(), b.Bytes(), 0644)
}
_, err = io.Copy(os.Stderr, b)
return err
}
func runConvert() error {
f := *convertFile
d, err := ioutil.ReadAll(f)
if err != nil {
return err
}
m := converter.Metadata{
Filename: f.Name(),
URL: *convertAddr,
}
b, err := converter.Convert(d, m)
if err != nil {
return err
}
if *formatSave {
return ioutil.WriteFile(f.Name(), b, 0644)
}
_, err = io.Copy(os.Stderr, bytes.NewReader(b))
return err
}
func runLint() error {
f := *lintFile
m, err := yaml.Parse(f)
if err != nil {
return err
}
for _, r := range m.Resources {
err := linter.Lint(r, *lintPriv)
if err != nil {
return err
}
}
return nil
}
func runSign() error {
f := *signFile
d, err := ioutil.ReadAll(f)
if err != nil {
return err
}
k := signer.KeyString(*signKey)
if *signSave {
out, err := signer.SignUpdate(d, k)
if err != nil {
return err
}
return ioutil.WriteFile(f.Name(), out, 0644)
}
hmac, err := signer.Sign(d, k)
if err != nil {
return err
}
fmt.Println(hmac)
return nil
}
func runVerify() error {
f := *verifyFile
d, err := ioutil.ReadAll(f)
if err != nil {
return err
}
k := signer.KeyString(*verifyKey)
ok, err := signer.Verify(d, k)
if err != nil {
return err
} else if !ok {
return errors.New("cannot verify yaml signature")
}
fmt.Println("success: yaml signature verified")
return nil
}
var (
trusted = compile.Flag("trusted", "trusted mode").Bool()
labels = compile.Flag("label", "container labels").StringMap()
clone = compile.Flag("clone", "clone step").Bool()
volume = compile.Flag("volume", "attached volumes").StringMap()
network = compile.Flag("network", "attached networks").Strings()
environ = compile.Flag("env", "environment variable").StringMap()
dind = compile.Flag("dind", "dind images").Default("plugins/docker").Strings()
event = compile.Flag("event", "event type").PlaceHolder("<event>").Enum("push", "pull_request", "tag", "deployment")
repo = compile.Flag("repo", "repository name").PlaceHolder("octocat/hello-world").String()
remote = compile.Flag("git-remote", "git remote url").PlaceHolder("https://github.com/octocat/hello-world.git").String()
branch = compile.Flag("git-branch", "git commit branch").PlaceHolder("master").String()
ref = compile.Flag("git-ref", "git commit ref").PlaceHolder("refs/heads/master").String()
sha = compile.Flag("git-sha", "git commit sha").String()
creds = compile.Flag("git-creds", "git credentials").URLList()
cron = compile.Flag("cron", "cron job name").String()
instance = compile.Flag("instance", "drone instance hostname").PlaceHolder("drone.company.com").String()
deploy = compile.Flag("deploy-to", "target deployment").PlaceHolder("production").String()
secrets = compile.Flag("secret", "secret variable").StringMap()
registries = compile.Flag("registry", "registry credentials").URLList()
username = compile.Flag("netrc-username", "netrc username").PlaceHolder("<token>").String()
password = compile.Flag("netrc-password", "netrc password").PlaceHolder("x-oauth-basic").String()
machine = compile.Flag("netrc-machine", "netrc machine").PlaceHolder("github.com").String()
memlimit = compile.Flag("mem-limit", "memory limit").PlaceHolder("1GB").Bytes()
)
func runCompile() error {
m, err := yaml.Parse(*compileIn)
if err != nil {
return err
}
var p *yaml.Pipeline
for _, r := range m.Resources {
v, ok := r.(*yaml.Pipeline)
if !ok {
continue
}
if *compileName == "" ||
*compileName == v.Name {
p = v
break
}
}
if p == nil {
return errors.New("cannot find pipeline resource")
}
// the user has the option to disable the git clone
// if the pipeline is being executed on the local
// codebase.
if *clone == false {
p.Clone.Disable = true
}
var auths []*engine.DockerAuth
for _, uri := range *registries {
if uri.User == nil {
log.Fatalln("Expect registry format [user]:[password]@hostname")
}
password, ok := uri.User.Password()
if !ok {
log.Fatalln("Invalid or missing registry password")
}
auths = append(auths, &engine.DockerAuth{
Address: uri.Host,
Username: uri.User.Username(),
Password: password,
})
}
comp := new(compiler.Compiler)
comp.GitCredentialsFunc = defaultCreds // TODO create compiler.GitCredentialsFunc and compiler.GlobalGitCredentialsFunc
comp.NetrcFunc = nil // TODO create compiler.NetrcFunc and compiler.GlobalNetrcFunc
comp.PrivilegedFunc = compiler.DindFunc(*dind)
comp.SkipFunc = compiler.SkipFunc(
compiler.SkipData{
Branch: *branch,
Cron: *cron,
Event: *event,
Instance: *instance,
Ref: *ref,
Repo: *repo,
Target: *deploy,
},
)
comp.TransformFunc = transform.Combine(
transform.WithAuths(auths),
transform.WithEnviron(*environ),
transform.WithEnviron(defaultEnvs()),
transform.WithLables(*labels),
transform.WithLimits(int64(*memlimit), 0),
transform.WithNetrc(*machine, *username, *password),
transform.WithNetworks(*network),
transform.WithProxy(),
transform.WithSecrets(*secrets),
transform.WithVolumes(*volume),
)
compiled := comp.Compile(p)
// // for drone-exec we will need to change the workspace
// // to a host volume mount, to the current working dir.
// for _, volume := range compiled.Docker.Volumes {
// if volume.Metadata.Name == "workspace" {
// volume.EmptyDir = nil
// volume.HostPath = &engine.VolumeHostPath{
// Path: "", // pwd
// }
// break
// }
// }
// // then we need to change the base mount for every container
// // to use the workspace base + path.
// for _, container := range compiled.Steps {
// for _, volume := range container.Volumes {
// if volume.Name == "workspace" {
// volume.Path = container.Envs["DRONE_WORKSPACE"]
// }
// }
// }
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(compiled)
}
// helper function returns the git credential function,
// used to return a git credentials file.
func defaultCreds() []byte {
urls := *creds
if len(urls) == 0 {
return nil
}
var buf bytes.Buffer
for _, url := range urls {
buf.WriteString(url.String())
buf.WriteByte('\n')
}
return buf.Bytes()
}
// helper function returns the minimum required environment
// variables to clone a repository. All other environment
// variables should be passed via the --env flag.
func defaultEnvs() map[string]string {
envs := map[string]string{}
envs["DRONE_COMMIT_BRANCH"] = *branch
envs["DRONE_COMMIT_SHA"] = *sha
envs["DRONE_COMMIT_REF"] = *ref
envs["DRONE_REMOTE_URL"] = *remote
envs["DRONE_BUILD_EVENT"] = *event
if strings.HasPrefix(*ref, "refs/tags/") {
envs["DRONE_TAG"] = strings.TrimPrefix(*ref, "refs/tags/")
}
return envs
}