From 23591fe5e61d2ee00efe9cfee7d57b0e05353a45 Mon Sep 17 00:00:00 2001 From: Lukas Lueg Date: Sun, 24 Sep 2017 16:26:37 +0200 Subject: [PATCH] More lint cleaning --- src/bin/cargo.rs | 10 ++-- src/bin/init.rs | 4 +- src/bin/install.rs | 2 +- src/bin/new.rs | 2 +- src/bin/run.rs | 2 +- src/bin/verify_project.rs | 2 +- src/cargo/core/dependency.rs | 6 +- src/cargo/core/features.rs | 4 +- src/cargo/core/manifest.rs | 10 ++-- src/cargo/core/package.rs | 7 +-- src/cargo/core/package_id.rs | 4 +- src/cargo/core/package_id_spec.rs | 26 ++++----- src/cargo/core/registry.rs | 13 ++--- src/cargo/core/resolver/encode.rs | 18 +++--- src/cargo/core/resolver/mod.rs | 51 ++++++++--------- src/cargo/core/source.rs | 1 + src/cargo/core/workspace.rs | 17 +++--- src/cargo/ops/cargo_clean.rs | 10 ++-- src/cargo/ops/cargo_compile.rs | 30 +++++----- src/cargo/ops/cargo_generate_lockfile.rs | 8 +-- src/cargo/ops/cargo_install.rs | 38 ++++++------- src/cargo/ops/cargo_new.rs | 29 +++++----- src/cargo/ops/cargo_package.rs | 26 ++++----- src/cargo/ops/cargo_read_manifest.rs | 13 ++--- src/cargo/ops/cargo_run.rs | 4 +- src/cargo/ops/cargo_rustc/compilation.rs | 2 +- src/cargo/ops/cargo_rustc/context.rs | 61 +++++++++------------ src/cargo/ops/cargo_rustc/custom_build.rs | 16 ++---- src/cargo/ops/cargo_rustc/fingerprint.rs | 26 +++------ src/cargo/ops/cargo_rustc/job_queue.rs | 6 +- src/cargo/ops/cargo_rustc/layout.rs | 3 +- src/cargo/ops/cargo_rustc/mod.rs | 55 +++++++++---------- src/cargo/ops/cargo_rustc/output_depinfo.rs | 10 ++-- src/cargo/ops/lockfile.rs | 2 +- src/cargo/ops/registry.rs | 20 +++---- src/cargo/ops/resolve.rs | 4 +- src/cargo/sources/directory.rs | 2 +- src/cargo/sources/git/utils.rs | 14 ++--- src/cargo/sources/path.rs | 33 ++++++----- src/cargo/sources/registry/remote.rs | 4 +- tests/build.rs | 3 +- tests/cargo.rs | 11 ++-- tests/login.rs | 6 +- tests/publish.rs | 2 +- tests/resolve.rs | 40 +++++++------- tests/search.rs | 2 +- tests/small-fd-limits.rs | 2 +- 47 files changed, 305 insertions(+), 356 deletions(-) diff --git a/src/bin/cargo.rs b/src/bin/cargo.rs index c87370e4c..48c2a1347 100644 --- a/src/bin/cargo.rs +++ b/src/bin/cargo.rs @@ -225,11 +225,11 @@ fn execute(flags: Flags, config: &Config) -> CliResult { } }; - if let Some(r) = try_execute_builtin_command(&config, &args) { + if let Some(r) = try_execute_builtin_command(config, &args) { return r; } - let alias_list = aliased_command(&config, &args[1])?; + let alias_list = aliased_command(config, &args[1])?; let args = match alias_list { Some(alias_command) => { let chain = args.iter() @@ -238,7 +238,7 @@ fn execute(flags: Flags, config: &Config) -> CliResult { .chain(args.iter().skip(2)) .map(|s| s.to_string()) .collect::>(); - if let Some(r) = try_execute_builtin_command(&config, &chain) { + if let Some(r) = try_execute_builtin_command(config, &chain) { return r; } else { chain @@ -266,7 +266,7 @@ fn try_execute_builtin_command(config: &Config, args: &[String]) -> Option CargoResult>> { +fn aliased_command(config: &Config, command: &str) -> CargoResult>> { let alias_name = format!("alias.{}", command); let mut result = Ok(None); match config.get_string(&alias_name) { @@ -298,7 +298,7 @@ fn find_closest(config: &Config, cmd: &str) -> Option { // Only consider candidates with a lev_distance of 3 or less so we don't // suggest out-of-the-blue options. let mut filtered = cmds.iter() - .map(|c| (lev_distance(&c, cmd), c)) + .map(|c| (lev_distance(c, cmd), c)) .filter(|&(d, _)| d < 4) .collect::>(); filtered.sort_by(|a, b| a.0.cmp(&b.0)); diff --git a/src/bin/init.rs b/src/bin/init.rs index 6d5c37185..29319e181 100644 --- a/src/bin/init.rs +++ b/src/bin/init.rs @@ -54,7 +54,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult { let Options { flag_bin, flag_lib, arg_path, flag_name, flag_vcs, .. } = options; - let path = &arg_path.unwrap_or(format!(".")); + let path = &arg_path.unwrap_or_else(|| String::from(".")); let opts = ops::NewOptions::new(flag_vcs, flag_bin, flag_lib, @@ -62,7 +62,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult { flag_name.as_ref().map(|s| s.as_ref())); let opts_lib = opts.lib; - ops::init(opts, config)?; + ops::init(&opts, config)?; config.shell().status("Created", format!("{} project", if opts_lib { "library" } diff --git a/src/bin/install.rs b/src/bin/install.rs index 1e34ece16..4fedab896 100644 --- a/src/bin/install.rs +++ b/src/bin/install.rs @@ -145,7 +145,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult { } else if let Some(path) = options.flag_path { SourceId::for_path(&config.cwd().join(path))? } else if options.arg_crate.is_empty() { - SourceId::for_path(&config.cwd())? + SourceId::for_path(config.cwd())? } else { SourceId::crates_io(config)? }; diff --git a/src/bin/new.rs b/src/bin/new.rs index 9b0c97d95..dc0878d19 100644 --- a/src/bin/new.rs +++ b/src/bin/new.rs @@ -61,7 +61,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult { flag_name.as_ref().map(|s| s.as_ref())); let opts_lib = opts.lib; - ops::new(opts, config)?; + ops::new(&opts, config)?; config.shell().status("Created", format!("{} `{}` project", if opts_lib { "library" } diff --git a/src/bin/run.rs b/src/bin/run.rs index 64f30877d..d6bee1f09 100644 --- a/src/bin/run.rs +++ b/src/bin/run.rs @@ -116,7 +116,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult { Some(err) => { // If we never actually spawned the process then that sounds pretty // bad and we always want to forward that up. - let exit = match err.exit.clone() { + let exit = match err.exit { Some(exit) => exit, None => return Err( CliError::new(CargoErrorKind::ProcessErrorKind(err).into(), 101)), diff --git a/src/bin/verify_project.rs b/src/bin/verify_project.rs index 00127e1fe..208905671 100644 --- a/src/bin/verify_project.rs +++ b/src/bin/verify_project.rs @@ -48,7 +48,7 @@ pub fn execute(args: Flags, config: &Config) -> CliResult { &args.flag_z)?; let mut contents = String::new(); - let filename = args.flag_manifest_path.unwrap_or("Cargo.toml".into()); + let filename = args.flag_manifest_path.unwrap_or_else(|| "Cargo.toml".into()); let filename = match find_root_manifest_for_wd(Some(filename), config.cwd()) { Ok(manifest_path) => manifest_path, Err(e) => fail("invalid", &e.to_string()), diff --git a/src/cargo/core/dependency.rs b/src/cargo/core/dependency.rs index 2d8b4d038..24d6c9f35 100644 --- a/src/cargo/core/dependency.rs +++ b/src/cargo/core/dependency.rs @@ -61,7 +61,7 @@ impl ser::Serialize for Dependency { { SerializedDependency { name: self.name(), - source: &self.source_id(), + source: self.source_id(), req: self.version_req().to_string(), kind: self.kind(), optional: self.is_optional(), @@ -262,7 +262,7 @@ impl Dependency { /// an exact version req. pub fn is_locked(&self) -> bool { // Kind of a hack to figure this out, but it works! - self.inner.req.to_string().starts_with("=") + self.inner.req.to_string().starts_with('=') } /// Returns false if the dependency is only used to build the local package. @@ -348,7 +348,7 @@ impl FromStr for Platform { type Err = CargoError; fn from_str(s: &str) -> CargoResult { - if s.starts_with("cfg(") && s.ends_with(")") { + if s.starts_with("cfg(") && s.ends_with(')') { let s = &s[4..s.len()-1]; s.parse().map(Platform::Cfg).chain_err(|| { format!("failed to parse `{}` as a cfg expression", s) diff --git a/src/cargo/core/features.rs b/src/cargo/core/features.rs index 51b82076c..c73c1bc47 100644 --- a/src/cargo/core/features.rs +++ b/src/cargo/core/features.rs @@ -232,7 +232,7 @@ pub struct CliUnstable { impl CliUnstable { pub fn parse(&mut self, flags: &[String]) -> CargoResult<()> { - if flags.len() > 0 && !nightly_features_allowed() { + if !flags.is_empty() && !nightly_features_allowed() { bail!("the `-Z` flag is only accepted on the nightly channel of Cargo") } for flag in flags { @@ -267,7 +267,7 @@ impl CliUnstable { fn channel() -> String { env::var("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS").unwrap_or_else(|_| { ::version().cfg_info.map(|c| c.release_channel) - .unwrap_or(String::from("dev")) + .unwrap_or_else(|| String::from("dev")) }) } diff --git a/src/cargo/core/manifest.rs b/src/cargo/core/manifest.rs index 74187bc9c..06f66a6b0 100644 --- a/src/cargo/core/manifest.rs +++ b/src/cargo/core/manifest.rs @@ -470,11 +470,11 @@ impl Target { pub fn doctested(&self) -> bool { self.doctest && match self.kind { TargetKind::Lib(ref kinds) => { - kinds.iter().find(|k| { - *k == &LibKind::Rlib || - *k == &LibKind::Lib || - *k == &LibKind::ProcMacro - }).is_some() + kinds.iter().any(|k| { + *k == LibKind::Rlib || + *k == LibKind::Lib || + *k == LibKind::ProcMacro + }) } _ => false, } diff --git a/src/cargo/core/package.rs b/src/cargo/core/package.rs index 9d16b1f28..afc047f88 100644 --- a/src/cargo/core/package.rs +++ b/src/cargo/core/package.rs @@ -53,7 +53,7 @@ impl ser::Serialize for Package { let description = manmeta.description.as_ref().map(String::as_ref); SerializedPackage { - name: &package_id.name(), + name: package_id.name(), version: &package_id.version().to_string(), id: package_id, license: license, @@ -61,7 +61,7 @@ impl ser::Serialize for Package { description: description, source: summary.source_id(), dependencies: summary.dependencies(), - targets: &self.manifest.targets(), + targets: self.manifest.targets(), features: summary.features(), manifest_path: &self.manifest_path.display().to_string(), }.serialize(s) @@ -80,8 +80,7 @@ impl Package { pub fn for_path(manifest_path: &Path, config: &Config) -> CargoResult { let path = manifest_path.parent().unwrap(); let source_id = SourceId::for_path(path)?; - let (pkg, _) = ops::read_package(&manifest_path, &source_id, - config)?; + let (pkg, _) = ops::read_package(manifest_path, &source_id, config)?; Ok(pkg) } diff --git a/src/cargo/core/package_id.rs b/src/cargo/core/package_id.rs index 321848c91..908798555 100644 --- a/src/cargo/core/package_id.rs +++ b/src/cargo/core/package_id.rs @@ -53,7 +53,7 @@ impl<'de> de::Deserialize<'de> for PackageId { Some(s) => s, None => return Err(de::Error::custom("invalid serialized PackageId")), }; - let url = if url.starts_with("(") && url.ends_with(")") { + let url = if url.starts_with('(') && url.ends_with(')') { &url[1..url.len() - 1] } else { return Err(de::Error::custom("invalid serialized PackageId")) @@ -134,7 +134,7 @@ impl PackageId { } pub fn stable_hash<'a>(&'a self, workspace: &'a Path) -> PackageIdStableHash<'a> { - PackageIdStableHash(&self, workspace) + PackageIdStableHash(self, workspace) } } diff --git a/src/cargo/core/package_id_spec.rs b/src/cargo/core/package_id_spec.rs index 3136e3fd6..d271f2f66 100644 --- a/src/cargo/core/package_id_spec.rs +++ b/src/cargo/core/package_id_spec.rs @@ -17,7 +17,7 @@ pub struct PackageIdSpec { impl PackageIdSpec { pub fn parse(spec: &str) -> CargoResult { - if spec.contains("/") { + if spec.contains('/') { if let Ok(url) = spec.to_url() { return PackageIdSpec::from_url(url); } @@ -117,9 +117,10 @@ impl PackageIdSpec { pub fn matches(&self, package_id: &PackageId) -> bool { if self.name() != package_id.name() { return false } - match self.version { - Some(ref v) => if v != package_id.version() { return false }, - None => {} + if let Some(ref v) = self.version { + if v != package_id.version() { + return false; + } } match self.url { @@ -148,20 +149,20 @@ impl PackageIdSpec { self.name(), self); let mut vec = vec![ret, other]; vec.extend(ids); - minimize(&mut msg, vec, self); + minimize(&mut msg, &vec, self); Err(msg.into()) } None => Ok(ret) }; fn minimize(msg: &mut String, - ids: Vec<&PackageId>, + ids: &[&PackageId], spec: &PackageIdSpec) { let mut version_cnt = HashMap::new(); - for id in ids.iter() { + for id in ids { *version_cnt.entry(id.version()).or_insert(0) += 1; } - for id in ids.iter() { + for id in ids { if version_cnt[id.version()] == 1 { msg.push_str(&format!("\n {}:{}", spec.name(), id.version())); @@ -184,18 +185,15 @@ impl fmt::Display for PackageIdSpec { } else { write!(f, "{}", url)?; } - if url.path_segments().unwrap().next_back().unwrap() != &self.name { + if url.path_segments().unwrap().next_back().unwrap() != self.name { printed_name = true; write!(f, "#{}", self.name)?; } } None => { printed_name = true; write!(f, "{}", self.name)? } } - match self.version { - Some(ref v) => { - write!(f, "{}{}", if printed_name {":"} else {"#"}, v)?; - } - None => {} + if let Some(ref v) = self.version { + write!(f, "{}{}", if printed_name {":"} else {"#"}, v)?; } Ok(()) } diff --git a/src/cargo/core/registry.rs b/src/cargo/core/registry.rs index 70efc66df..7052ba509 100644 --- a/src/cargo/core/registry.rs +++ b/src/cargo/core/registry.rs @@ -243,7 +243,7 @@ impl<'cfg> PackageRegistry<'cfg> { let src = self.sources.get_mut(s).unwrap(); let dep = Dependency::new_override(dep.name(), s); let mut results = src.query_vec(&dep)?; - if results.len() > 0 { + if !results.is_empty() { return Ok(Some(results.remove(0))) } } @@ -303,13 +303,12 @@ http://doc.crates.io/specifying-dependencies.html#overriding-dependencies return Ok(()) } - for id in real_deps { + if let Some(id) = real_deps.get(0) { let msg = format!("\ path override for crate `{}` has altered the original list of dependencies; the dependency on `{}` was removed\n\n {}", override_summary.package_id().name(), id.name(), boilerplate); self.source_config.config().shell().warn(&msg)?; - return Ok(()) } Ok(()) @@ -322,7 +321,7 @@ impl<'cfg> Registry for PackageRegistry<'cfg> { f: &mut FnMut(Summary)) -> CargoResult<()> { let (override_summary, n, to_warn) = { // Look for an override and get ready to query the real source. - let override_summary = self.query_overrides(&dep)?; + let override_summary = self.query_overrides(dep)?; // Next up on our list of candidates is to check the `[patch]` // section of the manifest. Here we look through all patches @@ -353,7 +352,7 @@ impl<'cfg> Registry for PackageRegistry<'cfg> { } } } else { - if patches.len() > 0 { + if !patches.is_empty() { debug!("found {} patches with an unlocked dep, \ looking at sources", patches.len()); } @@ -400,7 +399,7 @@ impl<'cfg> Registry for PackageRegistry<'cfg> { // to sanity check its results. We don't actually use any of // the summaries it gives us though. (Some(override_summary), Some(source)) => { - if patches.len() > 0 { + if !patches.is_empty() { bail!("found patches and a path override") } let mut n = 0; @@ -526,7 +525,7 @@ fn lock(locked: &LockedMap, } trace!("\tnope, unlocked"); - return dep + dep }) } diff --git a/src/cargo/core/resolver/encode.rs b/src/cargo/core/resolver/encode.rs index 4ca01c49a..344082bf6 100644 --- a/src/cargo/core/resolver/encode.rs +++ b/src/cargo/core/resolver/encode.rs @@ -34,7 +34,7 @@ impl EncodableResolve { let path_deps = build_path_deps(ws); let packages = { - let mut packages = self.package.unwrap_or(Vec::new()); + let mut packages = self.package.unwrap_or_default(); if let Some(root) = self.root { packages.insert(0, root); } @@ -57,7 +57,7 @@ impl EncodableResolve { return Err(internal(format!("package `{}` is specified twice in the lockfile", pkg.name))); } - let id = match pkg.source.as_ref().or(path_deps.get(&pkg.name)) { + let id = match pkg.source.as_ref().or_else(|| path_deps.get(&pkg.name)) { // We failed to find a local package in the workspace. // It must have been removed and should be ignored. None => continue, @@ -90,7 +90,7 @@ impl EncodableResolve { g.add(id.clone(), &[]); } - for &(ref id, ref pkg) in live_pkgs.values() { + for &(ref id, pkg) in live_pkgs.values() { let deps = match pkg.dependencies { Some(ref deps) => deps, None => continue @@ -107,7 +107,7 @@ impl EncodableResolve { let replacements = { let mut replacements = HashMap::new(); - for &(ref id, ref pkg) in live_pkgs.values() { + for &(ref id, pkg) in live_pkgs.values() { if let Some(ref replace) = pkg.replace { assert!(pkg.dependencies.is_none()); if let Some(replace_id) = lookup_id(replace)? { @@ -118,7 +118,7 @@ impl EncodableResolve { replacements }; - let mut metadata = self.metadata.unwrap_or(BTreeMap::new()); + let mut metadata = self.metadata.unwrap_or_default(); // Parse out all package checksums. After we do this we can be in a few // situations: @@ -163,7 +163,7 @@ impl EncodableResolve { let mut unused_patches = Vec::new(); for pkg in self.patch.unused { - let id = match pkg.source.as_ref().or(path_deps.get(&pkg.name)) { + let id = match pkg.source.as_ref().or_else(|| path_deps.get(&pkg.name)) { Some(src) => PackageId::new(&pkg.name, &pkg.version, src)?, None => continue, }; @@ -272,7 +272,7 @@ impl FromStr for EncodablePackageId { })?; let source_id = match s.next() { Some(s) => { - if s.starts_with("(") && s.ends_with(")") { + if s.starts_with('(') && s.ends_with(')') { Some(SourceId::from_url(&s[1..s.len() - 1])?) } else { bail!("invalid serialized PackageId") @@ -345,10 +345,10 @@ impl<'a, 'cfg> ser::Serialize for WorkspaceResolve<'a, 'cfg> { checksum.to_string()); } - let metadata = if metadata.len() == 0 {None} else {Some(metadata)}; + let metadata = if metadata.is_empty() { None } else { Some(metadata) }; let root = match root { - Some(root) if self.use_root_key => Some(encodable_resolve_node(&root, self.resolve)), + Some(root) if self.use_root_key => Some(encodable_resolve_node(root, self.resolve)), _ => None, }; diff --git a/src/cargo/core/resolver/mod.rs b/src/cargo/core/resolver/mod.rs index a2f4e1139..573a6be1c 100644 --- a/src/cargo/core/resolver/mod.rs +++ b/src/cargo/core/resolver/mod.rs @@ -119,23 +119,18 @@ impl Resolve { pub fn path_to_top(&self, pkg: &PackageId) -> Vec<&PackageId> { let mut result = Vec::new(); let mut pkg = pkg; - loop { - match self.graph - .get_nodes() - .iter() - .filter_map(|(pulling, pulled)| - if pulled.contains(pkg) { - Some(pulling) - } else { - None - }) - .nth(0) { - Some(pulling) => { - result.push(pulling); - pkg = pulling; - }, - None => break - } + while let Some(pulling) = self.graph + .get_nodes() + .iter() + .filter_map(|(pulling, pulled)| + if pulled.contains(pkg) { + Some(pulling) + } else { + None + }) + .nth(0) { + result.push(pulling); + pkg = pulling; } result } @@ -376,7 +371,7 @@ pub fn resolve(summaries: &[(Summary, Method)], replacements: replacements, warnings: RcList::new(), }; - let _p = profile::start(format!("resolving")); + let _p = profile::start("resolving"); let cx = activate_deps_loop(cx, registry, summaries)?; let mut resolve = Resolve { @@ -483,7 +478,7 @@ impl RcVecIter { impl Clone for RcVecIter { fn clone(&self) -> RcVecIter { RcVecIter { - vec: self.vec.clone(), + vec: Rc::clone(&self.vec), rest: self.rest.clone(), } } @@ -569,12 +564,12 @@ impl RemainingCandidates { // define "compatible" here in terms of the semver sense where if // the left-most nonzero digit is the same they're considered // compatible. - self.remaining.by_ref().map(|p| p.1).filter(|b| { + self.remaining.by_ref().map(|p| p.1).find(|b| { prev_active.iter().any(|a| *a == b.summary) || prev_active.iter().all(|a| { !compatible(a.version(), b.summary.version()) }) - }).next() + }) } } @@ -686,7 +681,7 @@ fn activate_deps_loop<'a>(mut cx: Context<'a>, &mut features) { None => return Err(activation_error(&cx, registry, &parent, &dep, - &cx.prev_active(&dep), + cx.prev_active(&dep), &candidates)), Some(candidate) => candidate, } @@ -729,7 +724,7 @@ fn find_candidate<'a>(backtrack_stack: &mut Vec>, *remaining_deps = frame.deps_backup.clone(); *parent = frame.parent.clone(); *dep = frame.dep.clone(); - *features = frame.features.clone(); + *features = Rc::clone(&frame.features); backtrack_stack.push(frame); } else { *cx = frame.context_backup; @@ -751,7 +746,7 @@ fn activation_error(cx: &Context, dep: &Dependency, prev_active: &[Summary], candidates: &[Candidate]) -> CargoError { - if candidates.len() > 0 { + if !candidates.is_empty() { let mut msg = format!("failed to select a version for `{}` \ (required by `{}`):\n\ all possible versions conflict with \ @@ -832,7 +827,7 @@ fn activation_error(cx: &Context, // indicate that we updated a sub-package and forgot to run `cargo // update`. In this case try to print a helpful error! if dep.source_id().is_path() - && dep.version_req().to_string().starts_with("=") { + && dep.version_req().to_string().starts_with('=') { msg.push_str("\nconsider running `cargo update` to update \ a path dependency's locked version"); } @@ -1062,7 +1057,7 @@ impl<'a> Context<'a> { spec, dep.source_id(), dep.version_req()) })?; let summaries = summaries.collect::>(); - if summaries.len() > 0 { + if !summaries.is_empty() { let bullets = summaries.iter().map(|s| { format!(" * {}", s.package_id()) }).collect::>(); @@ -1188,7 +1183,7 @@ impl<'a> Context<'a> { replacements.insert(k, v); cur = &node.1; } - return replacements + replacements } fn graph(&self) -> Graph { @@ -1201,7 +1196,7 @@ impl<'a> Context<'a> { } cur = &node.1; } - return graph + graph } } diff --git a/src/cargo/core/source.rs b/src/cargo/core/source.rs index 5d1347238..b9218bd5a 100644 --- a/src/cargo/core/source.rs +++ b/src/cargo/core/source.rs @@ -499,6 +499,7 @@ impl<'a> fmt::Display for PrettyRef<'a> { } } +#[derive(Default)] pub struct SourceMap<'src> { map: HashMap>, } diff --git a/src/cargo/core/workspace.rs b/src/cargo/core/workspace.rs index 87c0ec1be..48d379343 100644 --- a/src/cargo/core/workspace.rs +++ b/src/cargo/core/workspace.rs @@ -163,7 +163,7 @@ impl<'cfg> Workspace<'cfg> { }; ws.members.push(ws.current_manifest.clone()); } - return Ok(ws) + Ok(ws) } /// Returns the current package of this workspace. @@ -283,11 +283,11 @@ impl<'cfg> Workspace<'cfg> { .join(root_link) .join("Cargo.toml"); debug!("find_root - pointer {}", path.display()); - return Ok(paths::normalize_path(&path)) + Ok(paths::normalize_path(&path)) }; { - let current = self.packages.load(&manifest_path)?; + let current = self.packages.load(manifest_path)?; match *current.workspace_config() { WorkspaceConfig::Root { .. } => { debug!("find_root - is root {}", manifest_path.display()); @@ -392,13 +392,10 @@ impl<'cfg> Workspace<'cfg> { } let root = root_manifest.parent().unwrap(); - match *self.packages.load(root_manifest)?.workspace_config() { - WorkspaceConfig::Root { ref members, ref exclude } => { - if is_excluded(members, exclude, root, &manifest_path) { - return Ok(()) - } + if let WorkspaceConfig::Root { ref members, ref exclude } = *self.packages.load(root_manifest)?.workspace_config() { + if is_excluded(members, exclude, root, &manifest_path) { + return Ok(()) } - _ => {} } debug!("find_members - {}", manifest_path.display()); @@ -624,7 +621,7 @@ impl<'cfg> Packages<'cfg> { Entry::Vacant(v) => { let source_id = SourceId::for_path(key)?; let (manifest, _nested_paths) = - read_manifest(&manifest_path, &source_id, self.config)?; + read_manifest(manifest_path, &source_id, self.config)?; Ok(v.insert(match manifest { EitherManifest::Real(manifest) => { MaybePackage::Package(Package::new(manifest, diff --git a/src/cargo/ops/cargo_clean.rs b/src/cargo/ops/cargo_clean.rs index 19f518f80..9b266b0bb 100644 --- a/src/cargo/ops/cargo_clean.rs +++ b/src/cargo/ops/cargo_clean.rs @@ -34,7 +34,7 @@ pub fn clean(ws: &Workspace, opts: &CleanOptions) -> CargoResult<()> { let host_triple = opts.config.rustc()?.host.clone(); let mut cx = Context::new(ws, &resolve, &packages, opts.config, BuildConfig { - host_triple: host_triple, + host_triple, requested_target: opts.target.map(|s| s.to_owned()), release: opts.release, jobs: 1, @@ -46,7 +46,7 @@ pub fn clean(ws: &Workspace, opts: &CleanOptions) -> CargoResult<()> { for spec in opts.spec { // Translate the spec to a Package let pkgid = resolve.query(spec)?; - let pkg = packages.get(&pkgid)?; + let pkg = packages.get(pkgid)?; // Generate all relevant `Unit` targets for this package for target in pkg.targets() { @@ -60,9 +60,9 @@ pub fn clean(ws: &Workspace, opts: &CleanOptions) -> CargoResult<()> { test_deps, bench_deps, check, doctest]; for profile in profiles.iter() { units.push(Unit { - pkg: &pkg, - target: target, - profile: profile, + pkg, + target, + profile, kind: *kind, }); } diff --git a/src/cargo/ops/cargo_compile.rs b/src/cargo/ops/cargo_compile.rs index a8e9ce704..685911203 100644 --- a/src/cargo/ops/cargo_compile.rs +++ b/src/cargo/ops/cargo_compile.rs @@ -112,7 +112,7 @@ pub enum Packages<'a> { } impl<'a> Packages<'a> { - pub fn from_flags(virtual_ws: bool, all: bool, exclude: &'a Vec, package: &'a Vec) + pub fn from_flags(virtual_ws: bool, all: bool, exclude: &'a [String], package: &'a [String]) -> CargoResult { let all = all || (virtual_ws && package.is_empty()); @@ -150,7 +150,7 @@ impl<'a> Packages<'a> { .into_iter().collect() } Packages::Packages(packages) => { - packages.iter().map(|p| PackageIdSpec::parse(&p)).collect::>>()? + packages.iter().map(|p| PackageIdSpec::parse(p)).collect::>>()? } }; Ok(specs) @@ -320,7 +320,7 @@ pub fn compile_ws<'a>(ws: &Workspace<'a>, exec)? }; - ret.to_doc_test = to_builds.iter().map(|&p| p.clone()).collect(); + ret.to_doc_test = to_builds.into_iter().cloned().collect(); return Ok(ret); @@ -370,7 +370,7 @@ impl<'a> FilterRule<'a> { pub fn try_collect(&self) -> Option> { match *self { FilterRule::All => None, - FilterRule::Just(targets) => Some(targets.iter().map(|t| t.clone()).collect()), + FilterRule::Just(targets) => Some(targets.to_vec()), } } } @@ -527,7 +527,7 @@ fn propose_indicated_targets<'a>(pkg: &'a Package, required: false, } }); - return Ok(result.collect()); + Ok(result.collect()) } FilterRule::Just(names) => { let mut targets = Vec::new(); @@ -556,7 +556,7 @@ fn propose_indicated_targets<'a>(pkg: &'a Package, required: true, }); } - return Ok(targets); + Ok(targets) } } } @@ -669,7 +669,7 @@ fn scrape_build_config(config: &Config, if v.val <= 0 { bail!("build.jobs must be positive, but found {} in {}", v.val, v.definition) - } else if v.val >= u32::max_value() as i64 { + } else if v.val >= i64::from(u32::max_value()) { bail!("build.jobs is too large: found {} in {}", v.val, v.definition) } else { @@ -689,7 +689,7 @@ fn scrape_build_config(config: &Config, }; base.host = scrape_target_config(config, &base.host_triple)?; base.target = match target.as_ref() { - Some(triple) => scrape_target_config(config, &triple)?, + Some(triple) => scrape_target_config(config, triple)?, None => base.host.clone(), }; Ok(base) @@ -736,32 +736,32 @@ fn scrape_target_config(config: &Config, triple: &str) let key = format!("{}.{}", key, k); match &k[..] { "rustc-flags" => { - let (flags, definition) = value.string(&k)?; + let (flags, definition) = value.string(k)?; let whence = format!("in `{}` (in {})", key, definition.display()); let (paths, links) = - BuildOutput::parse_rustc_flags(&flags, &whence) + BuildOutput::parse_rustc_flags(flags, &whence) ?; output.library_paths.extend(paths); output.library_links.extend(links); } "rustc-link-lib" => { - let list = value.list(&k)?; + let list = value.list(k)?; output.library_links.extend(list.iter() .map(|v| v.0.clone())); } "rustc-link-search" => { - let list = value.list(&k)?; + let list = value.list(k)?; output.library_paths.extend(list.iter().map(|v| { PathBuf::from(&v.0) })); } "rustc-cfg" => { - let list = value.list(&k)?; + let list = value.list(k)?; output.cfgs.extend(list.iter().map(|v| v.0.clone())); } "rustc-env" => { - for (name, val) in value.table(&k)?.0 { + for (name, val) in value.table(k)?.0 { let val = val.string(name)?.0; output.env.push((name.clone(), val.to_string())); } @@ -772,7 +772,7 @@ fn scrape_target_config(config: &Config, triple: &str) bail!("`{}` is not supported in build script overrides", k); } _ => { - let val = value.string(&k)?.0; + let val = value.string(k)?.0; output.metadata.push((k.clone(), val.to_string())); } } diff --git a/src/cargo/ops/cargo_generate_lockfile.rs b/src/cargo/ops/cargo_generate_lockfile.rs index 29c3749c6..7be8ae05a 100644 --- a/src/cargo/ops/cargo_generate_lockfile.rs +++ b/src/cargo/ops/cargo_generate_lockfile.rs @@ -105,7 +105,7 @@ pub fn update_lockfile(ws: &Workspace, opts: &UpdateOptions) } } - ops::write_pkg_lockfile(&ws, &resolve)?; + ops::write_pkg_lockfile(ws, &resolve)?; return Ok(()); fn fill_with_deps<'a>(resolve: &'a Resolve, dep: &'a PackageId, @@ -162,13 +162,13 @@ pub fn update_lockfile(ws: &Workspace, opts: &UpdateOptions) let mut changes = BTreeMap::new(); let empty = (Vec::new(), Vec::new()); for dep in previous_resolve.iter() { - changes.entry(key(dep)).or_insert(empty.clone()).0.push(dep); + changes.entry(key(dep)).or_insert_with(|| empty.clone()).0.push(dep); } for dep in resolve.iter() { - changes.entry(key(dep)).or_insert(empty.clone()).1.push(dep); + changes.entry(key(dep)).or_insert_with(|| empty.clone()).1.push(dep); } - for (_, v) in changes.iter_mut() { + for v in changes.values_mut() { let (ref mut old, ref mut new) = *v; old.sort(); new.sort(); diff --git a/src/cargo/ops/cargo_install.rs b/src/cargo/ops/cargo_install.rs index b6b87a82b..beb934210 100644 --- a/src/cargo/ops/cargo_install.rs +++ b/src/cargo/ops/cargo_install.rs @@ -1,7 +1,6 @@ use std::collections::btree_map::Entry; use std::collections::{BTreeMap, BTreeSet}; use std::env; -use std::ffi::OsString; use std::fs::{self, File}; use std::io::prelude::*; use std::io::SeekFrom; @@ -64,7 +63,7 @@ pub fn install(root: Option<&str>, let map = SourceConfigMap::new(opts.config)?; let (installed_anything, scheduled_error) = if krates.len() <= 1 { - install_one(root.clone(), map, krates.into_iter().next(), source_id, vers, opts, + install_one(&root, &map, krates.into_iter().next(), source_id, vers, opts, force, true)?; (true, false) } else { @@ -74,7 +73,8 @@ pub fn install(root: Option<&str>, for krate in krates { let root = root.clone(); let map = map.clone(); - match install_one(root, map, Some(krate), source_id, vers, opts, force, first) { + match install_one(&root, &map, Some(krate), source_id, vers, + opts, force, first) { Ok(()) => succeeded.push(krate), Err(e) => { ::handle_error(e, &mut opts.config.shell()); @@ -102,7 +102,7 @@ pub fn install(root: Option<&str>, // Print a warning that if this directory isn't in PATH that they won't be // able to run these commands. let dst = metadata(opts.config, &root)?.parent().join("bin"); - let path = env::var_os("PATH").unwrap_or(OsString::new()); + let path = env::var_os("PATH").unwrap_or_default(); for path in env::split_paths(&path) { if path == dst { return Ok(()) @@ -121,8 +121,8 @@ pub fn install(root: Option<&str>, Ok(()) } -fn install_one(root: Filesystem, - map: SourceConfigMap, +fn install_one(root: &Filesystem, + map: &SourceConfigMap, krate: Option<&str>, source_id: &SourceId, vers: Option<&str>, @@ -179,7 +179,7 @@ fn install_one(root: Filesystem, // We have to check this again afterwards, but may as well avoid building // anything if we're gonna throw it away anyway. { - let metadata = metadata(config, &root)?; + let metadata = metadata(config, root)?; let list = read_crate_list(metadata.file())?; let dst = metadata.parent().join("bin"); check_overwrites(&dst, pkg, &opts.filter, &list, force)?; @@ -210,7 +210,7 @@ fn install_one(root: Filesystem, features"); } - let metadata = metadata(config, &root)?; + let metadata = metadata(config, root)?; let mut list = read_crate_list(metadata.file())?; let dst = metadata.parent().join("bin"); let duplicates = check_overwrites(&dst, pkg, &opts.filter, @@ -225,10 +225,8 @@ fn install_one(root: Filesystem, for &(bin, src) in binaries.iter() { let dst = staging_dir.path().join(bin); // Try to move if `target_dir` is transient. - if !source_id.is_path() { - if fs::rename(src, &dst).is_ok() { - continue - } + if !source_id.is_path() && fs::rename(src, &dst).is_ok() { + continue } fs::copy(src, &dst).chain_err(|| { format!("failed to copy `{}` to `{}`", src.display(), @@ -392,7 +390,7 @@ fn select_pkg<'a, T>(mut source: T, } None => { let vers_info = vers.map(|v| format!(" with version `{}`", v)) - .unwrap_or(String::new()); + .unwrap_or_default(); Err(format!("could not find `{}` in `{}`{}", name, source.source_id(), vers_info).into()) } @@ -448,13 +446,11 @@ fn check_overwrites(dst: &Path, filter: &ops::CompileFilter, prev: &CrateListingV1, force: bool) -> CargoResult>> { - if !filter.is_specific() { - // If explicit --bin or --example flags were passed then those'll - // get checked during cargo_compile, we only care about the "build - // everything" case here - if pkg.targets().iter().filter(|t| t.is_bin()).next().is_none() { - bail!("specified package has no binaries") - } + // If explicit --bin or --example flags were passed then those'll + // get checked during cargo_compile, we only care about the "build + // everything" case here + if !filter.is_specific() && !pkg.targets().iter().any(|t| t.is_bin()) { + bail!("specified package has no binaries") } let duplicates = find_duplicates(dst, pkg, filter, prev); if force || duplicates.is_empty() { @@ -462,7 +458,7 @@ fn check_overwrites(dst: &Path, } // Format the error message. let mut msg = String::new(); - for (ref bin, p) in duplicates.iter() { + for (bin, p) in duplicates.iter() { msg.push_str(&format!("binary `{}` already exists in destination", bin)); if let Some(p) = p.as_ref() { msg.push_str(&format!(" as part of `{}`\n", p)); diff --git a/src/cargo/ops/cargo_new.rs b/src/cargo/ops/cargo_new.rs index 4ece45cc2..b7b30f7e2 100644 --- a/src/cargo/ops/cargo_new.rs +++ b/src/cargo/ops/cargo_new.rs @@ -175,12 +175,12 @@ fn detect_source_paths_and_types(project_path : &Path, } let tests = vec![ - Test { proposed_path: format!("src/main.rs"), handling: H::Bin }, - Test { proposed_path: format!("main.rs"), handling: H::Bin }, + Test { proposed_path: String::from("src/main.rs"), handling: H::Bin }, + Test { proposed_path: String::from("main.rs"), handling: H::Bin }, Test { proposed_path: format!("src/{}.rs", name), handling: H::Detect }, - Test { proposed_path: format!("{}.rs", name), handling: H::Detect }, - Test { proposed_path: format!("src/lib.rs"), handling: H::Lib }, - Test { proposed_path: format!("lib.rs"), handling: H::Lib }, + Test { proposed_path: format!("{}.rs", name), handling: H::Detect }, + Test { proposed_path: String::from("src/lib.rs"), handling: H::Lib }, + Test { proposed_path: String::from("lib.rs"), handling: H::Lib }, ]; for i in tests { @@ -265,7 +265,7 @@ fn plan_new_source_file(bin: bool, project_name: String) -> SourceFileInformatio } } -pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> { +pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> { let path = config.cwd().join(opts.path); if fs::metadata(&path).is_ok() { bail!("destination `{}` already exists\n\n\ @@ -278,7 +278,7 @@ pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> { bail!("can't specify both lib and binary outputs") } - let name = get_name(&path, &opts, config)?; + let name = get_name(&path, opts, config)?; check_name(name, opts.bin)?; let mkopts = MkOptions { @@ -295,7 +295,7 @@ pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> { }) } -pub fn init(opts: NewOptions, config: &Config) -> CargoResult<()> { +pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<()> { let path = config.cwd().join(opts.path); let cargotoml_path = path.join("Cargo.toml"); @@ -307,14 +307,14 @@ pub fn init(opts: NewOptions, config: &Config) -> CargoResult<()> { bail!("can't specify both lib and binary outputs"); } - let name = get_name(&path, &opts, config)?; + let name = get_name(&path, opts, config)?; check_name(name, opts.bin)?; let mut src_paths_types = vec![]; detect_source_paths_and_types(&path, name, &mut src_paths_types)?; - if src_paths_types.len() == 0 { + if src_paths_types.is_empty() { src_paths_types.push(plan_new_source_file(opts.bin, name.to_string())); } else { // --bin option may be ignored if lib.rs or src/lib.rs present @@ -406,8 +406,7 @@ fn mk(config: &Config, opts: &MkOptions) -> CargoResult<()> { let in_existing_vcs_repo = existing_vcs_repo(path.parent().unwrap_or(path), config.cwd()); let vcs = match (opts.version_control, cfg.version_control, in_existing_vcs_repo) { (None, None, false) => VersionControl::Git, - (None, Some(option), false) => option, - (Some(option), _, _) => option, + (None, Some(option), false) | (Some(option), _, _) => option, (_, _, true) => VersionControl::NoVcs, }; match vcs { @@ -462,14 +461,12 @@ name = "{}" path = {} "#, i.target_name, toml::Value::String(i.relative_path.clone()))); } - } else { - if i.relative_path != "src/lib.rs" { - cargotoml_path_specifier.push_str(&format!(r#" + } else if i.relative_path != "src/lib.rs" { + cargotoml_path_specifier.push_str(&format!(r#" [lib] name = "{}" path = {} "#, i.target_name, toml::Value::String(i.relative_path.clone()))); - } } } diff --git a/src/cargo/ops/cargo_package.rs b/src/cargo/ops/cargo_package.rs index 9050beece..f12ce12f3 100644 --- a/src/cargo/ops/cargo_package.rs +++ b/src/cargo/ops/cargo_package.rs @@ -29,7 +29,7 @@ pub fn package(ws: &Workspace, opts: &PackageOpts) -> CargoResult> { let pkg = ws.current()?; let config = ws.config(); - if pkg.manifest().features().activated().len() > 0 { + if !pkg.manifest().features().activated().is_empty() { bail!("cannot package or publish crates which activate nightly-only \ cargo features") } @@ -42,12 +42,12 @@ pub fn package(ws: &Workspace, check_metadata(pkg, config)?; } - verify_dependencies(&pkg)?; + verify_dependencies(pkg)?; if opts.list { let root = pkg.root(); - let mut list: Vec<_> = src.list_files(&pkg)?.iter().map(|file| { - util::without_prefix(&file, &root).unwrap().to_path_buf() + let mut list: Vec<_> = src.list_files(pkg)?.iter().map(|file| { + util::without_prefix(file, root).unwrap().to_path_buf() }).collect(); list.sort(); for file in list.iter() { @@ -57,7 +57,7 @@ pub fn package(ws: &Workspace, } if !opts.allow_dirty { - check_not_dirty(&pkg, &src)?; + check_not_dirty(pkg, &src)?; } let filename = format!("{}-{}.crate", pkg.name(), pkg.version()); @@ -118,7 +118,7 @@ fn check_metadata(pkg: &Package, config: &Config) -> CargoResult<()> { if !things.is_empty() { things.push_str(" or "); } - things.push_str(&missing.last().unwrap()); + things.push_str(missing.last().unwrap()); config.shell().warn( &format!("manifest has no {things}.\n\ @@ -131,12 +131,10 @@ fn check_metadata(pkg: &Package, config: &Config) -> CargoResult<()> { // check that the package dependencies are safe to deploy. fn verify_dependencies(pkg: &Package) -> CargoResult<()> { for dep in pkg.dependencies() { - if dep.source_id().is_path() { - if !dep.specified_req() { - bail!("all path dependencies must have a version specified \ - when packaging.\ndependency `{}` does not specify \ - a version.", dep.name()) - } + if dep.source_id().is_path() && !dep.specified_req() { + bail!("all path dependencies must have a version specified \ + when packaging.\ndependency `{}` does not specify \ + a version.", dep.name()) } } Ok(()) @@ -202,7 +200,7 @@ fn tar(ws: &Workspace, let config = ws.config(); let root = pkg.root(); for file in src.list_files(pkg)?.iter() { - let relative = util::without_prefix(&file, &root).unwrap(); + let relative = util::without_prefix(file, root).unwrap(); check_filename(relative)?; let relative = relative.to_str().ok_or_else(|| { format!("non-utf8 path in source directory: {}", @@ -334,7 +332,7 @@ fn check_filename(file: &Path) -> CargoResult<()> { } }; let bad_chars = ['/', '\\', '<', '>', ':', '"', '|', '?', '*']; - for c in bad_chars.iter().filter(|c| name.contains(**c)) { + if let Some(c) = bad_chars.iter().find(|c| name.contains(**c)) { bail!("cannot package a filename with a special character `{}`: {}", c, file.display()) } diff --git a/src/cargo/ops/cargo_read_manifest.rs b/src/cargo/ops/cargo_read_manifest.rs index 3cc736a2d..dc8b74786 100644 --- a/src/cargo/ops/cargo_read_manifest.rs +++ b/src/cargo/ops/cargo_read_manifest.rs @@ -1,4 +1,5 @@ use std::collections::{HashMap, HashSet}; +use std::collections::hash_map::Entry; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -38,7 +39,7 @@ pub fn read_packages(path: &Path, source_id: &SourceId, config: &Config) // Don't recurse into hidden/dot directories unless we're at the toplevel if dir != path { let name = dir.file_name().and_then(|s| s.to_str()); - if name.map(|s| s.starts_with(".")) == Some(true) { + if name.map(|s| s.starts_with('.')) == Some(true) { return Ok(false) } @@ -137,12 +138,10 @@ fn read_nested_packages(path: &Path, }; let pkg = Package::new(manifest, &manifest_path); - let pkg_id = pkg.package_id().clone(); - if !all_packages.contains_key(&pkg_id) { - all_packages.insert(pkg_id, pkg); - } else { - info!("skipping nested package `{}` found at `{}`", - pkg.name(), path.to_string_lossy()); + match all_packages.entry(pkg.package_id().clone()) { + Entry::Occupied(_) => { info!("skipping nested package `{}` found at `{}`", + pkg.name(), path.to_string_lossy()); }, + Entry::Vacant(e) => { e.insert(pkg); } } // Registry sources are not allowed to have `path=` dependencies because diff --git a/src/cargo/ops/cargo_run.rs b/src/cargo/ops/cargo_run.rs index ab7698577..3a4e7f6f2 100644 --- a/src/cargo/ops/cargo_run.rs +++ b/src/cargo/ops/cargo_run.rs @@ -53,13 +53,13 @@ pub fn run(ws: &Workspace, let compile = ops::compile(ws, options)?; assert_eq!(compile.binaries.len(), 1); let exe = &compile.binaries[0]; - let exe = match util::without_prefix(&exe, config.cwd()) { + let exe = match util::without_prefix(exe, config.cwd()) { Some(path) if path.file_name() == Some(path.as_os_str()) => Path::new(".").join(path).to_path_buf(), Some(path) => path.to_path_buf(), None => exe.to_path_buf(), }; - let mut process = compile.target_process(exe, &pkg)?; + let mut process = compile.target_process(exe, pkg)?; process.args(args).cwd(config.cwd()); config.shell().status("Running", process.to_string())?; diff --git a/src/cargo/ops/cargo_rustc/compilation.rs b/src/cargo/ops/cargo_rustc/compilation.rs index c853290c7..b3643b6bf 100644 --- a/src/cargo/ops/cargo_rustc/compilation.rs +++ b/src/cargo/ops/cargo_rustc/compilation.rs @@ -104,7 +104,7 @@ impl<'cfg> Compilation<'cfg> { /// See `process`. pub fn target_process>(&self, cmd: T, pkg: &Package) -> CargoResult { - let builder = if let &Some((ref runner, ref args)) = self.target_runner()? { + let builder = if let Some((ref runner, ref args)) = *self.target_runner()? { let mut builder = process(runner); builder.args(args); builder.arg(cmd); diff --git a/src/cargo/ops/cargo_rustc/context.rs b/src/cargo/ops/cargo_rustc/context.rs index cec2e39b0..219d16846 100755 --- a/src/cargo/ops/cargo_rustc/context.rs +++ b/src/cargo/ops/cargo_rustc/context.rs @@ -97,9 +97,9 @@ impl<'a, 'cfg> Context<'a, 'cfg> { profiles: &'a Profiles) -> CargoResult> { let dest = if build_config.release { "release" } else { "debug" }; - let host_layout = Layout::new(ws, None, &dest)?; + let host_layout = Layout::new(ws, None, dest)?; let target_layout = match build_config.requested_target.as_ref() { - Some(target) => Some(Layout::new(ws, Some(&target), dest)?), + Some(target) => Some(Layout::new(ws, Some(target), dest)?), None => None, }; @@ -171,15 +171,12 @@ impl<'a, 'cfg> Context<'a, 'cfg> { let _p = profile::start("preparing layout"); self.host.prepare().chain_err(|| { - internal(format!("couldn't prepare build directories")) + internal("couldn't prepare build directories") })?; - match self.target { - Some(ref mut target) => { - target.prepare().chain_err(|| { - internal(format!("couldn't prepare build directories")) - })?; - } - None => {} + if let Some(ref mut target) = self.target { + target.prepare().chain_err(|| { + internal("couldn't prepare build directories") + })?; } self.compilation.host_deps_output = self.host.deps().to_path_buf(); @@ -230,7 +227,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { } })); } - for dep in self.dep_targets(&unit)? { + for dep in self.dep_targets(unit)? { self.visit_crate_type(&dep, crate_types, visited_units)?; } Ok(()) @@ -242,7 +239,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { -> CargoResult<()> { let rustflags = env_args(self.config, &self.build_config, - &self.info(&kind), + self.info(&kind), kind, "RUSTFLAGS")?; let mut process = self.config.rustc()?.process(); @@ -271,8 +268,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { has_cfg_and_sysroot = false; process.exec_with_output() }).chain_err(|| { - format!("failed to run `rustc` to learn about \ - target-specific information") + "failed to run `rustc` to learn about target-specific information" })?; let error = str::from_utf8(&output.stderr).unwrap(); @@ -433,7 +429,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { /// Return the target triple which this context is targeting. pub fn target_triple(&self) -> &str { - self.requested_target().unwrap_or(self.host_triple()) + self.requested_target().unwrap_or_else(|| self.host_triple()) } /// Requested (not actual) target for the build @@ -529,7 +525,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { unit.target.name().hash(&mut hasher); unit.target.kind().hash(&mut hasher); - if let Ok(ref rustc) = self.config.rustc() { + if let Ok(rustc) = self.config.rustc() { rustc.verbose_version.hash(&mut hasher); } @@ -589,9 +585,8 @@ impl<'a, 'cfg> Context<'a, 'cfg> { } } else if bin_stem == file_stem { None - } else if src_dir.ends_with("examples") { - Some((src_dir, bin_stem)) - } else if src_dir.parent().unwrap().ends_with("build") { + } else if src_dir.ends_with("examples") + || src_dir.parent().unwrap().ends_with("build") { Some((src_dir, bin_stem)) } else { None @@ -606,12 +601,12 @@ impl<'a, 'cfg> Context<'a, 'cfg> { pub fn target_filenames(&mut self, unit: &Unit<'a>) -> CargoResult, bool)>>> { if let Some(cache) = self.target_filenames.get(unit) { - return Ok(cache.clone()) + return Ok(Arc::clone(cache)) } let result = self.calc_target_filenames(unit); if let Ok(ref ret) = result { - self.target_filenames.insert(*unit, ret.clone()); + self.target_filenames.insert(*unit, Arc::clone(ret)); } result } @@ -644,7 +639,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { let crate_type_info = match entry { Entry::Occupied(o) => &*o.into_mut(), Entry::Vacant(v) => { - let value = info.discover_crate_type(&v.key())?; + let value = info.discover_crate_type(v.key())?; &*v.insert(value) } }; @@ -688,7 +683,7 @@ impl<'a, 'cfg> Context<'a, 'cfg> { } } if ret.is_empty() { - if unsupported.len() > 0 { + if !unsupported.is_empty() { bail!("cannot produce {} for `{}` as the target `{}` \ does not support these crate types", unsupported.join(", "), unit.pkg, self.target_triple()) @@ -1010,14 +1005,12 @@ impl<'a, 'cfg> Context<'a, 'cfg> { // (see also https://github.com/rust-lang/cargo/issues/3972) return Ok(vec![format!("-Zincremental={}", self.layout(unit.kind).incremental().display())]); - } else { - if unit.profile.codegen_units.is_none() { - // For non-incremental builds we set a higher number of - // codegen units so we get faster compiles. It's OK to do - // so because the user has already opted into slower - // runtime code by setting CARGO_INCREMENTAL. - return Ok(vec![format!("-Ccodegen-units={}", ::num_cpus::get())]); - } + } else if unit.profile.codegen_units.is_none() { + // For non-incremental builds we set a higher number of + // codegen units so we get faster compiles. It's OK to do + // so because the user has already opted into slower + // runtime code by setting CARGO_INCREMENTAL. + return Ok(vec![format!("-Ccodegen-units={}", ::num_cpus::get())]); } } @@ -1081,8 +1074,8 @@ fn env_args(config: &Config, } // First try RUSTFLAGS from the environment - if let Some(a) = env::var(name).ok() { - let args = a.split(" ") + if let Ok(a) = env::var(name) { + let args = a.split(' ') .map(str::trim) .filter(|s| !s.is_empty()) .map(str::to_string); @@ -1103,7 +1096,7 @@ fn env_args(config: &Config, if let Some(ref target_cfg) = target_info.cfg { if let Some(table) = config.get_table("target")? { let cfgs = table.val.keys().filter_map(|t| { - if t.starts_with("cfg(") && t.ends_with(")") { + if t.starts_with("cfg(") && t.ends_with(')') { let cfg = &t[4..t.len() - 1]; CfgExpr::from_str(cfg) .ok() diff --git a/src/cargo/ops/cargo_rustc/custom_build.rs b/src/cargo/ops/cargo_rustc/custom_build.rs index 267021ebe..fee750c4c 100644 --- a/src/cargo/ops/cargo_rustc/custom_build.rs +++ b/src/cargo/ops/cargo_rustc/custom_build.rs @@ -143,9 +143,9 @@ fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) match *cfg { Cfg::Name(ref n) => { cfg_map.insert(n.clone(), None); } Cfg::KeyPair(ref k, ref v) => { - match *cfg_map.entry(k.clone()).or_insert(Some(Vec::new())) { - Some(ref mut values) => values.push(v.clone()), - None => { /* ... */ } + if let Some(ref mut values) = *cfg_map.entry(k.clone()) + .or_insert_with(|| Some(Vec::new())) { + values.push(v.clone()) } } } @@ -174,7 +174,7 @@ fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) }).collect::>() }; let pkg_name = unit.pkg.to_string(); - let build_state = cx.build_state.clone(); + let build_state = Arc::clone(&cx.build_state); let id = unit.pkg.package_id().clone(); let (output_file, err_file) = { let build_output_parent = build_output.parent().unwrap(); @@ -182,7 +182,7 @@ fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) let err_file = build_output_parent.join("stderr"); (output_file, err_file) }; - let all = (id.clone(), pkg_name.clone(), build_state.clone(), + let all = (id.clone(), pkg_name.clone(), Arc::clone(&build_state), output_file.clone()); let build_scripts = super::load_build_deps(cx, unit); let kind = unit.kind; @@ -398,11 +398,7 @@ impl BuildOutput { let mut flags_iter = value.split(|c: char| c.is_whitespace()) .filter(|w| w.chars().any(|c| !c.is_whitespace())); let (mut library_paths, mut library_links) = (Vec::new(), Vec::new()); - loop { - let flag = match flags_iter.next() { - Some(f) => f, - None => break - }; + while let Some(flag) = flags_iter.next() { if flag != "-l" && flag != "-L" { bail!("Only `-l` and `-L` flags are allowed in {}: `{}`", whence, value) diff --git a/src/cargo/ops/cargo_rustc/fingerprint.rs b/src/cargo/ops/cargo_rustc/fingerprint.rs index e4d2dd124..fdd37f05f 100644 --- a/src/cargo/ops/cargo_rustc/fingerprint.rs +++ b/src/cargo/ops/cargo_rustc/fingerprint.rs @@ -144,7 +144,7 @@ pub struct Fingerprint { rustflags: Vec, } -fn serialize_deps(deps: &Vec<(String, Arc)>, ser: S) +fn serialize_deps(deps: &[(String, Arc)], ser: S) -> Result where S: ser::Serializer, { @@ -287,16 +287,8 @@ impl Fingerprint { impl hash::Hash for Fingerprint { fn hash(&self, h: &mut H) { - let Fingerprint { - rustc, - ref features, - target, - profile, - ref deps, - ref local, - memoized_hash: _, - ref rustflags, - } = *self; + let Fingerprint { rustc, ref features, target, profile, ref deps, + ref local, ref rustflags, .. } = *self; (rustc, features, target, profile, local, rustflags).hash(h); h.write_usize(deps.len()); @@ -350,7 +342,7 @@ impl<'de> de::Deserialize<'de> for MtimeSlot { fn calculate<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult> { if let Some(s) = cx.fingerprints.get(unit) { - return Ok(s.clone()) + return Ok(Arc::clone(s)) } // Next, recursively calculate the fingerprint for all of our dependencies. @@ -395,7 +387,7 @@ fn calculate<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) memoized_hash: Mutex::new(None), rustflags: extra_flags, }); - cx.fingerprints.insert(*unit, fingerprint.clone()); + cx.fingerprints.insert(*unit, Arc::clone(&fingerprint)); Ok(fingerprint) } @@ -459,7 +451,7 @@ pub fn prepare_build_cmd<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) // Hence, if there were some `rerun-if-changed` directives forcibly change // the kind of fingerprint by reinterpreting the dependencies output by the // build script. - let state = cx.build_state.clone(); + let state = Arc::clone(&cx.build_state); let key = (unit.pkg.package_id().clone(), unit.kind); let root = unit.pkg.root().to_path_buf(); let write_fingerprint = Work::new(move |_| { @@ -532,13 +524,13 @@ fn local_fingerprints_deps(deps: &BuildDeps, root: &Path) -> Vec CargoResult<()> { let hash = fingerprint.hash(); debug!("write fingerprint: {}", loc.display()); - paths::write(&loc, util::to_hex(hash).as_bytes())?; + paths::write(loc, util::to_hex(hash).as_bytes())?; paths::write(&loc.with_extension("json"), &serde_json::to_vec(&fingerprint).unwrap())?; Ok(()) @@ -570,7 +562,7 @@ fn compare_old_fingerprint(loc: &Path, new_fingerprint: &Fingerprint) let old_fingerprint_json = paths::read(&loc.with_extension("json"))?; let old_fingerprint = serde_json::from_str(&old_fingerprint_json) - .chain_err(|| internal(format!("failed to deserialize json")))?; + .chain_err(|| internal("failed to deserialize json"))?; new_fingerprint.compare(&old_fingerprint) } diff --git a/src/cargo/ops/cargo_rustc/job_queue.rs b/src/cargo/ops/cargo_rustc/job_queue.rs index fac58f77e..5bfc5d458 100644 --- a/src/cargo/ops/cargo_rustc/job_queue.rs +++ b/src/cargo/ops/cargo_rustc/job_queue.rs @@ -223,7 +223,7 @@ impl<'a> JobQueue<'a> { info!("end: {:?}", key); self.active -= 1; if self.active > 0 { - assert!(tokens.len() > 0); + assert!(!tokens.is_empty()); drop(tokens.pop()); } match result { @@ -258,12 +258,12 @@ impl<'a> JobQueue<'a> { let mut opt_type = String::from(if profile.opt_level == "0" { "unoptimized" } else { "optimized" }); if profile.debuginfo.is_some() { - opt_type = opt_type + " + debuginfo"; + opt_type += " + debuginfo"; } let duration = start_time.elapsed(); let time_elapsed = format!("{}.{1:.2} secs", duration.as_secs(), - duration.subsec_nanos() / 10000000); + duration.subsec_nanos() / 10_000_000); if self.queue.is_empty() { let message = format!("{} [{}] target(s) in {}", build_type, diff --git a/src/cargo/ops/cargo_rustc/layout.rs b/src/cargo/ops/cargo_rustc/layout.rs index e5b2baec3..426188b28 100644 --- a/src/cargo/ops/cargo_rustc/layout.rs +++ b/src/cargo/ops/cargo_rustc/layout.rs @@ -70,8 +70,7 @@ pub struct Layout { pub fn is_bad_artifact_name(name: &str) -> bool { ["deps", "examples", "build", "native", "incremental"] .iter() - .find(|&&reserved| reserved == name) - .is_some() + .any(|&reserved| reserved == name) } impl Layout { diff --git a/src/cargo/ops/cargo_rustc/mod.rs b/src/cargo/ops/cargo_rustc/mod.rs index bc00ccbcd..6a12a215c 100644 --- a/src/cargo/ops/cargo_rustc/mod.rs +++ b/src/cargo/ops/cargo_rustc/mod.rs @@ -100,7 +100,7 @@ pub trait Executor: Send + Sync + 'static { } } -/// A DefaultExecutor calls rustc without doing anything else. It is Cargo's +/// A `DefaultExecutor` calls rustc without doing anything else. It is Cargo's /// default behaviour. #[derive(Copy, Clone)] pub struct DefaultExecutor; @@ -150,7 +150,7 @@ pub fn compile_targets<'a, 'cfg: 'a>(ws: &Workspace<'cfg>, // part of this, that's all done next as part of the `execute` // function which will run everything in order with proper // parallelism. - compile(&mut cx, &mut queue, unit, exec.clone())?; + compile(&mut cx, &mut queue, unit, Arc::clone(&exec))?; } // Now that we've figured out everything that we're going to do, do it! @@ -199,7 +199,7 @@ pub fn compile_targets<'a, 'cfg: 'a>(ws: &Workspace<'cfg>, })); } - let feats = cx.resolve.features(&unit.pkg.package_id()); + let feats = cx.resolve.features(unit.pkg.package_id()); cx.compilation.cfgs.entry(unit.pkg.package_id().clone()) .or_insert_with(HashSet::new) .extend(feats.iter().map(|feat| format!("feature=\"{}\"", feat))); @@ -237,7 +237,7 @@ fn compile<'a, 'cfg: 'a>(cx: &mut Context<'a, 'cfg>, let p = profile::start(format!("preparing: {}/{}", unit.pkg, unit.target.name())); fingerprint::prepare_init(cx, unit)?; - cx.links.validate(&cx.resolve, unit)?; + cx.links.validate(cx.resolve, unit)?; let (dirty, fresh, freshness) = if unit.profile.run_custom_build { custom_build::prepare(cx, unit)? @@ -249,7 +249,7 @@ fn compile<'a, 'cfg: 'a>(cx: &mut Context<'a, 'cfg>, let work = if unit.profile.doc { rustdoc(cx, unit)? } else { - rustc(cx, unit, exec.clone())? + rustc(cx, unit, Arc::clone(&exec))? }; // Need to link targets on both the dirty and fresh let dirty = work.then(link_targets(cx, unit, false)?).then(dirty); @@ -275,8 +275,7 @@ fn compile<'a, 'cfg: 'a>(cx: &mut Context<'a, 'cfg>, fn rustc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>, exec: Arc) -> CargoResult { - let crate_types = unit.target.rustc_crate_types(); - let mut rustc = prepare_rustc(cx, crate_types, unit)?; + let mut rustc = prepare_rustc(cx, &unit.target.rustc_crate_types(), unit)?; let name = unit.pkg.name().to_string(); @@ -296,7 +295,7 @@ fn rustc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, let kind = unit.kind; // Prepare the native lib state (extra -L and -l flags) - let build_state = cx.build_state.clone(); + let build_state = Arc::clone(&cx.build_state); let current_id = unit.pkg.package_id().clone(); let build_deps = load_build_deps(cx, unit); @@ -323,8 +322,8 @@ fn rustc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, let package_id = unit.pkg.package_id().clone(); let target = unit.target.clone(); - exec.init(cx, &unit); - let exec = exec.clone(); + exec.init(cx, unit); + let exec = Arc::clone(&exec); let root_output = cx.target_root().to_path_buf(); @@ -352,7 +351,7 @@ fn rustc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, // If there is both an rmeta and rlib, rustc will prefer to use the // rlib, even if it is older. Therefore, we must delete the rlib to // force using the new rmeta. - if dsts[0].extension() == Some(&OsStr::new("rmeta")) { + if dsts[0].extension() == Some(OsStr::new("rmeta")) { dsts.push(root.join(filename).with_extension("rlib")); } for dst in &dsts { @@ -469,7 +468,7 @@ fn rustc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, } } -/// Link the compiled target (often of form foo-{metadata_hash}) to the +/// Link the compiled target (often of form `foo-{metadata_hash}`) to the /// final target. This must happen during both "Fresh" and "Compile" fn link_targets<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>, @@ -551,7 +550,7 @@ fn add_plugin_deps(rustc: &mut ProcessBuilder, root_output: &PathBuf) -> CargoResult<()> { let var = util::dylib_path_envvar(); - let search_path = rustc.get_env(var).unwrap_or(OsString::new()); + let search_path = rustc.get_env(var).unwrap_or_default(); let mut search_path = env::split_paths(&search_path).collect::>(); for id in build_scripts.plugins.iter() { let key = (id.clone(), Kind::Host); @@ -600,11 +599,11 @@ fn filter_dynamic_search_path<'a, I>(paths :I, root_output: &PathBuf) -> Vec(cx: &mut Context<'a, 'cfg>, - crate_types: Vec<&str>, + crate_types: &[&str], unit: &Unit<'a>) -> CargoResult { let mut base = cx.compilation.rustc_process(unit.pkg)?; base.inherit_jobserver(&cx.jobserver); - build_base_args(cx, &mut base, unit, &crate_types); + build_base_args(cx, &mut base, unit, crate_types); build_deps_args(&mut base, cx, unit)?; Ok(base) } @@ -646,7 +645,7 @@ fn rustdoc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, rustdoc.args(&cx.rustdocflags_args(unit)?); let name = unit.pkg.name().to_string(); - let build_state = cx.build_state.clone(); + let build_state = Arc::clone(&cx.build_state); let key = (unit.pkg.package_id().clone(), unit.kind); Ok(Work::new(move |state| { @@ -691,7 +690,7 @@ fn build_base_args<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, let Profile { ref opt_level, lto, codegen_units, ref rustc_args, debuginfo, debug_assertions, overflow_checks, rpath, test, doc: _doc, - run_custom_build, ref panic, rustdoc_args: _, check, + run_custom_build, ref panic, check, .. } = *unit.profile; assert!(!run_custom_build); @@ -727,7 +726,7 @@ fn build_base_args<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, let prefer_dynamic = (unit.target.for_host() && !unit.target.is_custom_build()) || (crate_types.contains(&"dylib") && - cx.ws.members().find(|&p| p != unit.pkg).is_some()); + cx.ws.members().any(|p| p != unit.pkg)); if prefer_dynamic { cmd.arg("-C").arg("prefer-dynamic"); } @@ -756,12 +755,10 @@ fn build_base_args<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, // exclusive. if unit.target.can_lto() && lto && !unit.target.for_host() { cmd.args(&["-C", "lto"]); - } else { + } else if let Some(n) = codegen_units { // There are some restrictions with LTO and codegen-units, so we // only add codegen units when LTO is not used. - if let Some(n) = codegen_units { - cmd.arg("-C").arg(&format!("codegen-units={}", n)); - } + cmd.arg("-C").arg(&format!("codegen-units={}", n)); } if let Some(debuginfo) = debuginfo { @@ -784,15 +781,13 @@ fn build_base_args<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, } else if overflow_checks { cmd.args(&["-C", "overflow-checks=on"]); } - } else { - if !debug_assertions { - cmd.args(&["-C", "debug-assertions=off"]); - if overflow_checks { - cmd.args(&["-C", "overflow-checks=on"]); - } - } else if !overflow_checks { - cmd.args(&["-C", "overflow-checks=off"]); + } else if !debug_assertions { + cmd.args(&["-C", "debug-assertions=off"]); + if overflow_checks { + cmd.args(&["-C", "overflow-checks=on"]); } + } else if !overflow_checks { + cmd.args(&["-C", "overflow-checks=off"]); } if test && unit.target.harness() { diff --git a/src/cargo/ops/cargo_rustc/output_depinfo.rs b/src/cargo/ops/cargo_rustc/output_depinfo.rs index 60adf939e..0a0644d91 100644 --- a/src/cargo/ops/cargo_rustc/output_depinfo.rs +++ b/src/cargo/ops/cargo_rustc/output_depinfo.rs @@ -16,7 +16,7 @@ fn render_filename>(path: P, basedir: Option<&str>) -> CargoResul _ => path, } }; - relpath.to_str().ok_or(internal("path not utf-8")).map(|f| f.replace(" ", "\\ ")) + relpath.to_str().ok_or_else(|| internal("path not utf-8")).map(|f| f.replace(" ", "\\ ")) } fn add_deps_for_unit<'a, 'b>(deps: &mut HashSet, context: &mut Context<'a, 'b>, @@ -72,14 +72,12 @@ pub fn output_depinfo<'a, 'b>(context: &mut Context<'a, 'b>, unit: &Unit<'a>) -> write!(outfile, " {}", render_filename(dep, basedir)?)?; } writeln!(outfile, "")?; - } else { + } else if let Err(err) = fs::remove_file(output_path) { // dep-info generation failed, so delete output file. This will usually // cause the build system to always rerun the build rule, which is correct // if inefficient. - if let Err(err) = fs::remove_file(output_path) { - if err.kind() != ErrorKind::NotFound { - return Err(err.into()); - } + if err.kind() != ErrorKind::NotFound { + return Err(err.into()); } } } diff --git a/src/cargo/ops/lockfile.rs b/src/cargo/ops/lockfile.rs index e4e4463f4..64de6f1ea 100644 --- a/src/cargo/ops/lockfile.rs +++ b/src/cargo/ops/lockfile.rs @@ -131,7 +131,7 @@ fn emit_package(dep: &toml::value::Table, out: &mut String) { out.push_str(&format!("source = {}\n", &dep["source"])); } - if let Some(ref s) = dep.get("dependencies") { + if let Some(s) = dep.get("dependencies") { let slice = s.as_array().unwrap(); if !slice.is_empty() { diff --git a/src/cargo/ops/registry.rs b/src/cargo/ops/registry.rs index 087007893..6d7cf6701 100644 --- a/src/cargo/ops/registry.rs +++ b/src/cargo/ops/registry.rs @@ -45,7 +45,7 @@ pub fn publish(ws: &Workspace, opts: &PublishOpts) -> CargoResult<()> { bail!("some crates cannot be published.\n\ `{}` is marked as unpublishable", pkg.name()); } - if pkg.manifest().patch().len() > 0 { + if !pkg.manifest().patch().is_empty() { bail!("published crates cannot contain [patch] sections"); } @@ -265,10 +265,10 @@ fn http_proxy(config: &Config) -> CargoResult> { /// /// * cargo's `http.proxy` /// * git's `http.proxy` -/// * http_proxy env var -/// * HTTP_PROXY env var -/// * https_proxy env var -/// * HTTPS_PROXY env var +/// * `http_proxy` env var +/// * `HTTP_PROXY` env var +/// * `https_proxy` env var +/// * `HTTPS_PROXY` env var pub fn http_proxy_exists(config: &Config) -> CargoResult { if http_proxy(config)?.is_some() { Ok(true) @@ -286,7 +286,7 @@ pub fn http_timeout(config: &Config) -> CargoResult> { } pub fn registry_login(config: &Config, token: String) -> CargoResult<()> { - let RegistryConfig { index: _, token: old_token } = registry_configuration(config)?; + let RegistryConfig { token: old_token, .. } = registry_configuration(config)?; if let Some(old_token) = old_token { if old_token == token { return Ok(()); @@ -432,12 +432,12 @@ pub fn search(query: &str, } let search_max_limit = 100; - if total_crates > limit as u32 && limit < search_max_limit { + if total_crates > u32::from(limit) && limit < search_max_limit { println!("... and {} crates more (use --limit N to see more)", - total_crates - limit as u32); - } else if total_crates > limit as u32 && limit >= search_max_limit { + total_crates - u32::from(limit)); + } else if total_crates > u32::from(limit) && limit >= search_max_limit { println!("... and {} crates more (go to http://crates.io/search?q={} to see more)", - total_crates - limit as u32, + total_crates - u32::from(limit), percent_encode(query.as_bytes(), QUERY_ENCODE_SET)); } diff --git a/src/cargo/ops/resolve.rs b/src/cargo/ops/resolve.rs index cd88738ca..f26eb8e97 100644 --- a/src/cargo/ops/resolve.rs +++ b/src/cargo/ops/resolve.rs @@ -32,7 +32,7 @@ pub fn resolve_ws_precisely<'a>(ws: &Workspace<'a>, let features = features.iter() .flat_map(|s| s.split_whitespace()) .flat_map(|s| s.split(',')) - .filter(|s| s.len() > 0) + .filter(|s| !s.is_empty()) .map(|s| s.to_string()) .collect::>(); @@ -270,7 +270,7 @@ pub fn resolve_with_previous<'a>(registry: &mut PackageRegistry, if let Some(previous) = previous { resolved.merge_from(previous)?; } - return Ok(resolved); + Ok(resolved) } /// Read the `paths` configuration variable to discover all path overrides that diff --git a/src/cargo/sources/directory.rs b/src/cargo/sources/directory.rs index 711676574..902d64d22 100644 --- a/src/cargo/sources/directory.rs +++ b/src/cargo/sources/directory.rs @@ -107,7 +107,7 @@ impl<'cfg> Source for DirectorySource<'cfg> { let mut only_dotfile = true; for entry in path.read_dir()?.filter_map(|e| e.ok()) { if let Some(s) = entry.file_name().to_str() { - if s.starts_with(".") { + if s.starts_with('.') { continue } } diff --git a/src/cargo/sources/git/utils.rs b/src/cargo/sources/git/utils.rs index 030bf764b..505fd24a8 100644 --- a/src/cargo/sources/git/utils.rs +++ b/src/cargo/sources/git/utils.rs @@ -44,16 +44,16 @@ impl GitShortID { } } -/// GitRemote represents a remote repository. It gets cloned into a local -/// GitDatabase. +/// `GitRemote` represents a remote repository. It gets cloned into a local +/// `GitDatabase`. #[derive(PartialEq, Clone, Debug, Serialize)] pub struct GitRemote { #[serde(serialize_with = "serialize_str")] url: Url, } -/// GitDatabase is a local clone of a remote repository's database. Multiple -/// GitCheckouts can be cloned from this GitDatabase. +/// `GitDatabase` is a local clone of a remote repository's database. Multiple +/// `GitCheckouts` can be cloned from this `GitDatabase`. #[derive(Serialize)] pub struct GitDatabase { remote: GitRemote, @@ -62,9 +62,9 @@ pub struct GitDatabase { repo: git2::Repository, } -/// GitCheckout is a local checkout of a particular revision. Calling +/// `GitCheckout` is a local checkout of a particular revision. Calling /// `clone_into` with a reference will resolve the reference into a revision, -/// and return a CargoError if no revision for that reference was found. +/// and return a `CargoError` if no revision for that reference was found. #[derive(Serialize)] pub struct GitCheckout<'a> { database: &'a GitDatabase, @@ -295,7 +295,7 @@ impl<'a> GitCheckout<'a> { fn update_submodules(repo: &git2::Repository, cargo_config: &Config) -> CargoResult<()> { info!("update submodules for: {:?}", repo.workdir().unwrap()); - for mut child in repo.submodules()?.into_iter() { + for mut child in repo.submodules()? { update_submodule(repo, &mut child, cargo_config) .map_err(CargoError::into_internal) .chain_err(|| { diff --git a/src/cargo/sources/path.rs b/src/cargo/sources/path.rs index 16995ba76..980d311fa 100644 --- a/src/cargo/sources/path.rs +++ b/src/cargo/sources/path.rs @@ -113,7 +113,7 @@ impl<'cfg> PathSource<'cfg> { let pattern: &str = if p.starts_with('/') { &p[1..p.len()] } else { - &p + p }; Pattern::new(pattern).map_err(|e| { CargoError::from(format!("could not parse glob pattern `{}`: {}", p, e)) @@ -216,8 +216,7 @@ impl<'cfg> PathSource<'cfg> { relative_path.display() ))?; } - } else { - if no_include_option { + } else if no_include_option { self.config .shell() .warn(format!( @@ -226,16 +225,15 @@ impl<'cfg> PathSource<'cfg> { See https://github.com/rust-lang/cargo/issues/4268 for more info", relative_path.display() ))?; - } else { - self.config - .shell() - .warn(format!( - "Pattern matching for Cargo's include/exclude fields is changing and \ - file `{}` WILL be included in a future Cargo version.\n\ - See https://github.com/rust-lang/cargo/issues/4268 for more info", - relative_path.display() - ))?; - } + } else { + self.config + .shell() + .warn(format!( + "Pattern matching for Cargo's include/exclude fields is changing and \ + file `{}` WILL be included in a future Cargo version.\n\ + See https://github.com/rust-lang/cargo/issues/4268 for more info", + relative_path.display() + ))?; } } @@ -294,7 +292,7 @@ impl<'cfg> PathSource<'cfg> { None => break, } } - return None; + None } fn list_files_git(&self, pkg: &Package, repo: git2::Repository, @@ -453,8 +451,9 @@ impl<'cfg> PathSource<'cfg> { let name = path.file_name().and_then(|s| s.to_str()); // Skip dotfile directories if name.map(|s| s.starts_with('.')) == Some(true) { - continue - } else if is_root { + continue; + } + if is_root { // Skip cargo artifacts match name { Some("target") | Some("Cargo.lock") => continue, @@ -533,7 +532,7 @@ impl<'cfg> Source for PathSource<'cfg> { // as 0. let mtime = fs::metadata(&file).map(|meta| { FileTime::from_last_modification_time(&meta) - }).unwrap_or(FileTime::zero()); + }).unwrap_or_else(|_| FileTime::zero()); warn!("{} {}", mtime, file.display()); if mtime > max { max = mtime; diff --git a/src/cargo/sources/registry/remote.rs b/src/cargo/sources/registry/remote.rs index 27870d67c..6704282b8 100644 --- a/src/cargo/sources/registry/remote.rs +++ b/src/cargo/sources/registry/remote.rs @@ -130,7 +130,7 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> { let repo = self.repo()?; let tree = self.tree()?; let entry = tree.get_path(path)?; - let object = entry.to_object(&repo)?; + let object = entry.to_object(repo)?; let blob = match object.as_blob() { Some(blob) => blob, None => bail!("path `{}` is not a blob in the git repo", path.display()), @@ -145,7 +145,7 @@ impl<'cfg> RegistryData for RemoteRegistry<'cfg> { "the registry index")?; let mut config = None; self.load(Path::new(""), Path::new("config.json"), &mut |json| { - config = Some(serde_json::from_slice(&json)?); + config = Some(serde_json::from_slice(json)?); Ok(()) })?; Ok(config) diff --git a/tests/build.rs b/tests/build.rs index 23deb6e33..3bc34ca3a 100644 --- a/tests/build.rs +++ b/tests/build.rs @@ -3605,8 +3605,7 @@ fn same_metadata_different_directory() { )); let metadata = output .split_whitespace() - .filter(|arg| arg.starts_with("metadata=")) - .next() + .find(|arg| arg.starts_with("metadata=")) .unwrap(); let p = project("foo2") diff --git a/tests/cargo.rs b/tests/cargo.rs index 43e76c6ec..6f488a980 100644 --- a/tests/cargo.rs +++ b/tests/cargo.rs @@ -3,7 +3,6 @@ extern crate cargotest; extern crate hamcrest; use std::env; -use std::ffi::OsString; use std::fs::{self, File}; use std::io::prelude::*; use std::path::{Path, PathBuf}; @@ -22,11 +21,11 @@ enum FakeKind<'a> { /// Add an empty file with executable flags (and platform-dependent suffix). /// TODO: move this to `ProjectBuilder` if other cases using this emerge. -fn fake_file(proj: ProjectBuilder, dir: &Path, name: &str, kind: FakeKind) -> ProjectBuilder { +fn fake_file(proj: ProjectBuilder, dir: &Path, name: &str, kind: &FakeKind) -> ProjectBuilder { let path = proj.root().join(dir).join(&format!("{}{}", name, env::consts::EXE_SUFFIX)); path.parent().unwrap().mkdir_p(); - match kind { + match *kind { FakeKind::Executable => { File::create(&path).unwrap(); make_executable(&path); @@ -59,13 +58,13 @@ fn fake_file(proj: ProjectBuilder, dir: &Path, name: &str, kind: FakeKind) -> Pr } fn path() -> Vec { - env::split_paths(&env::var_os("PATH").unwrap_or(OsString::new())).collect() + env::split_paths(&env::var_os("PATH").unwrap_or_default()).collect() } #[test] fn list_command_looks_at_path() { let proj = project("list-non-overlapping"); - let proj = fake_file(proj, Path::new("path-test"), "cargo-1", FakeKind::Executable); + let proj = fake_file(proj, Path::new("path-test"), "cargo-1", &FakeKind::Executable); let mut pr = cargo_process(); let mut path = path(); @@ -86,7 +85,7 @@ fn list_command_resolves_symlinks() { let proj = project("list-non-overlapping"); let proj = fake_file(proj, Path::new("path-test"), "cargo-2", - FakeKind::Symlink{target:&cargo_exe()}); + &FakeKind::Symlink{target:&cargo_exe()}); let mut pr = cargo_process(); let mut path = path(); diff --git a/tests/login.rs b/tests/login.rs index d3b9b601b..9bb060a1d 100644 --- a/tests/login.rs +++ b/tests/login.rs @@ -24,7 +24,7 @@ const CONFIG_FILE: &str = r#" fn setup_old_credentials() { let config = cargo_home().join("config"); t!(fs::create_dir_all(config.parent().unwrap())); - t!(t!(File::create(&config)).write_all(&CONFIG_FILE.as_bytes())); + t!(t!(File::create(&config)).write_all(CONFIG_FILE.as_bytes())); } fn setup_new_credentials() { @@ -61,7 +61,7 @@ fn login_with_old_credentials() { let mut contents = String::new(); File::open(&config).unwrap().read_to_string(&mut contents).unwrap(); - assert!(CONFIG_FILE == &contents); + assert_eq!(CONFIG_FILE, contents); let credentials = cargo_home().join("credentials"); assert_that(&credentials, existing_file()); @@ -124,5 +124,5 @@ fn new_credentials_is_used_instead_old() { let config = Config::new(Shell::new(), cargo_home(), cargo_home()); let token = config.get_string("registry.token").unwrap().map(|p| p.val); - assert!(token.unwrap() == TOKEN); + assert_eq!(token.unwrap(), TOKEN); } diff --git a/tests/publish.rs b/tests/publish.rs index 41856dbd6..ea4986195 100644 --- a/tests/publish.rs +++ b/tests/publish.rs @@ -53,7 +53,7 @@ See [..] // Verify the tarball let mut rdr = GzDecoder::new(f).unwrap(); - assert_eq!(rdr.header().filename().unwrap(), "foo-0.0.1.crate".as_bytes()); + assert_eq!(rdr.header().filename().unwrap(), b"foo-0.0.1.crate"); let mut contents = Vec::new(); rdr.read_to_end(&mut contents).unwrap(); let mut ar = Archive::new(&contents[..]); diff --git a/tests/resolve.rs b/tests/resolve.rs index 61541b747..03fa38eb6 100644 --- a/tests/resolve.rs +++ b/tests/resolve.rs @@ -13,7 +13,7 @@ use cargo::core::{Dependency, PackageId, Summary, Registry}; use cargo::util::{CargoResult, ToUrl}; use cargo::core::resolver::{self, Method}; -fn resolve(pkg: PackageId, deps: Vec, registry: &[Summary]) +fn resolve(pkg: &PackageId, deps: Vec, registry: &[Summary]) -> CargoResult> { struct MyRegistry<'a>(&'a [Summary]); @@ -143,8 +143,8 @@ fn loc_names(names: &[(&'static str, &'static str)]) -> Vec { #[test] fn test_resolving_empty_dependency_list() { - let res = resolve(pkg_id("root"), Vec::new(), - &mut registry(vec![])).unwrap(); + let res = resolve(&pkg_id("root"), Vec::new(), + ®istry(vec![])).unwrap(); assert_that(&res, equal_to(&names(&["root"]))); } @@ -152,7 +152,7 @@ fn test_resolving_empty_dependency_list() { #[test] fn test_resolving_only_package() { let reg = registry(vec![pkg("foo")]); - let res = resolve(pkg_id("root"), vec![dep("foo")], ®); + let res = resolve(&pkg_id("root"), vec![dep("foo")], ®); assert_that(&res.unwrap(), contains(names(&["root", "foo"])).exactly()); } @@ -160,7 +160,7 @@ fn test_resolving_only_package() { #[test] fn test_resolving_one_dep() { let reg = registry(vec![pkg("foo"), pkg("bar")]); - let res = resolve(pkg_id("root"), vec![dep("foo")], ®); + let res = resolve(&pkg_id("root"), vec![dep("foo")], ®); assert_that(&res.unwrap(), contains(names(&["root", "foo"])).exactly()); } @@ -168,7 +168,7 @@ fn test_resolving_one_dep() { #[test] fn test_resolving_multiple_deps() { let reg = registry(vec![pkg!("foo"), pkg!("bar"), pkg!("baz")]); - let res = resolve(pkg_id("root"), vec![dep("foo"), dep("baz")], + let res = resolve(&pkg_id("root"), vec![dep("foo"), dep("baz")], ®).unwrap(); assert_that(&res, contains(names(&["root", "foo", "baz"])).exactly()); @@ -177,7 +177,7 @@ fn test_resolving_multiple_deps() { #[test] fn test_resolving_transitive_deps() { let reg = registry(vec![pkg!("foo"), pkg!("bar" => ["foo"])]); - let res = resolve(pkg_id("root"), vec![dep("bar")], ®).unwrap(); + let res = resolve(&pkg_id("root"), vec![dep("bar")], ®).unwrap(); assert_that(&res, contains(names(&["root", "foo", "bar"]))); } @@ -185,7 +185,7 @@ fn test_resolving_transitive_deps() { #[test] fn test_resolving_common_transitive_deps() { let reg = registry(vec![pkg!("foo" => ["bar"]), pkg!("bar")]); - let res = resolve(pkg_id("root"), vec![dep("foo"), dep("bar")], + let res = resolve(&pkg_id("root"), vec![dep("foo"), dep("bar")], ®).unwrap(); assert_that(&res, contains(names(&["root", "foo", "bar"]))); @@ -197,7 +197,7 @@ fn test_resolving_with_same_name() { pkg_loc("bar", "http://second.example.com")]; let reg = registry(list); - let res = resolve(pkg_id("root"), + let res = resolve(&pkg_id("root"), vec![dep_loc("foo", "http://first.example.com"), dep_loc("bar", "http://second.example.com")], ®); @@ -219,7 +219,7 @@ fn test_resolving_with_dev_deps() { pkg!("bat") ]); - let res = resolve(pkg_id("root"), + let res = resolve(&pkg_id("root"), vec![dep("foo"), dep_kind("baz", Development)], ®).unwrap(); @@ -233,7 +233,7 @@ fn resolving_with_many_versions() { pkg!(("foo", "1.0.2")), ]); - let res = resolve(pkg_id("root"), vec![dep("foo")], ®).unwrap(); + let res = resolve(&pkg_id("root"), vec![dep("foo")], ®).unwrap(); assert_that(&res, contains(names(&[("root", "1.0.0"), ("foo", "1.0.2")]))); @@ -246,7 +246,7 @@ fn resolving_with_specific_version() { pkg!(("foo", "1.0.2")), ]); - let res = resolve(pkg_id("root"), vec![dep_req("foo", "=1.0.1")], + let res = resolve(&pkg_id("root"), vec![dep_req("foo", "=1.0.1")], ®).unwrap(); assert_that(&res, contains(names(&[("root", "1.0.0"), @@ -263,7 +263,7 @@ fn test_resolving_maximum_version_with_transitive_deps() { pkg!("bar" => [dep_req("util", ">=1.0.1")]), ]); - let res = resolve(pkg_id("root"), vec![dep_req("foo", "1.0.0"), dep_req("bar", "1.0.0")], + let res = resolve(&pkg_id("root"), vec![dep_req("foo", "1.0.0"), dep_req("bar", "1.0.0")], ®).unwrap(); assert_that(&res, contains(names(&[("root", "1.0.0"), @@ -282,7 +282,7 @@ fn resolving_incompat_versions() { pkg!("bar" => [dep_req("foo", "=1.0.2")]), ]); - assert!(resolve(pkg_id("root"), vec![ + assert!(resolve(&pkg_id("root"), vec![ dep_req("foo", "=1.0.1"), dep("bar"), ], ®).is_err()); @@ -297,7 +297,7 @@ fn resolving_backtrack() { pkg!("baz"), ]); - let res = resolve(pkg_id("root"), vec![ + let res = resolve(&pkg_id("root"), vec![ dep_req("foo", "^1"), ], ®).unwrap(); @@ -321,7 +321,7 @@ fn resolving_allows_multiple_compatible_versions() { pkg!("d4" => [dep_req("foo", "0.2")]), ]); - let res = resolve(pkg_id("root"), vec![ + let res = resolve(&pkg_id("root"), vec![ dep("bar"), ], ®).unwrap(); @@ -354,7 +354,7 @@ fn resolving_with_deep_backtracking() { pkg!(("dep_req", "2.0.0")), ]); - let res = resolve(pkg_id("root"), vec![ + let res = resolve(&pkg_id("root"), vec![ dep_req("foo", "1"), ], ®).unwrap(); @@ -369,7 +369,7 @@ fn resolving_but_no_exists() { let reg = registry(vec![ ]); - let res = resolve(pkg_id("root"), vec![ + let res = resolve(&pkg_id("root"), vec![ dep_req("foo", "1"), ], ®); assert!(res.is_err()); @@ -387,7 +387,7 @@ fn resolving_cycle() { pkg!("foo" => ["foo"]), ]); - let _ = resolve(pkg_id("root"), vec![ + let _ = resolve(&pkg_id("root"), vec![ dep_req("foo", "1"), ], ®); } @@ -401,7 +401,7 @@ fn hard_equality() { pkg!(("bar", "1.0.0") => [dep_req("foo", "1.0.0")]), ]); - let res = resolve(pkg_id("root"), vec![ + let res = resolve(&pkg_id("root"), vec![ dep_req("bar", "1"), dep_req("foo", "=1.0.0"), ], ®).unwrap(); diff --git a/tests/search.rs b/tests/search.rs index 06410349a..7ea7103ad 100644 --- a/tests/search.rs +++ b/tests/search.rs @@ -35,7 +35,7 @@ fn setup() { fn cargo_process(s: &str) -> ProcessBuilder { let mut b = cargotest::cargo_process(); b.arg(s); - return b + b } #[test] diff --git a/tests/small-fd-limits.rs b/tests/small-fd-limits.rs index e8249cafc..f4d2943db 100644 --- a/tests/small-fd-limits.rs +++ b/tests/small-fd-limits.rs @@ -95,7 +95,7 @@ fn use_git_gc() { // notably not on AppVeyor's machines. Sounds like another but for another day. #[cfg_attr(windows, ignore)] fn avoid_using_git() { - let path = env::var_os("PATH").unwrap_or(Default::default()); + let path = env::var_os("PATH").unwrap_or_default(); let mut paths = env::split_paths(&path).collect::>(); let idx = paths.iter().position(|p| { p.join("git").exists() || p.join("git.exe").exists() -- 2.30.2