Skip to content

Commit

Permalink
feat: emit dependency relationships found in Cargo.lock (#3443)
Browse files Browse the repository at this point in the history
* feat: emit dependency relationships found in Cargo.lock

Include updating test Cargo.lock to have dependencies on multiple
versions of the same crate.

Signed-off-by: Will Murphy <willmurphyscode@users.noreply.github.com>
  • Loading branch information
willmurphyscode authored Nov 14, 2024
1 parent 926486a commit bc35345
Show file tree
Hide file tree
Showing 3 changed files with 352 additions and 160 deletions.
41 changes: 36 additions & 5 deletions syft/pkg/cataloger/rust/parse_cargo_lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,50 @@ func parseCargoLock(_ context.Context, _ file.Resolver, _ *generic.Environment,
}

var pkgs []pkg.Package
pkgIndex := make(map[string]int)

for _, p := range m.Packages {
if p.Dependencies == nil {
p.Dependencies = make([]string, 0)
}
newPkg := newPackageFromCargoMetadata(
p,
reader.Location.WithAnnotation(pkg.EvidenceAnnotationKey, pkg.PrimaryEvidenceAnnotation),
)
pkgs = append(
pkgs,
newPackageFromCargoMetadata(
p,
reader.Location.WithAnnotation(pkg.EvidenceAnnotationKey, pkg.PrimaryEvidenceAnnotation),
),
newPkg,
)
newIx := len(pkgs) - 1
// Cargo.lock dependencies are strings that are the name of a package, if that
// is unambiguous, or a string like "name version" if the name alone is not
// ambiguous. Set both keys in the map, since we don't know which key is
// going to be used until we're trying to resolve dependencies. If the
// first key is overwritten, that means the package name was an ambiguous dependency
// and "name version" will be used as the key anyway.
keys := []string{
newPkg.Name,
fmt.Sprintf("%s %s", newPkg.Name, newPkg.Version),
}
for _, k := range keys {
pkgIndex[k] = newIx
}
}
var relationships []artifact.Relationship
for _, p := range pkgs {
meta := p.Metadata.(pkg.RustCargoLockEntry)
for _, d := range meta.Dependencies {
i, ok := pkgIndex[d]
if !ok {
continue
}
relationships = append(relationships, artifact.Relationship{
From: p,
To: pkgs[i],
Type: artifact.DependencyOfRelationship,
})
}
}

return pkgs, nil, unknown.IfEmptyf(pkgs, "unable to determine packages")
return pkgs, relationships, unknown.IfEmptyf(pkgs, "unable to determine packages")
}
Loading

0 comments on commit bc35345

Please # to comment.