mirror of
https://github.com/anchore/syft.git
synced 2026-11-04 00:16:38 +01:00
chore: add more detail on SPDX file IDs (#1769)
This commit is contained in:
@@ -4,6 +4,7 @@ package spdxhelpers
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -131,13 +132,30 @@ func ToFormatModel(s sbom.SBOM) *spdx.Document {
|
||||
}
|
||||
|
||||
func toSPDXID(identifiable artifact.Identifiable) spdx.ElementID {
|
||||
maxLen := 40
|
||||
id := ""
|
||||
if p, ok := identifiable.(pkg.Package); ok {
|
||||
id = SanitizeElementID(fmt.Sprintf("Package-%+v-%s-%s", p.Type, p.Name, p.ID()))
|
||||
} else {
|
||||
switch it := identifiable.(type) {
|
||||
case pkg.Package:
|
||||
id = SanitizeElementID(fmt.Sprintf("Package-%s-%s-%s", it.Type, it.Name, it.ID()))
|
||||
case source.Coordinates:
|
||||
p := ""
|
||||
parts := strings.Split(it.RealPath, "/")
|
||||
for i := len(parts); i > 0; i-- {
|
||||
part := parts[i-1]
|
||||
if len(part) == 0 {
|
||||
continue
|
||||
}
|
||||
if i < len(parts) && len(p)+len(part)+3 > maxLen {
|
||||
p = "..." + p
|
||||
break
|
||||
}
|
||||
p = path.Join(part, p)
|
||||
}
|
||||
id = SanitizeElementID(fmt.Sprintf("File-%s-%s", p, it.ID()))
|
||||
default:
|
||||
id = string(identifiable.ID())
|
||||
}
|
||||
// NOTE: the spdx libraries prepend SPDXRef-, so we don't do it here
|
||||
// NOTE: the spdx library prepend SPDXRef-, so we don't do it here
|
||||
return spdx.ElementID(id)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package spdxhelpers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/spdx/tools-golang/spdx"
|
||||
@@ -501,3 +502,43 @@ func Test_OtherLicenses(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_toSPDXID(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
it artifact.Identifiable
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "short filename",
|
||||
it: source.Coordinates{
|
||||
RealPath: "/short/path/file.txt",
|
||||
},
|
||||
expected: "File-short-path-file.txt",
|
||||
},
|
||||
{
|
||||
name: "long filename",
|
||||
it: source.Coordinates{
|
||||
RealPath: "/some/long/path/with/a/lot/of-text/that-contains-a/file.txt",
|
||||
},
|
||||
expected: "File-...a-lot-of-text-that-contains-a-file.txt",
|
||||
},
|
||||
{
|
||||
name: "package",
|
||||
it: pkg.Package{
|
||||
Type: pkg.NpmPkg,
|
||||
Name: "some-package",
|
||||
},
|
||||
expected: "Package-npm-some-package",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := string(toSPDXID(test.it))
|
||||
// trim the hash
|
||||
got = regexp.MustCompile(`-[a-z0-9]*$`).ReplaceAllString(got, "")
|
||||
require.Equal(t, test.expected, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user