Skip to content

Commit 402bdfb

Browse files
authored
Merge pull request #20 from codacy/add_api_token_to_upload
Allow the usage of the API token to upload results
2 parents 9f9e1f0 + 5081189 commit 402bdfb

File tree

3 files changed

+278
-180
lines changed

3 files changed

+278
-180
lines changed

README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,19 @@ The `codacy-cli-v2` is a command-line tool for Codacy that supports analyzing co
1414
- `--fix, -f`: Automatically fixes issues when possible.
1515
- `--new-pr`: Creates a new GitHub PR with fixed issues.
1616

17-
- **`upload` Command**: Uploads a SARIF file containing analysis results to Codacy.
17+
- **`upload` Command With Project Token**: Uploads a SARIF file containing analysis results to Codacy.
1818
- `--sarif-path, -s`: Path to the SARIF report.
1919
- `--commit-uuid, -c`: Commit UUID.
2020
- `--project-token, -t`: Project token for Codacy API.
2121

22+
- **`upload` Command With API Token**: Uploads a SARIF file containing analysis results to Codacy.
23+
- `--sarif-path, -s`: Path to the SARIF report.
24+
- `--commit-uuid, -c`: Commit UUID.
25+
- `--api-token, -a`: User level token for Codacy API.
26+
- `--provider, -p`: Provider name (e.g., gh, gl, bb).
27+
- `--owner, -o`: Repository owner.
28+
- `--repository, -r`: Repository name.
29+
2230
### Important Concepts
2331

2432
- **`.codacy/.codacy.yaml`**: Configuration file to specify `node` and `eslint` versions for the CLI.

cmd/analyze.go

Lines changed: 0 additions & 179 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package cmd
22

33
import (
4-
"bytes"
54
"codacy/cli-v2/config"
65
"codacy/cli-v2/tools"
76
"codacy/cli-v2/utils"
@@ -12,8 +11,6 @@ import (
1211
"net/http"
1312
"os"
1413
"os/exec"
15-
"strconv"
16-
"strings"
1714

1815
"github.com/spf13/cobra"
1916
)
@@ -101,42 +98,6 @@ func init() {
10198
analyzeCmd.Flags().BoolVarP(&autoFix, "fix", "f", false, "Apply auto fix to your issues when available")
10299
analyzeCmd.Flags().BoolVar(&doNewPr, "new-pr", false, "Create a new PR on GitHub containing the fixed issues")
103100
rootCmd.AddCommand(analyzeCmd)
104-
uploadResultsCmd.Flags().StringVarP(&sarifPath, "sarif-path", "s", "", "Path to the SARIF report")
105-
uploadResultsCmd.Flags().StringVarP(&commitUuid, "commit-uuid", "c", "", "Commit UUID")
106-
uploadResultsCmd.Flags().StringVarP(&projectToken, "project-token", "t", "", "Project token for Codacy API")
107-
rootCmd.AddCommand(uploadResultsCmd)
108-
}
109-
110-
var uploadResultsCmd = &cobra.Command{
111-
Use: "upload",
112-
Short: "Uploads a sarif file to Codacy",
113-
Long: "YADA",
114-
Run: func(cmd *cobra.Command, args []string) {
115-
processSarifAndSendResults(sarifPath, commitUuid, projectToken)
116-
},
117-
}
118-
119-
func processSarifAndSendResults(sarifPath string, commitUuid string, projectToken string) {
120-
fmt.Printf("Loading SARIF file from path: %s\n", sarifPath)
121-
//Load SARIF file
122-
sarifFile, err := os.Open(sarifPath)
123-
if err != nil {
124-
fmt.Printf("Error opening SARIF file: %v\n", err)
125-
panic("panic")
126-
}
127-
defer sarifFile.Close()
128-
129-
var sarif Sarif
130-
fmt.Println("Parsing SARIF file...")
131-
err = json.NewDecoder(sarifFile).Decode(&sarif)
132-
if err != nil {
133-
fmt.Printf("Error parsing SARIF file: %v\n", err)
134-
os.Exit(1)
135-
}
136-
137-
fmt.Println("Loading Codacy patterns...")
138-
processSarif(sarif)
139-
140101
}
141102

142103
func loadsToolAndPatterns(toolName string) (Tool, []Pattern) {
@@ -207,115 +168,6 @@ func loadsToolAndPatterns(toolName string) (Tool, []Pattern) {
207168
return tool, patterns
208169
}
209170

210-
func processSarif(sarif Sarif) {
211-
var codacyIssues []map[string]interface{}
212-
213-
for _, run := range sarif.Runs {
214-
var toolName = getToolName(strings.ToLower(run.Tool.Driver.Name), run.Tool.Driver.Version)
215-
tool, patterns := loadsToolAndPatterns(toolName)
216-
for _, result := range run.Results {
217-
modifiedType := tool.Prefix + strings.Replace(result.RuleID, "/", "_", -1)
218-
pattern := getPatternById(patterns, modifiedType)
219-
if pattern == nil {
220-
fmt.Printf("Rule '%s' doesn't have a direct mapping on Codacy\n", modifiedType)
221-
continue
222-
}
223-
for _, location := range result.Locations {
224-
codacyIssues = append(codacyIssues, map[string]interface{}{
225-
"source": location.PhysicalLocation.ArtifactLocation.URI,
226-
"line": location.PhysicalLocation.Region.StartLine,
227-
"type": modifiedType,
228-
"message": result.Message.Text,
229-
"level": pattern.Level,
230-
"category": pattern.Category,
231-
})
232-
}
233-
}
234-
groups := make(map[string]map[string]interface{})
235-
for _, obj := range codacyIssues {
236-
source := obj["source"].(string)
237-
if _, ok := groups[source]; !ok {
238-
groups[source] = map[string]interface{}{
239-
"filename": source,
240-
"results": []interface{}{},
241-
}
242-
}
243-
groups[source]["results"] = append(groups[source]["results"].([]interface{}), map[string]interface{}{
244-
"Issue": map[string]interface{}{
245-
"patternId": map[string]string{
246-
"value": obj["type"].(string),
247-
},
248-
"filename": source,
249-
"message": map[string]string{
250-
"text": obj["message"].(string),
251-
},
252-
"level": obj["level"].(string),
253-
"category": obj["category"].(string),
254-
"location": map[string]interface{}{
255-
"LineLocation": map[string]int{
256-
"line": obj["line"].(int),
257-
},
258-
},
259-
},
260-
})
261-
}
262-
payload := []map[string]interface{}{
263-
{
264-
"tool": toolName,
265-
"issues": map[string]interface{}{
266-
"Success": map[string]interface{}{
267-
"results": groups,
268-
},
269-
},
270-
},
271-
}
272-
sendResults(payload, commitUuid, projectToken)
273-
}
274-
275-
resultsFinal(commitUuid, projectToken)
276-
277-
}
278-
279-
func resultsFinal(commitUuid string, projectToken string) {
280-
url := fmt.Sprintf("https://api.codacy.com/2.0/commit/%s/resultsFinal", commitUuid)
281-
req, _ := http.NewRequest("POST", url, nil)
282-
req.Header.Set("Content-Type", "application/json")
283-
req.Header.Set("project-token", projectToken)
284-
285-
client := &http.Client{}
286-
resp, err := client.Do(req)
287-
if err != nil {
288-
fmt.Println("Error:", err)
289-
return
290-
}
291-
defer resp.Body.Close()
292-
body, _ := io.ReadAll(resp.Body)
293-
fmt.Println("Response:", resp.Status)
294-
fmt.Println("Response Body:", string(body))
295-
}
296-
297-
func getPatternById(patterns []Pattern, patternId string) *Pattern {
298-
for _, p := range patterns {
299-
if p.ID == patternId {
300-
return &p
301-
}
302-
}
303-
return nil
304-
}
305-
306-
func getMajorVersion(version string) int {
307-
parts := strings.Split(version, ".")
308-
if len(parts) > 0 {
309-
major, err := strconv.Atoi(parts[0])
310-
if err != nil {
311-
fmt.Println("Error converting major version to integer:", err)
312-
return -1
313-
}
314-
return major
315-
}
316-
return -1
317-
}
318-
319171
func getToolName(toolName string, version string) string {
320172

321173
if toolName == "eslint" {
@@ -334,37 +186,6 @@ func getToolName(toolName string, version string) string {
334186
return toolName
335187
}
336188

337-
func sendResults(payload []map[string]interface{}, commitUuid string, projectToken string) {
338-
339-
payloadBytes, err := json.Marshal(payload)
340-
if err != nil {
341-
fmt.Printf("Error marshaling payload: %v\n", err)
342-
panic("panic")
343-
}
344-
345-
url := fmt.Sprintf("https://api.codacy.com/2.0/commit/%s/issuesRemoteResults", commitUuid)
346-
fmt.Printf("Sending results to URL: %s\n", url)
347-
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
348-
if err != nil {
349-
fmt.Printf("Error creating request: %v\n", err)
350-
os.Exit(1)
351-
}
352-
req.Header.Set("content-type", "application/json")
353-
req.Header.Set("project-token", projectToken)
354-
355-
resp, err := http.DefaultClient.Do(req)
356-
if err != nil {
357-
fmt.Printf("Error sending results: %v\n", err)
358-
os.Exit(1)
359-
}
360-
defer resp.Body.Close()
361-
362-
if resp.StatusCode != http.StatusOK {
363-
fmt.Printf("Error sending results, status code: %d\n", resp.StatusCode)
364-
os.Exit(1)
365-
}
366-
}
367-
368189
var analyzeCmd = &cobra.Command{
369190
Use: "analyze",
370191
Short: "Runs all linters.",

0 commit comments

Comments
 (0)