Skip to content

Commit fc94b13

Browse files
committed
add config creator to dartanalyzer
1 parent 044878e commit fc94b13

File tree

6 files changed

+68
-146
lines changed

6 files changed

+68
-146
lines changed

cmd/init.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,13 @@ func createToolFileConfigurations(tool tools.Tool, patternConfiguration []domain
380380
}
381381
}
382382
fmt.Println("Pylint configuration created based on Codacy settings")
383+
case DartAnalyzer:
384+
if len(patternConfiguration) > 0 {
385+
err := createDartAnalyzerConfigFile(patternConfiguration, toolsConfigDir)
386+
if err != nil {
387+
return fmt.Errorf("failed to create Dart Analyzer config: %v", err)
388+
}
389+
}
383390
}
384391
return nil
385392
}
@@ -414,6 +421,12 @@ func createTrivyConfigFile(config []domain.PatternConfiguration, toolsConfigDir
414421
return os.WriteFile(filepath.Join(toolsConfigDir, "trivy.yaml"), []byte(trivyConfigurationString), utils.DefaultFilePerms)
415422
}
416423

424+
func createDartAnalyzerConfigFile(config []domain.PatternConfiguration, toolsConfigDir string) error {
425+
426+
dartAnalyzerConfigurationString := tools.CreateDartAnalyzerConfig(config)
427+
return os.WriteFile(filepath.Join(toolsConfigDir, "analysis_options.yaml"), []byte(dartAnalyzerConfigurationString), utils.DefaultFilePerms)
428+
}
429+
417430
// createDefaultTrivyConfigFile creates a default trivy.yaml configuration file
418431
func createDefaultTrivyConfigFile(toolsConfigDir string) error {
419432
// Use empty tool configuration to get default settings

domain/patternConfiguration.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,13 @@ type ParameterConfiguration struct {
66
}
77

88
type PatternDefinition struct {
9-
Id string `json:"id"`
9+
Id string `json:"id"`
10+
Category string `json:"category"`
11+
Level string `json:"level"`
1012
}
1113

1214
type PatternConfiguration struct {
1315
PatternDefinition PatternDefinition `json:"patternDefinition"`
16+
Enabled bool `json:"enabled"`
1417
Parameters []ParameterConfiguration
1518
}

plugins/tool-utils.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,13 +122,11 @@ func ProcessTools(configs []ToolConfig, toolDir string, runtimes map[string]*Run
122122
if err != nil {
123123
return nil, fmt.Errorf("error reading plugin.yaml for %s: %w", config.Name, err)
124124
}
125-
fmt.Println("Plugin path", pluginPath)
126125
var pluginConfig ToolPluginConfig
127126
err = yaml.Unmarshal(data, &pluginConfig)
128127
if err != nil {
129128
return nil, fmt.Errorf("error parsing plugin.yaml for %s: %w", config.Name, err)
130129
}
131-
fmt.Println("EOD")
132130
// Create the install directory path
133131
installDir := path.Join(toolDir, fmt.Sprintf("%s@%s", config.Name, config.Version))
134132

tools/dartanalyzerConfigCreator.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package tools
2+
3+
import (
4+
"codacy/cli-v2/domain"
5+
"fmt"
6+
"slices"
7+
"strconv"
8+
"strings"
9+
10+
"gopkg.in/yaml.v3"
11+
)
12+
13+
func CreateDartAnalyzerConfig(configuration []domain.PatternConfiguration) string {
14+
15+
// Find Dart Analyzer patterns
16+
errorPatterns := []string{"ErrorProne", "Security", "Performance"}
17+
// Create analysis_options.yaml content
18+
config := map[string]interface{}{
19+
"analyzer": map[string]interface{}{
20+
"errors": map[string]string{},
21+
},
22+
"linter": map[string]interface{}{
23+
"rules": map[string]string{},
24+
},
25+
}
26+
27+
errorsMap := config["analyzer"].(map[string]interface{})["errors"].(map[string]string)
28+
lintsMap := config["linter"].(map[string]interface{})["rules"].(map[string]string)
29+
for _, pattern := range configuration {
30+
fmt.Println(pattern.PatternDefinition.Id, pattern.Enabled, pattern.PatternDefinition.Category)
31+
if slices.Contains(errorPatterns, pattern.PatternDefinition.Category) {
32+
if pattern.Enabled {
33+
errorsMap[strings.TrimPrefix(pattern.PatternDefinition.Id, patternPrefix)] = strings.ToLower(pattern.PatternDefinition.Level)
34+
} else {
35+
errorsMap[strings.TrimPrefix(pattern.PatternDefinition.Id, patternPrefix)] = "ignore"
36+
}
37+
38+
} else {
39+
lintsMap[strings.TrimPrefix(pattern.PatternDefinition.Id, patternPrefix)] = strconv.FormatBool(pattern.Enabled)
40+
}
41+
}
42+
43+
// Write config to file
44+
yamlData, err := yaml.Marshal(config)
45+
if err != nil {
46+
return ""
47+
}
48+
return string(yamlData)
49+
}

tools/dartanalyzerRunner.go

Lines changed: 1 addition & 143 deletions
Original file line numberDiff line numberDiff line change
@@ -10,24 +10,18 @@ import (
1010
"os"
1111
"os/exec"
1212
"path/filepath"
13-
"slices"
1413
"strconv"
1514
"strings"
1615
"time"
17-
18-
"gopkg.in/yaml.v3"
1916
)
2017

21-
// TODO: Move to config or centralized place
2218
const CodacyApiBase = "https://app.codacy.com"
2319
const codacyToolName = "dartanalyzer"
2420
const patternPrefix = "dartanalyzer_"
2521

2622
func RunDartAnalyzer(workDirectory string, toolInfo *plugins.ToolInfo, files []string, outputFile string, outputFormat string, apiToken string, provider string, owner string, repository string) {
2723

2824
configFiles := []string{"analysis_options.yaml", "analysis_options.yml"}
29-
needToCleanUp := false
30-
configPath := ""
3125
dartAnalyzerPath := filepath.Join(toolInfo.InstallDir, "bin", "dart")
3226
fmt.Println(dartAnalyzerPath)
3327

@@ -55,28 +49,7 @@ func RunDartAnalyzer(workDirectory string, toolInfo *plugins.ToolInfo, files []s
5549
}
5650

5751
if !configExists {
58-
fmt.Println("No config file found, trying to generate one")
59-
if apiToken == "" {
60-
fmt.Println("Error: Project token is required for dartanalyzer if no config file exists")
61-
return
62-
}
63-
tool, err := getToolFromCodacy(apiToken, provider, owner, repository)
64-
if err != nil {
65-
fmt.Printf("Error getting tools from Codacy: %v\n", err)
66-
return
67-
}
68-
if tool.Settings.UsesConfigFile {
69-
fmt.Println("Codacy is expecting a config file, please add one to your project or change the tool settings")
70-
return
71-
}
72-
73-
// Create default analysis_options.yaml if no config exists
74-
configPath = filepath.Join(workDirectory, "analysis_options.yaml")
75-
if err := generateDartAnalyzerConfig(configPath, apiToken, provider, owner, repository, tool.Uuid); err != nil {
76-
fmt.Printf("Error generating dart analyzer config: %v\n", err)
77-
return
78-
}
79-
needToCleanUp = true
52+
fmt.Println("No config file found, using tool defaults")
8053
} else {
8154
fmt.Println("Config file found, using it")
8255
}
@@ -164,10 +137,6 @@ func RunDartAnalyzer(workDirectory string, toolInfo *plugins.ToolInfo, files []s
164137
cmd.Run()
165138
}
166139

167-
if needToCleanUp {
168-
fmt.Println("Cleaning up", configPath)
169-
os.Remove(configPath)
170-
}
171140
}
172141

173142
func convertDartAnalyzerOutputToSarif(output string) (string, error) {
@@ -280,114 +249,3 @@ func getToolFromCodacy(apiToken string, provider string, owner string, repositor
280249
}
281250
return nil, fmt.Errorf("tool %s not found", codacyToolName)
282251
}
283-
284-
func generateDartAnalyzerConfig(configPath string, apiToken string, provider string, owner string, repository string, toolUuid string) error {
285-
286-
// Get enabled patterns from Codacy API
287-
288-
url := fmt.Sprintf("%s/api/v3/analysis/organizations/%s/%s/repositories/%s/tools/%s/patterns",
289-
CodacyApiBase,
290-
provider,
291-
owner,
292-
repository,
293-
toolUuid)
294-
295-
fmt.Println(configPath)
296-
297-
client := &http.Client{
298-
Timeout: 10 * time.Second,
299-
}
300-
301-
req, err := http.NewRequest("GET", url, nil)
302-
if err != nil {
303-
return fmt.Errorf("error creating request: %v", err)
304-
}
305-
306-
// Set project token header
307-
req.Header.Set("Accept", "application/json")
308-
req.Header.Set("api-token", apiToken)
309-
310-
resp, err := client.Do(req)
311-
if err != nil {
312-
return fmt.Errorf("error making request: %v", err)
313-
}
314-
defer resp.Body.Close()
315-
316-
if resp.StatusCode >= 400 {
317-
return fmt.Errorf("failed to get patterns from Codacy API: %v", resp.Status)
318-
}
319-
320-
var patterns struct {
321-
Data []struct {
322-
PatternDefinition struct {
323-
ID string `json:"id"`
324-
Title string `json:"title"`
325-
Category string `json:"category"`
326-
SubCategory string `json:"subCategory"`
327-
Level string `json:"level"`
328-
Languages []string `json:"languages"`
329-
} `json:"patternDefinition"`
330-
Enabled bool `json:"enabled"`
331-
IsCustom bool `json:"isCustom"`
332-
Parameters []struct {
333-
Name string `json:"name"`
334-
Value string `json:"value"`
335-
} `json:"parameters"`
336-
EnabledBy []struct {
337-
ID int `json:"id"`
338-
Name string `json:"name"`
339-
} `json:"enabledBy"`
340-
} `json:"data"`
341-
Pagination struct {
342-
Cursor string `json:"cursor"`
343-
Limit int `json:"limit"`
344-
Total int `json:"total"`
345-
} `json:"pagination"`
346-
Meta struct {
347-
TotalEnabled int `json:"totalEnabled"`
348-
} `json:"meta"`
349-
}
350-
351-
if err := json.NewDecoder(resp.Body).Decode(&patterns); err != nil {
352-
return fmt.Errorf("error decoding response: %v", err)
353-
}
354-
355-
// Find Dart Analyzer patterns
356-
errorPatterns := []string{"ErrorProne", "Security", "Performance"}
357-
// Create analysis_options.yaml content
358-
config := map[string]interface{}{
359-
"analyzer": map[string]interface{}{
360-
"errors": map[string]string{},
361-
},
362-
"linter": map[string]interface{}{
363-
"rules": map[string]string{},
364-
},
365-
}
366-
367-
errorsMap := config["analyzer"].(map[string]interface{})["errors"].(map[string]string)
368-
lintsMap := config["linter"].(map[string]interface{})["rules"].(map[string]string)
369-
for _, pattern := range patterns.Data {
370-
fmt.Println(pattern.PatternDefinition.ID, pattern.Enabled, pattern.PatternDefinition.Category)
371-
if slices.Contains(errorPatterns, pattern.PatternDefinition.Category) {
372-
if pattern.Enabled {
373-
errorsMap[strings.TrimPrefix(pattern.PatternDefinition.ID, patternPrefix)] = strings.ToLower(pattern.PatternDefinition.Level)
374-
} else {
375-
errorsMap[strings.TrimPrefix(pattern.PatternDefinition.ID, patternPrefix)] = "ignore"
376-
}
377-
378-
} else {
379-
lintsMap[strings.TrimPrefix(pattern.PatternDefinition.ID, patternPrefix)] = strconv.FormatBool(pattern.Enabled)
380-
}
381-
}
382-
383-
// Write config to file
384-
yamlData, err := yaml.Marshal(config)
385-
if err != nil {
386-
return fmt.Errorf("error marshaling config: %v", err)
387-
}
388-
389-
if err := os.WriteFile(configPath, yamlData, 0644); err != nil {
390-
return fmt.Errorf("error writing config file: %v", err)
391-
}
392-
return nil
393-
}

tools/getTools.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ func GetRepositoryTools(codacyBase string, apiToken string, provider string, org
9090
defer resp.Body.Close()
9191

9292
if resp.StatusCode != 200 {
93+
fmt.Println("Error:", url)
9394
return nil, errors.New("failed to get repository tools from Codacy API")
9495
}
9596

0 commit comments

Comments
 (0)