/
run.go
96 lines (88 loc) · 1.92 KB
/
run.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
// Copyright (c) 2023 Blockwatch Data Inc.
// Author: alex@blockwatch.cc, abdul@blockwatch.cc
package compose
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
)
type RunMode byte
const (
RunModeValidate RunMode = iota
RunModeSimulate
RunModeExecute
)
type Spec struct {
Version string `yaml:"version"`
Filename string `yaml:"-"`
}
func Run(ctx Context, fpath string, mode RunMode) error {
ctx.Log.Debug("Initializing context...")
ctx.WithMode(mode)
if err := ctx.Init(); err != nil {
return err
}
visitRecursive := strings.HasSuffix(fpath, "...")
fpath = strings.TrimSuffix(fpath, "...")
finfo, err := os.Stat(fpath)
if err != nil {
return err
}
if finfo.IsDir() {
isFirst := true
return filepath.WalkDir(fpath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if visitRecursive || isFirst {
isFirst = false
return nil
} else {
return filepath.SkipDir
}
}
if _, ok := yamlExts[filepath.Ext(path)]; !ok {
return nil
}
return handleFile(ctx, path, mode)
})
} else {
return handleFile(ctx, fpath, mode)
}
}
func handleFile(ctx Context, fpath string, mode RunMode) error {
ctx.Log.Debugf("Reading file %s", fpath)
s, err := ParseFile[Spec](fpath)
if err != nil {
return err
}
s.Filename = fpath
ver := s.Version
if ver == "" {
ver = lastVersion
}
if !HasVersion(ver) {
return fmt.Errorf("%s: %v", fpath, ErrInvalidVersion)
}
eng := New(ver)
switch mode {
case RunModeValidate:
ctx.Log.Debugf("Validating file %s", s.Filename)
err = eng.Validate(ctx, s.Filename)
case RunModeSimulate:
ctx.Log.Debugf("Simulating file %s", s.Filename)
err = eng.Run(ctx, s.Filename)
case RunModeExecute:
ctx.Log.Debugf("Running file %s", s.Filename)
err = eng.Run(ctx, s.Filename)
}
if err != nil {
return fmt.Errorf("%s: %v", fpath, err)
} else {
ctx.Log.Infof("%s OK", s.Filename)
}
return nil
}