Skip to content

Commit

Permalink
Fix clippy suggestions and unused imports
Browse files Browse the repository at this point in the history
  • Loading branch information
kmicklas committed Sep 27, 2023
1 parent 8a33aec commit 456fb97
Show file tree
Hide file tree
Showing 10 changed files with 41 additions and 41 deletions.
7 changes: 3 additions & 4 deletions crate2nix/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
//! Managing the `crate2nix.json` config.
use anyhow::{bail, Context, Error};
use anyhow::{Context, Error};
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeMap,
fmt::Display,
fs::File,
io::{BufReader, BufWriter},
path::Path,
str::FromStr,
};

impl Config {
Expand Down Expand Up @@ -64,8 +63,8 @@ impl Config {

let max_len = self
.sources
.iter()
.map(|(n, _)| n.len())
.keys()
.map(|n| n.len())
.max()
.unwrap_or_default();
for (name, source) in &self.sources {
Expand Down
5 changes: 2 additions & 3 deletions crate2nix/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,7 @@ fn cargo_metadata(config: &GenerateConfig, cargo_toml: &Path) -> Result<Metadata
let mut cmd = cargo_metadata::MetadataCommand::new();
let mut other_options = config.other_metadata_options.clone();
other_options.push("--locked".into());
cmd.manifest_path(&cargo_toml)
.other_options(&*other_options);
cmd.manifest_path(cargo_toml).other_options(&*other_options);
cmd.exec().map_err(|e| {
format_err!(
"while retrieving metadata about {}: {}",
Expand All @@ -180,7 +179,7 @@ fn prefetch_and_fill_crates_sha256(
default_nix: &mut BuildInfo,
) -> Result<(), Error> {
let mut from_lock_file: HashMap<PackageId, String> =
extract_hashes_from_lockfile(&config, default_nix)?;
extract_hashes_from_lockfile(config, default_nix)?;
for (_package_id, hash) in from_lock_file.iter_mut() {
let bytes =
hex::decode(&hash).map_err(|e| format_err!("while decoding '{}': {}", hash, e))?;
Expand Down
2 changes: 1 addition & 1 deletion crate2nix/src/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl EncodableResolve {
}

pub fn load_lock_string(path: &Path, config: &str) -> Result<EncodableResolve, Error> {
let resolve: toml::Value = toml::from_str(&config)
let resolve: toml::Value = toml::from_str(config)
.map_err(|e| format_err!("while parsing toml from {}: {}", path.display(), e))?;

let v: EncodableResolve = resolve
Expand Down
14 changes: 7 additions & 7 deletions crate2nix/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,16 +112,16 @@ impl IndexedMetadata {
.map(|node| {
(
id_shortener.shorten(&node.id),
id_shortener.shorten_in_node(&node),
id_shortener.shorten_in_node(node),
)
})
.collect();

Ok(IndexedMetadata {
root: root.as_ref().map(|id| id_shortener.shorten(&id)),
root: root.as_ref().map(|id| id_shortener.shorten(id)),
workspace_members: workspace_members
.iter()
.map(|id| id_shortener.shorten(&id))
.map(|id| id_shortener.shorten(id))
.collect(),
pkgs_by_id,
nodes_by_id,
Expand All @@ -132,7 +132,7 @@ impl IndexedMetadata {
#[cfg(test)]
pub fn root_package(&self) -> Option<&Package> {
let root = self.root.as_ref()?;
self.pkgs_by_id.get(&root)
self.pkgs_by_id.get(root)
}
}

Expand Down Expand Up @@ -200,16 +200,16 @@ impl PackageIdShortener {
}

pub fn lengthen_ref<'a>(&'a self, package_id: &'a PackageId) -> &'a PackageId {
self.reverse.get(&package_id).unwrap_or(&package_id)
self.reverse.get(package_id).unwrap_or(package_id)
}

pub fn shorten_ref<'a>(&'a self, package_id: &'a PackageId) -> &'a PackageId {
self.substitution.get(&package_id).unwrap_or(&package_id)
self.substitution.get(package_id).unwrap_or(package_id)
}

pub fn shorten(&self, package_id: &PackageId) -> PackageId {
self.substitution
.get(&package_id)
.get(package_id)
.cloned()
.unwrap_or_else(|| package_id.clone())
}
Expand Down
4 changes: 2 additions & 2 deletions crate2nix/src/nix_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn nix_build(
&format!("Building {}", project_dir),
Command::new("nix")
.current_dir(&project_dir)
.args(&[
.args([
"--show-trace",
"build",
"-f",
Expand All @@ -42,7 +42,7 @@ pub fn nix_build(
);

if result.is_err() {
dump_with_lines(&project_dir_path.join("default.nix"))?;
dump_with_lines(project_dir_path.join("default.nix"))?;
}

result
Expand Down
2 changes: 1 addition & 1 deletion crate2nix/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ fn cfg_to_nix_expr_filter(
if key.starts_with("cfg(") && key.ends_with(')') {
let cfg = &key[4..key.len() - 1];

let expr = CfgExpr::from_str(&cfg).map_err(|e| {
let expr = CfgExpr::from_str(cfg).map_err(|e| {
tera::Error::msg(format!(
"cfg_to_nix_expr_filter: Could not parse '{}': {}",
cfg, e
Expand Down
16 changes: 8 additions & 8 deletions crate2nix/src/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ impl CrateDerivation {
// name anymore. So we need to extract it from the path.
let configured_source = package_path
.file_name()
.and_then(|file_name| crate2nix_json.sources.get(&*file_name).cloned());
.and_then(|file_name| crate2nix_json.sources.get(file_name).cloned());

if !crate2nix_json.sources.is_empty() && configured_source.is_none() {
eprintln!(
Expand All @@ -109,7 +109,7 @@ impl CrateDerivation {
let source = if let Some(configured) = configured_source {
configured.into()
} else {
ResolvedSource::new(&config, &package, &package_path)?
ResolvedSource::new(config, package, package_path)?
};

let package_path = package_path.canonicalize().map_err(|e| {
Expand All @@ -128,13 +128,13 @@ impl CrateDerivation {
k == "lib" || k == "cdylib" || k == "dylib" || k == "rlib" || k == "proc-macro"
})
})
.and_then(|target| BuildTarget::new(&target, &package_path).ok());
.and_then(|target| BuildTarget::new(target, &package_path).ok());

let build = package
.targets
.iter()
.find(|t| t.kind.iter().any(|k| k == "custom-build"))
.and_then(|target| BuildTarget::new(&target, &package_path).ok());
.and_then(|target| BuildTarget::new(target, &package_path).ok());

let proc_macro = package
.targets
Expand All @@ -146,7 +146,7 @@ impl CrateDerivation {
.iter()
.filter_map(|t| {
if t.kind.iter().any(|k| k == "bin") {
BuildTarget::new(&t, &package_path).ok()
BuildTarget::new(t, &package_path).ok()
} else {
None
}
Expand Down Expand Up @@ -228,7 +228,7 @@ pub fn minimal_resolve() {
crate_derivation.version,
semver::Version::parse("1.2.3").unwrap()
);
assert_eq!(crate_derivation.is_root_or_workspace_member, true);
assert!(crate_derivation.is_root_or_workspace_member);
let empty: Vec<String> = vec![];
assert_eq!(crate_derivation.lib_crate_types, empty);

Expand All @@ -249,7 +249,7 @@ pub fn configured_source_is_used_instead_of_local_directory() {
// By simulating this layout, we ensure that we do not canonicalize paths at the "wrong"
// moment.
let simulated_store_path = env.temp_dir();
std::fs::File::create(&simulated_store_path.join("Cargo.toml")).expect("File creation failed");
std::fs::File::create(simulated_store_path.join("Cargo.toml")).expect("File creation failed");
let workspace_with_symlink = env.temp_dir();
std::os::unix::fs::symlink(
&simulated_store_path,
Expand All @@ -272,7 +272,7 @@ pub fn configured_source_is_used_instead_of_local_directory() {
version: semver::Version::from_str("1.2.3").unwrap(),
sha256: "123".to_string(),
};
crate2nix_json.upsert_source(None, source.clone());
crate2nix_json.upsert_source(None, source);
let crate_derivation =
CrateDerivation::resolve(&config, &crate2nix_json, &indexed, root_package).unwrap();

Expand Down
12 changes: 6 additions & 6 deletions crate2nix/src/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn crates_io_source(name: String, version: Version) -> Result<config::Source
sha256: None,
};

eprint!("Prefetching {}: ", prefetchable.to_string());
eprint!("Prefetching {}: ", prefetchable);
let sha256 = prefetchable.prefetch()?;
eprintln!("done.");

Expand All @@ -42,7 +42,7 @@ pub fn git_io_source(url: Url, rev: String) -> Result<config::Source, Error> {
sha256: None,
};

eprint!("Prefetching {}: ", prefetchable.to_string());
eprint!("Prefetching {}: ", prefetchable);
let sha256 = prefetchable.prefetch()?;
eprintln!("done.");

Expand Down Expand Up @@ -87,7 +87,7 @@ impl<'a> FetchedSources<'a> {
}

if self.sources_nix().exists() {
let reader = std::io::BufReader::new(File::open(&self.sources_nix())?);
let reader = std::io::BufReader::new(File::open(self.sources_nix())?);
let generated = reader.lines().any(|l| {
l.map(|l| l.contains("@generated by crate2nix"))
.unwrap_or(false)
Expand All @@ -97,7 +97,7 @@ impl<'a> FetchedSources<'a> {
}
}

crate::render::SOURCES_NIX.write_to_file(&self.sources_nix(), &info)?;
crate::render::SOURCES_NIX.write_to_file(self.sources_nix(), &info)?;

Ok(())
}
Expand All @@ -110,7 +110,7 @@ impl<'a> FetchedSources<'a> {
let fetched_sources_symlink = self.project_dir().join(FETCHED_SOURCES);
download_and_link_out_of_tree_sources(
self.project_dir(),
&self.sources_nix(),
self.sources_nix(),
&fetched_sources_symlink,
"fetchedSources",
)
Expand Down Expand Up @@ -200,7 +200,7 @@ fn download_and_link_out_of_tree_sources(
let caption = format!("Fetching sources via {} {}", sources_nix, nix_attr);
crate::command::run(
&caption,
Command::new("nix").current_dir(&project_dir).args(&[
Command::new("nix").current_dir(&project_dir).args([
"--show-trace",
"build",
"-f",
Expand Down
16 changes: 9 additions & 7 deletions crate2nix/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ impl MetadataEnv {
}

fn mut_resolve(&mut self) -> &mut Resolve {
self.metadata.resolve.get_or_insert_with(|| empty_resolve())
self.metadata.resolve.get_or_insert_with(empty_resolve)
}

pub fn add_package_and_node(&mut self, name: &str) -> PackageAndNode {
Expand Down Expand Up @@ -103,7 +103,7 @@ impl<'a> PackageAndNode<'a> {
.mut_metadata()
.workspace_members
.push(package_id.clone());
self.env.mut_resolve().root = Some(package_id.clone());
self.env.mut_resolve().root = Some(package_id);
self
}

Expand Down Expand Up @@ -264,11 +264,13 @@ where
T: serde::de::DeserializeOwned,
{
use serde_json::{from_value, to_string_pretty};
from_value(json()).expect(&format!(
"invalid {}: {}",
std::any::type_name::<T>(),
to_string_pretty(&json()).unwrap()
))
from_value(json()).unwrap_or_else(|_| {
panic!(
"invalid {}: {}",
std::any::type_name::<T>(),
to_string_pretty(&json()).unwrap()
)
})
}

/// Return value from given JSON.
Expand Down
4 changes: 2 additions & 2 deletions crate2nix/tests/self_build_up_to_date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ fn pregenerated_up_to_date() {
Some(pregenerated_build) => {
let cargo_nix = PathBuf::from_str(&pregenerated_build)
.expect("pregeneratedBuild must be valid path");
assert_up_to_date(&cargo_nix.parent().expect("Cargo.nix must be in directory"));
assert_up_to_date(cargo_nix.parent().expect("Cargo.nix must be in directory"));
}
None => println!("Skipping not pregenerated {}", test_config.name),
}
Expand Down Expand Up @@ -125,7 +125,7 @@ struct TestConfig {

fn get_test_configs() -> Result<Vec<TestConfig>, Error> {
let output = Command::new("nix")
.args(&["eval", "--json", "-f", "../tests.nix", "buildTestConfigs"])
.args(["eval", "--json", "-f", "../tests.nix", "buildTestConfigs"])
.output()
.map_err(|e| format_err!("while spawning nix: {}", e))?;
if !output.status.success() {
Expand Down

0 comments on commit 456fb97

Please sign in to comment.