enable source.Location to be identifiable

Signed-off-by: Alex Goodman <alex.goodman@anchore.com>
This commit is contained in:
Alex Goodman 2021-11-10 09:05:33 -05:00
parent 2356539ebe
commit b519340b86
No known key found for this signature in database
GPG Key ID: 5CB45AE22BAB7EA7
3 changed files with 33 additions and 17 deletions

View File

@ -1,8 +1,26 @@
package artifact
import (
"fmt"
"github.com/mitchellh/hashstructure/v2"
)
// ID represents a unique value for each package added to a package catalog.
type ID string
type Identifiable interface {
ID() ID
}
func DeriveID(obj interface{}) (ID, error) {
f, err := hashstructure.Hash(obj, hashstructure.FormatV2, &hashstructure.HashOptions{
ZeroNil: true,
SlicesAsSets: true,
})
if err != nil {
return "", fmt.Errorf("could not build ID for object=%+v: %+v", obj, err)
}
return ID(fmt.Sprint(f)), nil
}

View File

@ -9,7 +9,6 @@ import (
"github.com/anchore/syft/internal/log"
"github.com/anchore/syft/syft/artifact"
"github.com/anchore/syft/syft/source"
"github.com/mitchellh/hashstructure/v2"
)
// Package represents an application or library that has been bundled into a distributable format.
@ -29,29 +28,17 @@ type Package struct {
}
func (p Package) ID() artifact.ID {
f, err := p.Fingerprint()
f, err := artifact.DeriveID(p)
if err != nil {
// TODO: what to do in this case?
log.Warnf("unable to get fingerprint of package=%s@%s: %+v", p.Name, p.Version, err)
return ""
}
return artifact.ID(f)
return f
}
// Stringer to represent a package.
func (p Package) String() string {
return fmt.Sprintf("Pkg(type=%s, name=%s, version=%s)", p.Type, p.Name, p.Version)
}
func (p Package) Fingerprint() (string, error) {
f, err := hashstructure.Hash(p, hashstructure.FormatV2, &hashstructure.HashOptions{
ZeroNil: true,
SlicesAsSets: true,
})
if err != nil {
return "", fmt.Errorf("could not build package fingerprint for: %s version: %s", p.Name, p.Version)
}
return fmt.Sprint(f), nil
}

View File

@ -3,10 +3,10 @@ package source
import (
"fmt"
"github.com/anchore/syft/internal/log"
"github.com/anchore/stereoscope/pkg/file"
"github.com/anchore/stereoscope/pkg/image"
"github.com/anchore/syft/internal/log"
"github.com/anchore/syft/syft/artifact"
)
// Location represents a path relative to a particular filesystem resolved to a specific file.Reference. This struct is used as a key
@ -73,3 +73,14 @@ func (l Location) String() string {
}
return fmt.Sprintf("Location<%s>", str)
}
func (l Location) ID() artifact.ID {
f, err := artifact.DeriveID(l)
if err != nil {
// TODO: what to do in this case?
log.Warnf("unable to get fingerprint of location=%+v: %+v", l, err)
return ""
}
return f
}