More lint cleaning
authorLukas Lueg <lukas.lueg@gmail.com>
Sun, 24 Sep 2017 14:26:37 +0000 (16:26 +0200)
committerLukas Lueg <lukas.lueg@gmail.com>
Sun, 24 Sep 2017 14:26:37 +0000 (16:26 +0200)
47 files changed:
src/bin/cargo.rs
src/bin/init.rs
src/bin/install.rs
src/bin/new.rs
src/bin/run.rs
src/bin/verify_project.rs
src/cargo/core/dependency.rs
src/cargo/core/features.rs
src/cargo/core/manifest.rs
src/cargo/core/package.rs
src/cargo/core/package_id.rs
src/cargo/core/package_id_spec.rs
src/cargo/core/registry.rs
src/cargo/core/resolver/encode.rs
src/cargo/core/resolver/mod.rs
src/cargo/core/source.rs
src/cargo/core/workspace.rs
src/cargo/ops/cargo_clean.rs
src/cargo/ops/cargo_compile.rs
src/cargo/ops/cargo_generate_lockfile.rs
src/cargo/ops/cargo_install.rs
src/cargo/ops/cargo_new.rs
src/cargo/ops/cargo_package.rs
src/cargo/ops/cargo_read_manifest.rs
src/cargo/ops/cargo_run.rs
src/cargo/ops/cargo_rustc/compilation.rs
src/cargo/ops/cargo_rustc/context.rs
src/cargo/ops/cargo_rustc/custom_build.rs
src/cargo/ops/cargo_rustc/fingerprint.rs
src/cargo/ops/cargo_rustc/job_queue.rs
src/cargo/ops/cargo_rustc/layout.rs
src/cargo/ops/cargo_rustc/mod.rs
src/cargo/ops/cargo_rustc/output_depinfo.rs
src/cargo/ops/lockfile.rs
src/cargo/ops/registry.rs
src/cargo/ops/resolve.rs
src/cargo/sources/directory.rs
src/cargo/sources/git/utils.rs
src/cargo/sources/path.rs
src/cargo/sources/registry/remote.rs
tests/build.rs
tests/cargo.rs
tests/login.rs
tests/publish.rs
tests/resolve.rs
tests/search.rs
tests/small-fd-limits.rs

index c87370e4c99eb1c414de93fa315d92d013e108a2..48c2a134799a51b6e3b695657dc4b61c700d0ce7 100644 (file)
@@ -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::<Vec<_>>();
-            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<CliRe
     None
 }
 
-fn aliased_command(config: &Config, command: &String) -> CargoResult<Option<Vec<String>>> {
+fn aliased_command(config: &Config, command: &str) -> CargoResult<Option<Vec<String>>> {
     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<String> {
     // 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::<Vec<_>>();
     filtered.sort_by(|a, b| a.0.cmp(&b.0));
index 6d5c37185f62d202dfcc0dbb505cea39de1ea136..29319e181913e4c13ac8d27b0fa03f75d47f55c0 100644 (file)
@@ -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" }
index 1e34ece162f21106d546404f0f094e823b7fa839..4fedab896eda3f1f243e07cbebded8d3d93abe96 100644 (file)
@@ -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)?
     };
index 9b0c97d9561ccd006fc8d3b9ae893ed02f72982b..dc0878d195c2264e2c50bb7dc76702b3e5e4e3af 100644 (file)
@@ -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" }
index 64f30877d82b4a1e7ce52ad7f95168fc740d9423..d6bee1f09f55cc56d13dcdbcbb529a1ab3002714 100644 (file)
@@ -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)),
index 00127e1fe076fe685229652f5714356fe72ad1c7..208905671fa75930fd3f261ff7dcd3cb65bb2dc4 100644 (file)
@@ -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()),
index 2d8b4d038539ecc2bb8cfee07f131e5ba8825e03..24d6c9f35f80b59b51dfac0ee197f79eb69adc8f 100644 (file)
@@ -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<Platform> {
-        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)
index 51b82076ce9d37a5d7bb5a4b613054602b75d922..c73c1bc474bf8ebb7fd3673618c903ca4a65015d 100644 (file)
@@ -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"))
     })
 }
 
index 74187bc9cc4b0326c705cfb8a376edf131fb2a6a..06f66a6b08ec53ec46174f6961bd7fe8c82f42f7 100644 (file)
@@ -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,
         }
index 9d16b1f28561b669b5b5b9710fbde2efd28ec769..afc047f88f6e3538894ae0d53719493b8a627e9a 100644 (file)
@@ -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<Package> {
         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)
     }
 
index 321848c91c3f37578c22429ad79b05b071799432..90879855581d4b3866b0db700403925582e77dd4 100644 (file)
@@ -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)
     }
 }
 
index 3136e3fd6feeaf0ef9f747549cf46fee225aea11..d271f2f66606ba63b258df993f212fe2ba86539d 100644 (file)
@@ -17,7 +17,7 @@ pub struct PackageIdSpec {
 
 impl PackageIdSpec {
     pub fn parse(spec: &str) -> CargoResult<PackageIdSpec> {
-        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(())
     }
index 70efc66dfe9312a1d3dc1fff153c4785e2b343de..7052ba509ff956e69d69facfdbfdefe2ab6881ef 100644 (file)
@@ -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
     })
 }
 
index 4ca01c49a3178434c9408261ccda17ec74d4417b..344082bf60eed1b36d10fa4e4c074a98315537ae 100644 (file)
@@ -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,
         };
 
index a2f4e11392b737db589f56e5d84d271e882d0d06..573a6be1c914845d6d6fb866a6672a3423005592 100644 (file)
@@ -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<T> RcVecIter<T> {
 impl<T> Clone for RcVecIter<T> {
     fn clone(&self) -> RcVecIter<T> {
         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<BacktrackFrame<'a>>,
                 *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::<Vec<_>>();
-            if summaries.len() > 0 {
+            if !summaries.is_empty() {
                 let bullets = summaries.iter().map(|s| {
                     format!("  * {}", s.package_id())
                 }).collect::<Vec<_>>();
@@ -1188,7 +1183,7 @@ impl<'a> Context<'a> {
             replacements.insert(k, v);
             cur = &node.1;
         }
-        return replacements
+        replacements
     }
 
     fn graph(&self) -> Graph<PackageId> {
@@ -1201,7 +1196,7 @@ impl<'a> Context<'a> {
             }
             cur = &node.1;
         }
-        return graph
+        graph
     }
 }
 
index 5d1347238c973ba724730528d0b16dd0c8bd2852..b9218bd5acabb6645f47765ee46f4fb7464a65f8 100644 (file)
@@ -499,6 +499,7 @@ impl<'a> fmt::Display for PrettyRef<'a> {
     }
 }
 
+#[derive(Default)]
 pub struct SourceMap<'src> {
     map: HashMap<SourceId, Box<Source + 'src>>,
 }
index 87c0ec1bee4c547288e28f0fc64c4ec7831758f8..48d379343c9883e706e004558fa36c89271f9812 100644 (file)
@@ -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,
index 19f518f8016f7c185a91c3de280357aa6121b58e..9b266b0bbf890a69b6b0ea9d68b2867ad1af2f9f 100644 (file)
@@ -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,
                     });
                 }
index a8e9ce7048fcacd6b7ccbe9b9639cb00e9fdd914..685911203dec60f46340aff865ff4c10d555b5df 100644 (file)
@@ -112,7 +112,7 @@ pub enum Packages<'a> {
 }
 
 impl<'a> Packages<'a> {
-    pub fn from_flags(virtual_ws: bool, all: bool, exclude: &'a Vec<String>, package: &'a Vec<String>)
+    pub fn from_flags(virtual_ws: bool, all: bool, exclude: &'a [String], package: &'a [String])
         -> CargoResult<Self>
     {
         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::<CargoResult<Vec<_>>>()?
+                packages.iter().map(|p| PackageIdSpec::parse(p)).collect::<CargoResult<Vec<_>>>()?
             }
         };
         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<Vec<String>> {
         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()));
                 }
             }
index 29c3749c62c1403b7af18fe4e4192ecd1aa4fdd5..7be8ae05ae5cc78fdc4eb5992ce4aa88ab5f2e3f 100644 (file)
@@ -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();
index b6b87a82bb1cc42a0884edadedbbdc1a981fd6ae..beb934210d94d96c4a4eeb676103852d75a763a7 100644 (file)
@@ -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<BTreeMap<String, Option<PackageId>>> {
-    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));
index 4ece45cc23e2b8da6de6858934eeb4ef880a0294..b7b30f7e27ae5dc6f26b4f249d848290b803d4ed 100644 (file)
@@ -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())));
-            }
         }
     }
 
index 9050beeced68a80450cae6250b208735dd309af3..f12ce12f35a70decb723660756be0ac2cfe2d60b 100644 (file)
@@ -29,7 +29,7 @@ pub fn package(ws: &Workspace,
                opts: &PackageOpts) -> CargoResult<Option<FileLock>> {
     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())
     }
index 3cc736a2d63aec1367a4654aa19333f6776130b4..dc8b747868489b90f46581c07861172ef9ef9470 100644 (file)
@@ -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
index ab769857754a76964da2b566c3731d77dc3aebb1..3a4e7f6f2d6ede731353cd09831106d46f44394b 100644 (file)
@@ -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())?;
index c853290c7565b44bd5bce13525c12981e4691ffb..b3643b6bf29347bf0787c602a9ea3b32bce12971 100644 (file)
@@ -104,7 +104,7 @@ impl<'cfg> Compilation<'cfg> {
     /// See `process`.
     pub fn target_process<T: AsRef<OsStr>>(&self, cmd: T, pkg: &Package)
                                            -> CargoResult<ProcessBuilder> {
-        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);
index cec2e39b051e69324c2e2ef4f9d297aaffc2a147..219d16846ee28443872c3eebea03955ed8c4dd74 100755 (executable)
@@ -97,9 +97,9 @@ impl<'a, 'cfg> Context<'a, 'cfg> {
                profiles: &'a Profiles) -> CargoResult<Context<'a, 'cfg>> {
 
         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<Arc<Vec<(PathBuf, Option<PathBuf>, 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()
index 267021ebec5639a7c9b6b07d97bf381b28b04378..fee750c4cb5c5b8ffbf24958aa17d9ded2f06da4 100644 (file)
@@ -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::<Vec<_>>()
     };
     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)
index e4d2dd1245c8e79aee07cf4ce01bfa057b61bc36..fdd37f05f1cc2fd2851e3bc48f7ae263871ba669 100644 (file)
@@ -144,7 +144,7 @@ pub struct Fingerprint {
     rustflags: Vec<String>,
 }
 
-fn serialize_deps<S>(deps: &Vec<(String, Arc<Fingerprint>)>, ser: S)
+fn serialize_deps<S>(deps: &[(String, Arc<Fingerprint>)], ser: S)
                      -> Result<S::Ok, S::Error>
     where S: ser::Serializer,
 {
@@ -287,16 +287,8 @@ impl Fingerprint {
 
 impl hash::Hash for Fingerprint {
     fn hash<H: Hasher>(&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<Arc<Fingerprint>> {
     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<LocalFingerprin
         local.push(LocalFingerprint::EnvBased(var.clone(), val));
     }
 
-    return local
+    local
 }
 
 fn write_fingerprint(loc: &Path, fingerprint: &Fingerprint) -> 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)
 }
 
index fac58f77eee7698ae3029446113f5b420bd3892e..5bfc5d4585049bc53a2a8db6891ac983a9149bad 100644 (file)
@@ -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,
index e5b2baec3f51ecabab83b751c652655b56885bd6..426188b288dd97802eceab6c2585fa0ec9e2358c 100644 (file)
@@ -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 {
index bc00ccbcdb648af363a76ad1a0c196b0582f4b47..6a12a215ccbf630ecc04c0fc369cabbd1910d5cd 100644 (file)
@@ -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<Executor>) -> CargoResult<Work> {
-    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::<Vec<_>>();
     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<Pat
 }
 
 fn prepare_rustc<'a, 'cfg>(cx: &mut Context<'a, 'cfg>,
-                           crate_types: Vec<&str>,
+                           crate_types: &[&str],
                            unit: &Unit<'a>) -> CargoResult<ProcessBuilder> {
     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() {
index 60adf939e6e255236c4b11131fa5f5495b08fd76..0a0644d910a6b2ae1648aaa148190972c2280cf7 100644 (file)
@@ -16,7 +16,7 @@ fn render_filename<P: AsRef<Path>>(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<PathBuf>, 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());
                 }
             }
         }
index e4e4463f4f585506a61af65d98fde893c9baec22..64de6f1ea37a1fe058ef0c9d9939d01555a738d9 100644 (file)
@@ -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() {
index 087007893c2e706f89b8fe7453d732add749ae6d..6d7cf670123933efc6ff2e846b2cd32f16064a43 100644 (file)
@@ -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<Option<String>> {
 ///
 /// * 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<bool> {
     if http_proxy(config)?.is_some() {
         Ok(true)
@@ -286,7 +286,7 @@ pub fn http_timeout(config: &Config) -> CargoResult<Option<i64>> {
 }
 
 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));
     }
 
index cd88738cae4577d7ff5c2797b8fc4510c2db6d49..f26eb8e9798f4f241be3b7cc4547d9dafbd9f4a0 100644 (file)
@@ -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::<Vec<String>>();
 
@@ -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
index 7116765747fb1cdec2ba62ce500d91de82e5c198..902d64d22498c661a953fa7d044519c186419740 100644 (file)
@@ -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
                     }
                 }
index 030bf764bf078af3586bf6e180e225da8aeeed19..505fd24a80c4d577f15ec3b883db8ede716288d7 100644 (file)
@@ -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(|| {
index 16995ba760c98431cae95b34324b2ec3f321ee50..980d311fac74baf8f17307dc1c2b1755642d10c5 100644 (file)
@@ -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;
index 27870d67c77040314166cbea2d591faedce7a03f..6704282b897d8138e7f1875e3f9d63dc724bf663 100644 (file)
@@ -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)
index 23deb6e331f690d4cfc9cc481d3f45f934328f42..3bc34ca3a2b0299a47a8ec59b0c1a717e009e940 100644 (file)
@@ -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")
index 43e76c6ec153ed4d6b8a11e07939ae9c347cb298..6f488a98059e91b8dbcb8e64fb08e9ab748d6915 100644 (file)
@@ -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<PathBuf> {
-    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();
index d3b9b601b2feb8327a1a8228976472ce295e348c..9bb060a1d12a026b0b28fab110a642434ad72760 100644 (file)
@@ -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);
 }
index 41856dbd664b64a074a672ef55f301c090b8331a..ea4986195173cf8d7952018df7a401236cee12ff 100644 (file)
@@ -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[..]);
index 61541b747898393de1d7747c39f46b95030304d4..03fa38eb6e326bad75c99f21258ca99c6ec59fa7 100644 (file)
@@ -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<Dependency>, registry: &[Summary])
+fn resolve(pkg: &PackageId, deps: Vec<Dependency>, registry: &[Summary])
     -> CargoResult<Vec<PackageId>>
 {
     struct MyRegistry<'a>(&'a [Summary]);
@@ -143,8 +143,8 @@ fn loc_names(names: &[(&'static str, &'static str)]) -> Vec<PackageId> {
 
 #[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(),
+                      &registry(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")], &reg);
+    let res = resolve(&pkg_id("root"), vec![dep("foo")], &reg);
 
     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")], &reg);
+    let res = resolve(&pkg_id("root"), vec![dep("foo")], &reg);
 
     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")],
                       &reg).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")], &reg).unwrap();
+    let res = resolve(&pkg_id("root"), vec![dep("bar")], &reg).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")],
                       &reg).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")],
                       &reg);
@@ -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)],
                       &reg).unwrap();
 
@@ -233,7 +233,7 @@ fn resolving_with_many_versions() {
         pkg!(("foo", "1.0.2")),
     ]);
 
-    let res = resolve(pkg_id("root"), vec![dep("foo")], &reg).unwrap();
+    let res = resolve(&pkg_id("root"), vec![dep("foo")], &reg).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")],
                       &reg).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")],
                       &reg).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"),
     ], &reg).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"),
     ], &reg).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"),
     ], &reg).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"),
     ], &reg).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"),
     ], &reg);
     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"),
     ], &reg);
 }
@@ -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"),
     ], &reg).unwrap();
index 06410349a9a9ab34c2ad1fe2f90b744b84325426..7ea7103ad8fedb4e30c351e132f7916cce5e08b9 100644 (file)
@@ -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]
index e8249cafcdac4bb85ac213bdc726a3867b321e42..f4d2943dbd6402955732fe163ca0d31fba7c80bd 100644 (file)
@@ -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::<Vec<_>>();
     let idx = paths.iter().position(|p| {
         p.join("git").exists() || p.join("git.exe").exists()