Skip to content

Commit

Permalink
ISSUE-16 - Remove cargo core usage:
Browse files Browse the repository at this point in the history
* Remove cargo core usage from scan module
* Remove cargo core usage from traversal module
* Remove cargo core usage from format module
* Remove cargo core usage from scan module
* Refactor krates_utils into separate modules

Signed-off-by: joshmc <[email protected]>
  • Loading branch information
jmcconnell26 committed Nov 12, 2020
1 parent 5fe50b5 commit 1640619
Show file tree
Hide file tree
Showing 20 changed files with 518 additions and 367 deletions.
50 changes: 34 additions & 16 deletions cargo-geiger/src/format/display.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
use crate::format::pattern::Pattern;
use crate::format::Chunk;

use crate::utils::{
CargoMetadataParameters, GetPackageNameFromCargoMetadataPackageId,
GetPackageVersionFromCargoMetadataPackageId,
};
use cargo::core::manifest::ManifestMetadata;
use cargo::core::PackageId;
use std::fmt;

pub struct Display<'a> {
pub cargo_metadata_parameters: &'a CargoMetadataParameters<'a>,
pub pattern: &'a Pattern,
pub package: &'a PackageId,
pub package: &'a cargo_metadata::PackageId,
pub metadata: &'a ManifestMetadata,
}

Expand All @@ -24,8 +28,16 @@ impl<'a> fmt::Display for Display<'a> {
(write!(
fmt,
"{} {}",
self.package.name(),
self.package.version()
self.cargo_metadata_parameters
.krates
.get_package_name_from_cargo_metadata_package_id(
self.package
),
self.cargo_metadata_parameters
.krates
.get_package_version_from_cargo_metadata_package_id(
self.package
)
))?
}
Chunk::Raw(ref s) => (fmt.write_str(s))?,
Expand All @@ -48,8 +60,8 @@ pub mod display_tests {
use crate::format::Chunk;

use cargo::core::manifest::ManifestMetadata;
use cargo::core::{PackageId, SourceId};
use cargo::util::ToSemver;
use cargo_metadata::{CargoOpt, MetadataCommand};
use krates::Builder;
use rstest::*;

#[rstest(
Expand All @@ -61,7 +73,7 @@ pub mod display_tests {
),
case(
Pattern(vec![Chunk::Package]),
"package_name 1.2.3"
"cargo-geiger 0.10.2"
),
case(
Pattern(vec![Chunk::Raw(String::from("chunk_value"))]),
Expand All @@ -76,15 +88,17 @@ pub mod display_tests {
input_pattern: Pattern,
expected_formatted_string: &str,
) {
let package_id = PackageId::new(
"package_name",
"1.2.3".to_semver().unwrap(),
SourceId::from_url(
"git+https://github.com/rust-secure-code/cargo-geiger",
)
.unwrap(),
)
.unwrap();
let metadata = MetadataCommand::new()
.manifest_path("./Cargo.toml")
.features(CargoOpt::AllFeatures)
.exec()
.unwrap();

let krates = Builder::new()
.build_with_metadata(metadata.clone(), |_| ())
.unwrap();

let package_id = metadata.root_package().unwrap().id.clone();

let manifest_metadata = ManifestMetadata {
authors: vec![],
Expand All @@ -102,6 +116,10 @@ pub mod display_tests {
};

let display = Display {
cargo_metadata_parameters: &CargoMetadataParameters {
krates: &krates,
metadata: &metadata,
},
pattern: &input_pattern,
package: &package_id,
metadata: &manifest_metadata,
Expand Down
6 changes: 4 additions & 2 deletions cargo-geiger/src/format/pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use crate::format::{Chunk, RawChunk};

use super::display::Display;

use crate::utils::CargoMetadataParameters;
use cargo::core::manifest::ManifestMetadata;
use cargo::core::PackageId;
use std::error::Error;

#[derive(Debug, PartialEq)]
Expand All @@ -13,10 +13,12 @@ pub struct Pattern(pub Vec<Chunk>);
impl Pattern {
pub fn display<'a>(
&'a self,
package: &'a PackageId,
cargo_metadata_parameters: &'a CargoMetadataParameters,
metadata: &'a ManifestMetadata,
package: &'a cargo_metadata::PackageId,
) -> Display<'a> {
Display {
cargo_metadata_parameters,
pattern: self,
package,
metadata,
Expand Down
3 changes: 3 additions & 0 deletions cargo-geiger/src/format/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use handle_text_tree_line::{
};
use total_package_counts::TotalPackageCounts;

use crate::utils::CargoMetadataParameters;
use cargo::core::package::PackageSet;
use cargo_geiger_serde::{Count, CounterBlock};
use std::collections::HashSet;
Expand All @@ -31,6 +32,7 @@ pub const UNSAFE_COUNTERS_HEADER: [&str; 6] = [
];

pub fn create_table_from_text_tree_lines(
cargo_metadata_parameters: &CargoMetadataParameters,
package_set: &PackageSet,
table_parameters: &TableParameters,
text_tree_lines: Vec<TextTreeLine>,
Expand Down Expand Up @@ -61,6 +63,7 @@ pub fn create_table_from_text_tree_lines(
id: package_id,
tree_vines,
} => handle_text_tree_line_package(
cargo_metadata_parameters,
&emoji_symbols,
&mut handle_package_parameters,
package_id,
Expand Down
29 changes: 16 additions & 13 deletions cargo-geiger/src/format/table/handle_text_tree_line.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
use crate::format::emoji_symbols::EmojiSymbols;
use crate::format::print_config::colorize;
use crate::format::{get_kind_group_name, CrateDetectionStatus, SymbolKind};
use crate::scan::unsafe_stats;
use crate::utils::{CargoMetadataParameters, ToPackage};

use super::total_package_counts::TotalPackageCounts;
use super::TableParameters;
use super::{table_row, table_row_empty};

use crate::format::emoji_symbols::EmojiSymbols;
use cargo::core::dependency::DepKind;
use cargo::core::package::PackageSet;
use cargo::core::PackageId;
use std::collections::HashSet;

pub struct HandlePackageParameters<'a> {
pub total_package_counts: &'a mut TotalPackageCounts,
pub visited_package_ids: &'a mut HashSet<PackageId>,
pub visited_package_ids: &'a mut HashSet<cargo_metadata::PackageId>,
pub warning_count: &'a mut u64,
}

Expand All @@ -33,22 +33,24 @@ pub fn handle_text_tree_line_extra_deps_group(
table_lines.push(format!("{}{}{}", table_row_empty(), tree_vines, name));
}

#[allow(clippy::too_many_arguments)]
pub fn handle_text_tree_line_package(
cargo_metadata_parameters: &CargoMetadataParameters,
emoji_symbols: &EmojiSymbols,
handle_package_parameters: &mut HandlePackageParameters,
package_id: PackageId,
package_id: cargo_metadata::PackageId,
package_set: &PackageSet,
table_lines: &mut Vec<String>,
table_parameters: &TableParameters,
tree_vines: String,
) {
let package_is_new = handle_package_parameters
.visited_package_ids
.insert(package_id);
let package = package_set.get_one(package_id).unwrap_or_else(|_| {
// TODO: Avoid panic, return Result.
panic!("Expected to find package by id: {}", package_id);
});
.insert(package_id.clone());

let package =
package_id.to_package(cargo_metadata_parameters.krates, package_set);

let package_metrics = match table_parameters
.geiger_context
.package_id_to_metrics
Expand Down Expand Up @@ -97,10 +99,11 @@ pub fn handle_text_tree_line_package(
let package_name = colorize(
format!(
"{}",
table_parameters
.print_config
.format
.display(&package_id, package.manifest().metadata())
table_parameters.print_config.format.display(
cargo_metadata_parameters,
package.manifest().metadata(),
&package_id
)
),
&crate_detection_status,
);
Expand Down
2 changes: 1 addition & 1 deletion cargo-geiger/src/graph.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::args::{Args, DepsArgs, TargetArgs};
use crate::cli::get_cfgs;
use crate::krates_utils::{
use crate::utils::{
CargoMetadataParameters, DepsNotReplaced, MatchesIgnoringSource,
Replacement,
};
Expand Down
9 changes: 6 additions & 3 deletions cargo-geiger/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ mod args;
mod cli;
mod format;
mod graph;
mod krates_utils;
mod scan;
mod tree;
mod utils;

use crate::args::{Args, HELP};
use crate::cli::{
Expand All @@ -25,7 +25,9 @@ use crate::cli::{
use crate::graph::build_graph;
use crate::scan::scan;

use crate::krates_utils::{CargoMetadataParameters, ToCargoMetadataPackage};
use crate::utils::{
CargoMetadataParameters, ToCargoMetadataPackage, ToCargoMetadataPackageId,
};
use cargo::core::shell::{ColorChoice, Shell};
use cargo::{CliResult, Config};

Expand Down Expand Up @@ -109,7 +111,8 @@ fn real_main(args: &Args, config: &mut Config) -> CliResult {
config,
&graph,
&package_set,
root_package_id,
root_package_id
.to_cargo_metadata_package_id(cargo_metadata_parameters.metadata),
&workspace,
)
}
Expand Down
50 changes: 28 additions & 22 deletions cargo-geiger/src/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,15 @@ mod rs_file;
use crate::args::Args;
use crate::format::print_config::PrintConfig;
use crate::graph::Graph;
use crate::utils::{CargoMetadataParameters, ToCargoCoreDepKind, ToPackageId};

pub use rs_file::RsFileMetricsWrapper;

use default::scan_unsafe;
use forbid::scan_forbid_unsafe;

use crate::krates_utils::{
CargoMetadataParameters, ToCargoCoreDepKind, ToCargoMetadataPackageId,
ToPackageId,
};
use cargo::core::dependency::DepKind;
use cargo::core::{PackageId, PackageSet, Workspace};
use cargo::core::{PackageSet, Workspace};
use cargo::{CliResult, Config};
use cargo_geiger_serde::{
CounterBlock, DependencyKind, PackageInfo, UnsafeInfo,
Expand All @@ -30,7 +27,8 @@ use url::Url;
/// Provides a more terse and searchable name for the wrapped generic
/// collection.
pub struct GeigerContext {
pub package_id_to_metrics: HashMap<PackageId, PackageMetrics>,
pub package_id_to_metrics:
HashMap<cargo_metadata::PackageId, PackageMetrics>,
}

#[derive(Clone, Debug, Default)]
Expand Down Expand Up @@ -61,7 +59,7 @@ pub fn scan(
config: &Config,
graph: &Graph,
package_set: &PackageSet,
root_package_id: PackageId,
root_package_id: cargo_metadata::PackageId,
workspace: &Workspace,
) -> CliResult {
let print_config = PrintConfig::new(args)?;
Expand Down Expand Up @@ -170,30 +168,32 @@ fn package_metrics(
geiger_context: &GeigerContext,
graph: &Graph,
package_set: &PackageSet,
root_package_id: PackageId,
root_package_id: cargo_metadata::PackageId,
) -> Vec<(PackageInfo, Option<PackageMetrics>)> {
let mut package_metrics =
Vec::<(PackageInfo, Option<PackageMetrics>)>::new();
let root_index = graph.nodes[&root_package_id
.to_cargo_metadata_package_id(cargo_metadata_parameters.metadata)];
let root_index = graph.nodes[&root_package_id];
let mut indices = vec![root_index];
let mut visited = HashSet::new();

while !indices.is_empty() {
let i = indices.pop().unwrap();
let package_id = graph.graph[i]
.to_package_id(cargo_metadata_parameters.krates, package_set);
let mut package = PackageInfo::new(from_cargo_package_id(package_id));
let package_id = graph.graph[i].clone();
let mut package = PackageInfo::new(from_cargo_package_id(
cargo_metadata_parameters,
package_id.clone(),
package_set,
));
for edge in graph.graph.edges(i) {
let dep_index = edge.target();
if visited.insert(dep_index) {
indices.push(dep_index);
}
let dep =
from_cargo_package_id(graph.graph[dep_index].to_package_id(
cargo_metadata_parameters.krates,
package_set,
));
let dep = from_cargo_package_id(
cargo_metadata_parameters,
graph.graph[dep_index].clone(),
package_set,
);
package.add_dependency(
dep,
from_cargo_dependency_kind(
Expand All @@ -216,8 +216,14 @@ fn package_metrics(
package_metrics
}

fn from_cargo_package_id(id: PackageId) -> cargo_geiger_serde::PackageId {
let source = id.source_id();
fn from_cargo_package_id(
cargo_metadata_parameters: &CargoMetadataParameters,
cargo_metadata_package_id: cargo_metadata::PackageId,
package_set: &PackageSet,
) -> cargo_geiger_serde::PackageId {
let package_id = cargo_metadata_package_id
.to_package_id(cargo_metadata_parameters.krates, package_set);
let source = package_id.source_id();
let source_url = source.url();
// Canonicalize paths as cargo does not seem to do so on all platforms.
let source_url = if source_url.scheme() == "file" {
Expand Down Expand Up @@ -253,8 +259,8 @@ fn from_cargo_package_id(id: PackageId) -> cargo_geiger_serde::PackageId {
panic!("Unsupported source type: {:?}", source)
};
cargo_geiger_serde::PackageId {
name: id.name().to_string(),
version: id.version().clone(),
name: package_id.name().to_string(),
version: package_id.version().clone(),
source,
}
}
Expand Down
Loading

0 comments on commit 1640619

Please sign in to comment.