fix match sort ordering for different locations (#1944)

* introduce failing test: inconsistent location sorting

Signed-off-by: Dan Luhring <dluhring@chainguard.dev>

* fix: inconsistent matches sort ordering

Signed-off-by: Dan Luhring <dluhring@chainguard.dev>

---------

Signed-off-by: Dan Luhring <dluhring@chainguard.dev>
This commit is contained in:
Dan Luhring 2024-06-14 14:02:12 -04:00 committed by GitHub
parent f994fe68b3
commit f599a66257
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 38 additions and 6 deletions

View file

@ -3,6 +3,7 @@ package match
import (
"testing"
"github.com/anchore/syft/syft/file"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -104,20 +105,36 @@ func TestMatchesSortMixedDimensions(t *testing.T) {
},
},
Package: pkg.Package{
ID: pkg.ID(uuid.NewString()),
Name: "package-d",
Version: "2.0.0",
Type: syftPkg.RpmPkg,
ID: pkg.ID(uuid.NewString()),
Name: "package-d",
Version: "2.0.0",
Type: syftPkg.RpmPkg,
Locations: file.NewLocationSet(file.NewLocation("/some/first-path")),
},
}
ninth := Match{
Vulnerability: vulnerability.Vulnerability{
ID: "CVE-2020-0020",
Fix: vulnerability.Fix{
Versions: []string{"3.0.0"},
},
},
Package: pkg.Package{
ID: pkg.ID(uuid.NewString()),
Name: "package-d",
Version: "2.0.0",
Type: syftPkg.RpmPkg,
Locations: file.NewLocationSet(file.NewLocation("/some/other-path")),
},
}
input := []Match{
// shuffle vulnerability id, package name, package version, and package type
fifth, eighth, third, seventh, first, sixth, second, fourth,
ninth, fifth, eighth, third, seventh, first, sixth, second, fourth,
}
matches := NewMatches(input...)
assertMatchOrder(t, []Match{first, second, third, fourth, fifth, sixth, seventh, eighth}, matches.Sorted())
assertMatchOrder(t, []Match{first, second, third, fourth, fifth, sixth, seventh, eighth, ninth}, matches.Sorted())
}

View file

@ -28,6 +28,21 @@ func (m ByElements) Less(i, j int) bool {
sort.Strings(fixVersions2)
fixStr1 := strings.Join(fixVersions1, ",")
fixStr2 := strings.Join(fixVersions2, ",")
if fixStr1 == fixStr2 {
loc1 := m[i].Package.Locations.ToSlice()
loc2 := m[j].Package.Locations.ToSlice()
var locStr1 string
for _, location := range loc1 {
locStr1 += location.String()
}
var locStr2 string
for _, location := range loc2 {
locStr2 += location.String()
}
return locStr1 < locStr2
}
return fixStr1 < fixStr2
}
return m[i].Package.Type < m[j].Package.Type