-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathlist.go
More file actions
311 lines (256 loc) · 9.05 KB
/
list.go
File metadata and controls
311 lines (256 loc) · 9.05 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
package list
import (
"context"
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/MakeNowJust/heredoc"
"github.com/deepsourcelabs/cli/config"
"github.com/deepsourcelabs/cli/deepsource"
"github.com/deepsourcelabs/cli/deepsource/issues"
"github.com/deepsourcelabs/cli/utils"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
)
const MAX_ISSUE_LIMIT = 100
type IssuesListOptions struct {
FileArg []string
RepoArg string
AnalyzerArg []string
SeverityArg []string
LimitArg int
OutputFilenameArg string
JSONArg bool
CSVArg bool
SARIFArg bool
SelectedRemote *utils.RemoteData
issuesData []issues.Issue
ptermTable [][]string
}
func NewCmdIssuesList() *cobra.Command {
opts := IssuesListOptions{
FileArg: []string{""},
RepoArg: "",
LimitArg: 30,
}
doc := heredoc.Docf(`
List issues reported by DeepSource.
To list issues for the current repository:
%[1]s
To list issues for a specific repository, use the %[2]s flag:
%[3]s
To list issues for a specific analyzer, use the %[4]s flag:
%[5]s
To limit the number of issues reported, use the %[6]s flag:
%[7]s
To export listed issues to a file, use the %[8]s flag:
%[9]s
To export listed issues to a JSON file, use the %[10]s flag:
%[11]s
To export listed issues to a CSV file, use the %[12]s flag:
%[13]s
To export listed issues to a SARIF file, use the %[14]s flag:
%[15]s
To list issues for specific severities, use the %[16]s flag:
%[17]s
`, utils.Cyan("deepsource issues list"), utils.Yellow("--repo"), utils.Cyan("deepsource issues list --repo repo_name"), utils.Yellow("--analyzer"), utils.Cyan("deepsource issues list --analyzer python"), utils.Yellow("--limit"), utils.Cyan("deepsource issues list --limit 100"), utils.Yellow("--output-file"), utils.Cyan("deepsource issues list --output-file file_name"), utils.Yellow("--json"), utils.Cyan("deepsource issues list --json --output-file example.json"), utils.Yellow("--csv"), utils.Cyan("deepsource issues list --csv --output-file example.csv"), utils.Yellow("--sarif"), utils.Cyan("deepsource issues list --sarif --output-file example.sarif"), utils.Yellow("--severity"), utils.Cyan("deepsource issues list --severity critical --severity major"))
cmd := &cobra.Command{
Use: "list",
Short: "List issues reported by DeepSource",
Long: doc,
RunE: func(cmd *cobra.Command, args []string) error {
opts.FileArg = args
return opts.Run()
},
}
// --repo, -r flag
cmd.Flags().StringVarP(&opts.RepoArg, "repo", "r", "", "List the issues of the specified repository")
// --severity -s flag
cmd.Flags().StringArrayVarP(&opts.SeverityArg, "severity", "s", nil, "List issues for specified severity (CRITICAL, MAJOR, MINOR)")
// --analyzer, -a flag
cmd.Flags().StringArrayVarP(&opts.AnalyzerArg, "analyzer", "a", nil, "List the issues for the specified analyzer")
// --limit, -l flag
cmd.Flags().IntVarP(&opts.LimitArg, "limit", "l", 30, "Fetch the issues upto the specified limit")
// --output-file, -o flag
cmd.Flags().StringVarP(&opts.OutputFilenameArg, "output-file", "o", "", "Output file to write the reported issues to")
// --json flag
cmd.Flags().BoolVar(&opts.JSONArg, "json", false, "Output reported issues in JSON format")
// --csv flag
cmd.Flags().BoolVar(&opts.CSVArg, "csv", false, "Output reported issues in CSV format")
// --sarif flag
cmd.Flags().BoolVar(&opts.SARIFArg, "sarif", false, "Output reported issues in SARIF format")
return cmd
}
// Execute the command
func (opts *IssuesListOptions) Run() (err error) {
// Fetch config
cfg, err := config.GetConfig()
if err != nil {
return fmt.Errorf("Error while reading DeepSource CLI config : %v", err)
}
err = cfg.VerifyAuthentication()
if err != nil {
return err
}
// The current limit of querying issues at once is 100.
// If the limit passed by user is greater than 100, exit
// with an error message
if opts.LimitArg > MAX_ISSUE_LIMIT {
return fmt.Errorf("The maximum allowed limit to fetch issues is 100. Found %d", opts.LimitArg)
}
// Get the remote repository URL for which issues have to be listed
opts.SelectedRemote, err = utils.ResolveRemote(opts.RepoArg)
if err != nil {
return err
}
// Fetch the list of issues using SDK (deepsource package) based on user input
ctx := context.Background()
err = opts.getIssuesData(ctx)
if err != nil {
return err
}
if opts.JSONArg {
opts.exportJSON(opts.OutputFilenameArg)
} else if opts.CSVArg {
opts.exportCSV(opts.OutputFilenameArg)
} else if opts.SARIFArg {
opts.exportSARIF(opts.OutputFilenameArg)
} else {
opts.showIssues()
}
return nil
}
// Gets the data about issues using the SDK based on the user input
// i.e for a single file or for the whole project
func (opts *IssuesListOptions) getIssuesData(ctx context.Context) (err error) {
// Get the deepsource client for using the issue fetching SDK to fetch the list of issues
deepsource, err := deepsource.New(deepsource.ClientOpts{
Token: config.Cfg.Token,
HostName: config.Cfg.Host,
})
if err != nil {
return err
}
// Fetch list of issues for the whole project
opts.issuesData, err = deepsource.GetIssues(ctx, opts.SelectedRemote.Owner, opts.SelectedRemote.RepoName, opts.SelectedRemote.VCSProvider, opts.LimitArg)
if err != nil {
return err
}
var filteredIssues []issues.Issue
// Fetch issues for a certain FileArg (filepath) passed by the user
// Example: `deepsource issues list api/hello.py`
if len(opts.FileArg) != 0 {
var fetchedIssues []issues.Issue
for _, arg := range opts.FileArg {
// Filter issues for the valid directories/files
filteredIssues, err = filterIssuesByPath(arg, opts.issuesData)
if err != nil {
return err
}
fetchedIssues = append(fetchedIssues, filteredIssues...)
}
// set fetched issues as issue data
opts.issuesData = getUniqueIssues(fetchedIssues)
}
if len(opts.AnalyzerArg) != 0 {
var fetchedIssues []issues.Issue
// Filter issues based on the analyzer shortcode
filteredIssues, err = filterIssuesByAnalyzer(opts.AnalyzerArg, opts.issuesData)
if err != nil {
return err
}
fetchedIssues = append(fetchedIssues, filteredIssues...)
// set fetched issues as issue data
opts.issuesData = getUniqueIssues(fetchedIssues)
}
if len(opts.SeverityArg) != 0 {
var fetchedIssues []issues.Issue
//Filter issues based on the severity option specified
filteredIssues, err = filterIssuesBySeverity(opts.SeverityArg, opts.issuesData)
if err != nil {
return err
}
fetchedIssues = append(fetchedIssues, filteredIssues...)
// set fetched issues as issue data
opts.issuesData = getUniqueIssues(fetchedIssues)
}
return nil
}
// Parses the SDK response and formats the data in the form of a TAB separated table
// and renders it using pterm
func (opts *IssuesListOptions) showIssues() {
// A 2d array to contain list of issues details arrays
opts.ptermTable = make([][]string, len(opts.issuesData))
// Curating the data and appending to the 2d array
for index, issue := range opts.issuesData {
filePath := issue.Location.Path
beginLine := issue.Location.Position.BeginLine
issueLocation := fmt.Sprintf("%s:%d", filePath, beginLine)
analyzerShortcode := issue.Analyzer.Shortcode
issueCategory := issue.IssueCategory
issueSeverity := issue.IssueSeverity
issueCode := issue.IssueCode
issueTitle := issue.IssueText
opts.ptermTable[index] = []string{issueLocation, analyzerShortcode, issueCode, issueTitle, issueCategory, issueSeverity}
}
// Using pterm to render the list of list
pterm.DefaultTable.WithSeparator("\t").WithData(opts.ptermTable).Render()
}
// Handles exporting issues as JSON
func (opts *IssuesListOptions) exportJSON(filename string) (err error) {
issueJSON := convertJSON(opts.issuesData)
data, err := json.MarshalIndent(issueJSON, "", " ")
if err != nil {
return err
}
if filename == "" {
pterm.Println(string(data))
return nil
}
if err = ioutil.WriteFile(filename, data, 0o644); err != nil {
return err
}
pterm.Info.Printf("Saved issues to %s!\n", filename)
return nil
}
// Handles exporting issues as CSV
func (opts *IssuesListOptions) exportCSV(filename string) error {
records := convertCSV(opts.issuesData)
if filename == "" {
// write to stdout
w := csv.NewWriter(os.Stdout)
return w.WriteAll(records)
}
// create file
file, err := os.Create(filename)
if err != nil {
return err
}
// write to file
w := csv.NewWriter(file)
w.WriteAll(records)
if err := w.Error(); err != nil {
return err
}
pterm.Info.Printf("Saved issues to %s!\n", filename)
return nil
}
// Handles exporting issues as a SARIF file
func (opts *IssuesListOptions) exportSARIF(filename string) (err error) {
report := convertSARIF(opts.issuesData)
if filename == "" {
err = report.PrettyWrite(os.Stdout)
if err != nil {
return err
}
return nil
}
// write report to file
if err := report.WriteFile(filename); err != nil {
return err
}
pterm.Info.Printf("Saved issues to %s!\n", filename)
return nil
}