diff --git a/pkg/json.go b/pkg/json.go index f98766decef..f5c4ce71bb1 100644 --- a/pkg/json.go +++ b/pkg/json.go @@ -69,6 +69,8 @@ type jsonScorecardV2 struct { type jsonFloatScore float64 +var errNoDoc = errors.New("doc is nil") + func (s jsonFloatScore) MarshalJSON() ([]byte, error) { // Note: for integers, this will show as X.0. return []byte(fmt.Sprintf("%.1f", s)), nil @@ -147,6 +149,9 @@ func (r *ScorecardResult) AsJSON2(showDetails bool, if e != nil { return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("GetCheck: %s: %v", checkResult.Name, e)) } + if doc == nil { + return sce.WithMessage(sce.ErrScorecardInternal, fmt.Sprintf("GetCheck: %s: %v", checkResult.Name, errNoDoc)) + } tmpResult := jsonCheckResultV2{ Name: checkResult.Name, diff --git a/pkg/sarif.go b/pkg/sarif.go index dfa418439bf..bcb9849d695 100644 --- a/pkg/sarif.go +++ b/pkg/sarif.go @@ -550,6 +550,9 @@ func computeCategory(checkName string, repos []string) (string, error) { } } +// createSARIFRuns takes a map of runs and returns a sorted slice of runs. +// It sorts the keys of the map, iterates over them, and appends the corresponding run to the result slice. +// If the run is nil, it is skipped. func createSARIFRuns(runs map[string]*run) []run { res := []run{} // Sort keys. @@ -561,7 +564,9 @@ func createSARIFRuns(runs map[string]*run) []run { // Iterate over keys. for _, k := range keys { - res = append(res, *runs[k]) + if runs[k] != nil { + res = append(res, *runs[k]) + } } return res } diff --git a/pkg/sarif_test.go b/pkg/sarif_test.go index 49d8e7190e9..6a8912721ef 100644 --- a/pkg/sarif_test.go +++ b/pkg/sarif_test.go @@ -18,6 +18,7 @@ import ( "bytes" "fmt" "os" + "reflect" "testing" "time" @@ -852,3 +853,79 @@ func TestSARIFOutput(t *testing.T) { }) } } + +func Test_createSARIFRuns(t *testing.T) { + t.Parallel() + type args struct { + runs map[string]*run + } + tests := []struct { + name string + args args + want []run + }{ + { + name: "empty runs", + args: args{ + runs: map[string]*run{}, + }, + want: []run{}, + }, + { + name: "nil runs are skipped", + args: args{ + runs: map[string]*run{ + "run1": nil, + "run2": { + Tool: tool{ + Driver: driver{ + Name: "name", + }, + }, + }, + }, + }, + want: []run{ + { + Tool: tool{ + Driver: driver{ + Name: "name", + }, + }, + }, + }, + }, + { + name: "one run", + args: args{ + runs: map[string]*run{ + "run1": { + Tool: tool{ + Driver: driver{ + Name: "name", + }, + }, + }, + }, + }, + want: []run{ + { + Tool: tool{ + Driver: driver{ + Name: "name", + }, + }, + }, + }, + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := createSARIFRuns(tt.args.runs); !reflect.DeepEqual(got, tt.want) { + t.Errorf("createSARIFRuns() = %v, want %v", got, tt.want) + } + }) + } +}