-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmain.go
More file actions
340 lines (303 loc) · 9.53 KB
/
main.go
File metadata and controls
340 lines (303 loc) · 9.53 KB
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
package main
import (
_ "embed"
"fmt"
"os"
"path/filepath"
"strings"
"text/tabwriter"
"github.com/mxlint/mxlint-cli/lint"
"github.com/mxlint/mxlint-cli/mpr"
"github.com/mxlint/mxlint-cli/serve"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
//go:embed default.yaml
var bakedDefaultConfigYAML []byte
// version is set at build time via ldflags.
var version = "dev"
func main() {
lint.SetDefaultConfigYAML(bakedDefaultConfigYAML)
var rootCmd = &cobra.Command{Use: "mxlint-cli"}
rootCmd.PersistentFlags().BoolP("verbose", "v", false, "Turn on debug logs for all commands")
rootCmd.PersistentFlags().String("config", "", "Path to config file (highest precedence)")
var cmdVersion = &cobra.Command{
Use: "version",
Short: "Show CLI version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(version)
},
}
rootCmd.AddCommand(cmdVersion)
var cmdExportModel = &cobra.Command{
Use: "export",
Aliases: []string{"export-model"},
Short: "Export Mendix model to yaml files",
Long: "The output is a text representation of the model. It is a one-way conversion that aims to keep the semantics yet readable for humans and computers.",
Run: func(cmd *cobra.Command, args []string) {
projectDir, err := os.Getwd()
if err != nil {
fmt.Printf("failed to resolve current working directory: %s\n", err)
os.Exit(1)
}
config, err := lint.LoadMergedConfigFromPath(projectDir, configPathForCommand(cmd))
if err != nil {
fmt.Printf("failed to load configuration: %s\n", err)
os.Exit(1)
}
log := logrus.New()
if isVerbose(cmd) {
log.SetLevel(logrus.DebugLevel)
} else {
log.SetLevel(logrus.InfoLevel)
}
mpr.SetLogger(log)
lint.SetConfig(config)
configureCache(config, projectDir)
inputDirectory := config.ProjectDirectory
outputDirectory := config.Modelsource
err = mpr.ExportModel(
inputDirectory,
outputDirectory,
boolValue(config.Export.Raw, false),
boolValue(config.Export.Appstore, false),
config.Export.Filter,
)
if err != nil {
log.Errorf("export failed: %s", err)
os.Exit(1)
}
},
}
rootCmd.AddCommand(cmdExportModel)
var cmdLint = &cobra.Command{
Use: "lint",
Short: "Evaluate Mendix model against rules. Requires the model to be exported first",
Long: "The model is evaluated against a set of rules. The rules are defined in OPA rego files. The output is a list of checked rules and their outcome.",
Run: func(cmd *cobra.Command, args []string) {
projectDir, err := os.Getwd()
if err != nil {
fmt.Printf("failed to resolve current working directory: %s\n", err)
os.Exit(1)
}
config, err := lint.LoadMergedConfigFromPath(projectDir, configPathForCommand(cmd))
if err != nil {
fmt.Printf("failed to load configuration: %s\n", err)
os.Exit(1)
}
log := logrus.New()
if isVerbose(cmd) {
log.SetLevel(logrus.DebugLevel)
} else {
log.SetLevel(logrus.InfoLevel)
}
lint.SetLogger(log)
lint.SetConfig(config)
configureCache(config, projectDir)
rulesDirectory := config.Rules.Path
modelDirectory := config.Modelsource
if !filepath.IsAbs(rulesDirectory) {
rulesDirectory = filepath.Join(projectDir, rulesDirectory)
}
if config != nil && len(config.Rules.Rulesets) > 0 {
log.Infof("Syncing %d rulesets to %s", len(config.Rules.Rulesets), rulesDirectory)
if err := lint.SyncRulesets(config.Rules.Rulesets, rulesDirectory, projectDir); err != nil {
log.Errorf("failed to sync rulesets: %s", err)
os.Exit(1)
}
}
err = lint.EvalAll(
rulesDirectory,
modelDirectory,
config.Lint.XunitReport,
config.Lint.JSONFile,
boolValue(config.Lint.IgnoreNoqa, false),
boolValue(config.Cache.Enable, true),
)
if err != nil {
log.Errorf("lint failed: %s", err)
os.Exit(1)
}
},
}
rootCmd.AddCommand(cmdLint)
var cmdConfig = &cobra.Command{
Use: "config",
Short: "Show merged active configuration",
Long: "Shows the merged active configuration and which config sources were found and used.",
Run: func(cmd *cobra.Command, args []string) {
projectDir, err := os.Getwd()
if err != nil {
fmt.Printf("failed to resolve current working directory: %s\n", err)
os.Exit(1)
}
config, report, err := lint.LoadMergedConfigWithReportFromPath(projectDir, configPathForCommand(cmd))
if err != nil {
fmt.Printf("failed to load configuration: %s\n", err)
os.Exit(1)
}
fmt.Println("Config Sources")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "SOURCE\tFOUND\tUSED\tPATH")
fmt.Fprintf(w, "%s\t%t\t%t\t%s\n", report.Default.Name, report.Default.Found, report.Default.Used, report.Default.Path)
fmt.Fprintf(w, "%s\t%t\t%t\t%s\n", report.System.Name, report.System.Found, report.System.Used, report.System.Path)
fmt.Fprintf(w, "%s\t%t\t%t\t%s\n", report.Project.Name, report.Project.Found, report.Project.Used, report.Project.Path)
fmt.Fprintf(w, "%s\t%t\t%t\t%s\n", report.Explicit.Name, report.Explicit.Found, report.Explicit.Used, report.Explicit.Path)
_ = w.Flush()
yamlBytes, err := yaml.Marshal(config)
if err != nil {
fmt.Printf("failed to marshal merged configuration: %s\n", err)
os.Exit(1)
}
fmt.Println("\nMerged Active Configuration")
fmt.Print(string(yamlBytes))
},
}
rootCmd.AddCommand(cmdConfig)
// Add the serve command
serveCmd := serve.NewServeCommand()
rootCmd.AddCommand(serveCmd)
var cmdRules = &cobra.Command{
Use: "test-rules",
Short: "Ensure rules are working as expected against predefined test cases",
Long: "When you are developing a new rule, you can use this command to ensure it works as expected against predefined test cases.",
Run: func(cmd *cobra.Command, args []string) {
projectDir, err := os.Getwd()
if err != nil {
fmt.Printf("failed to resolve current working directory: %s\n", err)
os.Exit(1)
}
config, err := lint.LoadMergedConfigFromPath(projectDir, configPathForCommand(cmd))
if err != nil {
fmt.Printf("failed to load configuration: %s\n", err)
os.Exit(1)
}
log := logrus.New()
if isVerbose(cmd) {
log.SetLevel(logrus.DebugLevel)
} else {
log.SetLevel(logrus.InfoLevel)
}
lint.SetLogger(log)
err = lint.TestAll(config.Rules.Path)
if err != nil {
log.Errorf("Test rules failed: %s", err)
os.Exit(1)
}
},
}
rootCmd.AddCommand(cmdRules)
var cmdCacheClear = &cobra.Command{
Use: "cache-clear",
Short: "Clear the lint results cache",
Long: "Removes all cached lint results. The cache is used to speed up repeated linting operations when rules and model files haven't changed.",
Run: func(cmd *cobra.Command, args []string) {
projectDir, err := os.Getwd()
if err != nil {
fmt.Printf("failed to resolve current working directory: %s\n", err)
os.Exit(1)
}
config, err := lint.LoadMergedConfigFromPath(projectDir, configPathForCommand(cmd))
if err != nil {
fmt.Printf("failed to load configuration: %s\n", err)
os.Exit(1)
}
lint.SetConfig(config)
configureCache(config, projectDir)
log := logrus.New()
if isVerbose(cmd) {
log.SetLevel(logrus.DebugLevel)
} else {
log.SetLevel(logrus.InfoLevel)
}
lint.SetLogger(log)
err = lint.ClearCache()
if err != nil {
log.Errorf("Failed to clear cache: %s", err)
os.Exit(1)
}
},
}
rootCmd.AddCommand(cmdCacheClear)
var cmdCacheStats = &cobra.Command{
Use: "cache-stats",
Short: "Show cache statistics",
Long: "Displays information about the cached lint results, including number of entries and total size.",
Run: func(cmd *cobra.Command, args []string) {
projectDir, err := os.Getwd()
if err != nil {
fmt.Printf("failed to resolve current working directory: %s\n", err)
os.Exit(1)
}
config, err := lint.LoadMergedConfigFromPath(projectDir, configPathForCommand(cmd))
if err != nil {
fmt.Printf("failed to load configuration: %s\n", err)
os.Exit(1)
}
lint.SetConfig(config)
configureCache(config, projectDir)
log := logrus.New()
if isVerbose(cmd) {
log.SetLevel(logrus.DebugLevel)
} else {
log.SetLevel(logrus.InfoLevel)
}
lint.SetLogger(log)
count, size, err := lint.GetCacheStats()
if err != nil {
log.Errorf("Failed to get cache stats: %s", err)
os.Exit(1)
}
sizeInKB := float64(size) / 1024.0
sizeInMB := sizeInKB / 1024.0
log.Infof("Cache Statistics:")
log.Infof(" Entries: %d", count)
if sizeInMB >= 1.0 {
log.Infof(" Total Size: %.2f MB", sizeInMB)
} else {
log.Infof(" Total Size: %.2f KB", sizeInKB)
}
},
}
rootCmd.AddCommand(cmdCacheStats)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func configureCache(config *lint.Config, projectDir string) {
if config == nil {
return
}
cacheBase := strings.TrimSpace(config.Cache.Directory)
if cacheBase == "" {
return
}
if !filepath.IsAbs(cacheBase) {
cacheBase = filepath.Join(projectDir, cacheBase)
}
lint.SetCacheDirectory(filepath.Join(cacheBase, "lint"))
mpr.SetPersistentYAMLCacheDirectory(filepath.Join(cacheBase, "mpr-v2-yaml"))
mpr.SetPersistentYAMLCacheEnabled(boolValue(config.Cache.Enable, true))
}
func boolValue(value *bool, fallback bool) bool {
if value == nil {
return fallback
}
return *value
}
func isVerbose(cmd *cobra.Command) bool {
verbose, err := cmd.Flags().GetBool("verbose")
if err != nil {
return false
}
return verbose
}
func configPathForCommand(cmd *cobra.Command) string {
configPath, err := cmd.Flags().GetString("config")
if err != nil {
return ""
}
return configPath
}