Skip to content

Detect property to exclude Cargo dependencies #1421

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 31 commits into from
Jun 30, 2025
Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
10883f5
property to exclude dev dependencies in cargo cli detector add
zahidblackduck Apr 23, 2025
0354a8e
cargo cli extractor dev dependencies exclusion add
zahidblackduck Apr 24, 2025
2830904
cargo lockfile detector dependency exclusion add
zahidblackduck Apr 28, 2025
1ac92d4
detect rule factory edit
zahidblackduck Apr 30, 2025
5344176
cargo version match util update
zahidblackduck Apr 30, 2025
fba1188
cargo version match util add
zahidblackduck Apr 30, 2025
f6e48d9
cargo lockfile dev,build dependency exclusion add
zahidblackduck May 6, 2025
b66b9f7
Merge conflict resolve with master
zahidblackduck May 6, 2025
37c4ed6
cargo lock file dependency transformer refactor
zahidblackduck May 6, 2025
9e1e4a4
wildcard imports cleared
zahidblackduck May 7, 2025
95d1bac
method name refactor to express actual intent
zahidblackduck May 7, 2025
1293fb9
doc description updated for new detect properties
zahidblackduck May 8, 2025
1a0e93a
handle dependency exclusion if present in multiple sections of Cargo.…
zahidblackduck May 15, 2025
0d8f6f2
handle dependency exclusion if present in multiple sections of Cargo.…
zahidblackduck May 15, 2025
d2a8a6c
properties doc updated with an example usage
zahidblackduck May 15, 2025
5eb9b16
Merge remote-tracking branch 'origin/master' into dev/zahidblackduck/…
zahidblackduck May 15, 2025
d2be399
refactor dependency exclusion to use NameVersion without precedence f…
zahidblackduck May 16, 2025
83ebdf1
remove code comment and empty line
zahidblackduck May 16, 2025
ae1ee8e
refactor condition to check actual dependency exclusion filter
zahidblackduck May 20, 2025
383b99e
Merge remote-tracking branch 'origin/master' into dev/zahidblackduck/…
zahidblackduck May 22, 2025
204b05f
parse dependencies to exclude map key change to NameVersion
zahidblackduck May 22, 2025
538bc03
Merge remote-tracking branch 'origin/master' into dev/zahidblackduck/…
zahidblackduck May 27, 2025
537760c
Merge remote-tracking branch 'origin/master' into dev/zahidblackduck/…
zahidblackduck Jun 16, 2025
f1be648
transitive dependencies resolve for cargo lock file detector dependen…
zahidblackduck Jun 20, 2025
f3130f8
version util update to follow cargo version matching properly
zahidblackduck Jun 23, 2025
9955084
Merge remote-tracking branch 'origin/master' into dev/zahidblackduck/…
zahidblackduck Jun 25, 2025
44a70b2
exclusion strategy update for cargo lockfile detector
zahidblackduck Jun 25, 2025
26ec154
exclusion logic re-implement in preemptive approach
zahidblackduck Jun 26, 2025
8bdcb52
Merge remote-tracking branch 'origin/master' into dev/zahidblackduck/…
zahidblackduck Jun 30, 2025
ff370af
refactor to construct package lookup map beforehand
zahidblackduck Jun 30, 2025
2f9f6a8
detect properties update for cargo
zahidblackduck Jun 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -87,4 +87,7 @@ public boolean shouldExclude(T enumValue) {
return excludedSet.contains(enumValue);
}

public boolean shouldIncludeAll() {
return excludedSet.isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,17 @@ public class CargoCliDetectable extends Detectable {
private final CargoResolver cargoResolver;
private final CargoCliExtractor cargoCliExtractor;
private final DetectableExecutableRunner executableRunner;
private final CargoDetectableOptions cargoDetectableOptions;
private ExecutableTarget cargoExe;
private File cargoToml;

public CargoCliDetectable(DetectableEnvironment environment, FileFinder fileFinder, CargoResolver cargoResolver, CargoCliExtractor cargoCliExtractor, DetectableExecutableRunner executableRunner) {
public CargoCliDetectable(DetectableEnvironment environment, FileFinder fileFinder, CargoResolver cargoResolver, CargoCliExtractor cargoCliExtractor, DetectableExecutableRunner executableRunner, CargoDetectableOptions cargoDetectableOptions) {
super(environment);
this.fileFinder = fileFinder;
this.cargoResolver = cargoResolver;
this.cargoCliExtractor = cargoCliExtractor;
this.executableRunner = executableRunner;
this.cargoDetectableOptions = cargoDetectableOptions;
}

@Override
Expand Down Expand Up @@ -72,7 +74,7 @@ public DetectableResult extractable() throws DetectableException {
@Override
public Extraction extract(ExtractionEnvironment extractionEnvironment) throws IOException, DetectableException, MissingExternalIdException, ExecutableRunnerException {
try {
return cargoCliExtractor.extract(environment.getDirectory(), cargoExe, cargoToml);
return cargoCliExtractor.extract(environment.getDirectory(), cargoExe, cargoToml, cargoDetectableOptions);
} catch (Exception e) {
logger.error("Failed to extract Cargo dependencies.", e);
return new Extraction.Builder().failure("Cargo extraction failed due to an exception: " + e.getMessage()).build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;
import java.util.Map;
import java.util.EnumMap;

public class CargoCliExtractor {
private static final List<String> CARGO_TREE_COMMAND = Arrays.asList("tree", "--no-dedupe", "--prefix", "depth");
Expand All @@ -32,8 +35,12 @@ public CargoCliExtractor(DetectableExecutableRunner executableRunner, CargoDepen
this.cargoTomlParser = cargoTomlParser;
}

public Extraction extract(File directory, ExecutableTarget cargoExe, File cargoTomlFile) throws ExecutableFailedException, IOException {
ExecutableOutput cargoOutput = executableRunner.executeSuccessfully(ExecutableUtils.createFromTarget(directory, cargoExe, CARGO_TREE_COMMAND));
public Extraction extract(File directory, ExecutableTarget cargoExe, File cargoTomlFile, CargoDetectableOptions cargoDetectableOptions) throws ExecutableFailedException, IOException {
List<String> cargoTreeCommand = new ArrayList<>(CARGO_TREE_COMMAND);

addEdgeExclusions(cargoTreeCommand, cargoDetectableOptions);

ExecutableOutput cargoOutput = executableRunner.executeSuccessfully(ExecutableUtils.createFromTarget(directory, cargoExe, cargoTreeCommand));
List<String> cargoTreeOutput = cargoOutput.getStandardOutputAsList();

DependencyGraph graph = cargoDependencyTransformer.transform(cargoTreeOutput);
Expand All @@ -51,4 +58,24 @@ public Extraction extract(File directory, ExecutableTarget cargoExe, File cargoT
.nameVersionIfPresent(projectNameVersion)
.build();
}

private void addEdgeExclusions(List<String> cargoTreeCommand, CargoDetectableOptions options) {
Map<CargoDependencyType, String> exclusionMap = new EnumMap<>(CargoDependencyType.class);
exclusionMap.put(CargoDependencyType.NORMAL, "no-normal");
exclusionMap.put(CargoDependencyType.BUILD, "no-build");
exclusionMap.put(CargoDependencyType.DEV, "no-dev");
exclusionMap.put(CargoDependencyType.PROC_MACRO, "no-proc-macro");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you describe situations in which PROC_MACRO exclusion is useful? And I guess it's not applicable to lock file extractions?


List<String> exclusions = new ArrayList<>();
for (Map.Entry<CargoDependencyType, String> entry : exclusionMap.entrySet()) {
if (options.getDependencyTypeFilter().shouldExclude(entry.getKey())) {
exclusions.add(entry.getValue());
}
}

if (!exclusions.isEmpty()) {
cargoTreeCommand.add("--edges");
cargoTreeCommand.add(String.join(",", exclusions));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.blackduck.integration.detectable.detectables.cargo;

public enum CargoDependencyType {
NORMAL,
BUILD,
DEV,
PROC_MACRO
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.blackduck.integration.detectable.detectables.cargo;

import com.blackduck.integration.detectable.detectable.util.EnumListFilter;

public class CargoDetectableOptions {
private final EnumListFilter<CargoDependencyType> dependencyTypeFilter;

public CargoDetectableOptions(EnumListFilter<CargoDependencyType> dependencyTypeFilter) {
this.dependencyTypeFilter = dependencyTypeFilter;
}

public EnumListFilter<CargoDependencyType> getDependencyTypeFilter() {
return dependencyTypeFilter;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.blackduck.integration.detectable.detectable.util.EnumListFilter;
import com.blackduck.integration.detectable.detectables.cargo.data.CargoLockPackageData;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.Nullable;

Expand Down Expand Up @@ -39,26 +48,152 @@ public CargoExtractor(
this.cargoLockPackageTransformer = cargoLockPackageTransformer;
}

public Extraction extract(File cargoLockFile, @Nullable File cargoTomlFile) throws IOException, DetectableException, MissingExternalIdException {
public Extraction extract(File cargoLockFile, @Nullable File cargoTomlFile, CargoDetectableOptions cargoDetectableOptions) throws IOException, DetectableException, MissingExternalIdException {
CargoLockData cargoLockData = new Toml().read(cargoLockFile).to(CargoLockData.class);
List<CargoLockPackage> packages = cargoLockData.getPackages()
.orElse(new ArrayList<>()).stream()
List<CargoLockPackageData> cargoLockPackageDataList = cargoLockData.getPackages().orElse(new ArrayList<>());
List<CargoLockPackageData> filteredPackages = cargoLockPackageDataList;
boolean exclusionEnabled = isDependencyExclusionEnabled(cargoDetectableOptions);
String cargoTomlContents = null;

if(cargoTomlFile == null && exclusionEnabled) {
return new Extraction.Builder()
.failure("Cargo.toml file is required to exclude dependencies, but was not provided.")
.build();
}

if (cargoTomlFile != null) {
cargoTomlContents = FileUtils.readFileToString(cargoTomlFile, StandardCharsets.UTF_8);
}

if (cargoTomlFile != null && exclusionEnabled) {
Set<NameVersion> dependenciesToInclude = cargoTomlParser.parseDependenciesToInclude(
cargoTomlContents, cargoDetectableOptions.getDependencyTypeFilter());
filteredPackages = includeDependencies(cargoLockPackageDataList, dependenciesToInclude);
}

List<CargoLockPackage> packages = filteredPackages.stream()
.map(cargoLockPackageDataTransformer::transform)
.collect(Collectors.toList());

DependencyGraph graph = cargoLockPackageTransformer.transformToGraph(packages);

Optional<NameVersion> projectNameVersion = Optional.empty();
if (cargoTomlFile != null) {
String cargoTomlContents = FileUtils.readFileToString(cargoTomlFile, StandardCharsets.UTF_8);
projectNameVersion = cargoTomlParser.parseNameVersionFromCargoToml(cargoTomlContents);
}

CodeLocation codeLocation = new CodeLocation(graph); //TODO: Consider for producing a ProjectDependencyGraph

return new Extraction.Builder()
.success(codeLocation)
.nameVersionIfPresent(projectNameVersion)
.build();
}

private boolean isDependencyExclusionEnabled(CargoDetectableOptions options) {
if (options == null) {
return false;
}

EnumListFilter<CargoDependencyType> filter = options.getDependencyTypeFilter();
return filter != null && !filter.shouldIncludeAll();
}


private List<CargoLockPackageData> includeDependencies(
List<CargoLockPackageData> packages,
Set<NameVersion> dependenciesToInclude
) {
processTransitiveDependenciesForInclusion(packages, dependenciesToInclude); // Collect all transitive dependencies to include
return filterPackagesByInclusion(packages, dependenciesToInclude); // Only keep direct and transitive dependencies
}

private void processTransitiveDependenciesForInclusion(List<CargoLockPackageData> packages, Set<NameVersion> dependenciesToInclude) {
Set<NameVersion> resolvedToInclude = new HashSet<>();
for (NameVersion nv : dependenciesToInclude) {
CargoLockPackageData pkg = findPackageByNameVersion(nv, packages);
if (pkg != null) {
String name = pkg.getName().orElse(null);
String version = pkg.getVersion().orElse(null);
resolvedToInclude.add(new NameVersion(name, version));
} else {
resolvedToInclude.add(nv);
}
}
dependenciesToInclude.clear();
dependenciesToInclude.addAll(resolvedToInclude);

Deque<NameVersion> queue = new ArrayDeque<>(dependenciesToInclude);
while (!queue.isEmpty()) {
NameVersion current = queue.pop();
CargoLockPackageData currentPkg = findPackageByNameVersion(current, packages);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This find is done inside of a loop so it might be worth it to do some preprocessing for faster lookups.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may still be a concern for big projects. You could try indexing packages by name for faster lookups before starting loops that call this method. There are a couple such loops.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, are you suggesting to construct a HashMap of package names beforehand? I mean the findPackageByNameVersion method matches for versions. For example, which 7.0.0 should match version which 7.0.2. And there can be another which 8.0.1 to which the first one should not match.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that's the idea. It can be a map of names to multiple name/versions.
That would allow us to quickly find all possible versions for a given dependency instead of iterating through the entire list of dependencies for every single lookup.

if (currentPkg != null) {
currentPkg.getDependencies().ifPresent(dependencies -> {
for (String depStr : dependencies) {
NameVersion nameVersion = extractPackageNameVersion(depStr, packages);
if (nameVersion != null && dependenciesToInclude.add(nameVersion)) {
queue.add(nameVersion);
}
}
});
}
}
}

private List<CargoLockPackageData> filterPackagesByInclusion(
List<CargoLockPackageData> packages,
Set<NameVersion> dependenciesToInclude
) {
List<CargoLockPackageData> result = new ArrayList<>();
for (CargoLockPackageData pkg : packages) {
String name = pkg.getName().orElse(null);
String version = VersionUtils.stripBuildMetadata(pkg.getVersion().orElse(null));
for (NameVersion include : dependenciesToInclude) {
String includeName = include.getName();
String includeVersion = VersionUtils.stripBuildMetadata(include.getVersion());
if (Objects.equals(name, includeName) && VersionUtils.versionMatches(includeVersion, version)) {
result.add(pkg);
break;
}
}
}
return result;
}

private NameVersion extractPackageNameVersion(String dependencyString, List<CargoLockPackageData> packages) {
if (dependencyString == null || dependencyString.isEmpty()) {
return null;
}

String[] parts = dependencyString.split(" ");
String depName = parts[0].trim();
String depVersion = (parts.length > 1) ? parts[1].trim() : null;

// If depVersion is null or empty, find by name only.
// Otherwise, find by name and version.
if (depVersion == null || depVersion.isEmpty()) {
for (CargoLockPackageData pkg : packages) {
String name = pkg.getName().orElse(null);
String version = pkg.getVersion().orElse(null);
if (depName.equals(name)) {
return new NameVersion(name, version);
}
}
}
return new NameVersion(depName, depVersion);
}

private CargoLockPackageData findPackageByNameVersion(NameVersion nv, List<CargoLockPackageData> packages) {
for (CargoLockPackageData pkg : packages) {
String name = pkg.getName().orElse(null);
String version = pkg.getVersion().orElse(null);

// Matching name and use VersionUtils to check if the versions are compatible
if (nv.getName().equals(name)
&& version != null
&& VersionUtils.versionMatches(VersionUtils.stripBuildMetadata(nv.getVersion()), VersionUtils.stripBuildMetadata(version))) {
return pkg;
}
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,15 @@ public class CargoLockDetectable extends Detectable {

private final FileFinder fileFinder;
private final CargoExtractor cargoExtractor;

private final CargoDetectableOptions cargoDetectableOptions;
private File cargoLock;
private File cargoToml;

public CargoLockDetectable(DetectableEnvironment environment, FileFinder fileFinder, CargoExtractor cargoExtractor) {
public CargoLockDetectable(DetectableEnvironment environment, FileFinder fileFinder, CargoExtractor cargoExtractor, CargoDetectableOptions cargoDetectableOptions) {
super(environment);
this.fileFinder = fileFinder;
this.cargoExtractor = cargoExtractor;
this.cargoDetectableOptions = cargoDetectableOptions;
}

@Override
Expand All @@ -52,6 +53,6 @@ public DetectableResult extractable() {

@Override
public Extraction extract(ExtractionEnvironment extractionEnvironment) throws IOException, DetectableException, MissingExternalIdException {
return cargoExtractor.extract(cargoLock, cargoToml);
return cargoExtractor.extract(cargoLock, cargoToml, cargoDetectableOptions);
}
}
Loading