forked from simplesurance/baur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
462 lines (371 loc) · 11.6 KB
/
app.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package baur
import (
"fmt"
"path"
"path/filepath"
"sort"
"strings"
"github.com/pkg/errors"
"github.com/rs/xid"
"github.com/simplesurance/baur/cfg"
"github.com/simplesurance/baur/digest"
"github.com/simplesurance/baur/digest/sha384"
"github.com/simplesurance/baur/log"
"github.com/simplesurance/baur/resolve/gitpath"
"github.com/simplesurance/baur/resolve/glob"
"github.com/simplesurance/baur/resolve/gosource"
"github.com/simplesurance/baur/upload/scheduler"
)
// App represents an application
type App struct {
RelPath string
Path string
Name string
BuildCmd string
Repository *Repository
Outputs []BuildOutput
totalInputDigest *digest.Digest
UseLastBuild bool
UnresolvedInputs []*cfg.BuildInput
buildInputs []*File
}
func replaceUUIDvar(in string) string {
return strings.Replace(in, "$UUID", xid.New().String(), -1)
}
func replaceROOTvar(in string, r *Repository) string {
return strings.Replace(in, "$ROOT", r.Path, -1)
}
func replaceAppNameVar(in, appName string) string {
return strings.Replace(in, "$APPNAME", appName, -1)
}
func replaceGitCommitVar(in string, r *Repository) (string, error) {
commitID, err := r.GitCommitID()
if err != nil {
return "", err
}
return strings.Replace(in, "$GITCOMMIT", commitID, -1), nil
}
func (a *App) addBuildOutput(buildOutput *cfg.BuildOutput) error {
if err := a.addDockerBuildOutputs(buildOutput); err != nil {
return errors.Wrap(err, "error in DockerImage section")
}
if err := a.addFileOutputs(buildOutput); err != nil {
return errors.Wrap(err, "error in File section")
}
return nil
}
func (a *App) addDockerBuildOutputs(buildOutput *cfg.BuildOutput) error {
for _, di := range buildOutput.DockerImage {
tag, err := replaceGitCommitVar(di.RegistryUpload.Tag, a.Repository)
if err != nil {
return errors.Wrap(err, "replacing $GITCOMMIT in tag failed")
}
tag = replaceUUIDvar(tag)
repository := replaceAppNameVar(di.RegistryUpload.Repository, a.Name)
a.Outputs = append(a.Outputs, &DockerArtifact{
ImageIDFile: path.Join(a.Path, replaceAppNameVar(di.IDFile, a.Name)),
Tag: tag,
Repository: repository,
})
}
return nil
}
func (a *App) addFileOutputs(buildOutput *cfg.BuildOutput) error {
for _, f := range buildOutput.File {
filePath := replaceAppNameVar(f.Path, a.Name)
if !f.S3Upload.IsEmpty() {
destFile, err := replaceGitCommitVar(f.S3Upload.DestFile, a.Repository)
if err != nil {
return errors.Wrap(err, "replacing $GITCOMMIT in dest_file failed")
}
destFile = replaceUUIDvar(replaceAppNameVar(destFile, a.Name))
s3Bucket := replaceAppNameVar(f.S3Upload.Bucket, a.Name)
url := "s3://" + s3Bucket + "/" + destFile
src := path.Join(a.Path, filePath)
a.Outputs = append(a.Outputs, &FileArtifact{
RelPath: path.Join(a.RelPath, filePath),
Path: src,
DestFile: destFile,
UploadURL: url,
uploadJob: &scheduler.S3Job{
DestURL: url,
FilePath: src,
},
})
}
if !f.FileCopy.IsEmpty() {
dest, err := replaceGitCommitVar(f.FileCopy.Path, a.Repository)
if err != nil {
return errors.Wrap(err, "replacing $GITCOMMIT in path failed")
}
dest = replaceUUIDvar(replaceAppNameVar(dest, a.Name))
src := path.Join(a.Path, filePath)
a.Outputs = append(a.Outputs, &FileArtifact{
RelPath: path.Join(a.RelPath, filePath),
Path: src,
DestFile: dest,
UploadURL: dest,
uploadJob: &scheduler.FileCopyJob{
Src: src,
Dst: dest,
},
})
}
}
return nil
}
func (a *App) include(inc *cfg.Include) error {
a.UnresolvedInputs = append(a.UnresolvedInputs, &inc.BuildInput)
return a.addBuildOutput(&inc.BuildOutput)
}
func (a *App) loadIncludes(appCfg *cfg.App) error {
for _, includePath := range appCfg.Build.Includes {
path := replaceROOTvar(includePath, a.Repository)
if !filepath.IsAbs(path) {
path = filepath.Join(a.Path, path)
}
inc, err := a.Repository.includeCache.load(path)
if err != nil {
return errors.Wrapf(err, "loading include '%s' failed", includePath)
}
err = a.include(inc)
if err != nil {
return errors.Wrapf(err, "including '%s' failed", includePath)
}
}
return nil
}
func (a *App) addCfgsToBuildInputs(appCfg *cfg.App) {
buildInput := cfg.BuildInput{}
buildInput.Files.Paths = append(buildInput.Files.Paths, AppCfgFile)
buildInput.Files.Paths = append(buildInput.Files.Paths, appCfg.Build.Includes...)
a.UnresolvedInputs = append(a.UnresolvedInputs, &buildInput)
}
// NewApp reads the configuration file and returns a new App
func NewApp(repository *Repository, cfgPath string) (*App, error) {
appCfg, err := cfg.AppFromFile(cfgPath)
if err != nil {
return nil, errors.Wrapf(err,
"reading application config %s failed", cfgPath)
}
err = appCfg.Validate()
if err != nil {
return nil, errors.Wrapf(err,
"validating application config %s failed",
cfgPath)
}
appAbsPath := path.Dir(cfgPath)
appRelPath, err := filepath.Rel(repository.Path, appAbsPath)
if err != nil {
return nil, errors.Wrapf(err, "%s: resolving repository relative application path failed", appCfg.Name)
}
app := App{
Repository: repository,
Path: path.Dir(cfgPath),
RelPath: appRelPath,
Name: appCfg.Name,
UseLastBuild: appCfg.UseLastBuild,
BuildCmd: strings.TrimSpace(appCfg.Build.Command),
}
err = app.addBuildOutput(&appCfg.Build.Output)
if err != nil {
return nil, errors.Wrapf(err, "%s: processing Build.Output section failed", app.Name)
}
app.UnresolvedInputs = []*cfg.BuildInput{&appCfg.Build.Input}
app.addCfgsToBuildInputs(appCfg)
err = app.loadIncludes(appCfg)
if err != nil {
return nil, errors.Wrapf(err, "%s: processing application config failed failed", app.Name)
}
return &app, nil
}
// String returns the string representation of an app
func (a *App) String() string {
return a.Name
}
func (a *App) pathsToUniqFiles(paths []string) ([]*File, error) {
dedupMap := make(map[string]struct{}, len(paths))
res := make([]*File, 0, len(paths))
for _, path := range paths {
if _, exist := dedupMap[path]; exist {
log.Debugf("%s: removed duplicate Build Input '%s'", a.Name, path)
continue
}
dedupMap[path] = struct{}{}
relPath, err := filepath.Rel(a.Repository.Path, path)
if err != nil {
return nil, errors.Wrapf(err, "resolving relative path to '%s' from '%s' failed", path, a.Repository.Path)
}
// TODO: should resolving the relative path be done in
// Newfile() instead?
res = append(res, NewFile(a.Repository.Path, relPath))
}
return res, nil
}
func (a *App) resolveGlobFileInputs() ([]string, error) {
var res []string
for _, bi := range a.UnresolvedInputs {
for _, globPath := range bi.Files.Paths {
if strings.HasPrefix(globPath, "$ROOT") {
globPath = filepath.Clean(replaceROOTvar(globPath, a.Repository))
}
if !filepath.IsAbs(globPath) {
globPath = filepath.Join(a.Path, globPath)
}
resolver := glob.NewResolver(globPath)
paths, err := resolver.Resolve()
if err != nil {
return nil, errors.Wrap(err, globPath)
}
if len(paths) == 0 {
return nil, fmt.Errorf("'%s' matched 0 files", globPath)
}
res = append(res, paths...)
}
}
return res, nil
}
func (a *App) resolveGitFileInputs() ([]string, error) {
var res []string
for _, bi := range a.UnresolvedInputs {
if len(bi.GitFiles.Paths) == 0 {
continue
}
paths := make([]string, 0, len(bi.GitFiles.Paths))
for _, path := range bi.GitFiles.Paths {
if !strings.HasPrefix(path, "$ROOT") {
paths = append(paths, path)
continue
}
absPath := replaceROOTvar(path, a.Repository)
relPath, err := filepath.Rel(a.Path, absPath)
if err != nil {
return nil, err
}
paths = append(paths, relPath)
}
resolver := gitpath.NewResolver(a.Path, paths...)
paths, err := resolver.Resolve()
if err != nil {
return nil, err
}
if len(paths) == 0 {
return nil, fmt.Errorf("'%s' matched 0 files", strings.Join(paths, ", "))
}
res = append(res, paths...)
}
return res, nil
}
func (a *App) resolveGoSrcInputs() ([]string, error) {
var res []string
for _, bi := range a.UnresolvedInputs {
if len(bi.GolangSources.Paths) == 0 {
continue
}
absGoSourcePaths := make([]string, 0, len(bi.GolangSources.Paths))
for _, relGosrcpath := range bi.GolangSources.Paths {
absPath := path.Join(a.Path, relGosrcpath)
absGoSourcePaths = append(absGoSourcePaths, absPath)
}
goSrcEnv := make([]string, 0, len(bi.GolangSources.Environment))
for _, val := range bi.GolangSources.Environment {
goSrcEnv = append(goSrcEnv, path.Clean(replaceROOTvar(val, a.Repository)))
}
resolver := gosource.NewResolver(log.Debugf, goSrcEnv, absGoSourcePaths...)
paths, err := resolver.Resolve()
if err != nil {
return nil, err
}
if len(paths) == 0 {
return nil, fmt.Errorf("'%s' matched 0 files", strings.Join(paths, ", "))
}
res = append(res, paths...)
}
return res, nil
}
func (a *App) resolveBuildInputPaths() ([]string, error) {
globPaths, err := a.resolveGlobFileInputs()
if err != nil {
return nil, errors.Wrapf(err, "resolving File BuildInputs failed")
}
gitPaths, err := a.resolveGitFileInputs()
if err != nil {
return nil, errors.Wrapf(err, "resolving GitFile BuildInputs failed")
}
goSrcPaths, err := a.resolveGoSrcInputs()
if err != nil {
return nil, errors.Wrapf(err, "resolving GoLangSources BuildInputs failed")
}
paths := make([]string, 0, len(globPaths)+len(gitPaths)+len(goSrcPaths))
paths = append(paths, globPaths...)
paths = append(paths, gitPaths...)
paths = append(paths, goSrcPaths...)
return paths, nil
}
// HasBuildInputs returns true if BuildInputs are defined for the app
func (a *App) HasBuildInputs() bool {
for _, bi := range a.UnresolvedInputs {
if len(bi.Files.Paths) != 0 {
return true
}
if len(bi.GitFiles.Paths) != 0 {
return true
}
if len(bi.GolangSources.Paths) != 0 {
return true
}
}
return false
}
// BuildInputs resolves all build inputs of the app.
// The BuildInputs are deduplicates before they are returned.
// If one more resolved path does not match a file an error is generated.
// If not build inputs are defined, an empty slice and no error is returned.
// If the function is called the first time, the BuildInputPaths are resolved
// and stored. On following calls the stored BuildInputs are returned.
func (a *App) BuildInputs() ([]*File, error) {
if a.buildInputs != nil {
return a.buildInputs, nil
}
paths, err := a.resolveBuildInputPaths()
if err != nil {
return nil, err
}
a.buildInputs, err = a.pathsToUniqFiles(paths)
if err != nil {
return nil, err
}
return a.buildInputs, nil
}
// TotalInputDigest returns the total input digest that is calculated over all
// input sources. The calculation is only done on the 1. call on following calls
// the stored digest is returned
func (a *App) TotalInputDigest() (digest.Digest, error) {
if a.totalInputDigest != nil {
return *a.totalInputDigest, nil
}
buildInputs, err := a.BuildInputs()
if err != nil {
return digest.Digest{}, err
}
digests := make([]*digest.Digest, 0, len(buildInputs))
for _, bi := range buildInputs {
d, err := bi.Digest()
if err != nil {
return digest.Digest{}, errors.Wrapf(err, "calculating input digest of %q failed", bi)
}
digests = append(digests, &d)
}
totalDigest, err := sha384.Sum(digests)
if err != nil {
return digest.Digest{}, errors.Wrap(err, "calculating total input digest")
}
a.totalInputDigest = totalDigest
return *a.totalInputDigest, nil
}
// SortAppsByName sorts the apps in the slice by Name
func SortAppsByName(apps []*App) {
sort.Slice(apps, func(i int, j int) bool {
return apps[i].Name < apps[j].Name
})
}