From 1a92e183f67e7f77616f758ffabedd70ab92f5e7 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Thu, 11 Apr 2019 15:52:27 +0700 Subject: [PATCH] Fix most of clippy warnings --- download/src/lib.rs | 12 +-- src/cli/common.rs | 32 +++---- src/cli/download_tracker.rs | 2 +- src/cli/log.rs | 10 +- src/cli/proxy_mode.rs | 4 +- src/cli/rustup_mode.rs | 70 +++++++------- src/cli/self_update.rs | 148 +++++++++++++++--------------- src/cli/setup_mode.rs | 2 +- src/cli/term2.rs | 8 +- src/config.rs | 35 +++---- src/dist/component/components.rs | 14 ++- src/dist/component/package.rs | 10 +- src/dist/component/transaction.rs | 6 +- src/dist/config.rs | 18 ++-- src/dist/dist.rs | 29 +++--- src/dist/download.rs | 18 ++-- src/dist/manifest.rs | 30 +++--- src/dist/manifestation.rs | 77 ++++++++-------- src/dist/prefix.rs | 4 +- src/dist/temp.rs | 10 +- src/install.rs | 4 +- src/settings.rs | 14 +-- src/toolchain.rs | 51 +++++----- src/utils/raw.rs | 14 +-- src/utils/utils.rs | 49 +++++----- tests/cli-rustup.rs | 8 +- tests/cli-v2.rs | 2 +- 27 files changed, 335 insertions(+), 346 deletions(-) diff --git a/download/src/lib.rs b/download/src/lib.rs index 9a58e7ed84..1d3ddfc9d7 100644 --- a/download/src/lib.rs +++ b/download/src/lib.rs @@ -266,7 +266,7 @@ pub mod reqwest_be { if !res.status().is_success() { let code: u16 = res.status().into(); - return Err(ErrorKind::HttpStatus(code as u32).into()); + return Err(ErrorKind::HttpStatus(u32::from(code)).into()); } let buffer_size = 0x10000; @@ -345,13 +345,13 @@ pub mod reqwest_be { return Err(ErrorKind::FileNotFound.into()); } - let ref mut f = fs::File::open(src).chain_err(|| "unable to open downloaded file")?; - io::Seek::seek(f, io::SeekFrom::Start(resume_from))?; + let mut f = fs::File::open(src).chain_err(|| "unable to open downloaded file")?; + io::Seek::seek(&mut f, io::SeekFrom::Start(resume_from))?; - let ref mut buffer = vec![0u8; 0x10000]; + let mut buffer = vec![0u8; 0x10000]; loop { - let bytes_read = - io::Read::read(f, buffer).chain_err(|| "unable to read downloaded file")?; + let bytes_read = io::Read::read(&mut f, &mut buffer) + .chain_err(|| "unable to read downloaded file")?; if bytes_read == 0 { break; } diff --git a/src/cli/common.rs b/src/cli/common.rs index 19ac6edbf7..8b9515bc88 100644 --- a/src/cli/common.rs +++ b/src/cli/common.rs @@ -100,7 +100,7 @@ pub fn read_line() -> Result { lines .next() .and_then(|l| l.ok()) - .ok_or("unable to read from stdin for confirmation".into()) + .ok_or_else(|| "unable to read from stdin for confirmation".into()) } pub fn set_globals(verbose: bool) -> Result { @@ -146,8 +146,8 @@ fn show_channel_updates( toolchains: Vec<(String, rustup::Result)>, ) -> Result<()> { let data = toolchains.into_iter().map(|(name, result)| { - let ref toolchain = cfg.get_toolchain(&name, false).expect(""); - let version = rustc_version(toolchain); + let toolchain = cfg.get_toolchain(&name, false).expect(""); + let version = rustc_version(&toolchain); let banner; let color; @@ -195,7 +195,7 @@ fn show_channel_updates( let _ = t.reset(); let _ = writeln!(t, " - {}", version); } - let _ = writeln!(t, ""); + let _ = writeln!(t); Ok(()) } @@ -355,20 +355,18 @@ pub fn list_toolchains(cfg: &Cfg) -> Result<()> { if toolchains.is_empty() { println!("no installed toolchains"); + } else if let Ok(Some(def_toolchain)) = cfg.find_default() { + for toolchain in toolchains { + let if_default = if def_toolchain.name() == &*toolchain { + " (default)" + } else { + "" + }; + println!("{}{}", &toolchain, if_default); + } } else { - if let Ok(Some(def_toolchain)) = cfg.find_default() { - for toolchain in toolchains { - let if_default = if def_toolchain.name() == &*toolchain { - " (default)" - } else { - "" - }; - println!("{}{}", &toolchain, if_default); - } - } else { - for toolchain in toolchains { - println!("{}", &toolchain); - } + for toolchain in toolchains { + println!("{}", &toolchain); } } Ok(()) diff --git a/src/cli/download_tracker.rs b/src/cli/download_tracker.rs index baf8811734..b2d0124a9e 100644 --- a/src/cli/download_tracker.rs +++ b/src/cli/download_tracker.rs @@ -105,7 +105,7 @@ impl DownloadTracker { if self.displayed_progress { // Display the finished state self.display(); - let _ = writeln!(self.term.as_mut().unwrap(), ""); + let _ = writeln!(self.term.as_mut().unwrap()); } self.prepare_for_new_download(); } diff --git a/src/cli/log.rs b/src/cli/log.rs index 2b8b0f0391..4e7a07462d 100644 --- a/src/cli/log.rs +++ b/src/cli/log.rs @@ -27,7 +27,7 @@ pub fn warn_fmt(args: fmt::Arguments<'_>) { let _ = write!(t, "warning: "); let _ = t.reset(); let _ = t.write_fmt(args); - let _ = write!(t, "\n"); + let _ = writeln!(t); } pub fn err_fmt(args: fmt::Arguments<'_>) { @@ -37,7 +37,7 @@ pub fn err_fmt(args: fmt::Arguments<'_>) { let _ = write!(t, "error: "); let _ = t.reset(); let _ = t.write_fmt(args); - let _ = write!(t, "\n"); + let _ = writeln!(t); } pub fn info_fmt(args: fmt::Arguments<'_>) { @@ -46,7 +46,7 @@ pub fn info_fmt(args: fmt::Arguments<'_>) { let _ = write!(t, "info: "); let _ = t.reset(); let _ = t.write_fmt(args); - let _ = write!(t, "\n"); + let _ = writeln!(t); } pub fn verbose_fmt(args: fmt::Arguments<'_>) { @@ -56,7 +56,7 @@ pub fn verbose_fmt(args: fmt::Arguments<'_>) { let _ = write!(t, "verbose: "); let _ = t.reset(); let _ = t.write_fmt(args); - let _ = write!(t, "\n"); + let _ = writeln!(t); } pub fn debug_fmt(args: fmt::Arguments<'_>) { @@ -67,6 +67,6 @@ pub fn debug_fmt(args: fmt::Arguments<'_>) { let _ = write!(t, "verbose: "); let _ = t.reset(); let _ = t.write_fmt(args); - let _ = write!(t, "\n"); + let _ = writeln!(t); } } diff --git a/src/cli/proxy_mode.rs b/src/cli/proxy_mode.rs index 4b21e760f6..17c74532d0 100644 --- a/src/cli/proxy_mode.rs +++ b/src/cli/proxy_mode.rs @@ -22,7 +22,7 @@ pub fn main() -> Result<()> { .as_ref() .and_then(|a| a.file_name()) .and_then(|a| a.to_str()); - let ref arg0 = arg0.ok_or(ErrorKind::NoExeName)?; + let arg0 = arg0.ok_or(ErrorKind::NoExeName)?; // Check for a toolchain specifier. let arg1 = args.next(); @@ -41,7 +41,7 @@ pub fn main() -> Result<()> { let cfg = set_globals(false)?; cfg.check_metadata_version()?; - direct_proxy(&cfg, arg0, toolchain, &cmd_args)? + direct_proxy(&cfg, &arg0, toolchain, &cmd_args)? }; process::exit(c) diff --git a/src/cli/rustup_mode.rs b/src/cli/rustup_mode.rs index 7ceca2802d..783752592f 100644 --- a/src/cli/rustup_mode.rs +++ b/src/cli/rustup_mode.rs @@ -26,11 +26,11 @@ fn handle_epipe(res: Result<()>) -> Result<()> { pub fn main() -> Result<()> { crate::self_update::cleanup_self_updater()?; - let ref matches = cli().get_matches(); + let matches = cli().get_matches(); let verbose = matches.is_present("verbose"); - let ref cfg = common::set_globals(verbose)?; + let cfg = &common::set_globals(verbose)?; - if maybe_upgrade_data(cfg, matches)? { + if maybe_upgrade_data(cfg, &matches)? { return Ok(()); } @@ -408,7 +408,7 @@ pub fn cli() -> App<'static, 'static> { ) .args( &DOCS_DATA - .into_iter() + .iter() .map(|(name, help_msg, _)| Arg::with_name(name).long(name).help(help_msg)) .collect::>(), ) @@ -421,7 +421,7 @@ pub fn cli() -> App<'static, 'static> { .group( ArgGroup::with_name("page").args( &DOCS_DATA - .into_iter() + .iter() .map(|(name, _, _)| *name) .collect::>(), ), @@ -497,7 +497,7 @@ fn update_bare_triple_check(cfg: &Cfg, name: &str) -> Result<()> { warn!("(partial) target triple specified instead of toolchain name"); let installed_toolchains = cfg.list_toolchains()?; let default = cfg.find_default()?; - let default_name = default.map(|t| t.name().to_string()).unwrap_or("".into()); + let default_name = default.map(|t| t.name().to_string()).unwrap_or_default(); let mut candidates = vec![]; for t in installed_toolchains { if t == default_name { @@ -545,11 +545,11 @@ fn default_bare_triple_check(cfg: &Cfg, name: &str) -> Result<()> { if let Some(triple) = PartialTargetTriple::from_str(name) { warn!("(partial) target triple specified instead of toolchain name"); let default = cfg.find_default()?; - let default_name = default.map(|t| t.name().to_string()).unwrap_or("".into()); + let default_name = default.map(|t| t.name().to_string()).unwrap_or_default(); if let Ok(mut desc) = PartialToolchainDesc::from_str(&default_name) { desc.target = triple; let maybe_toolchain = format!("{}", desc); - let ref toolchain = cfg.get_toolchain(maybe_toolchain.as_ref(), false)?; + let toolchain = cfg.get_toolchain(maybe_toolchain.as_ref(), false)?; if toolchain.name() == default_name { warn!( "(partial) triple '{}' resolves to a toolchain that is already default", @@ -569,9 +569,9 @@ fn default_bare_triple_check(cfg: &Cfg, name: &str) -> Result<()> { fn default_(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { if m.is_present("toolchain") { - let ref toolchain = m.value_of("toolchain").expect(""); + let toolchain = m.value_of("toolchain").expect(""); default_bare_triple_check(cfg, toolchain)?; - let ref toolchain = cfg.get_toolchain(toolchain, false)?; + let toolchain = cfg.get_toolchain(toolchain, false)?; let status = if !toolchain.is_custom() { Some(toolchain.install_from_dist_if_not_installed()?) @@ -634,7 +634,7 @@ fn update(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { } fn run(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { - let ref toolchain = m.value_of("toolchain").expect(""); + let toolchain = m.value_of("toolchain").expect(""); let args = m.values_of("command").unwrap(); let args: Vec<_> = args.collect(); let cmd = cfg.create_command_for_toolchain(toolchain, m.is_present("install"), args[0])?; @@ -669,9 +669,9 @@ fn show(cfg: &Cfg) -> Result<()> { writeln!(t)?; } - let ref cwd = utils::current_dir()?; + let cwd = utils::current_dir()?; let installed_toolchains = cfg.list_toolchains()?; - let active_toolchain = cfg.find_override_toolchain_or_default(cwd); + let active_toolchain = cfg.find_override_toolchain_or_default(&cwd); // active_toolchain will carry the reason we don't have one in its detail. let active_targets = if let Ok(ref at) = active_toolchain { @@ -791,8 +791,8 @@ fn show(cfg: &Cfg) -> Result<()> { } fn show_active_toolchain(cfg: &Cfg) -> Result<()> { - let ref cwd = utils::current_dir()?; - if let Some((toolchain, reason)) = cfg.find_override_toolchain_or_default(cwd)? { + let cwd = utils::current_dir()?; + if let Some((toolchain, reason)) = cfg.find_override_toolchain_or_default(&cwd)? { if reason.is_some() { println!("{} ({})", toolchain.name(), reason.unwrap()); } else { @@ -895,18 +895,20 @@ fn explicit_or_dir_toolchain<'a>(cfg: &'a Cfg, m: &ArgMatches<'_>) -> Result) -> Result<()> { - let ref toolchain = m.value_of("toolchain").expect(""); - let ref path = m.value_of("path").expect(""); + let toolchain = m.value_of("toolchain").expect(""); + let path = m.value_of("path").expect(""); let toolchain = cfg.get_toolchain(toolchain, true)?; - Ok(toolchain.install_from_dir(Path::new(path), true)?) + toolchain + .install_from_dir(Path::new(path), true) + .map_err(|e| e.into()) } fn toolchain_remove(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { @@ -918,7 +920,7 @@ fn toolchain_remove(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { } fn override_add(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { - let ref toolchain = m.value_of("toolchain").expect(""); + let toolchain = m.value_of("toolchain").expect(""); let toolchain = cfg.get_toolchain(toolchain, false)?; let status = if !toolchain.is_custom() { @@ -957,12 +959,10 @@ fn override_remove(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { info!("no nonexistent paths detected"); } list + } else if m.is_present("path") { + vec![m.value_of("path").unwrap().to_string()] } else { - if m.is_present("path") { - vec![m.value_of("path").unwrap().to_string()] - } else { - vec![utils::current_dir()?.to_str().unwrap().to_string()] - } + vec![utils::current_dir()?.to_str().unwrap().to_string()] }; for path in paths { @@ -984,7 +984,7 @@ fn override_remove(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { Ok(()) } -const DOCS_DATA: &[(&'static str, &'static str, &'static str,)] = &[ +const DOCS_DATA: &[(&str, &str, &str,)] = &[ // flags can be used to open specific documents, e.g. `rustup doc --nomicon` // tuple elements: document name used as flag, help message, document index path ("alloc", "The Rust core allocation and collections library", "alloc/index.html"), @@ -1006,21 +1006,19 @@ const DOCS_DATA: &[(&'static str, &'static str, &'static str,)] = &[ fn doc(cfg: &Cfg, m: &ArgMatches<'_>) -> Result<()> { let toolchain = explicit_or_dir_toolchain(cfg, m)?; - let doc_url = if let Some((_, _, path)) = DOCS_DATA - .into_iter() - .find(|(name, _, _)| m.is_present(name)) - { - path - } else { - "index.html" - }; + let doc_url = + if let Some((_, _, path)) = DOCS_DATA.iter().find(|(name, _, _)| m.is_present(name)) { + path + } else { + "index.html" + }; if m.is_present("path") { let doc_path = toolchain.doc_path(doc_url)?; println!("{}", doc_path.display()); Ok(()) } else { - Ok(toolchain.open_docs(doc_url)?) + toolchain.open_docs(doc_url).map_err(Into::into) } } diff --git a/src/cli/self_update.rs b/src/cli/self_update.rs index df857e779d..cf1cd9c7fa 100644 --- a/src/cli/self_update.rs +++ b/src/cli/self_update.rs @@ -205,7 +205,7 @@ fn canonical_cargo_home() -> Result { let mut path_str = path.to_string_lossy().to_string(); let default_cargo_home = utils::home_dir() - .unwrap_or(PathBuf::from(".")) + .unwrap_or_else(|| PathBuf::from(".")) .join(".cargo"); if default_cargo_home == path { if cfg!(unix) { @@ -240,7 +240,7 @@ pub fn install(no_prompt: bool, verbose: bool, mut opts: InstallOpts) -> Result< } if !no_prompt { - let ref msg = pre_install_msg(opts.no_modify_path)?; + let msg = pre_install_msg(opts.no_modify_path)?; term2::stdout().md(msg); @@ -270,9 +270,9 @@ pub fn install(no_prompt: bool, verbose: bool, mut opts: InstallOpts) -> Result< maybe_install_rust(&opts.default_toolchain, &opts.default_host_triple, verbose)?; if cfg!(unix) { - let ref env_file = utils::cargo_home()?.join("env"); - let ref env_str = format!("{}\n", shell_export_string()?); - utils::write_file("env", env_file, env_str)?; + let env_file = utils::cargo_home()?.join("env"); + let env_str = format!("{}\n", shell_export_string()?); + utils::write_file("env", &env_file, &env_str)?; } Ok(()) @@ -301,18 +301,16 @@ pub fn install(no_prompt: bool, verbose: bool, mut opts: InstallOpts) -> Result< } else { format!(post_install_msg_win!(), cargo_home = cargo_home) } + } else if cfg!(unix) { + format!( + post_install_msg_unix_no_modify_path!(), + cargo_home = cargo_home + ) } else { - if cfg!(unix) { - format!( - post_install_msg_unix_no_modify_path!(), - cargo_home = cargo_home - ) - } else { - format!( - post_install_msg_win_no_modify_path!(), - cargo_home = cargo_home - ) - } + format!( + post_install_msg_win_no_modify_path!(), + cargo_home = cargo_home + ) }; term2::stdout().md(msg); @@ -444,8 +442,6 @@ fn do_pre_install_options_sanity_checks(opts: &InstallOpts) -> Result<()> { fn do_anti_sudo_check(no_prompt: bool) -> Result<()> { #[cfg(unix)] pub fn home_mismatch() -> bool { - use libc as c; - use std::env; use std::ffi::CStr; use std::mem; @@ -462,13 +458,13 @@ fn do_anti_sudo_check(no_prompt: bool) -> Result<()> { return false; } let mut buf = [0u8; 1024]; - let mut pwd = unsafe { mem::uninitialized::() }; - let mut pwdp: *mut c::passwd = ptr::null_mut(); + let mut pwd = unsafe { mem::uninitialized::() }; + let mut pwdp: *mut libc::passwd = ptr::null_mut(); let rv = unsafe { - c::getpwuid_r( - c::geteuid(), + libc::getpwuid_r( + libc::geteuid(), &mut pwd, - mem::transmute(&mut buf), + &mut buf as *mut [u8] as *mut i8, buf.len(), &mut pwdp, ) @@ -611,26 +607,26 @@ fn customize_install(mut opts: InstallOpts) -> Result { } fn install_bins() -> Result<()> { - let ref bin_path = utils::cargo_home()?.join("bin"); - let ref this_exe_path = utils::current_exe()?; - let ref rustup_path = bin_path.join(&format!("rustup{}", EXE_SUFFIX)); + let bin_path = utils::cargo_home()?.join("bin"); + let this_exe_path = utils::current_exe()?; + let rustup_path = bin_path.join(&format!("rustup{}", EXE_SUFFIX)); - utils::ensure_dir_exists("bin", bin_path, &|_| {})?; + utils::ensure_dir_exists("bin", &bin_path, &|_| {})?; // NB: Even on Linux we can't just copy the new binary over the (running) // old binary; we must unlink it first. if rustup_path.exists() { - utils::remove_file("rustup-bin", rustup_path)?; + utils::remove_file("rustup-bin", &rustup_path)?; } - utils::copy_file(this_exe_path, rustup_path)?; - utils::make_executable(rustup_path)?; + utils::copy_file(&this_exe_path, &rustup_path)?; + utils::make_executable(&rustup_path)?; install_proxies() } pub fn install_proxies() -> Result<()> { - let ref bin_path = utils::cargo_home()?.join("bin"); - let ref rustup_path = bin_path.join(&format!("rustup{}", EXE_SUFFIX)); + let bin_path = utils::cargo_home()?.join("bin"); + let rustup_path = bin_path.join(&format!("rustup{}", EXE_SUFFIX)); - let rustup = Handle::from_path(rustup_path)?; + let rustup = Handle::from_path(&rustup_path)?; let mut tool_handles = Vec::new(); let mut link_afterwards = Vec::new(); @@ -668,8 +664,8 @@ pub fn install_proxies() -> Result<()> { } for tool in DUP_TOOLS { - let ref tool_path = bin_path.join(&format!("{}{}", tool, EXE_SUFFIX)); - if let Ok(handle) = Handle::from_path(tool_path) { + let tool_path = bin_path.join(&format!("{}{}", tool, EXE_SUFFIX)); + if let Ok(handle) = Handle::from_path(&tool_path) { // Like above, don't clobber anything that's already hardlinked to // avoid extraneous errors from being returned. if rustup == handle { @@ -694,19 +690,19 @@ pub fn install_proxies() -> Result<()> { continue; } } - utils::hard_or_symlink_file(rustup_path, tool_path)?; + utils::hard_or_symlink_file(&rustup_path, &tool_path)?; } drop(tool_handles); for path in link_afterwards { - utils::hard_or_symlink_file(rustup_path, &path)?; + utils::hard_or_symlink_file(&rustup_path, &path)?; } Ok(()) } fn maybe_install_rust(toolchain_str: &str, default_host_triple: &str, verbose: bool) -> Result<()> { - let ref cfg = common::set_globals(verbose)?; + let cfg = common::set_globals(verbose)?; // If there is already an install, then `toolchain_str` may not be // a toolchain the user actually wants. Don't do anything. FIXME: @@ -722,7 +718,7 @@ fn maybe_install_rust(toolchain_str: &str, default_host_triple: &str, verbose: b let status = toolchain.install_from_dist(false)?; cfg.set_default(toolchain_str)?; println!(); - common::show_channel_update(cfg, toolchain_str, Ok(status))?; + common::show_channel_update(&cfg, toolchain_str, Ok(status))?; } else { info!("updating existing rustup installation"); println!(); @@ -738,7 +734,7 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { process::exit(1); } - let ref cargo_home = utils::cargo_home()?; + let cargo_home = utils::cargo_home()?; if !cargo_home .join(&format!("bin/rustup{}", EXE_SUFFIX)) @@ -749,7 +745,7 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { if !no_prompt { println!(); - let ref msg = format!(pre_uninstall_msg!(), cargo_home = canonical_cargo_home()?); + let msg = format!(pre_uninstall_msg!(), cargo_home = canonical_cargo_home()?); term2::stdout().md(msg); if !common::confirm("\nContinue? (y/N)", false)? { info!("aborting uninstallation"); @@ -760,9 +756,9 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { info!("removing rustup home"); // Delete RUSTUP_HOME - let ref rustup_dir = utils::rustup_home()?; + let rustup_dir = utils::rustup_home()?; if rustup_dir.exists() { - utils::remove_dir("rustup_home", rustup_dir, &|_| {})?; + utils::remove_dir("rustup_home", &rustup_dir, &|_| {})?; } let read_dir_err = "failure reading directory"; @@ -770,13 +766,13 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { info!("removing cargo home"); // Remove CARGO_HOME/bin from PATH - let ref remove_path_methods = get_remove_path_methods()?; - do_remove_from_path(remove_path_methods)?; + let remove_path_methods = get_remove_path_methods()?; + do_remove_from_path(&remove_path_methods)?; // Delete everything in CARGO_HOME *except* the rustup bin // First everything except the bin directory - for dirent in fs::read_dir(cargo_home).chain_err(|| read_dir_err)? { + for dirent in fs::read_dir(&cargo_home).chain_err(|| read_dir_err)? { let dirent = dirent.chain_err(|| read_dir_err)?; if dirent.file_name().to_str() != Some("bin") { if dirent.path().is_dir() { @@ -821,8 +817,8 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { #[cfg(unix)] fn delete_rustup_and_cargo_home() -> Result<()> { - let ref cargo_home = utils::cargo_home()?; - utils::remove_dir("cargo_home", cargo_home, &|_| ())?; + let cargo_home = utils::cargo_home()?; + utils::remove_dir("cargo_home", &cargo_home, &|_| ())?; Ok(()) } @@ -863,9 +859,9 @@ fn delete_rustup_and_cargo_home() -> Result<()> { use std::time::Duration; // CARGO_HOME, hopefully empty except for bin/rustup.exe - let ref cargo_home = utils::cargo_home()?; + let cargo_home = utils::cargo_home()?; // The rustup.exe bin - let ref rustup_path = cargo_home.join(&format!("bin/rustup{}", EXE_SUFFIX)); + let rustup_path = cargo_home.join(&format!("bin/rustup{}", EXE_SUFFIX)); // The directory containing CARGO_HOME let work_path = cargo_home @@ -890,7 +886,7 @@ fn delete_rustup_and_cargo_home() -> Result<()> { unsafe { // Copy rustup (probably this process's exe) to the gc exe - utils::copy_file(rustup_path, &gc_exe)?; + utils::copy_file(&rustup_path, &gc_exe)?; let mut gc_exe_win: Vec<_> = gc_exe.as_os_str().encode_wide().collect(); gc_exe_win.push(0); @@ -947,8 +943,8 @@ pub fn complete_windows_uninstall() -> Result<()> { wait_for_parent()?; // Now that the parent has exited there are hopefully no more files open in CARGO_HOME - let ref cargo_home = utils::cargo_home()?; - utils::remove_dir("cargo_home", cargo_home, &|_| ())?; + let cargo_home = utils::cargo_home()?; + utils::remove_dir("cargo_home", &cargo_home, &|_| ())?; // Now, run a *system* binary to inherit the DELETE_ON_CLOSE // handle to *this* process, then exit. The OS will delete the gc @@ -1100,9 +1096,9 @@ fn do_add_to_path(methods: &[PathUpdateMethod]) -> Result<()> { } else { String::new() }; - let ref addition = format!("\n{}", shell_export_string()?); - if !file.contains(addition) { - utils::append_file("rcfile", rcpath, addition)?; + let addition = format!("\n{}", shell_export_string()?); + if !file.contains(&addition) { + utils::append_file("rcfile", rcpath, &addition)?; } } else { unreachable!() @@ -1219,9 +1215,9 @@ fn get_remove_path_methods() -> Result> { let export_str = shell_export_string()?; let matching_rcfiles = existing_rcfiles.filter(|f| { - let file = utils::read_file("rcfile", f).unwrap_or(String::new()); - let ref addition = format!("\n{}", export_str); - file.contains(addition) + let file = utils::read_file("rcfile", f).unwrap_or_default(); + let addition = format!("\n{}", export_str); + file.contains(&addition) }); Ok(matching_rcfiles.map(PathUpdateMethod::RcFile).collect()) @@ -1246,11 +1242,11 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { return Ok(()); }; - let ref path_str = utils::cargo_home()? + let path_str = utils::cargo_home()? .join("bin") .to_string_lossy() .to_string(); - let idx = if let Some(i) = old_path.find(path_str) { + let idx = if let Some(i) = old_path.find(&path_str) { i } else { return Ok(()); @@ -1317,8 +1313,8 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { if let Some(i) = idx { let mut new_file_bytes = file_bytes[..i].to_vec(); new_file_bytes.extend(&file_bytes[i + addition_bytes.len()..]); - let ref new_file = String::from_utf8(new_file_bytes).unwrap(); - utils::write_file("rcfile", rcpath, new_file)?; + let new_file = String::from_utf8(new_file_bytes).unwrap(); + utils::write_file("rcfile", rcpath, &new_file)?; } else { // Weird case. rcfile no longer needs to be modified? } @@ -1392,16 +1388,16 @@ fn parse_new_rustup_version(version: String) -> String { } pub fn prepare_update() -> Result> { - let ref cargo_home = utils::cargo_home()?; - let ref rustup_path = cargo_home.join(&format!("bin/rustup{}", EXE_SUFFIX)); - let ref setup_path = cargo_home.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); + let cargo_home = utils::cargo_home()?; + let rustup_path = cargo_home.join(&format!("bin/rustup{}", EXE_SUFFIX)); + let setup_path = cargo_home.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); if !rustup_path.exists() { return Err(ErrorKind::NotSelfInstalled(cargo_home.clone()).into()); } if setup_path.exists() { - utils::remove_file("setup", setup_path)?; + utils::remove_file("setup", &setup_path)?; } // Get build triple @@ -1419,7 +1415,7 @@ pub fn prepare_update() -> Result> { build_triple }; - let update_root = env::var("RUSTUP_UPDATE_ROOT").unwrap_or(String::from(UPDATE_ROOT)); + let update_root = env::var("RUSTUP_UPDATE_ROOT").unwrap_or_else(|_| String::from(UPDATE_ROOT)); let tempdir = TempDir::new("rustup-update").chain_err(|| "error creating temp directory")?; @@ -1438,15 +1434,15 @@ pub fn prepare_update() -> Result> { let schema = release_toml .get("schema-version") - .ok_or(Error::from("no schema key in rustup release file"))? + .ok_or_else(|| Error::from("no schema key in rustup release file"))? .as_str() - .ok_or(Error::from("invalid schema key in rustup release file"))?; + .ok_or_else(|| Error::from("invalid schema key in rustup release file"))?; let available_version = release_toml .get("version") - .ok_or(Error::from("no version key in rustup release file"))? + .ok_or_else(|| Error::from("no version key in rustup release file"))? .as_str() - .ok_or(Error::from("invalid version key in rustup release file"))?; + .ok_or_else(|| Error::from("invalid version key in rustup release file"))?; if schema != "1" { return Err(Error::from(&*format!( @@ -1474,9 +1470,9 @@ pub fn prepare_update() -> Result> { utils::download_file(&download_url, &setup_path, None, &|_| ())?; // Mark as executable - utils::make_executable(setup_path)?; + utils::make_executable(&setup_path)?; - Ok(Some(setup_path.to_owned())) + Ok(Some(setup_path)) } /// Tell the upgrader to replace the rustup bins, then delete @@ -1532,10 +1528,10 @@ pub fn self_replace() -> Result<()> { pub fn cleanup_self_updater() -> Result<()> { let cargo_home = utils::cargo_home()?; - let ref setup = cargo_home.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); + let setup = cargo_home.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); if setup.exists() { - utils::remove_file("setup", setup)?; + utils::remove_file("setup", &setup)?; } Ok(()) diff --git a/src/cli/setup_mode.rs b/src/cli/setup_mode.rs index 77a5f349eb..d2379663b7 100644 --- a/src/cli/setup_mode.rs +++ b/src/cli/setup_mode.rs @@ -60,7 +60,7 @@ pub fn main() -> Result<()> { let opts = InstallOpts { default_host_triple: default_host, default_toolchain: default_toolchain.to_owned(), - no_modify_path: no_modify_path, + no_modify_path, }; self_update::install(no_prompt, verbose, opts)?; diff --git a/src/cli/term2.rs b/src/cli/term2.rs index ea7aebee00..aba93bd8b4 100644 --- a/src/cli/term2.rs +++ b/src/cli/term2.rs @@ -67,7 +67,7 @@ struct LineWrapper<'a, T: io::Write> { impl<'a, T: io::Write + 'a> LineWrapper<'a, T> { // Just write a newline fn write_line(&mut self) { - let _ = writeln!(self.w, ""); + let _ = writeln!(self.w); // Reset column position to start of line self.pos = 0; } @@ -126,10 +126,10 @@ impl<'a, T: io::Write + 'a> LineWrapper<'a, T> { // Constructor fn new(w: &'a mut T, indent: u32, margin: u32) -> Self { LineWrapper { - indent: indent, - margin: margin, + indent, + margin, pos: indent, - w: w, + w, } } } diff --git a/src/config.rs b/src/config.rs index 7717d21bbc..648792affc 100644 --- a/src/config.rs +++ b/src/config.rs @@ -97,17 +97,17 @@ impl Cfg { let dist_root = dist_root_server.clone() + "/dist"; let cfg = Cfg { - rustup_dir: rustup_dir, - settings_file: settings_file, - toolchains_dir: toolchains_dir, - update_hash_dir: update_hash_dir, - download_dir: download_dir, - temp_cfg: temp_cfg, - gpg_key: gpg_key, - notify_handler: notify_handler, - env_override: env_override, + rustup_dir, + settings_file, + toolchains_dir, + update_hash_dir, + download_dir, + temp_cfg, + gpg_key, + notify_handler, + env_override, dist_root_url: dist_root, - dist_root_server: dist_root_server, + dist_root_server, }; // Run some basic checks against the constructed configuration @@ -206,9 +206,9 @@ impl Cfg { pub fn delete_data(&self) -> Result<()> { if utils::path_exists(&self.rustup_dir) { - Ok(utils::remove_dir("home", &self.rustup_dir, &|n| { + utils::remove_dir("home", &self.rustup_dir, &|n| { (self.notify_handler)(n.into()) - })?) + }) } else { Ok(()) } @@ -254,9 +254,10 @@ impl Cfg { // on a line after the proximate error. let reason_err = match reason { - OverrideReason::Environment => format!( + OverrideReason::Environment => { "the RUSTUP_TOOLCHAIN environment variable specifies an uninstalled toolchain" - ), + .to_string() + } OverrideReason::OverrideDB(ref path) => format!( "the directory override for '{}' specifies an uninstalled toolchain", path.display() @@ -413,7 +414,7 @@ impl Cfg { path: &Path, ) -> Result<(Toolchain<'_>, Option)> { self.find_override_toolchain_or_default(path) - .and_then(|r| r.ok_or("no default toolchain configured".into())) + .and_then(|r| r.ok_or_else(|| "no default toolchain configured".into())) } pub fn create_command_for_dir(&self, path: &Path, binary: &str) -> Result { @@ -432,12 +433,12 @@ impl Cfg { install_if_missing: bool, binary: &str, ) -> Result { - let ref toolchain = self.get_toolchain(toolchain, false)?; + let toolchain = self.get_toolchain(toolchain, false)?; if install_if_missing && !toolchain.exists() { toolchain.install_from_dist(false)?; } - if let Some(cmd) = self.maybe_do_cargo_fallback(toolchain, binary)? { + if let Some(cmd) = self.maybe_do_cargo_fallback(&toolchain, binary)? { Ok(cmd) } else { toolchain.create_command(binary) diff --git a/src/dist/component/components.rs b/src/dist/component/components.rs index c46fa0a655..a5718388f9 100644 --- a/src/dist/component/components.rs +++ b/src/dist/component/components.rs @@ -11,7 +11,7 @@ use crate::dist::component::transaction::Transaction; use std::fs::File; use std::path::{Path, PathBuf}; -const COMPONENTS_FILE: &'static str = "components"; +const COMPONENTS_FILE: &str = "components"; #[derive(Clone, Debug)] pub struct Components { @@ -20,7 +20,7 @@ pub struct Components { impl Components { pub fn open(prefix: InstallPrefix) -> Result { - let c = Components { prefix: prefix }; + let c = Components { prefix }; // Validate that the metadata uses a format we know if let Some(v) = c.read_version()? { @@ -74,12 +74,12 @@ impl Components { components: self.clone(), name: name.to_owned(), parts: Vec::new(), - tx: tx, + tx, } } pub fn find(&self, name: &str) -> Result> { let result = self.list()?; - Ok(result.into_iter().filter(|c| (c.name() == name)).next()) + Ok(result.into_iter().find(|c| (c.name() == name))) } pub fn prefix(&self) -> InstallPrefix { self.prefix.clone() @@ -151,7 +151,7 @@ impl ComponentPart { format!("{}:{}", &self.0, &self.1.to_string_lossy()) } pub fn decode(line: &str) -> Option { - line.find(":") + line.find(':') .map(|pos| ComponentPart(line[0..pos].to_owned(), PathBuf::from(&line[(pos + 1)..]))) } } @@ -277,9 +277,7 @@ impl Component { } } }; - if self.path_buf.is_none() { - return None; - } + self.path_buf.as_ref()?; let full_path = self.prefix.join(self.path_buf.as_ref().unwrap()); let empty = match read_dir(full_path) { Ok(dir) => dir.count() == 0, diff --git a/src/dist/component/package.rs b/src/dist/component/package.rs index b83dbb6ed3..930604b9f7 100644 --- a/src/dist/component/package.rs +++ b/src/dist/component/package.rs @@ -16,8 +16,8 @@ use std::io::Read; use std::path::{Path, PathBuf}; /// The current metadata revision used by rust-installer -pub const INSTALLER_VERSION: &'static str = "3"; -pub const VERSION_FILE: &'static str = "rust-installer-version"; +pub const INSTALLER_VERSION: &str = "3"; +pub const VERSION_FILE: &str = "rust-installer-version"; pub trait Package: fmt::Debug { fn contains(&self, component: &str, short_name: Option<&str>) -> bool; @@ -45,9 +45,9 @@ impl DirectoryPackage { let content = utils::read_file("package components", &path.join("components"))?; let components = content.lines().map(|l| l.to_owned()).collect(); Ok(DirectoryPackage { - path: path, - components: components, - copy: copy, + path, + components, + copy, }) } } diff --git a/src/dist/component/transaction.rs b/src/dist/component/transaction.rs index 1edd65489f..ca4f57071c 100644 --- a/src/dist/component/transaction.rs +++ b/src/dist/component/transaction.rs @@ -46,10 +46,10 @@ impl<'a> Transaction<'a> { notify_handler: &'a dyn Fn(Notification<'_>), ) -> Self { Transaction { - prefix: prefix, + prefix, changes: Vec::new(), - temp_cfg: temp_cfg, - notify_handler: notify_handler, + temp_cfg, + notify_handler, committed: false, } } diff --git a/src/dist/config.rs b/src/dist/config.rs index 0e63707755..761174e728 100644 --- a/src/dist/config.rs +++ b/src/dist/config.rs @@ -2,8 +2,8 @@ use super::manifest::Component; use crate::errors::*; use crate::utils::toml_utils::*; -pub const SUPPORTED_CONFIG_VERSIONS: [&'static str; 1] = ["1"]; -pub const DEFAULT_CONFIG_VERSION: &'static str = "1"; +pub const SUPPORTED_CONFIG_VERSIONS: [&str; 1] = ["1"]; +pub const DEFAULT_CONFIG_VERSION: &str = "1"; #[derive(Clone, Debug)] pub struct Config { @@ -24,10 +24,10 @@ impl Config { Ok(Config { config_version: version, - components: components, + components, }) } - pub fn to_toml(self) -> toml::value::Table { + pub fn into_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); result.insert( "config_version".to_owned(), @@ -46,7 +46,7 @@ impl Config { } pub fn stringify(self) -> String { - toml::Value::Table(self.to_toml()).to_string() + toml::Value::Table(self.into_toml()).to_string() } fn toml_to_components(arr: toml::value::Array, path: &str) -> Result> { @@ -65,12 +65,18 @@ impl Config { fn components_to_toml(components: Vec) -> toml::value::Array { let mut result = toml::value::Array::new(); for v in components { - result.push(toml::Value::Table(v.to_toml())); + result.push(toml::Value::Table(v.into_toml())); } result } pub fn new() -> Self { + Default::default() + } +} + +impl Default for Config { + fn default() -> Self { Config { config_version: DEFAULT_CONFIG_VERSION.to_owned(), components: Vec::new(), diff --git a/src/dist/dist.rs b/src/dist/dist.rs index 2f2e9e27bf..e011961992 100644 --- a/src/dist/dist.rs +++ b/src/dist/dist.rs @@ -14,10 +14,10 @@ use std::path::Path; use regex::Regex; -pub const DEFAULT_DIST_SERVER: &'static str = "https://static.rust-lang.org"; +pub const DEFAULT_DIST_SERVER: &str = "https://static.rust-lang.org"; // Deprecated -pub const DEFAULT_DIST_ROOT: &'static str = "https://static.rust-lang.org/dist"; +pub const DEFAULT_DIST_ROOT: &str = "https://static.rust-lang.org/dist"; // A toolchain descriptor from rustup's perspective. These contain // 'partial target triples', which allow toolchain names like @@ -100,14 +100,14 @@ static LIST_ENVS: &'static [&'static str] = &[ // Hence we could distinguish between the variants with compile-time cfg() // attributes alone. #[cfg(all(not(windows), target_endian = "big"))] -const TRIPLE_MIPS_UNKNOWN_LINUX_GNU: &'static str = "mips-unknown-linux-gnu"; +const TRIPLE_MIPS_UNKNOWN_LINUX_GNU: &str = "mips-unknown-linux-gnu"; #[cfg(all(not(windows), target_endian = "little"))] -const TRIPLE_MIPS_UNKNOWN_LINUX_GNU: &'static str = "mipsel-unknown-linux-gnu"; +const TRIPLE_MIPS_UNKNOWN_LINUX_GNU: &str = "mipsel-unknown-linux-gnu"; #[cfg(all(not(windows), target_endian = "big"))] -const TRIPLE_MIPS64_UNKNOWN_LINUX_GNUABI64: &'static str = "mips64-unknown-linux-gnuabi64"; +const TRIPLE_MIPS64_UNKNOWN_LINUX_GNUABI64: &str = "mips64-unknown-linux-gnuabi64"; #[cfg(all(not(windows), target_endian = "little"))] -const TRIPLE_MIPS64_UNKNOWN_LINUX_GNUABI64: &'static str = "mips64el-unknown-linux-gnuabi64"; +const TRIPLE_MIPS64_UNKNOWN_LINUX_GNUABI64: &str = "mips64el-unknown-linux-gnuabi64"; impl TargetTriple { pub fn from_str(name: &str) -> Self { @@ -371,7 +371,7 @@ impl ToolchainDesc { target: TargetTriple(c.get(3).unwrap().as_str().to_owned()), } }) - .ok_or(ErrorKind::InvalidToolchainName(name.to_string()).into()) + .ok_or_else(|| ErrorKind::InvalidToolchainName(name.to_string()).into()) } pub fn manifest_v1_url(&self, dist_root: &str) -> String { @@ -397,7 +397,7 @@ impl ToolchainDesc { pub fn package_dir(&self, dist_root: &str) -> String { match self.date { - None => format!("{}", dist_root), + None => dist_root.to_string(), Some(ref date) => format!("{}/{}", dist_root, date), } } @@ -554,7 +554,7 @@ pub fn update_from_dist_<'a>( changes, force_update, &download, - download.notify_handler.clone(), + &download.notify_handler, &toolchain.manifest_name(), )? { UpdateStatus::Unchanged => Ok(None), @@ -592,7 +592,7 @@ pub fn update_from_dist_<'a>( &manifest, update_hash, &download.temp_cfg, - download.notify_handler.clone(), + &download.notify_handler, ) { Ok(None) => Ok(None), Ok(Some(hash)) => Ok(Some(hash)), @@ -626,12 +626,9 @@ fn dl_v2_manifest<'a>( Ok(Some((manifest, manifest_hash))) } else { - match *manifest_dl_res.as_ref().unwrap_err().kind() { - // Checksum failed - issue warning to try again later - ErrorKind::ChecksumFailed { .. } => { - (download.notify_handler)(Notification::ManifestChecksumFailedHack) - } - _ => {} + // Checksum failed - issue warning to try again later + if let ErrorKind::ChecksumFailed { .. } = manifest_dl_res.as_ref().unwrap_err().kind() { + (download.notify_handler)(Notification::ManifestChecksumFailedHack) } Err(manifest_dl_res.unwrap_err()) } diff --git a/src/dist/download.rs b/src/dist/download.rs index 946714a965..6af4168b3d 100644 --- a/src/dist/download.rs +++ b/src/dist/download.rs @@ -77,21 +77,21 @@ impl<'a> DownloadCfg<'a> { if hash != actual_hash { // Incorrect hash - return Err(ErrorKind::ChecksumFailed { + Err(ErrorKind::ChecksumFailed { url: url.to_string(), expected: hash.to_string(), calculated: actual_hash, } - .into()); + .into()) } else { (self.notify_handler)(Notification::ChecksumValid(&url.to_string())); utils::rename_file("downloaded", &partial_file_path, &target_file)?; - return Ok(File { path: target_file }); + Ok(File { path: target_file }) } } - pub fn clean(&self, hashes: &Vec) -> Result<()> { + pub fn clean(&self, hashes: &[String]) -> Result<()> { for hash in hashes.iter() { let used_file = self.download_dir.join(hash); if self.download_dir.join(&used_file).exists() { @@ -171,15 +171,11 @@ fn file_hash(path: &Path) -> Result { use std::io::Read; let mut downloaded = fs::File::open(&path).chain_err(|| "opening already downloaded file")?; let mut buf = vec![0; 32768]; - loop { - if let Ok(n) = downloaded.read(&mut buf) { - if n == 0 { - break; - } - hasher.input(&buf[..n]); - } else { + while let Ok(n) = downloaded.read(&mut buf) { + if n == 0 { break; } + hasher.input(&buf[..n]); } Ok(format!("{:x}", hasher.result())) diff --git a/src/dist/manifest.rs b/src/dist/manifest.rs index 1b81c152f3..e12a22ff70 100644 --- a/src/dist/manifest.rs +++ b/src/dist/manifest.rs @@ -16,8 +16,8 @@ use crate::utils::toml_utils::*; use crate::dist::dist::TargetTriple; use std::collections::HashMap; -pub const SUPPORTED_MANIFEST_VERSIONS: [&'static str; 1] = ["2"]; -pub const DEFAULT_MANIFEST_VERSION: &'static str = "2"; +pub const SUPPORTED_MANIFEST_VERSIONS: [&str; 1] = ["2"]; +pub const DEFAULT_MANIFEST_VERSION: &str = "2"; #[derive(Clone, Debug, PartialEq)] pub struct Manifest { @@ -70,7 +70,7 @@ impl Manifest { Ok(manifest) } pub fn stringify(self) -> String { - toml::Value::Table(self.to_toml()).to_string() + toml::Value::Table(self.into_toml()).to_string() } pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { @@ -87,7 +87,7 @@ impl Manifest { reverse_renames, }) } - pub fn to_toml(self) -> toml::value::Table { + pub fn into_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); result.insert("date".to_owned(), toml::Value::String(self.date)); @@ -123,7 +123,7 @@ impl Manifest { fn packages_to_table(packages: HashMap) -> toml::value::Table { let mut result = toml::value::Table::new(); for (k, v) in packages { - result.insert(k, toml::Value::Table(v.to_toml())); + result.insert(k, toml::Value::Table(v.into_toml())); } result } @@ -180,13 +180,13 @@ impl Manifest { fn validate(&self) -> Result<()> { // Every component mentioned must have an actual package to download - for (_, pkg) in &self.packages { + for pkg in self.packages.values() { match pkg.targets { PackageTargets::Wildcard(ref tpkg) => { self.validate_targeted_package(tpkg)?; } PackageTargets::Targeted(ref tpkgs) => { - for (_, tpkg) in tpkgs { + for tpkg in tpkgs.values() { self.validate_targeted_package(tpkg)?; } } @@ -222,7 +222,7 @@ impl Package { targets: Self::toml_to_targets(table, path)?, }) } - pub fn to_toml(self) -> toml::value::Table { + pub fn into_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); result.insert("version".to_owned(), toml::Value::String(self.version)); @@ -257,11 +257,11 @@ impl Package { let mut result = toml::value::Table::new(); match targets { PackageTargets::Wildcard(tpkg) => { - result.insert("*".to_owned(), toml::Value::Table(tpkg.to_toml())); + result.insert("*".to_owned(), toml::Value::Table(tpkg.into_toml())); } PackageTargets::Targeted(tpkgs) => { for (k, v) in tpkgs { - result.insert(k.to_string(), toml::Value::Table(v.to_toml())); + result.insert(k.to_string(), toml::Value::Table(v.into_toml())); } } } @@ -329,7 +329,7 @@ impl TargetedPackage { }) } } - pub fn to_toml(self) -> toml::value::Table { + pub fn into_toml(self) -> toml::value::Table { let extensions = Self::components_to_toml(self.extensions); let components = Self::components_to_toml(self.components); let mut result = toml::value::Table::new(); @@ -372,7 +372,7 @@ impl TargetedPackage { fn components_to_toml(components: Vec) -> toml::value::Array { let mut result = toml::value::Array::new(); for v in components { - result.push(toml::Value::Table(v.to_toml())); + result.push(toml::Value::Table(v.into_toml())); } result } @@ -400,7 +400,7 @@ impl Component { })?, }) } - pub fn to_toml(self) -> toml::value::Table { + pub fn into_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); result.insert( "target".to_owned(), @@ -418,7 +418,7 @@ impl Component { if let Some(ref t) = self.target { format!("{}-{}", pkg, t) } else { - format!("{}", pkg) + pkg } } pub fn short_name(&self, manifest: &Manifest) -> String { @@ -444,7 +444,7 @@ impl Component { if let Some(ref t) = self.target { format!("{}-{}", pkg, t) } else { - format!("{}", pkg) + pkg.to_string() } } } diff --git a/src/dist/manifestation.rs b/src/dist/manifestation.rs index 21bc0cb6de..a875af5548 100644 --- a/src/dist/manifestation.rs +++ b/src/dist/manifestation.rs @@ -13,8 +13,8 @@ use crate::errors::*; use crate::utils::utils; use std::path::Path; -pub const DIST_MANIFEST: &'static str = "multirust-channel-manifest.toml"; -pub const CONFIG_FILE: &'static str = "multirust-config.toml"; +pub const DIST_MANIFEST: &str = "multirust-channel-manifest.toml"; +pub const CONFIG_FILE: &str = "multirust-config.toml"; enum Format { Gz, @@ -116,8 +116,8 @@ impl Manifestation { // Some vars we're going to need a few times let temp_cfg = download_cfg.temp_cfg; let prefix = self.installation.prefix(); - let ref rel_installed_manifest_path = prefix.rel_manifest_file(DIST_MANIFEST); - let ref installed_manifest_path = prefix.path().join(rel_installed_manifest_path); + let rel_installed_manifest_path = prefix.rel_manifest_file(DIST_MANIFEST); + let installed_manifest_path = prefix.path().join(&rel_installed_manifest_path); // Create the lists of components needed for installation let update = Update::build_update(self, new_manifest, changes, notify_handler)?; @@ -169,8 +169,8 @@ impl Manifestation { // If the previous installation was from a v1 manifest we need // to uninstall it first. - let ref config = self.read_config()?; - tx = self.maybe_handle_v2_upgrade(config, tx)?; + let config = self.read_config()?; + tx = self.maybe_handle_v2_upgrade(&config, tx)?; // Uninstall components for component in update.components_to_uninstall { @@ -185,7 +185,7 @@ impl Manifestation { component.target.as_ref(), )); - tx = self.uninstall_component(&component, new_manifest, tx, notify_handler.clone())?; + tx = self.uninstall_component(&component, new_manifest, tx, ¬ify_handler)?; } // Install components @@ -194,7 +194,7 @@ impl Manifestation { // names are not the same as the dist manifest component // names. Some are just the component name some are the // component name plus the target triple. - let ref pkg_name = component.name_in_manifest(); + let pkg_name = component.name_in_manifest(); let short_pkg_name = component.short_name_in_manifest(); let short_name = component.short_name(new_manifest); @@ -224,17 +224,17 @@ impl Manifestation { // If the package doesn't contain the component that the // manifest says it does then somebody must be playing a joke on us. - if !package.contains(pkg_name, Some(&short_pkg_name)) { + if !package.contains(&pkg_name, Some(&short_pkg_name)) { return Err(ErrorKind::CorruptComponent(short_name).into()); } - tx = package.install(&self.installation, pkg_name, Some(&short_pkg_name), tx)?; + tx = package.install(&self.installation, &pkg_name, Some(&short_pkg_name), tx)?; } // Install new distribution manifest - let ref new_manifest_str = new_manifest.clone().stringify(); + let new_manifest_str = new_manifest.clone().stringify(); tx.modify_file(rel_installed_manifest_path.to_owned())?; - utils::write_file("manifest", installed_manifest_path, new_manifest_str)?; + utils::write_file("manifest", &installed_manifest_path, &new_manifest_str)?; // Write configuration. // @@ -244,11 +244,11 @@ impl Manifestation { // name/target. Needs to be fixed in rust-installer. let mut config = Config::new(); config.components = update.final_component_list; - let ref config_str = config.stringify(); - let ref rel_config_path = prefix.rel_manifest_file(CONFIG_FILE); - let ref config_path = prefix.path().join(rel_config_path); + let config_str = config.stringify(); + let rel_config_path = prefix.rel_manifest_file(CONFIG_FILE); + let config_path = prefix.path().join(&rel_config_path); tx.modify_file(rel_config_path.to_owned())?; - utils::write_file("dist config", config_path, config_str)?; + utils::write_file("dist config", &config_path, &config_str)?; // End transaction tx.commit(); @@ -270,9 +270,8 @@ impl Manifestation { // Read configuration and delete it let rel_config_path = prefix.rel_manifest_file(CONFIG_FILE); - let ref config_str = - utils::read_file("dist config", &prefix.path().join(&rel_config_path))?; - let config = Config::parse(config_str)?; + let config_str = utils::read_file("dist config", &prefix.path().join(&rel_config_path))?; + let config = Config::parse(&config_str)?; tx.remove_file("dist config", rel_config_path)?; for component in config.components { @@ -294,8 +293,8 @@ impl Manifestation { // names are not the same as the dist manifest component // names. Some are just the component name some are the // component name plus the target triple. - let ref name = component.name_in_manifest(); - let ref short_name = component.short_name_in_manifest(); + let name = component.name_in_manifest(); + let short_name = component.short_name_in_manifest(); if let Some(c) = self.installation.find(&name)? { tx = c.uninstall(tx)?; } else if let Some(c) = self.installation.find(&short_name)? { @@ -313,11 +312,11 @@ impl Manifestation { // for v2 installations. pub fn read_config(&self) -> Result> { let prefix = self.installation.prefix(); - let ref rel_config_path = prefix.rel_manifest_file(CONFIG_FILE); - let ref config_path = prefix.path().join(rel_config_path); - if utils::path_exists(config_path) { - let ref config_str = utils::read_file("dist config", config_path)?; - Ok(Some(Config::parse(config_str)?)) + let rel_config_path = prefix.rel_manifest_file(CONFIG_FILE); + let config_path = prefix.path().join(rel_config_path); + if utils::path_exists(&config_path) { + let config_str = utils::read_file("dist config", &config_path)?; + Ok(Some(Config::parse(&config_str)?)) } else { Ok(None) } @@ -325,10 +324,10 @@ impl Manifestation { pub fn load_manifest(&self) -> Result> { let prefix = self.installation.prefix(); - let ref old_manifest_path = prefix.manifest_file(DIST_MANIFEST); - if utils::path_exists(old_manifest_path) { - let ref manifest_str = utils::read_file("installed manifest", old_manifest_path)?; - Ok(Some(Manifest::parse(manifest_str)?)) + let old_manifest_path = prefix.manifest_file(DIST_MANIFEST); + if utils::path_exists(&old_manifest_path) { + let manifest_str = utils::read_file("installed manifest", &old_manifest_path)?; + Ok(Some(Manifest::parse(&manifest_str)?)) } else { Ok(None) } @@ -376,8 +375,8 @@ impl Manifestation { let dlcfg = DownloadCfg { dist_root: "bogus", download_dir: &dld_dir, - temp_cfg: temp_cfg, - notify_handler: notify_handler, + temp_cfg, + notify_handler, }; let dl = dlcfg.download_and_check(&url, update_hash, ".tar.gz")?; @@ -468,7 +467,7 @@ impl Update { let starting_list = config .as_ref() .map(|c| c.components.clone()) - .unwrap_or(Vec::new()); + .unwrap_or_default(); let mut result = Update { components_to_uninstall: vec![], @@ -510,12 +509,10 @@ impl Update { for component in &result.final_component_list { if !starting_list.contains(component) { result.components_to_install.push(component.clone()); - } else { - if changes.add_extensions.contains(&component) { - notify_handler(Notification::ComponentAlreadyInstalled( - &component.description(new_manifest), - )); - } + } else if changes.add_extensions.contains(&component) { + notify_handler(Notification::ComponentAlreadyInstalled( + &component.description(new_manifest), + )); } } } else { @@ -603,7 +600,7 @@ impl Update { if self .final_component_list .iter() - .any(|c| &c.short_name_in_manifest() == pkg) + .any(|c| c.short_name_in_manifest() == pkg) { None } else { diff --git a/src/dist/prefix.rs b/src/dist/prefix.rs index b6a80d4f6e..b602ca17d0 100644 --- a/src/dist/prefix.rs +++ b/src/dist/prefix.rs @@ -1,6 +1,6 @@ use std::path::{Path, PathBuf}; -const REL_MANIFEST_DIR: &'static str = "lib/rustlib"; +const REL_MANIFEST_DIR: &str = "lib/rustlib"; #[derive(Clone, Debug)] pub struct InstallPrefix { @@ -8,7 +8,7 @@ pub struct InstallPrefix { } impl InstallPrefix { pub fn from(path: PathBuf) -> Self { - InstallPrefix { path: path } + InstallPrefix { path } } pub fn path(&self) -> &Path { &self.path diff --git a/src/dist/temp.rs b/src/dist/temp.rs index bea1ed93e2..3ea60ed516 100644 --- a/src/dist/temp.rs +++ b/src/dist/temp.rs @@ -109,13 +109,13 @@ impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> ::std::result::Result<(), fmt::Error> { use self::Error::*; match *self { - CreatingRoot { ref path, error: _ } => { + CreatingRoot { ref path, .. } => { write!(f, "could not create temp root: {}", path.display()) } - CreatingFile { ref path, error: _ } => { + CreatingFile { ref path, .. } => { write!(f, "could not create temp file: {}", path.display()) } - CreatingDirectory { ref path, error: _ } => { + CreatingDirectory { ref path, .. } => { write!(f, "could not create temp directory: {}", path.display()) } } @@ -129,9 +129,9 @@ impl Cfg { notify_handler: Box)>, ) -> Self { Cfg { - root_directory: root_directory, + root_directory, dist_server: dist_server.to_owned(), - notify_handler: notify_handler, + notify_handler, } } diff --git a/src/install.rs b/src/install.rs index f4f9cf1152..ab5c2d4519 100644 --- a/src/install.rs +++ b/src/install.rs @@ -100,7 +100,5 @@ impl<'a> InstallMethod<'a> { } pub fn uninstall(path: &Path, notify_handler: &dyn Fn(Notification<'_>)) -> Result<()> { - Ok(utils::remove_dir("install", path, &|n| { - notify_handler(n.into()) - })?) + utils::remove_dir("install", path, &|n| notify_handler(n.into())) } diff --git a/src/settings.rs b/src/settings.rs index b7d4440c07..983a5ad9d8 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -6,8 +6,8 @@ use std::cell::RefCell; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -pub const SUPPORTED_METADATA_VERSIONS: [&'static str; 2] = ["2", "12"]; -pub const DEFAULT_METADATA_VERSION: &'static str = "12"; +pub const SUPPORTED_METADATA_VERSIONS: [&str; 2] = ["2", "12"]; +pub const DEFAULT_METADATA_VERSION: &str = "12"; #[derive(Clone, Debug, PartialEq)] pub struct SettingsFile { @@ -18,7 +18,7 @@ pub struct SettingsFile { impl SettingsFile { pub fn new(path: PathBuf) -> Self { SettingsFile { - path: path, + path, cache: RefCell::new(None), } } @@ -118,7 +118,7 @@ impl Settings { notify_handler: &dyn Fn(Notification<'_>), ) -> Option { let key = Self::path_to_key(dir, notify_handler); - self.overrides.get(&key).map(|s| s.clone()) + self.overrides.get(&key).cloned() } pub fn parse(data: &str) -> Result { @@ -126,7 +126,7 @@ impl Settings { Self::from_toml(value, "") } pub fn stringify(self) -> String { - toml::Value::Table(self.to_toml()).to_string() + toml::Value::Table(self.into_toml()).to_string() } pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { @@ -135,13 +135,13 @@ impl Settings { return Err(ErrorKind::UnknownMetadataVersion(version).into()); } Ok(Settings { - version: version, + version, default_host_triple: get_opt_string(&mut table, "default_host_triple", path)?, default_toolchain: get_opt_string(&mut table, "default_toolchain", path)?, overrides: Self::table_to_overrides(&mut table, path)?, }) } - pub fn to_toml(self) -> toml::value::Table { + pub fn into_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); result.insert("version".to_owned(), toml::Value::String(self.version)); diff --git a/src/toolchain.rs b/src/toolchain.rs index c1910dc5a0..aadca5e5a8 100644 --- a/src/toolchain.rs +++ b/src/toolchain.rs @@ -47,7 +47,7 @@ impl<'a> Toolchain<'a> { let resolved_name = cfg.resolve_toolchain(name)?; let path = cfg.toolchains_dir.join(&resolved_name); Ok(Toolchain { - cfg: cfg, + cfg, name: resolved_name, path: path.clone(), dist_handler: Box::new(move |n| (cfg.notify_handler)(n.into())), @@ -80,7 +80,7 @@ impl<'a> Toolchain<'a> { utils::is_directory(&self.path) || is_symlink } pub fn verify(&self) -> Result<()> { - Ok(utils::assert_is_directory(&self.path)?) + utils::assert_is_directory(&self.path) } pub fn remove(&self) -> Result<()> { if self.exists() || self.is_symlink() { @@ -96,7 +96,7 @@ impl<'a> Toolchain<'a> { if !self.exists() { (self.cfg.notify_handler)(Notification::UninstalledToolchain(&self.name)); } - Ok(result?) + result } fn install(&self, install_method: InstallMethod<'_>) -> Result { assert!(self.is_valid_install_method(install_method)); @@ -384,11 +384,11 @@ impl<'a> Toolchain<'a> { #[cfg(not(target_os = "macos"))] mod sysenv { - pub const LOADER_PATH: &'static str = "LD_LIBRARY_PATH"; + pub const LOADER_PATH: &str = "LD_LIBRARY_PATH"; } #[cfg(target_os = "macos")] mod sysenv { - pub const LOADER_PATH: &'static str = "DYLD_LIBRARY_PATH"; + pub const LOADER_PATH: &str = "DYLD_LIBRARY_PATH"; } env_var::prepend_path(sysenv::LOADER_PATH, vec![new_path.clone()], cmd); @@ -423,17 +423,17 @@ impl<'a> Toolchain<'a> { pub fn open_docs(&self, relative: &str) -> Result<()> { self.verify()?; - Ok(utils::open_browser(&self.doc_path(relative)?)?) + utils::open_browser(&self.doc_path(relative)?) } pub fn make_default(&self) -> Result<()> { self.cfg.set_default(&self.name) } pub fn make_override(&self, path: &Path) -> Result<()> { - Ok(self.cfg.settings_file.with_mut(|s| { + self.cfg.settings_file.with_mut(|s| { s.add_override(path, self.name.clone(), self.cfg.notify_handler.as_ref()); Ok(()) - })?) + }) } pub fn list_components(&self) -> Result> { @@ -442,7 +442,7 @@ impl<'a> Toolchain<'a> { } let toolchain = &self.name; - let ref toolchain = ToolchainDesc::from_str(toolchain) + let toolchain = ToolchainDesc::from_str(toolchain) .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))?; let prefix = InstallPrefix::from(self.path.to_owned()); @@ -473,10 +473,12 @@ impl<'a> Toolchain<'a> { // Get the component so we can check if it is available let component_pkg = manifest .get_package(&component.short_name_in_manifest()) - .expect(&format!( - "manifest should contain component {}", - &component.short_name(&manifest) - )); + .unwrap_or_else(|_| { + panic!( + "manifest should contain component {}", + &component.short_name(&manifest) + ) + }); let component_target_pkg = component_pkg .targets .get(&toolchain.target) @@ -500,10 +502,12 @@ impl<'a> Toolchain<'a> { // Get the component so we can check if it is available let extension_pkg = manifest .get_package(&extension.short_name_in_manifest()) - .expect(&format!( - "manifest should contain extension {}", - &extension.short_name(&manifest) - )); + .unwrap_or_else(|_| { + panic!( + "manifest should contain extension {}", + &extension.short_name(&manifest) + ) + }); let extension_target_pkg = extension_pkg .targets .get(&toolchain.target) @@ -532,7 +536,7 @@ impl<'a> Toolchain<'a> { } let toolchain = &self.name; - let ref toolchain = ToolchainDesc::from_str(toolchain) + let toolchain = ToolchainDesc::from_str(toolchain) .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))?; let prefix = InstallPrefix::from(self.path.to_owned()); @@ -556,13 +560,14 @@ impl<'a> Toolchain<'a> { if targ_pkg.components.contains(&component) { // Treat it as a warning, see https://github.com/rust-lang/rustup.rs/issues/441 - return Ok(println!( + eprintln!( "{}", ErrorKind::AddingRequiredComponent( self.name.to_string(), component.description(&manifest), ), - )); + ); + return Ok(()); } if !targ_pkg.extensions.contains(&component) { @@ -588,7 +593,7 @@ impl<'a> Toolchain<'a> { changes, false, &self.download_cfg(), - self.download_cfg().notify_handler.clone(), + &self.download_cfg().notify_handler, &toolchain.manifest_name(), )?; @@ -604,7 +609,7 @@ impl<'a> Toolchain<'a> { } let toolchain = &self.name; - let ref toolchain = ToolchainDesc::from_str(toolchain) + let toolchain = ToolchainDesc::from_str(toolchain) .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))?; let prefix = InstallPrefix::from(self.path.to_owned()); @@ -658,7 +663,7 @@ impl<'a> Toolchain<'a> { changes, false, &self.download_cfg(), - self.download_cfg().notify_handler.clone(), + &self.download_cfg().notify_handler, &toolchain.manifest_name(), )?; diff --git a/src/utils/raw.rs b/src/utils/raw.rs index 19ee6847fa..e86f53cc3e 100644 --- a/src/utils/raw.rs +++ b/src/utils/raw.rs @@ -39,7 +39,7 @@ pub fn path_exists>(path: P) -> bool { pub fn random_string(length: usize) -> String { let chars = b"abcdefghijklmnopqrstuvwxyz0123456789_"; (0..length) - .map(|_| from_u32(chars[random::() % chars.len()] as u32).unwrap()) + .map(|_| from_u32(u32::from(chars[random::() % chars.len()])).unwrap()) .collect() } @@ -140,7 +140,7 @@ pub fn tee_file(path: &Path, w: &mut W) -> io::Result<()> { let bytes_read = io::Read::read(&mut file, &mut buffer)?; if bytes_read != 0 { - io::Write::write_all(w, &mut buffer[0..bytes_read])?; + io::Write::write_all(w, &buffer[0..bytes_read])?; } else { return Ok(()); } @@ -344,14 +344,14 @@ pub fn prefix_arg>(name: &str, s: S) -> OsString { pub fn has_cmd(cmd: &str) -> bool { let cmd = format!("{}{}", cmd, env::consts::EXE_SUFFIX); - let path = env::var_os("PATH").unwrap_or(OsString::new()); + let path = env::var_os("PATH").unwrap_or_default(); env::split_paths(&path) .map(|p| p.join(&cmd)) .any(|p| p.exists()) } pub fn find_cmd<'a>(cmds: &[&'a str]) -> Option<&'a str> { - cmds.into_iter().map(|&s| s).filter(|&s| has_cmd(s)).next() + cmds.iter().cloned().find(|&s| has_cmd(s)) } pub fn open_browser(path: &Path) -> io::Result { @@ -361,10 +361,10 @@ pub fn open_browser(path: &Path) -> io::Result { use std::process::Stdio; let env_browser = env::var_os("BROWSER").map(|b| env::split_paths(&b).collect::>()); - let env_commands = env_browser + let env_commands: Vec<&str> = env_browser .as_ref() .map(|cmds| cmds.iter().by_ref().filter_map(|b| b.to_str()).collect()) - .unwrap_or(vec![]); + .unwrap_or_default(); let commands = [ "xdg-open", @@ -373,7 +373,7 @@ pub fn open_browser(path: &Path) -> io::Result { "chromium", "sensible-browser", ]; - if let Some(cmd) = find_cmd(&env_commands).or(find_cmd(&commands)) { + if let Some(cmd) = find_cmd(&env_commands).or_else(|| find_cmd(&commands)) { Command::new(cmd) .arg(path) .stdin(Stdio::null()) diff --git a/src/utils/utils.rs b/src/utils/utils.rs index 30ba6b5c80..5e04809878 100644 --- a/src/utils/utils.rs +++ b/src/utils/utils.rs @@ -29,42 +29,42 @@ pub fn ensure_dir_exists( notify_handler(Notification::CreatingDirectory(name, p)) }) .chain_err(|| ErrorKind::CreatingDirectory { - name: name, + name, path: PathBuf::from(path), }) } pub fn read_file(name: &'static str, path: &Path) -> Result { raw::read_file(path).chain_err(|| ErrorKind::ReadingFile { - name: name, + name, path: PathBuf::from(path), }) } pub fn write_file(name: &'static str, path: &Path, contents: &str) -> Result<()> { raw::write_file(path, contents).chain_err(|| ErrorKind::WritingFile { - name: name, + name, path: PathBuf::from(path), }) } pub fn append_file(name: &'static str, path: &Path, line: &str) -> Result<()> { raw::append_file(path, line).chain_err(|| ErrorKind::WritingFile { - name: name, + name, path: PathBuf::from(path), }) } pub fn write_line(name: &'static str, file: &mut File, path: &Path, line: &str) -> Result<()> { writeln!(file, "{}", line).chain_err(|| ErrorKind::WritingFile { - name: name, + name, path: path.to_path_buf(), }) } pub fn write_str(name: &'static str, file: &mut File, path: &Path, s: &str) -> Result<()> { write!(file, "{}", s).chain_err(|| ErrorKind::WritingFile { - name: name, + name, path: path.to_path_buf(), }) } @@ -84,7 +84,7 @@ pub fn filter_file bool>( filter: F, ) -> Result { raw::filter_file(src, dest, filter).chain_err(|| ErrorKind::FilteringFile { - name: name, + name, src: PathBuf::from(src), dest: PathBuf::from(dest), }) @@ -96,7 +96,7 @@ pub fn match_file Option>( f: F, ) -> Result> { raw::match_file(src, f).chain_err(|| ErrorKind::ReadingFile { - name: name, + name, path: PathBuf::from(src), }) } @@ -110,7 +110,7 @@ pub fn canonicalize_path(path: &Path, notify_handler: &dyn Fn(Notification<'_>)) pub fn tee_file(name: &'static str, path: &Path, w: &mut W) -> Result<()> { raw::tee_file(path, w).chain_err(|| ErrorKind::ReadingFile { - name: name, + name, path: PathBuf::from(path), }) } @@ -136,8 +136,8 @@ pub fn download_file_with_resume( Ok(_) => Ok(()), Err(e) => { let is_client_error = match e.kind() { - &ErrorKind::Download(DEK::HttpStatus(400..=499)) => true, - &ErrorKind::Download(DEK::FileNotFound) => true, + ErrorKind::Download(DEK::HttpStatus(400..=499)) => true, + ErrorKind::Download(DEK::FileNotFound) => true, _ => false, }; Err(e).chain_err(|| { @@ -176,13 +176,10 @@ fn download_file_( // This callback will write the download to disk and optionally // hash the contents, then forward the notification up the stack let callback: &dyn Fn(Event<'_>) -> download::Result<()> = &|msg| { - match msg { - Event::DownloadDataReceived(data) => { - if let Some(ref mut h) = *hasher.borrow_mut() { - h.input(data); - } + if let Event::DownloadDataReceived(data) = msg { + if let Some(ref mut h) = *hasher.borrow_mut() { + h.input(data); } - _ => (), } match msg { @@ -325,14 +322,14 @@ pub fn remove_dir( ) -> Result<()> { notify_handler(Notification::RemovingDirectory(name, path)); raw::remove_dir(path).chain_err(|| ErrorKind::RemovingDirectory { - name: name, + name, path: PathBuf::from(path), }) } pub fn remove_file(name: &'static str, path: &Path) -> Result<()> { fs::remove_file(path).chain_err(|| ErrorKind::RemovingFile { - name: name, + name, path: PathBuf::from(path), }) } @@ -345,14 +342,14 @@ pub fn ensure_file_removed(name: &'static str, path: &Path) -> Result<()> { } } result.chain_err(|| ErrorKind::RemovingFile { - name: name, + name, path: PathBuf::from(path), }) } pub fn read_dir(name: &'static str, path: &Path) -> Result { fs::read_dir(path).chain_err(|| ErrorKind::ReadingDirectory { - name: name, + name, path: PathBuf::from(path), }) } @@ -527,7 +524,9 @@ pub fn cargo_home() -> Result { }; let user_home = home_dir().map(|p| p.join(".cargo")); - cargo_home.or(user_home).ok_or(ErrorKind::CargoHome.into()) + cargo_home + .or(user_home) + .ok_or_else(|| ErrorKind::CargoHome.into()) } // Creates a ~/.rustup folder @@ -549,7 +548,7 @@ fn dot_dir(name: &str) -> Option { } pub fn rustup_home_in_user_dir() -> Result { - dot_dir(".rustup").ok_or(ErrorKind::RustupHome.into()) + dot_dir(".rustup").ok_or_else(|| ErrorKind::RustupHome.into()) } pub fn rustup_home() -> Result { @@ -565,7 +564,7 @@ pub fn rustup_home() -> Result { let user_home = dot_dir(".rustup"); rustup_home .or(user_home) - .ok_or(ErrorKind::RustupHome.into()) + .ok_or_else(|| ErrorKind::RustupHome.into()) } pub fn format_path_for_display(path: &str) -> String { @@ -651,7 +650,7 @@ pub fn toolchain_sort>(v: &mut Vec) { fn rename(name: &'static str, src: &Path, dest: &Path) -> Result<()> { fs::rename(src, dest).chain_err(|| ErrorKind::RenamingFile { - name: name, + name, src: PathBuf::from(src), dest: PathBuf::from(dest), }) diff --git a/tests/cli-rustup.rs b/tests/cli-rustup.rs index 34da9b826a..27e8267ebf 100644 --- a/tests/cli-rustup.rs +++ b/tests/cli-rustup.rs @@ -686,7 +686,7 @@ fn list_default_toolchain() { } #[test] -#[ignore(windows)] // FIXME Windows shows UNC paths +#[ignore = "FIXME: Windows shows UNC paths"] fn show_toolchain_override() { setup(&|config| { let cwd = config.current_dir(); @@ -709,7 +709,7 @@ nightly-{0} (directory override for '{1}') } #[test] -#[ignore(windows)] // FIXME Windows shows UNC paths +#[ignore = "FIXME: Windows shows UNC paths"] fn show_toolchain_toolchain_file_override() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); @@ -748,7 +748,7 @@ nightly-{0} (overridden by '{1}') } #[test] -#[ignore(windows)] // FIXME Windows shows UNC paths +#[ignore = "FIXME: Windows shows UNC paths"] fn show_toolchain_version_nested_file_override() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); @@ -792,7 +792,7 @@ nightly-{0} (overridden by '{1}') } #[test] -#[ignore(windows)] // FIXME Windows shows UNC paths +#[ignore = "FIXME: Windows shows UNC paths"] fn show_toolchain_toolchain_file_override_not_installed() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); diff --git a/tests/cli-v2.rs b/tests/cli-v2.rs index 84223df520..ab7ff36e2d 100644 --- a/tests/cli-v2.rs +++ b/tests/cli-v2.rs @@ -648,7 +648,7 @@ fn add_target_host() { setup(&|config| { let trip = TargetTriple::from_build(); expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustup", "target", "add", &trip.to_string()], + expect_stderr_ok(config, &["rustup", "target", "add", &trip.to_string()], for_host!("component 'rust-std' for target '{0}' was automatically added because it is required for toolchain 'nightly-{0}'")); }); }