let library_paths = parsed_output.library_paths.iter().map(|l| {
l.display().to_string()
}).collect::<Vec<_>>();
- machine_message::emit(machine_message::BuildScript {
+ machine_message::emit(&machine_message::BuildScript {
package_id: &id,
linked_libs: &parsed_output.library_links,
linked_paths: &library_paths,
internal(&format!("compiler produced invalid json: `{}`", line))
})?;
- machine_message::emit(machine_message::FromCompiler {
+ machine_message::emit(&machine_message::FromCompiler {
package_id: &package_id,
target: &target,
message: compiler_message,
}
if json_messages {
- machine_message::emit(machine_message::Artifact {
+ machine_message::emit(&machine_message::Artifact {
package_id: &package_id,
target: &target,
profile: &profile,
let cfg_verbose = self.get_bool("term.verbose").unwrap_or(None).map(|v| v.val);
let cfg_color = self.get_string("term.color").unwrap_or(None).map(|v| v.val);
- let color = color.as_ref().or(cfg_color.as_ref());
+ let color = color.as_ref().or_else(|| cfg_color.as_ref());
let verbosity = match (verbose, cfg_verbose, quiet) {
(Some(true), _, None) |
path.display())
})?;
let toml = cargo_toml::parse(&contents,
- &path,
+ path,
self).chain_err(|| {
format!("could not parse TOML configuration in `{}`",
path.display())
})?;
- let value = CV::from_toml(&path, toml).chain_err(|| {
+ let value = CV::from_toml(path, toml).chain_err(|| {
format!("failed to load TOML configuration from `{}`",
path.display())
})?;
};
let registry = cfg.entry("registry".into())
- .or_insert(CV::Table(HashMap::new(), PathBuf::from(".")));
+ .or_insert_with(|| CV::Table(HashMap::new(), PathBuf::from(".")));
match (registry, value) {
(&mut CV::Table(ref mut old, _), CV::Table(ref mut new, _)) => {
let new = mem::replace(new, HashMap::new());
- for (key, value) in new.into_iter() {
+ for (key, value) in new {
old.insert(key, value);
}
}
/// as a path.
fn get_tool(&self, tool: &str) -> CargoResult<PathBuf> {
self.maybe_get_tool(tool)
- .map(|t| t.unwrap_or(PathBuf::from(tool)))
+ .map(|t| t.unwrap_or_else(|| PathBuf::from(tool)))
}
pub fn jobserver_from_env(&self) -> Option<&jobserver::Client> {
}
(&mut CV::Table(ref mut old, _), CV::Table(ref mut new, _)) => {
let new = mem::replace(new, HashMap::new());
- for (key, value) in new.into_iter() {
+ for (key, value) in new {
match old.entry(key.clone()) {
Occupied(mut entry) => {
let path = value.definition_path().to_path_buf();
}
}
+impl<K: Hash + Eq + Clone, V> Default for DependencyQueue<K, V> {
+ fn default() -> DependencyQueue<K, V> {
+ DependencyQueue::new()
+ }
+}
+
impl<K: Hash + Eq + Clone, V> DependencyQueue<K, V> {
/// Creates a new dependency queue with 0 packages.
pub fn new() -> DependencyQueue<K, V> {
}
fn is_human(&self) -> bool {
- match &self.0 {
- &CargoErrorKind::Msg(_) => true,
- &CargoErrorKind::TomlSer(_) => true,
- &CargoErrorKind::TomlDe(_) => true,
- &CargoErrorKind::Curl(_) => true,
- &CargoErrorKind::HttpNot200(..) => true,
- &CargoErrorKind::ProcessErrorKind(_) => true,
- &CargoErrorKind::CrateRegistry(_) => true,
- &CargoErrorKind::ParseSemver(_) |
- &CargoErrorKind::Semver(_) |
- &CargoErrorKind::Ignore(_) |
- &CargoErrorKind::Io(_) |
- &CargoErrorKind::SerdeJson(_) |
- &CargoErrorKind::ParseInt(_) |
- &CargoErrorKind::ParseBool(_) |
- &CargoErrorKind::Parse(_) |
- &CargoErrorKind::Git(_) |
- &CargoErrorKind::Internal(_) |
- &CargoErrorKind::CargoTestErrorKind(_) |
- &CargoErrorKind::__Nonexhaustive { .. } => false
+ match self.0 {
+ CargoErrorKind::Msg(_) |
+ CargoErrorKind::TomlSer(_) |
+ CargoErrorKind::TomlDe(_) |
+ CargoErrorKind::Curl(_) |
+ CargoErrorKind::HttpNot200(..) |
+ CargoErrorKind::ProcessErrorKind(_) |
+ CargoErrorKind::CrateRegistry(_) => true,
+ CargoErrorKind::ParseSemver(_) |
+ CargoErrorKind::Semver(_) |
+ CargoErrorKind::Ignore(_) |
+ CargoErrorKind::Io(_) |
+ CargoErrorKind::SerdeJson(_) |
+ CargoErrorKind::ParseInt(_) |
+ CargoErrorKind::ParseBool(_) |
+ CargoErrorKind::Parse(_) |
+ CargoErrorKind::Git(_) |
+ CargoErrorKind::Internal(_) |
+ CargoErrorKind::CargoTestErrorKind(_) |
+ CargoErrorKind::__Nonexhaustive { .. } => false
}
}
}
}
pub fn hint(&self) -> String {
- match &self.test {
- &Test::UnitTest(ref kind, ref name) => {
+ match self.test {
+ Test::UnitTest(ref kind, ref name) => {
match *kind {
TargetKind::Bench => format!("test failed, to rerun pass '--bench {}'", name),
TargetKind::Bin => format!("test failed, to rerun pass '--bin {}'", name),
_ => "test failed.".into()
}
},
- &Test::Doc => "test failed, to rerun pass '--doc'".into(),
+ Test::Doc => "test failed, to rerun pass '--doc'".into(),
_ => "test failed.".into()
}
}
/// Handles errors where other Cargo processes are also attempting to
/// concurrently create this directory.
pub fn create_dir(&self) -> io::Result<()> {
- return create_dir_all(&self.root);
+ create_dir_all(&self.root)
}
/// Returns an adaptor that can be used to print the path of this
fn create_dir_all(path: &Path) -> io::Result<()> {
match create_dir(path) {
- Ok(()) => return Ok(()),
+ Ok(()) => Ok(()),
Err(e) => {
if e.kind() == io::ErrorKind::NotFound {
if let Some(p) = path.parent() {
marks.insert(node.clone(), Mark::InProgress);
- for child in self.nodes[node].iter() {
+ for child in &self.nodes[node] {
self.visit(child, dst, marks);
}
}
}
+impl<N: Eq + Hash + Clone> Default for Graph<N> {
+ fn default() -> Graph<N> {
+ Graph::new()
+ }
+}
+
impl<N: fmt::Display + Eq + Hash> fmt::Debug for Graph<N> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
writeln!(fmt, "Graph {{")?;
- for (n, e) in self.nodes.iter() {
+ for (n, e) in &self.nodes {
writeln!(fmt, " - {}", n)?;
for n in e.iter() {
pub fn get_or_try_init<Error, F>(&self, init: F) -> Result<&T, Error>
where F: FnOnce() -> Result<T, Error>
{
- if self.borrow().is_none() {
- if self.fill(init()?).is_err() {
- unreachable!();
- }
+ if self.borrow().is_none() && self.fill(init()?).is_err() {
+ unreachable!();
}
Ok(self.borrow().unwrap())
}
fn reason(&self) -> &str;
}
-pub fn emit<T: Message>(t: T) {
- let mut json: Value = serde_json::to_value(&t).unwrap();
+pub fn emit<T: Message>(t: &T) {
+ let mut json: Value = serde_json::to_value(t).unwrap();
json["reason"] = json!(t.reason());
println!("{}", json);
}
use std::error::Error;
use error_chain::ChainedError;
-
use util::Config;
use util::errors::{CargoError, CargoErrorKind, CargoResult};
-
use git2;
+
fn maybe_spurious<E, EKind>(err: &E) -> bool
where E: ChainedError<ErrorKind=EKind> + 'static {
//Error inspection in non-verbose mode requires inspecting the
//the borrow's actual lifetime for purposes of downcasting and
//inspecting the error chain
unsafe fn extend_lifetime(r: &Error) -> &(Error + 'static) {
- std::mem::transmute::<&Error, &Error>(r)
+ std::mem::transmute::<&Error, &Error>(r)
}
for e in err.iter() {
_ => ()
}
}
- &CargoErrorKind::Curl(ref curl_err)
+ &CargoErrorKind::Curl(ref curl_err)
if curl_err.is_couldnt_connect() ||
curl_err.is_couldnt_resolve_proxy() ||
curl_err.is_couldnt_resolve_host() ||
/// Retry counts provided by Config object `net.retry`. Config shell outputs
/// a warning on per retry.
///
-/// Closure must return a CargoResult.
+/// Closure must return a `CargoResult`.
///
/// # Examples
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "`{}", self.program.to_string_lossy())?;
- for arg in self.args.iter() {
+ for arg in &self.args {
write!(f, " {}", escape(arg.to_string_lossy()))?;
}
if let Some(cwd) = self.get_cwd() {
command.current_dir(cwd);
}
- for arg in self.args.iter() {
+ for arg in &self.args {
command.arg(arg);
}
- for (k, v) in self.env.iter() {
+ for (k, v) in &self.env {
match *v {
Some(ref v) => { command.env(k, v); }
None => { command.env_remove(k); }
fn debug_string(&self) -> String {
let mut program = format!("{}", self.program.to_string_lossy());
- for arg in self.args.iter() {
+ for arg in &self.args {
program.push(' ');
program.push_str(&format!("{}", arg.to_string_lossy()));
}
let start = PROFILE_STACK.with(|stack| stack.borrow_mut().pop().unwrap());
let duration = start.elapsed();
- let duration_ms = duration.as_secs() * 1000 + (duration.subsec_nanos() / 1000000) as u64;
+ let duration_ms = duration.as_secs() * 1000 + u64::from(duration.subsec_nanos() / 1_000_000);
let stack_len = PROFILE_STACK.with(|stack| stack.borrow().len());
if stack_len == 0 {
let host = {
let triple = verbose_version.lines().find(|l| {
l.starts_with("host: ")
- }).map(|l| &l[6..]).ok_or(internal("rustc -v didn't have a line for `host:`"))?;
+ }).map(|l| &l[6..]).ok_or_else(|| internal("rustc -v didn't have a line for `host:`"))?;
triple.to_string()
};
Path::Root => {}
Path::Seq { parent, index } => {
stringify(dst, parent);
- if dst.len() > 0 {
- dst.push_str(".");
+ if !dst.is_empty() {
+ dst.push('.');
}
dst.push_str(&index.to_string());
}
Path::Map { parent, ref key } => {
stringify(dst, parent);
- if dst.len() > 0 {
- dst.push_str(".");
+ if !dst.is_empty() {
+ dst.push('.');
}
dst.push_str(key);
}
impl TomlManifest {
pub fn prepare_for_publish(&self) -> TomlManifest {
let mut package = self.package.as_ref()
- .or(self.project.as_ref())
+ .or_else(|| self.project.as_ref())
.unwrap()
.clone();
package.workspace = None;
bench: self.bench.clone(),
dependencies: map_deps(self.dependencies.as_ref()),
dev_dependencies: map_deps(self.dev_dependencies.as_ref()
- .or(self.dev_dependencies2.as_ref())),
+ .or_else(|| self.dev_dependencies2.as_ref())),
dev_dependencies2: None,
build_dependencies: map_deps(self.build_dependencies.as_ref()
- .or(self.build_dependencies2.as_ref())),
+ .or_else(|| self.build_dependencies2.as_ref())),
build_dependencies2: None,
features: self.features.clone(),
target: self.target.as_ref().map(|target_map| {
(k.clone(), TomlPlatform {
dependencies: map_deps(v.dependencies.as_ref()),
dev_dependencies: map_deps(v.dev_dependencies.as_ref()
- .or(v.dev_dependencies2.as_ref())),
+ .or_else(|| v.dev_dependencies2.as_ref())),
dev_dependencies2: None,
build_dependencies: map_deps(v.build_dependencies.as_ref()
- .or(v.build_dependencies2.as_ref())),
+ .or_else(|| v.build_dependencies2.as_ref())),
build_dependencies2: None,
})
}).collect()
process_dependencies(&mut cx, me.dependencies.as_ref(),
None)?;
let dev_deps = me.dev_dependencies.as_ref()
- .or(me.dev_dependencies2.as_ref());
+ .or_else(|| me.dev_dependencies2.as_ref());
process_dependencies(&mut cx, dev_deps, Some(Kind::Development))?;
let build_deps = me.build_dependencies.as_ref()
- .or(me.build_dependencies2.as_ref());
+ .or_else(|| me.build_dependencies2.as_ref());
process_dependencies(&mut cx, build_deps, Some(Kind::Build))?;
for (name, platform) in me.target.iter().flat_map(|t| t) {
process_dependencies(&mut cx, platform.dependencies.as_ref(),
None)?;
let build_deps = platform.build_dependencies.as_ref()
- .or(platform.build_dependencies2.as_ref());
+ .or_else(|| platform.build_dependencies2.as_ref());
process_dependencies(&mut cx, build_deps, Some(Kind::Build))?;
let dev_deps = platform.dev_dependencies.as_ref()
- .or(platform.dev_dependencies2.as_ref());
+ .or_else(|| platform.dev_dependencies2.as_ref());
process_dependencies(&mut cx, dev_deps, Some(Kind::Development))?;
}
{
let mut names_sources = HashMap::new();
- for dep in deps.iter() {
+ for dep in &deps {
let name = dep.name();
let prev = names_sources.insert(name, dep.source_id());
if prev.is_some() && prev != Some(dep.source_id()) {
}
}
- let exclude = project.exclude.clone().unwrap_or(Vec::new());
- let include = project.include.clone().unwrap_or(Vec::new());
+ let exclude = project.exclude.clone().unwrap_or_default();
+ let include = project.include.clone().unwrap_or_default();
let summary = Summary::new(pkgid, deps, me.features.clone()
.unwrap_or_else(HashMap::new))?;
homepage: project.homepage.clone(),
documentation: project.documentation.clone(),
readme: project.readme.clone(),
- authors: project.authors.clone().unwrap_or(Vec::new()),
+ authors: project.authors.clone().unwrap_or_default(),
license: project.license.clone(),
license_file: project.license_file.clone(),
repository: project.repository.clone(),
- keywords: project.keywords.clone().unwrap_or(Vec::new()),
- categories: project.categories.clone().unwrap_or(Vec::new()),
- badges: me.badges.clone().unwrap_or_else(HashMap::new),
+ keywords: project.keywords.clone().unwrap_or_default(),
+ categories: project.categories.clone().unwrap_or_default(),
+ badges: me.badges.clone().unwrap_or_default(),
};
let workspace_config = match (me.workspace.as_ref(),
(Some(config), None) => {
WorkspaceConfig::Root {
members: config.members.clone(),
- exclude: config.exclude.clone().unwrap_or(Vec::new()),
+ exclude: config.exclude.clone().unwrap_or_default(),
}
}
(None, root) => {
let publish = project.publish.unwrap_or(true);
let empty = Vec::new();
let cargo_features = me.cargo_features.as_ref().unwrap_or(&empty);
- let features = Features::new(&cargo_features, &mut warnings)?;
+ let features = Features::new(cargo_features, &mut warnings)?;
let mut manifest = Manifest::new(summary,
targets,
exclude,
workspace_config,
features,
project.im_a_teapot,
- me.clone());
+ Rc::clone(me));
if project.license_file.is_some() && project.license.is_some() {
manifest.add_warning("only one of `license` or \
`license-file` is necessary".to_string());
Some(ref config) => {
WorkspaceConfig::Root {
members: config.members.clone(),
- exclude: config.exclude.clone().unwrap_or(Vec::new()),
+ exclude: config.exclude.clone().unwrap_or_default(),
}
}
None => {
(&details.rev, "rev")
];
- for &(key, key_name) in git_only_keys.iter() {
+ for &(key, key_name) in &git_only_keys {
if key.is_some() {
let msg = format!("key `{}` is ignored for dependency ({}). \
This will be considered an error in future versions",
}
None => Dependency::parse_no_deprecated(name, version, &new_source_id)?,
};
- dep.set_features(details.features.unwrap_or(Vec::new()))
+ dep.set_features(details.features.unwrap_or_default())
.set_default_features(details.default_features
.or(details.default_features2)
.unwrap_or(true))
}
fn crate_types(&self) -> Option<&Vec<String>> {
- self.crate_type.as_ref().or(self.crate_type2.as_ref())
+ self.crate_type.as_ref().or_else(|| self.crate_type2.as_ref())
}
}
}
}
Some(TomlTarget {
- name: lib.name.clone().or(Some(package_name.to_owned())),
+ name: lib.name.clone().or_else(|| Some(package_name.to_owned())),
..lib.clone()
})
}
None => return Ok(None)
};
- validate_has_name(&lib, "library", "lib")?;
+ validate_has_name(lib, "library", "lib")?;
let path = match (lib.path.as_ref(), inferred) {
(Some(path), _) => package_root.join(&path.0),
}).collect()
};
- for bin in bins.iter() {
+ for bin in &bins {
validate_has_name(bin, "binary", "bin")?;
let name = bin.name();
validate_unique_names(&bins, "binary")?;
let mut result = Vec::new();
- for bin in bins.iter() {
+ for bin in &bins {
let path = target_path(bin, &inferred, "bin", package_root, &mut |_| {
if let Some(legacy_path) = legacy_bin_path(package_root, &bin.name(), has_lib) {
warnings.push(format!(
if path.exists() {
return Some(path);
}
- return None;
+ None
}
}
let inferred = infer_from_directory(&package_root.join("examples"));
let targets = clean_targets("example", "example",
- toml_examples, inferred,
+ toml_examples, &inferred,
package_root, errors)?;
let mut result = Vec::new();
let inferred = infer_from_directory(&package_root.join("tests"));
let targets = clean_targets("test", "test",
- toml_tests, inferred,
+ toml_tests, &inferred,
package_root, errors)?;
let mut result = Vec::new();
let inferred = infer_from_directory(&package_root.join("benches"));
let targets = clean_targets_with_legacy_path("benchmark", "bench",
- toml_benches, inferred,
+ toml_benches, &inferred,
package_root,
errors,
&mut legacy_bench_path)?;
fn clean_targets(target_kind_human: &str, target_kind: &str,
toml_targets: Option<&Vec<TomlTarget>>,
- inferred: Vec<(String, PathBuf)>,
+ inferred: &[(String, PathBuf)],
package_root: &Path,
errors: &mut Vec<String>)
-> CargoResult<Vec<(PathBuf, TomlTarget)>> {
fn clean_targets_with_legacy_path(target_kind_human: &str, target_kind: &str,
toml_targets: Option<&Vec<TomlTarget>>,
- inferred: Vec<(String, PathBuf)>,
+ inferred: &[(String, PathBuf)],
package_root: &Path,
errors: &mut Vec<String>,
legacy_path: &mut FnMut(&TomlTarget) -> Option<PathBuf>)
}).collect()
};
- for target in toml_targets.iter() {
+ for target in &toml_targets {
validate_has_name(target, target_kind_human, target_kind)?;
}
validate_unique_names(&toml_targets, target_kind)?;
let mut result = Vec::new();
for target in toml_targets {
- let path = target_path(&target, &inferred, target_kind, package_root, legacy_path);
+ let path = target_path(&target, inferred, target_kind, package_root, legacy_path);
let path = match path {
Ok(path) => path,
Err(e) => {
entries
.filter_map(|e| e.ok())
.filter(is_not_dotfile)
- .filter_map(infer_any)
+ .filter_map(|d| infer_any(&d))
.collect()
}
-fn infer_any(entry: DirEntry) -> Option<(String, PathBuf)> {
+fn infer_any(entry: &DirEntry) -> Option<(String, PathBuf)> {
if entry.path().extension().and_then(|p| p.to_str()) == Some("rs") {
infer_file(entry)
} else if entry.file_type().map(|t| t.is_dir()).ok() == Some(true) {
}
-fn infer_file(entry: DirEntry) -> Option<(String, PathBuf)> {
+fn infer_file(entry: &DirEntry) -> Option<(String, PathBuf)> {
let path = entry.path();
path
.file_stem()
- .and_then(|p| p.to_str())
+ .and_then(|p| p.to_str())
.map(|p| (p.to_owned(), path.clone()))
}
-fn infer_subdirectory(entry: DirEntry) -> Option<(String, PathBuf)> {
+fn infer_subdirectory(entry: &DirEntry) -> Option<(String, PathBuf)> {
let path = entry.path();
let main = path.join("main.rs");
let name = path.file_name().and_then(|n| n.to_str());
fn configure(toml: &TomlTarget, target: &mut Target) {
let t2 = target.clone();
- target.set_tested(toml.test.unwrap_or(t2.tested()))
- .set_doc(toml.doc.unwrap_or(t2.documented()))
- .set_doctest(toml.doctest.unwrap_or(t2.doctested()))
- .set_benched(toml.bench.unwrap_or(t2.benched()))
- .set_harness(toml.harness.unwrap_or(t2.harness()))
+ target.set_tested(toml.test.unwrap_or_else(|| t2.tested()))
+ .set_doc(toml.doc.unwrap_or_else(|| t2.documented()))
+ .set_doctest(toml.doctest.unwrap_or_else(|| t2.doctested()))
+ .set_benched(toml.bench.unwrap_or_else(|| t2.benched()))
+ .set_harness(toml.harness.unwrap_or_else(|| t2.harness()))
.set_for_host(match (toml.plugin, toml.proc_macro()) {
(None, None) => t2.for_host(),
(Some(true), _) | (_, Some(true)) => true,