-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
350 lines (323 loc) · 9.89 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
package main
import (
"bufio"
"fmt"
"os"
"runtime"
"runtime/pprof"
"github.com/charmbracelet/lipgloss"
"github.com/halleck45/ast-metrics/src/Cli"
"github.com/halleck45/ast-metrics/src/Command"
"github.com/halleck45/ast-metrics/src/Configuration"
"github.com/halleck45/ast-metrics/src/Engine"
"github.com/halleck45/ast-metrics/src/Engine/Golang"
"github.com/halleck45/ast-metrics/src/Engine/Php"
"github.com/halleck45/ast-metrics/src/Engine/Python"
"github.com/halleck45/ast-metrics/src/Watcher"
"github.com/pterm/pterm"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
var (
// Current version. Managed by goreleaser during build
// @see https://goreleaser.com/cookbooks/using-main.version/
version = "dev"
commit = "none"
date = "unknown"
)
func main() {
log.SetLevel(log.TraceLevel)
// Create a temporary directory
build, err := os.MkdirTemp("", "ast-metrics")
if err != nil {
log.Error(err)
}
defer os.RemoveAll(build)
// Prepare accepted languages
runnerPhp := Php.PhpRunner{}
runnerGolang := Golang.GolangRunner{}
runnerPython := Python.PythonRunner{}
runners := []Engine.Engine{&runnerPhp, &runnerGolang, &runnerPython}
app := &cli.App{
Name: "ast-metrics",
Usage: "Static code analysis tool",
Commands: []*cli.Command{
{
Name: "analyze",
Aliases: []string{"a"},
Usage: "Start analyzing the project",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "verbose",
Aliases: []string{"v"},
Usage: "Enable verbose mode",
Category: "Global options",
},
&cli.StringSliceFlag{
Name: "exclude",
Usage: "Regular expression to exclude files from analysis",
Category: "File selection",
},
&cli.BoolFlag{
Name: "non-interactive",
Aliases: []string{"i"},
Usage: "Disable interactive mode",
Category: "Global options",
},
// HTML report
&cli.StringFlag{
Name: "report-html",
Usage: "Generate an HTML report",
Category: "Report",
},
// Markdown report
&cli.StringFlag{
Name: "report-markdown",
Usage: "Generate an Markdown report file",
Category: "Report",
},
// JSON report
&cli.StringFlag{
Name: "report-json",
Usage: "Generate a report in JSON format",
Category: "Report",
},
// OpenMetrics report
// https://github.com/prometheus/OpenMetrics/blob/main/specification/OpenMetrics.md
&cli.StringFlag{
Name: "report-openmetrics",
Usage: "Generate a report in OpenMetrics format",
Category: "Report",
},
// Watch mode
&cli.BoolFlag{
Name: "watch",
Usage: "Re-run the analysis when files change",
Category: "Global options",
},
// CI mode (alias of --non-interactive, --report-html and --report-markdown)
&cli.BoolFlag{
Name: "ci",
Usage: "Enable CI mode",
Category: "Global options",
},
// Configuration
&cli.StringFlag{
Name: "config",
Usage: "Load configuration from file",
Category: "Configuration",
},
// Diff mode (comparaison between current branch and another one or commit)
&cli.StringFlag{
Name: "compare-with",
Usage: "Compare with another Git branch or commit",
Category: "Global options",
},
// Profiling (with pprof)
&cli.BoolFlag{
Name: "profile",
Usage: "Generate a profiling reports into files ast-metrics.cpu and ast-metrics.mem",
Category: "Global options",
},
},
Action: func(cCtx *cli.Context) error {
// get option --verbose
if cCtx.Bool("verbose") {
log.SetLevel(log.DebugLevel)
}
// get option --profile
profile := cCtx.Bool("profile")
if profile {
cpufile := "ast-metrics.cpu"
memfile := "ast-metrics.mem"
f, err := os.Create(cpufile)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
defer f.Close() // error handling omitted for example
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
f, err = os.Create(memfile)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
defer f.Close() // error handling omitted for example
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
}
// get option --non-interactive
isInteractive := true
if cCtx.Bool("non-interactive") || cCtx.Bool("ci") {
pterm.DisableColor()
isInteractive = false
}
// Stdout
outWriter := bufio.NewWriter(os.Stdout)
var style = lipgloss.NewStyle().Foreground(lipgloss.Color("#FFFFFF")).Bold(true)
fmt.Println(style.Render("\n🦫 AST Metrics is a language-agnostic static code analyzer."))
fmt.Println("")
// Prepare configuration object
configuration := Configuration.NewConfiguration()
// Load configuration file
loader := Configuration.NewConfigurationLoader()
if cCtx.String("config") != "" {
loader.FilenameToChecks = []string{cCtx.String("config")}
}
configuration, err = loader.Loads(configuration)
if err != nil {
pterm.Error.Println("Cannot load configuration file: " + err.Error())
}
// If no configuration file is found, we ask the user to select a file or take it from arguments
// If paths are provided in arguments, we use them
paths := cCtx.Args()
pathsSlice := make([]string, paths.Len())
for i := 0; i < paths.Len(); i++ {
pathsSlice[i] = paths.Get(i)
}
if cCtx.Args().Len() == 0 {
if configuration.SourcesToAnalyzePath == nil || len(configuration.SourcesToAnalyzePath) == 0 {
if isInteractive {
// we try to ask the user to select a file
pathsSlice = Cli.AskUserToSelectFile()
}
}
} else {
if len(pathsSlice) == 0 && (configuration.SourcesToAnalyzePath == nil || len(configuration.SourcesToAnalyzePath) == 0) {
pterm.Error.Println("Please provide a path to analyze")
return nil
}
err := configuration.SetSourcesToAnalyzePath(pathsSlice)
if err != nil {
pterm.Error.Println(err.Error())
return err
}
}
// Exclude patterns
if configuration.ExcludePatterns == nil {
excludePatterns := cCtx.StringSlice("exclude")
if excludePatterns != nil && len(excludePatterns) > 0 {
configuration.SetExcludePatterns(excludePatterns)
}
}
// Reports
if cCtx.String("report-html") != "" {
configuration.Reports.Html = cCtx.String("report-html")
}
if cCtx.String("report-markdown") != "" {
configuration.Reports.Markdown = cCtx.String("report-markdown")
}
if cCtx.String("report-json") != "" {
configuration.Reports.Json = cCtx.String("report-json")
}
if cCtx.String("report-openmetrics") != "" {
configuration.Reports.OpenMetrics = cCtx.String("report-openmetrics")
}
// CI mode
if cCtx.Bool("ci") {
if configuration.Reports.Html == "" {
configuration.Reports.Html = "ast-metrics-html-report"
}
if configuration.Reports.Markdown == "" {
configuration.Reports.Markdown = "ast-metrics-markdown-report.md"
}
if configuration.Reports.Json == "" {
configuration.Reports.Json = "ast-metrics-report.json"
}
if configuration.Reports.OpenMetrics == "" {
// we don't prefix the file with ast-metrics- because "metrics.txt" is a common filename for CI
// @see https://docs.gitlab.com/ee/ci/testing/metrics_reports.html
configuration.Reports.OpenMetrics = "metrics.txt"
}
}
// Compare with
if cCtx.String("compare-with") != "" {
configuration.CompareWith = cCtx.String("compare-with")
}
// Run command
command := Command.NewAnalyzeCommand(configuration, outWriter, runners, isInteractive)
// Watch mode
configuration.Watching = cCtx.Bool("watch")
err = Watcher.NewCommandWatcher(configuration).Start(command)
if err != nil {
pterm.Error.Println("Cannot watch files: " + err.Error())
}
// Execute command
err = command.Execute()
if err != nil {
pterm.Error.Println(err.Error())
return err
}
return nil
},
},
{
Name: "clean",
Aliases: []string{"c"},
Usage: "Clean workdir",
Action: func(cCtx *cli.Context) error {
// Run command
command := Command.NewCleanCommand()
err := command.Execute()
if err != nil {
pterm.Error.Println(err.Error())
return err
}
return nil
},
},
{
Name: "self-update",
Aliases: []string{"u"},
Usage: "Update current binary",
Action: func(cCtx *cli.Context) error {
// Run command
command := Command.NewSelfUpdateCommand(version)
err := command.Execute()
if err != nil {
pterm.Error.Println(err.Error())
return err
}
return nil
},
},
{
Name: "version",
Aliases: []string{"v"},
Usage: "Print version information",
Action: func(cCtx *cli.Context) error {
// Run command
command := Command.NewVersionCommand(version)
err := command.Execute()
if err != nil {
pterm.Error.Println(err.Error())
return err
}
return nil
},
},
{
Name: "init",
Aliases: []string{"i"},
Usage: "Create a default configuration file",
Action: func(cCtx *cli.Context) error {
// Run command
command := Command.NewInitConfigurationCommand()
err := command.Execute()
if err != nil {
pterm.Error.Println(err.Error())
return err
}
return nil
},
},
},
}
app.Suggest = true
if err := app.Run(os.Args); err != nil {
log.Error(err)
}
}