}
};
- 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()
.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
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) {
// 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));
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,
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" }
} 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)?
};
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" }
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)),
&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()),
{
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(),
/// 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.
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)
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 {
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"))
})
}
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,
}
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,
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)
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)
}
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"))
}
pub fn stable_hash<'a>(&'a self, workspace: &'a Path) -> PackageIdStableHash<'a> {
- PackageIdStableHash(&self, workspace)
+ PackageIdStableHash(self, workspace)
}
}
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);
}
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 {
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()));
} 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(())
}
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)))
}
}
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(())
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
}
}
} else {
- if patches.len() > 0 {
+ if !patches.is_empty() {
debug!("found {} patches with an unlocked dep, \
looking at sources", patches.len());
}
// 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;
}
trace!("\tnope, unlocked");
- return dep
+ dep
})
}
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);
}
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,
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
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)? {
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:
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,
};
})?;
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")
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,
};
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
}
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 {
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(),
}
}
// 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()
+ })
}
}
&mut features) {
None => return Err(activation_error(&cx, registry, &parent,
&dep,
- &cx.prev_active(&dep),
+ cx.prev_active(&dep),
&candidates)),
Some(candidate) => candidate,
}
*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;
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 \
// 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");
}
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<_>>();
replacements.insert(k, v);
cur = &node.1;
}
- return replacements
+ replacements
}
fn graph(&self) -> Graph<PackageId> {
}
cur = &node.1;
}
- return graph
+ graph
}
}
}
}
+#[derive(Default)]
pub struct SourceMap<'src> {
map: HashMap<SourceId, Box<Source + 'src>>,
}
};
ws.members.push(ws.current_manifest.clone());
}
- return Ok(ws)
+ Ok(ws)
}
/// Returns the current package of this workspace.
.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());
}
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());
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,
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,
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() {
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,
});
}
}
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());
.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)
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);
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()),
}
}
}
required: false,
}
});
- return Ok(result.collect());
+ Ok(result.collect())
}
FilterRule::Just(names) => {
let mut targets = Vec::new();
required: true,
});
}
- return Ok(targets);
+ Ok(targets)
}
}
}
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 {
};
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)
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()));
}
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()));
}
}
}
}
- 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,
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();
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;
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 {
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());
// 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(())
Ok(())
}
-fn install_one(root: Filesystem,
- map: SourceConfigMap,
+fn install_one(root: &Filesystem,
+ map: &SourceConfigMap,
krate: Option<&str>,
source_id: &SourceId,
vers: Option<&str>,
// 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)?;
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,
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(),
}
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())
}
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() {
}
// 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));
}
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 {
}
}
-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\
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 {
})
}
-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");
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
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 {
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())));
- }
}
}
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")
}
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() {
}
if !opts.allow_dirty {
- check_not_dirty(&pkg, &src)?;
+ check_not_dirty(pkg, &src)?;
}
let filename = format!("{}-{}.crate", pkg.name(), pkg.version());
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\
// 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(())
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: {}",
}
};
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())
}
use std::collections::{HashMap, HashSet};
+use std::collections::hash_map::Entry;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
// 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)
}
};
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
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())?;
/// 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);
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,
};
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();
}
}));
}
- for dep in self.dep_targets(&unit)? {
+ for dep in self.dep_targets(unit)? {
self.visit_crate_type(&dep, crate_types, visited_units)?;
}
Ok(())
-> 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();
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();
/// 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
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);
}
}
} 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
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
}
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)
}
};
}
}
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())
// (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())]);
}
}
}
// 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);
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()
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())
}
}
}
}).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();
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;
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)
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,
{
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());
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.
memoized_hash: Mutex::new(None),
rustflags: extra_flags,
});
- cx.fingerprints.insert(*unit, fingerprint.clone());
+ cx.fingerprints.insert(*unit, Arc::clone(&fingerprint));
Ok(fingerprint)
}
// 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 |_| {
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(())
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)
}
info!("end: {:?}", key);
self.active -= 1;
if self.active > 0 {
- assert!(tokens.len() > 0);
+ assert!(!tokens.is_empty());
drop(tokens.pop());
}
match result {
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,
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 {
}
}
-/// 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;
// 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!
}));
}
- 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)));
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)?
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);
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();
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);
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();
// 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 {
}
}
-/// 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>,
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);
}
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)
}
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| {
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);
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");
}
// 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 {
} 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() {
_ => 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>,
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());
}
}
}
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() {
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");
}
///
/// * 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)
}
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(());
}
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));
}
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>>();
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
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
}
}
}
}
-/// 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,
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,
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(|| {
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))
relative_path.display()
))?;
}
- } else {
- if no_include_option {
+ } else if no_include_option {
self.config
.shell()
.warn(format!(
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()
+ ))?;
}
}
None => break,
}
}
- return None;
+ None
}
fn list_files_git(&self, pkg: &Package, repo: git2::Repository,
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,
// 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;
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()),
"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)
));
let metadata = output
.split_whitespace()
- .filter(|arg| arg.starts_with("metadata="))
- .next()
+ .find(|arg| arg.starts_with("metadata="))
.unwrap();
let p = project("foo2")
extern crate hamcrest;
use std::env;
-use std::ffi::OsString;
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
/// 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);
}
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();
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();
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() {
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());
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);
}
// 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[..]);
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]);
#[test]
fn test_resolving_empty_dependency_list() {
- let res = resolve(pkg_id("root"), Vec::new(),
- &mut registry(vec![])).unwrap();
+ let res = resolve(&pkg_id("root"), Vec::new(),
+ ®istry(vec![])).unwrap();
assert_that(&res, equal_to(&names(&["root"])));
}
#[test]
fn test_resolving_only_package() {
let reg = registry(vec![pkg("foo")]);
- let res = resolve(pkg_id("root"), vec![dep("foo")], ®);
+ let res = resolve(&pkg_id("root"), vec![dep("foo")], ®);
assert_that(&res.unwrap(), contains(names(&["root", "foo"])).exactly());
}
#[test]
fn test_resolving_one_dep() {
let reg = registry(vec![pkg("foo"), pkg("bar")]);
- let res = resolve(pkg_id("root"), vec![dep("foo")], ®);
+ let res = resolve(&pkg_id("root"), vec![dep("foo")], ®);
assert_that(&res.unwrap(), contains(names(&["root", "foo"])).exactly());
}
#[test]
fn test_resolving_multiple_deps() {
let reg = registry(vec![pkg!("foo"), pkg!("bar"), pkg!("baz")]);
- let res = resolve(pkg_id("root"), vec![dep("foo"), dep("baz")],
+ let res = resolve(&pkg_id("root"), vec![dep("foo"), dep("baz")],
®).unwrap();
assert_that(&res, contains(names(&["root", "foo", "baz"])).exactly());
#[test]
fn test_resolving_transitive_deps() {
let reg = registry(vec![pkg!("foo"), pkg!("bar" => ["foo"])]);
- let res = resolve(pkg_id("root"), vec![dep("bar")], ®).unwrap();
+ let res = resolve(&pkg_id("root"), vec![dep("bar")], ®).unwrap();
assert_that(&res, contains(names(&["root", "foo", "bar"])));
}
#[test]
fn test_resolving_common_transitive_deps() {
let reg = registry(vec![pkg!("foo" => ["bar"]), pkg!("bar")]);
- let res = resolve(pkg_id("root"), vec![dep("foo"), dep("bar")],
+ let res = resolve(&pkg_id("root"), vec![dep("foo"), dep("bar")],
®).unwrap();
assert_that(&res, contains(names(&["root", "foo", "bar"])));
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")],
®);
pkg!("bat")
]);
- let res = resolve(pkg_id("root"),
+ let res = resolve(&pkg_id("root"),
vec![dep("foo"), dep_kind("baz", Development)],
®).unwrap();
pkg!(("foo", "1.0.2")),
]);
- let res = resolve(pkg_id("root"), vec![dep("foo")], ®).unwrap();
+ let res = resolve(&pkg_id("root"), vec![dep("foo")], ®).unwrap();
assert_that(&res, contains(names(&[("root", "1.0.0"),
("foo", "1.0.2")])));
pkg!(("foo", "1.0.2")),
]);
- let res = resolve(pkg_id("root"), vec![dep_req("foo", "=1.0.1")],
+ let res = resolve(&pkg_id("root"), vec![dep_req("foo", "=1.0.1")],
®).unwrap();
assert_that(&res, contains(names(&[("root", "1.0.0"),
pkg!("bar" => [dep_req("util", ">=1.0.1")]),
]);
- let res = resolve(pkg_id("root"), vec![dep_req("foo", "1.0.0"), dep_req("bar", "1.0.0")],
+ let res = resolve(&pkg_id("root"), vec![dep_req("foo", "1.0.0"), dep_req("bar", "1.0.0")],
®).unwrap();
assert_that(&res, contains(names(&[("root", "1.0.0"),
pkg!("bar" => [dep_req("foo", "=1.0.2")]),
]);
- assert!(resolve(pkg_id("root"), vec![
+ assert!(resolve(&pkg_id("root"), vec![
dep_req("foo", "=1.0.1"),
dep("bar"),
], ®).is_err());
pkg!("baz"),
]);
- let res = resolve(pkg_id("root"), vec![
+ let res = resolve(&pkg_id("root"), vec![
dep_req("foo", "^1"),
], ®).unwrap();
pkg!("d4" => [dep_req("foo", "0.2")]),
]);
- let res = resolve(pkg_id("root"), vec![
+ let res = resolve(&pkg_id("root"), vec![
dep("bar"),
], ®).unwrap();
pkg!(("dep_req", "2.0.0")),
]);
- let res = resolve(pkg_id("root"), vec![
+ let res = resolve(&pkg_id("root"), vec![
dep_req("foo", "1"),
], ®).unwrap();
let reg = registry(vec![
]);
- let res = resolve(pkg_id("root"), vec![
+ let res = resolve(&pkg_id("root"), vec![
dep_req("foo", "1"),
], ®);
assert!(res.is_err());
pkg!("foo" => ["foo"]),
]);
- let _ = resolve(pkg_id("root"), vec![
+ let _ = resolve(&pkg_id("root"), vec![
dep_req("foo", "1"),
], ®);
}
pkg!(("bar", "1.0.0") => [dep_req("foo", "1.0.0")]),
]);
- let res = resolve(pkg_id("root"), vec![
+ let res = resolve(&pkg_id("root"), vec![
dep_req("bar", "1"),
dep_req("foo", "=1.0.0"),
], ®).unwrap();
fn cargo_process(s: &str) -> ProcessBuilder {
let mut b = cargotest::cargo_process();
b.arg(s);
- return b
+ b
}
#[test]
// 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()