-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathinit.go
More file actions
517 lines (450 loc) · 17.2 KB
/
init.go
File metadata and controls
517 lines (450 loc) · 17.2 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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
package cmd
import (
codacyclient "codacy/cli-v2/codacy-client"
"codacy/cli-v2/config"
"codacy/cli-v2/domain"
"codacy/cli-v2/tools"
"codacy/cli-v2/tools/lizard"
"codacy/cli-v2/tools/pylint"
"codacy/cli-v2/utils"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
)
var initFlags domain.InitFlags
func init() {
initCmd.Flags().StringVar(&initFlags.ApiToken, "api-token", "", "optional codacy api token, if defined configurations will be fetched from codacy")
initCmd.Flags().StringVar(&initFlags.Provider, "provider", "", "provider (gh/bb/gl) to fetch configurations from codacy, required when api-token is provided")
initCmd.Flags().StringVar(&initFlags.Organization, "organization", "", "remote organization name to fetch configurations from codacy, required when api-token is provided")
initCmd.Flags().StringVar(&initFlags.Repository, "repository", "", "remote repository name to fetch configurations from codacy, required when api-token is provided")
rootCmd.AddCommand(initCmd)
}
var initCmd = &cobra.Command{
Use: "init",
Short: "Bootstraps project configuration",
Long: "Bootstraps project configuration, creates codacy configuration file",
Run: func(cmd *cobra.Command, args []string) {
// Create local codacy directory first
if err := config.Config.CreateLocalCodacyDir(); err != nil {
log.Fatalf("Failed to create local codacy directory: %v", err)
}
// Create tools-configs directory
toolsConfigDir := config.Config.ToolsConfigDirectory()
if err := os.MkdirAll(toolsConfigDir, 0777); err != nil {
log.Fatalf("Failed to create tools-configs directory: %v", err)
}
cliLocalMode := len(initFlags.ApiToken) == 0
if cliLocalMode {
fmt.Println()
fmt.Println("ℹ️ No project token was specified, fetching codacy default configurations")
noTools := []domain.Tool{}
err := createConfigurationFiles(noTools, cliLocalMode)
if err != nil {
log.Fatal(err)
}
// Create default configuration files
if err := buildDefaultConfigurationFiles(toolsConfigDir); err != nil {
log.Fatal(err)
}
if err := createLanguagesConfigFileLocal(toolsConfigDir); err != nil {
log.Fatal(err)
}
} else {
err := buildRepositoryConfigurationFiles(initFlags.ApiToken)
if err != nil {
log.Fatal(err)
}
}
createGitIgnoreFile()
fmt.Println()
fmt.Println("✅ Successfully initialized Codacy configuration!")
fmt.Println()
fmt.Println("🔧 Next steps:")
fmt.Println(" 1. Run 'codacy-cli install' to install all dependencies")
fmt.Println(" 2. Run 'codacy-cli analyze' to start analyzing your code")
fmt.Println()
},
}
func createLanguagesConfigFileLocal(toolsConfigDir string) error {
content := `tools:
- name: semgrep
languages: [CPP, Go, Java, JavaScript, JSON, Python, Ruby]
extensions: [.cc, .cpcac, .cpp, .cxx, .gemspec, .go, .hpp, .ino, .java, .jbuilder, .js, .jsm, .json, .jssssx, .jsx, .mjs, .opal, .podspec, .py, .pyx, .rake, .rb, .vue]
- name: trivy
languages: [Multiple]
extensions: []
- name: pmd
languages: [Java, JavaScript, XML, Ruby]
extensions: [.gemspec, .java, .jbuilder, .js, .jsm, .jssssx, .jsx, .mjs, .opal, .podspec, .pom, .rake, .rb, .vue, .wsdl, .xml, .xsl]
- name: pylint
languages: [Python]
extensions: [.py]
- name: lizard
languages: [CPP, Java, JavaScript, Python, Ruby]
extensions: [.cc, .cpcac, .cpp, .cxx, .gemspec, .hpp, .ino, .java, .jbuilder, .js, .jsm, .jssssx, .jsx, .mjs, .opal, .podspec, .py, .pyx, .rake, .rb, .vue]
- name: eslint
languages: [JavaScript]
extensions: [.js, .jsm, .jsx, .mjs, .vue]`
return os.WriteFile(filepath.Join(toolsConfigDir, "languages-config.yaml"), []byte(content), utils.DefaultFilePerms)
}
func createGitIgnoreFile() error {
gitIgnorePath := filepath.Join(config.Config.LocalCodacyDirectory(), ".gitignore")
gitIgnoreFile, err := os.Create(gitIgnorePath)
if err != nil {
return fmt.Errorf("failed to create .gitignore file: %w", err)
}
defer gitIgnoreFile.Close()
content := "# Codacy CLI\ntools-configs/\n.gitignore\ncli-config.yaml\nlogs/\n"
if _, err := gitIgnoreFile.WriteString(content); err != nil {
return fmt.Errorf("failed to write to .gitignore file: %w", err)
}
return nil
}
func createConfigurationFiles(tools []domain.Tool, cliLocalMode bool) error {
configFile, err := os.Create(config.Config.ProjectConfigFile())
if err != nil {
return fmt.Errorf("failed to create project config file: %w", err)
}
defer configFile.Close()
configContent := configFileTemplate(tools)
_, err = configFile.WriteString(configContent)
if err != nil {
return fmt.Errorf("failed to write project config file: %w", err)
}
cliConfigFile, err := os.Create(config.Config.CliConfigFile())
if err != nil {
return fmt.Errorf("failed to create CLI config file: %w", err)
}
defer cliConfigFile.Close()
cliConfigContent := cliConfigFileTemplate(cliLocalMode)
_, err = cliConfigFile.WriteString(cliConfigContent)
if err != nil {
return fmt.Errorf("failed to write CLI config file: %w", err)
}
return nil
}
func configFileTemplate(tools []domain.Tool) string {
// Maps to track which tools are enabled
toolsMap := make(map[string]bool)
toolVersions := make(map[string]string)
// Track needed runtimes
needsNode := false
needsPython := false
needsDart := false
needsJava := false
// Default versions
defaultVersions := map[string]string{
ESLint: "8.57.0",
Trivy: "0.59.1",
PyLint: "3.3.6",
PMD: "6.55.0",
DartAnalyzer: "3.7.2",
Semgrep: "1.78.0",
Lizard: "1.17.19",
}
// Build map of enabled tools with their versions
for _, tool := range tools {
toolsMap[tool.Uuid] = true
if tool.Version != "" {
toolVersions[tool.Uuid] = tool.Version
} else {
toolVersions[tool.Uuid] = defaultVersions[tool.Uuid]
}
// Check if tool needs a runtime
if tool.Uuid == ESLint {
needsNode = true
} else if tool.Uuid == PyLint || tool.Uuid == Lizard {
needsPython = true
} else if tool.Uuid == DartAnalyzer {
needsDart = true
} else if tool.Uuid == PMD {
needsJava = true
}
}
// Start building the YAML content
var sb strings.Builder
sb.WriteString("runtimes:\n")
// Only include runtimes needed by the enabled tools
if len(tools) > 0 {
if needsNode {
sb.WriteString(" - node@22.2.0\n")
}
if needsPython {
sb.WriteString(" - python@3.11.11\n")
}
if needsDart {
sb.WriteString(" - dart@3.7.2\n")
}
if needsJava {
sb.WriteString(" - java@17.0.10\n")
}
} else {
// In local mode with no tools specified, include all runtimes
sb.WriteString(" - node@22.2.0\n")
sb.WriteString(" - python@3.11.11\n")
sb.WriteString(" - dart@3.7.2\n")
sb.WriteString(" - java@17.0.10\n")
}
sb.WriteString("tools:\n")
// If we have tools from the API (enabled tools), use only those
if len(tools) > 0 {
// Add only the tools that are in the API response (enabled tools)
uuidToName := map[string]string{
ESLint: "eslint",
Trivy: "trivy",
PyLint: "pylint",
PMD: "pmd",
DartAnalyzer: "dartanalyzer",
Semgrep: "semgrep",
Lizard: "lizard",
}
for uuid, name := range uuidToName {
if toolsMap[uuid] {
sb.WriteString(fmt.Sprintf(" - %s@%s\n", name, toolVersions[uuid]))
}
}
} else {
// If no tools were specified (local mode), include all defaults
sb.WriteString(fmt.Sprintf(" - eslint@%s\n", defaultVersions[ESLint]))
sb.WriteString(fmt.Sprintf(" - trivy@%s\n", defaultVersions[Trivy]))
sb.WriteString(fmt.Sprintf(" - pylint@%s\n", defaultVersions[PyLint]))
sb.WriteString(fmt.Sprintf(" - pmd@%s\n", defaultVersions[PMD]))
sb.WriteString(fmt.Sprintf(" - dartanalyzer@%s\n", defaultVersions[DartAnalyzer]))
sb.WriteString(fmt.Sprintf(" - semgrep@%s\n", defaultVersions[Semgrep]))
sb.WriteString(fmt.Sprintf(" - lizard@%s\n", defaultVersions[Lizard]))
}
return sb.String()
}
func cliConfigFileTemplate(cliLocalMode bool) string {
var cliModeString string
if cliLocalMode {
cliModeString = "local"
} else {
cliModeString = "remote"
}
return fmt.Sprintf(`mode: %s`, cliModeString)
}
func buildRepositoryConfigurationFiles(token string) error {
fmt.Println("Fetching repository configuration from codacy ...")
toolsConfigDir := config.Config.ToolsConfigDirectory()
// Create tools-configs directory if it doesn't exist
if err := os.MkdirAll(toolsConfigDir, utils.DefaultDirPerms); err != nil {
return fmt.Errorf("failed to create tools-configs directory: %w", err)
}
// Clear any previous configuration files
if err := cleanConfigDirectory(toolsConfigDir); err != nil {
return fmt.Errorf("failed to clean configuration directory: %w", err)
}
apiTools, err := tools.GetRepositoryTools(initFlags)
if err != nil {
return err
}
// Map UUID to tool shortname for lookup
uuidToName := map[string]string{
ESLint: "eslint",
Trivy: "trivy",
PyLint: "pylint",
PMD: "pmd",
DartAnalyzer: "dartanalyzer",
Lizard: "lizard",
Semgrep: "semgrep",
}
// Generate languages configuration based on API tools response
if err := tools.CreateLanguagesConfigFile(apiTools, toolsConfigDir, uuidToName, initFlags); err != nil {
return fmt.Errorf("failed to create languages configuration file: %w", err)
}
// Filter out any tools that use configuration file
configuredToolsWithUI := tools.FilterToolsByConfigUsage(apiTools)
// Create main config files with all enabled API tools
err = createConfigurationFiles(apiTools, false)
if err != nil {
log.Fatal(err)
}
// Only generate config files for tools not using their own config file
for _, tool := range configuredToolsWithUI {
apiToolConfigurations, err := codacyclient.GetRepositoryToolPatterns(initFlags, tool.Uuid)
if err != nil {
fmt.Println("Error unmarshaling tool configurations:", err)
return err
}
createToolFileConfigurations(tool, apiToolConfigurations)
}
return nil
}
// map tool uuid to tool name
func createToolFileConfigurations(tool domain.Tool, patternConfiguration []domain.PatternConfiguration) error {
toolsConfigDir := config.Config.ToolsConfigDirectory()
switch tool.Uuid {
case ESLint:
err := tools.CreateEslintConfig(toolsConfigDir, patternConfiguration)
if err != nil {
return fmt.Errorf("failed to write eslint config: %v", err)
}
fmt.Println("ESLint configuration created based on Codacy settings. Ignoring plugin rules. ESLint plugins are not supported yet.")
case Trivy:
err := createTrivyConfigFile(patternConfiguration, toolsConfigDir)
if err != nil {
return fmt.Errorf("failed to create Trivy config: %v", err)
}
fmt.Println("Trivy configuration created based on Codacy settings")
case PMD:
err := createPMDConfigFile(patternConfiguration, toolsConfigDir)
if err != nil {
return fmt.Errorf("failed to create PMD config: %v", err)
}
fmt.Println("PMD configuration created based on Codacy settings")
case PyLint:
err := createPylintConfigFile(patternConfiguration, toolsConfigDir)
if err != nil {
return fmt.Errorf("failed to create Pylint config: %v", err)
}
fmt.Println("Pylint configuration created based on Codacy settings")
case DartAnalyzer:
err := createDartAnalyzerConfigFile(patternConfiguration, toolsConfigDir)
if err != nil {
return fmt.Errorf("failed to create Dart Analyzer config: %v", err)
}
fmt.Println("Dart configuration created based on Codacy settings")
case Semgrep:
err := createSemgrepConfigFile(patternConfiguration, toolsConfigDir)
if err != nil {
return fmt.Errorf("failed to create Semgrep config: %v", err)
}
fmt.Println("Semgrep configuration created based on Codacy settings")
case Lizard:
err := createLizardConfigFile(toolsConfigDir, patternConfiguration)
if err != nil {
return fmt.Errorf("failed to create Lizard config: %v", err)
}
fmt.Println("Lizard configuration created based on Codacy settings")
}
return nil
}
func createPMDConfigFile(config []domain.PatternConfiguration, toolsConfigDir string) error {
pmdConfigurationString := tools.CreatePmdConfig(config)
return os.WriteFile(filepath.Join(toolsConfigDir, "ruleset.xml"), []byte(pmdConfigurationString), utils.DefaultFilePerms)
}
func createPylintConfigFile(config []domain.PatternConfiguration, toolsConfigDir string) error {
pylintConfigurationString := pylint.GeneratePylintRC(config)
return os.WriteFile(filepath.Join(toolsConfigDir, "pylint.rc"), []byte(pylintConfigurationString), utils.DefaultFilePerms)
}
// createTrivyConfigFile creates a trivy.yaml configuration file based on the API configuration
func createTrivyConfigFile(config []domain.PatternConfiguration, toolsConfigDir string) error {
trivyConfigurationString := tools.CreateTrivyConfig(config)
// Write to file
return os.WriteFile(filepath.Join(toolsConfigDir, "trivy.yaml"), []byte(trivyConfigurationString), utils.DefaultFilePerms)
}
func createDartAnalyzerConfigFile(config []domain.PatternConfiguration, toolsConfigDir string) error {
dartAnalyzerConfigurationString := tools.CreateDartAnalyzerConfig(config)
return os.WriteFile(filepath.Join(toolsConfigDir, "analysis_options.yaml"), []byte(dartAnalyzerConfigurationString), utils.DefaultFilePerms)
}
// SemgrepRulesFile represents the structure of the rules.yaml file
type SemgrepRulesFile struct {
Rules []map[string]interface{} `yaml:"rules"`
}
// createSemgrepConfigFile creates a semgrep.yaml configuration file based on the API configuration
func createSemgrepConfigFile(config []domain.PatternConfiguration, toolsConfigDir string) error {
// Use the refactored function from tools package
configData, err := tools.GetSemgrepConfig(config)
if err != nil {
return fmt.Errorf("failed to create Semgrep config: %v", err)
}
// Write to file
return os.WriteFile(filepath.Join(toolsConfigDir, "semgrep.yaml"), configData, utils.DefaultFilePerms)
}
// cleanConfigDirectory removes all previous configuration files in the tools-configs directory
func cleanConfigDirectory(toolsConfigDir string) error {
// Check if directory exists
if _, err := os.Stat(toolsConfigDir); os.IsNotExist(err) {
return nil // Directory doesn't exist, nothing to clean
}
// Read directory contents
entries, err := os.ReadDir(toolsConfigDir)
if err != nil {
return fmt.Errorf("failed to read config directory: %w", err)
}
// Remove all files
for _, entry := range entries {
if !entry.IsDir() { // Only remove files, not subdirectories
filePath := filepath.Join(toolsConfigDir, entry.Name())
if err := os.Remove(filePath); err != nil {
return fmt.Errorf("failed to remove file %s: %w", filePath, err)
}
}
}
fmt.Println("Cleaned previous configuration files")
return nil
}
func createLizardConfigFile(toolsConfigDir string, patternConfiguration []domain.PatternConfiguration) error {
patterns := make([]domain.PatternDefinition, len(patternConfiguration))
for i, pattern := range patternConfiguration {
patterns[i] = pattern.PatternDefinition
}
err := lizard.CreateLizardConfig(toolsConfigDir, patterns)
if err != nil {
return fmt.Errorf("failed to create Lizard configuration: %w", err)
}
return nil
}
// buildDefaultConfigurationFiles creates default configuration files for all tools
func buildDefaultConfigurationFiles(toolsConfigDir string) error {
for _, tool := range AvailableTools {
patternsConfig, err := codacyclient.GetDefaultToolPatternsConfig(initFlags, tool)
if err != nil {
return fmt.Errorf("failed to get default tool patterns config: %w", err)
}
switch tool {
case ESLint:
if err := tools.CreateEslintConfig(toolsConfigDir, patternsConfig); err != nil {
return fmt.Errorf("failed to create eslint config file: %v", err)
}
case Trivy:
if err := createTrivyConfigFile(patternsConfig, toolsConfigDir); err != nil {
return fmt.Errorf("failed to create default Trivy configuration: %w", err)
}
case PMD:
if err := createPMDConfigFile(patternsConfig, toolsConfigDir); err != nil {
return fmt.Errorf("failed to create default PMD configuration: %w", err)
}
case PyLint:
if err := createPylintConfigFile(patternsConfig, toolsConfigDir); err != nil {
return fmt.Errorf("failed to create default Pylint configuration: %w", err)
}
case DartAnalyzer:
if err := createDartAnalyzerConfigFile(patternsConfig, toolsConfigDir); err != nil {
return fmt.Errorf("failed to create default Dart Analyzer configuration: %w", err)
}
case Semgrep:
if err := createSemgrepConfigFile(patternsConfig, toolsConfigDir); err != nil {
return fmt.Errorf("failed to create default Semgrep configuration: %w", err)
}
case Lizard:
if err := createLizardConfigFile(toolsConfigDir, patternsConfig); err != nil {
return fmt.Errorf("failed to create default Lizard configuration: %w", err)
}
}
}
return nil
}
const (
ESLint string = "f8b29663-2cb2-498d-b923-a10c6a8c05cd"
Trivy string = "2fd7fbe0-33f9-4ab3-ab73-e9b62404e2cb"
PMD string = "9ed24812-b6ee-4a58-9004-0ed183c45b8f"
PyLint string = "31677b6d-4ae0-4f56-8041-606a8d7a8e61"
DartAnalyzer string = "d203d615-6cf1-41f9-be5f-e2f660f7850f"
Semgrep string = "6792c561-236d-41b7-ba5e-9d6bee0d548b"
Lizard string = "76348462-84b3-409a-90d3-955e90abfb87"
)
// AvailableTools lists all tool UUIDs supported by Codacy CLI.
var AvailableTools = []string{
ESLint,
Trivy,
PMD,
PyLint,
DartAnalyzer,
Semgrep,
Lizard,
}