-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathanalyze.go
More file actions
260 lines (229 loc) · 6.91 KB
/
analyze.go
File metadata and controls
260 lines (229 loc) · 6.91 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
package cmd
import (
"codacy/cli-v2/config"
"codacy/cli-v2/tools"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/spf13/cobra"
)
var outputFile string
var toolToAnalyze string
var autoFix bool
var outputFormat string
var sarifPath string
var commitUuid string
var projectToken string
var pmdRulesetFile string
type Sarif struct {
Runs []struct {
Tool struct {
Driver struct {
Name string `json:"name"`
Version string `json:"version"`
Rules []struct {
ID string `json:"id"`
HelpURI string `json:"helpUri"`
ShortDescription struct {
Text string `json:"text"`
} `json:"shortDescription"`
} `json:"rules"`
} `json:"driver"`
} `json:"tool"`
Artifacts []struct {
Location struct {
URI string `json:"uri"`
} `json:"location"`
} `json:"artifacts"`
Results []struct {
Level string `json:"level"`
Message struct {
Text string `json:"text"`
} `json:"message"`
Locations []struct {
PhysicalLocation struct {
ArtifactLocation struct {
URI string `json:"uri"`
Index int `json:"index"`
} `json:"artifactLocation"`
Region struct {
StartLine int `json:"startLine"`
StartColumn int `json:"startColumn"`
EndLine int `json:"endLine"`
EndColumn int `json:"endColumn"`
} `json:"region"`
} `json:"physicalLocation"`
} `json:"locations"`
RuleID string `json:"ruleId"`
RuleIndex int `json:"ruleIndex"`
} `json:"results"`
} `json:"runs"`
}
type CodacyIssue struct {
Source string `json:"source"`
Line int `json:"line"`
Type string `json:"type"`
Message string `json:"message"`
Level string `json:"level"`
Category string `json:"category"`
}
type Tool struct {
UUID string `json:"uuid"`
ShortName string `json:"shortName"`
Prefix string `json:"prefix"`
}
type Pattern struct {
UUID string `json:"uuid"`
ID string `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
Description string `json:"description"`
Level string `json:"level"`
}
func init() {
analyzeCmd.Flags().StringVarP(&outputFile, "output", "o", "", "Output file for analysis results")
analyzeCmd.Flags().StringVarP(&toolToAnalyze, "tool", "t", "", "Which tool to run analysis with")
analyzeCmd.Flags().StringVar(&outputFormat, "format", "", "Output format (use 'sarif' for SARIF format)")
analyzeCmd.Flags().BoolVar(&autoFix, "fix", false, "Apply auto fix to your issues when available")
analyzeCmd.Flags().StringVar(&pmdRulesetFile, "rulesets", "", "Path to PMD ruleset file")
rootCmd.AddCommand(analyzeCmd)
}
func loadsToolAndPatterns(toolName string) (Tool, []Pattern) {
var toolsURL = "https://app.codacy.com/api/v3/tools"
req, err := http.NewRequest("GET", toolsURL, nil)
if err != nil {
fmt.Printf("Error creating request: %v\n", err)
panic("panic")
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("Error fetching patterns: %v\n", err)
panic("panic")
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var toolsResponse struct {
Data []Tool `json:"data"`
}
json.Unmarshal(body, &toolsResponse)
var tool Tool
for _, t := range toolsResponse.Data {
if t.ShortName == toolName {
tool = t
break
}
}
// TO DO - PANIC
//if tool == nil {
// return nil, nil
//}
var patterns []Pattern
var hasNext bool = true
cursor := ""
client := &http.Client{}
for hasNext {
baseURL := fmt.Sprintf("https://app.codacy.com/api/v3/tools/%s/patterns?limit=1000%s", tool.UUID, cursor)
req, _ := http.NewRequest("GET", baseURL, nil)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error:", err)
break
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var patternsResponse struct {
Data []Pattern `json:"data"`
Pagination struct {
Cursor string `json:"cursor"`
} `json:"pagination"`
}
json.Unmarshal(body, &patternsResponse)
patterns = append(patterns, patternsResponse.Data...)
hasNext = patternsResponse.Pagination.Cursor != ""
if hasNext {
cursor = "&cursor=" + patternsResponse.Pagination.Cursor
}
}
return tool, patterns
}
func getToolName(toolName string, version string) string {
if toolName == "eslint" {
majorVersion := getMajorVersion(version)
switch majorVersion {
case 7:
return "eslint"
case 8:
return "eslint-8"
case 9:
return "eslint-9"
}
}
return toolName
}
func runEslintAnalysis(workDirectory string, pathsToCheck []string, autoFix bool, outputFile string, outputFormat string) {
eslint := config.Config.Tools()["eslint"]
eslintInstallationDirectory := eslint.InstallDir
nodeRuntime := config.Config.Runtimes()["node"]
nodeBinary := nodeRuntime.Binaries["node"]
tools.RunEslint(workDirectory, eslintInstallationDirectory, nodeBinary, pathsToCheck, autoFix, outputFile, outputFormat)
}
func runTrivyAnalysis(workDirectory string, pathsToCheck []string, outputFile string, outputFormat string) {
trivy := config.Config.Tools()["trivy"]
trivyBinary := trivy.Binaries["trivy"]
err := tools.RunTrivy(workDirectory, trivyBinary, pathsToCheck, outputFile, outputFormat)
if err != nil {
log.Fatalf("Error running Trivy: %v", err)
}
}
func runPmdAnalysis(workDirectory string, pathsToCheck []string, outputFile string, outputFormat string) {
pmd := config.Config.Tools()["pmd"]
pmdBinary := pmd.Binaries["pmd"]
err := tools.RunPmd(workDirectory, pmdBinary, pathsToCheck, outputFile, outputFormat, pmdRulesetFile)
if err != nil {
log.Fatalf("Error running PMD: %v", err)
}
}
func runPylintAnalysis(workDirectory string, pathsToCheck []string, outputFile string, outputFormat string) {
pylint := config.Config.Tools()["pylint"]
err := tools.RunPylint(workDirectory, pylint, pathsToCheck, outputFile, outputFormat)
if err != nil {
log.Fatalf("Error running Pylint: %v", err)
}
}
var analyzeCmd = &cobra.Command{
Use: "analyze",
Short: "Runs all linters.",
Long: "Runs all tools for all runtimes.",
Run: func(cmd *cobra.Command, args []string) {
workDirectory, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
log.Printf("Running %s...\n", toolToAnalyze)
if outputFormat == "sarif" {
log.Println("Output will be in SARIF format")
}
if outputFile != "" {
log.Println("Output will be available at", outputFile)
}
switch toolToAnalyze {
case "eslint":
runEslintAnalysis(workDirectory, args, autoFix, outputFile, outputFormat)
case "trivy":
runTrivyAnalysis(workDirectory, args, outputFile, outputFormat)
case "pmd":
runPmdAnalysis(workDirectory, args, outputFile, outputFormat)
case "pylint":
runPylintAnalysis(workDirectory, args, outputFile, outputFormat)
case "":
log.Fatal("You need to specify a tool to run analysis with, e.g., '--tool eslint'")
default:
log.Fatal("Trying to run unsupported tool: ", toolToAnalyze)
}
},
}