From f38c84aa864c63de8283bd4b560f623e1fcb8ef7 Mon Sep 17 00:00:00 2001 From: Seiichi Uchida Date: Fri, 22 Dec 2017 19:13:25 +0900 Subject: [PATCH] Cargo fmt --all --- build.rs | 26 +- src/download/src/errors.rs | 2 - src/download/src/lib.rs | 219 ++-- src/download/tests/download-curl-resume.rs | 57 +- src/download/tests/download-reqwest-resume.rs | 58 +- src/download/tests/support/mod.rs | 22 +- src/rustup-cli/common.rs | 107 +- src/rustup-cli/download_tracker.rs | 48 +- src/rustup-cli/help.rs | 40 +- src/rustup-cli/job.rs | 127 +-- src/rustup-cli/main.rs | 55 +- src/rustup-cli/proxy_mode.rs | 33 +- src/rustup-cli/rustup_mode.rs | 951 +++++++++-------- src/rustup-cli/self_update.rs | 643 ++++++------ src/rustup-cli/setup_mode.rs | 57 +- src/rustup-cli/term2.rs | 55 +- src/rustup-dist/build.rs | 5 +- src/rustup-dist/src/component/components.rs | 95 +- src/rustup-dist/src/component/mod.rs | 1 - src/rustup-dist/src/component/package.rs | 147 +-- src/rustup-dist/src/component/transaction.rs | 112 ++- src/rustup-dist/src/config.rs | 16 +- src/rustup-dist/src/dist.rs | 280 +++--- src/rustup-dist/src/download.rs | 108 +- src/rustup-dist/src/errors.rs | 15 +- src/rustup-dist/src/lib.rs | 30 +- src/rustup-dist/src/manifest.rs | 129 ++- src/rustup-dist/src/manifestation.rs | 312 +++--- src/rustup-dist/src/notifications.rs | 63 +- src/rustup-dist/src/prefix.rs | 4 +- src/rustup-dist/src/temp.rs | 77 +- src/rustup-dist/tests/dist.rs | 952 ++++++++++++------ src/rustup-dist/tests/install.rs | 125 ++- src/rustup-dist/tests/manifest.rs | 10 +- src/rustup-dist/tests/transactions.rs | 195 +++- src/rustup-mock/src/clitools.rs | 397 +++++--- src/rustup-mock/src/dist.rs | 155 ++- src/rustup-mock/src/lib.rs | 71 +- src/rustup-utils/src/errors.rs | 6 +- src/rustup-utils/src/lib.rs | 26 +- src/rustup-utils/src/notifications.rs | 26 +- src/rustup-utils/src/raw.rs | 192 ++-- src/rustup-utils/src/toml_utils.rs | 23 +- src/rustup-utils/src/tty.rs | 6 +- src/rustup-utils/src/utils.rs | 446 ++++---- src/rustup-win-installer/build.rs | 24 +- src/rustup-win-installer/src/lib.rs | 27 +- src/rustup/command.rs | 77 +- src/rustup/config.rs | 276 ++--- src/rustup/env_var.rs | 6 +- src/rustup/install.rs | 43 +- src/rustup/lib.rs | 14 +- src/rustup/notifications.rs | 89 +- src/rustup/settings.rs | 81 +- src/rustup/telemetry.rs | 48 +- src/rustup/telemetry_analysis.rs | 58 +- src/rustup/toolchain.rs | 315 +++--- tests/cli-exact.rs | 292 ++++-- tests/cli-inst-interactive.rs | 61 +- tests/cli-misc.rs | 373 +++++-- tests/cli-rustup.rs | 658 ++++++++---- tests/cli-self-upd.rs | 343 ++++--- tests/cli-v1.rs | 115 ++- tests/cli-v2.rs | 356 ++++--- 64 files changed, 5858 insertions(+), 3922 deletions(-) diff --git a/build.rs b/build.rs index 3c642ea44b..b1508194ba 100644 --- a/build.rs +++ b/build.rs @@ -8,7 +8,8 @@ use std::process::Command; struct Ignore; impl From for Ignore - where E: Error +where + E: Error, { fn from(_: E) -> Ignore { Ignore @@ -35,18 +36,19 @@ fn commit_info() -> String { } fn commit_hash() -> Result { - Ok(try!(String::from_utf8(try!(Command::new("git") - .args(&["rev-parse", "--short=9", "HEAD"]) - .output()) - .stdout))) + Ok(String::from_utf8( + Command::new("git") + .args(&["rev-parse", "--short=9", "HEAD"]) + .output()? + .stdout, + )?) } fn commit_date() -> Result { - Ok(try!(String::from_utf8(try!(Command::new("git") - .args(&["log", - "-1", - "--date=short", - "--pretty=format:%cd"]) - .output()) - .stdout))) + Ok(String::from_utf8( + Command::new("git") + .args(&["log", "-1", "--date=short", "--pretty=format:%cd"]) + .output()? + .stdout, + )?) } diff --git a/src/download/src/errors.rs b/src/download/src/errors.rs index 54d9225321..f1a228a1c3 100644 --- a/src/download/src/errors.rs +++ b/src/download/src/errors.rs @@ -1,5 +1,3 @@ - - error_chain! { links { } diff --git a/src/download/src/lib.rs b/src/download/src/lib.rs index bfb78365fd..540b6404ef 100644 --- a/src/download/src/lib.rs +++ b/src/download/src/lib.rs @@ -4,11 +4,11 @@ extern crate error_chain; extern crate url; -#[cfg(feature = "reqwest-backend")] -extern crate reqwest; #[cfg(feature = "reqwest-backend")] #[macro_use] extern crate lazy_static; +#[cfg(feature = "reqwest-backend")] +extern crate reqwest; use url::Url; use std::path::Path; @@ -17,7 +17,10 @@ mod errors; pub use errors::*; #[derive(Debug, Copy, Clone)] -pub enum Backend { Curl, Reqwest } +pub enum Backend { + Curl, + Reqwest, +} #[derive(Debug, Copy, Clone)] pub enum Event<'a> { @@ -28,11 +31,12 @@ pub enum Event<'a> { DownloadDataReceived(&'a [u8]), } -fn download_with_backend(backend: Backend, - url: &Url, - resume_from: u64, - callback: &Fn(Event) -> Result<()>) - -> Result<()> { +fn download_with_backend( + backend: Backend, + url: &Url, + resume_from: u64, + callback: &Fn(Event) -> Result<()>, +) -> Result<()> { match backend { Backend::Curl => curl::download(url, resume_from, callback), Backend::Reqwest => reqwest_be::download(url, resume_from, callback), @@ -44,80 +48,81 @@ pub fn download_to_path_with_backend( url: &Url, path: &Path, resume_from_partial: bool, - callback: Option<&Fn(Event) -> Result<()>>) - -> Result<()> -{ + callback: Option<&Fn(Event) -> Result<()>>, +) -> Result<()> { use std::cell::RefCell; - use std::fs::{OpenOptions}; - use std::io::{Read, Write, Seek, SeekFrom}; + use std::fs::OpenOptions; + use std::io::{Read, Seek, SeekFrom, Write}; || -> Result<()> { let (file, resume_from) = if resume_from_partial { - let possible_partial = OpenOptions::new() - .read(true) - .open(&path); + let possible_partial = OpenOptions::new().read(true).open(&path); let downloaded_so_far = if let Ok(mut partial) = possible_partial { if let Some(cb) = callback { - try!(cb(Event::ResumingPartialDownload)); + cb(Event::ResumingPartialDownload)?; let mut buf = vec![0; 32768]; let mut downloaded_so_far = 0; loop { - let n = try!(partial.read(&mut buf)); + let n = partial.read(&mut buf)?; downloaded_so_far += n as u64; if n == 0 { break; } - try!(cb(Event::DownloadDataReceived(&buf[..n]))); + cb(Event::DownloadDataReceived(&buf[..n]))?; } downloaded_so_far } else { - let file_info = try!(partial.metadata()); + let file_info = partial.metadata()?; file_info.len() } } else { 0 }; - let mut possible_partial = - try!(OpenOptions::new() - .write(true) - .create(true) - .open(&path) - .chain_err(|| "error opening file for download")); + let mut possible_partial = OpenOptions::new() + .write(true) + .create(true) + .open(&path) + .chain_err(|| "error opening file for download")?; - try!(possible_partial.seek(SeekFrom::End(0))); + possible_partial.seek(SeekFrom::End(0))?; (possible_partial, downloaded_so_far) } else { - (try!(OpenOptions::new() + ( + OpenOptions::new() .write(true) .create(true) .open(&path) - .chain_err(|| "error creating file for download")), 0) + .chain_err(|| "error creating file for download")?, + 0, + ) }; let file = RefCell::new(file); - try!(download_with_backend(backend, url, resume_from, &|event| { + download_with_backend(backend, url, resume_from, &|event| { if let Event::DownloadDataReceived(data) = event { - try!(file.borrow_mut().write_all(data) - .chain_err(|| "unable to write download to disk")); + file.borrow_mut() + .write_all(data) + .chain_err(|| "unable to write download to disk")?; } match callback { Some(cb) => cb(event), - None => Ok(()) + None => Ok(()), } - })); + })?; - try!(file.borrow_mut().sync_data() - .chain_err(|| "unable to sync download to disk")); + file.borrow_mut() + .sync_data() + .chain_err(|| "unable to sync download to disk")?; Ok(()) - }().map_err(|e| { - + }() + .map_err(|e| { // TODO is there any point clearing up here? What kind of errors will leave us with an unusable partial? e }) @@ -138,10 +143,7 @@ pub mod curl { use url::Url; use super::Event; - pub fn download(url: &Url, - resume_from: u64, - callback: &Fn(Event) -> Result<()> ) - -> Result<()> { + pub fn download(url: &Url, resume_from: u64, callback: &Fn(Event) -> Result<()>) -> Result<()> { // Fetch either a cached libcurl handle (which will preserve open // connections) or create a new one if it isn't listed. // @@ -151,12 +153,17 @@ pub mod curl { EASY.with(|handle| { let mut handle = handle.borrow_mut(); - try!(handle.url(&url.to_string()).chain_err(|| "failed to set url")); - try!(handle.follow_location(true).chain_err(|| "failed to set follow redirects")); + handle + .url(&url.to_string()) + .chain_err(|| "failed to set url")?; + handle + .follow_location(true) + .chain_err(|| "failed to set follow redirects")?; if resume_from > 0 { - try!(handle.resume_from(resume_from) - .chain_err(|| "setting the range header for download resumption")); + handle + .resume_from(resume_from) + .chain_err(|| "setting the range header for download resumption")?; } else { // an error here indicates that the range header isn't supported by underlying curl, // so there's nothing to "clear" - safe to ignore this error. @@ -164,7 +171,9 @@ pub mod curl { } // Take at most 30s to connect - try!(handle.connect_timeout(Duration::new(30, 0)).chain_err(|| "failed to set connect timeout")); + handle + .connect_timeout(Duration::new(30, 0)) + .chain_err(|| "failed to set connect timeout")?; { let cberr = RefCell::new(None); @@ -173,40 +182,42 @@ pub mod curl { // Data callback for libcurl which is called with data that's // downloaded. We just feed it into our hasher and also write it out // to disk. - try!(transfer.write_function(|data| { - match callback(Event::DownloadDataReceived(data)) { + transfer + .write_function(|data| match callback(Event::DownloadDataReceived(data)) { Ok(()) => Ok(data.len()), Err(e) => { *cberr.borrow_mut() = Some(e); Ok(0) } - } - }).chain_err(|| "failed to set write")); + }) + .chain_err(|| "failed to set write")?; // Listen for headers and parse out a `Content-Length` if it comes // so we know how much we're downloading. - try!(transfer.header_function(|header| { - if let Ok(data) = str::from_utf8(header) { - let prefix = "Content-Length: "; - if data.starts_with(prefix) { - if let Ok(s) = data[prefix.len()..].trim().parse::() { - let msg = Event::DownloadContentLengthReceived(s + resume_from); - match callback(msg) { - Ok(()) => (), - Err(e) => { - *cberr.borrow_mut() = Some(e); - return false; + transfer + .header_function(|header| { + if let Ok(data) = str::from_utf8(header) { + let prefix = "Content-Length: "; + if data.starts_with(prefix) { + if let Ok(s) = data[prefix.len()..].trim().parse::() { + let msg = Event::DownloadContentLengthReceived(s + resume_from); + match callback(msg) { + Ok(()) => (), + Err(e) => { + *cberr.borrow_mut() = Some(e); + return false; + } } } } } - } - true - }).chain_err(|| "failed to set header")); + true + }) + .chain_err(|| "failed to set header")?; // If an error happens check to see if we had a filesystem error up // in `cberr`, but we always want to punt it up. - try!(transfer.perform().or_else(|e| { + transfer.perform().or_else(|e| { // If the original error was generated by one of our // callbacks, return it. match cberr.borrow_mut().take() { @@ -220,14 +231,18 @@ pub mod curl { } } } - })); + })?; } // If we didn't get a 20x or 0 ("OK" for files) then return an error - let code = try!(handle.response_code().chain_err(|| "failed to get response code")); + let code = handle + .response_code() + .chain_err(|| "failed to get response code")?; match code { - 0 | 200 ... 299 => {}, - _ => { return Err(ErrorKind::HttpStatus(code).into()); } + 0 | 200...299 => {} + _ => { + return Err(ErrorKind::HttpStatus(code).into()); + } }; Ok(()) @@ -246,18 +261,13 @@ pub mod reqwest_be { use super::Event; use reqwest::{header, Client, Proxy, Response}; - pub fn download(url: &Url, - resume_from: u64, - callback: &Fn(Event) -> Result<()>) - -> Result<()> { - + pub fn download(url: &Url, resume_from: u64, callback: &Fn(Event) -> Result<()>) -> Result<()> { // Short-circuit reqwest for the "file:" URL scheme if download_from_file_url(url, resume_from, callback)? { return Ok(()); } - let mut res = request(url, resume_from) - .chain_err(|| "failed to make network request")?; + let mut res = request(url, resume_from).chain_err(|| "failed to make network request")?; if !res.status().is_success() { let code: u16 = res.status().into(); @@ -272,8 +282,8 @@ pub mod reqwest_be { } loop { - let bytes_read = io::Read::read(&mut res, &mut buffer) - .chain_err(|| "error reading from socket")?; + let bytes_read = + io::Read::read(&mut res, &mut buffer).chain_err(|| "error reading from socket")?; if bytes_read != 0 { callback(Event::DownloadDataReceived(&buffer[0..bytes_read]))?; @@ -316,26 +326,26 @@ pub mod reqwest_be { let mut req = CLIENT.get(url.clone())?; if resume_from != 0 { - req.header(header::Range::Bytes( - vec![header::ByteRangeSpec::AllFrom(resume_from)] - )); + req.header(header::Range::Bytes(vec![ + header::ByteRangeSpec::AllFrom(resume_from), + ])); } req.send() } - fn download_from_file_url(url: &Url, - resume_from: u64, - callback: &Fn(Event) -> Result<()>) - -> Result { - + fn download_from_file_url( + url: &Url, + resume_from: u64, + callback: &Fn(Event) -> Result<()>, + ) -> Result { use std::fs; use std::io; // The file scheme is mostly for use by tests to mock the dist server if url.scheme() == "file" { - let src = try!(url.to_file_path() - .map_err(|_| Error::from(format!("bogus file url: '{}'", url)))); + let src = url.to_file_path() + .map_err(|_| Error::from(format!("bogus file url: '{}'", url)))?; if !src.is_file() { // Because some of rustup's logic depends on checking // the error when a downloaded file doesn't exist, make @@ -344,16 +354,17 @@ pub mod reqwest_be { return Err(ErrorKind::FileNotFound.into()); } - let ref mut f = try!(fs::File::open(src) - .chain_err(|| "unable to open downloaded file")); + 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 ref mut buffer = vec![0u8; 0x10000]; loop { - let bytes_read = try!(io::Read::read(f, buffer) - .chain_err(|| "unable to read downloaded file")); - if bytes_read == 0 { break } - try!(callback(Event::DownloadDataReceived(&buffer[0..bytes_read]))); + let bytes_read = + io::Read::read(f, buffer).chain_err(|| "unable to read downloaded file")?; + if bytes_read == 0 { + break; + } + callback(Event::DownloadDataReceived(&buffer[0..bytes_read]))?; } Ok(true) @@ -370,10 +381,11 @@ pub mod curl { use url::Url; use super::Event; - pub fn download(_url: &Url, - _resume_from: u64, - _callback: &Fn(Event) -> Result<()> ) - -> Result<()> { + pub fn download( + _url: &Url, + _resume_from: u64, + _callback: &Fn(Event) -> Result<()>, + ) -> Result<()> { Err(ErrorKind::BackendUnavailable("curl").into()) } } @@ -385,10 +397,11 @@ pub mod reqwest_be { use url::Url; use super::Event; - pub fn download(_url: &Url, - _resume_from: u64, - _callback: &Fn(Event) -> Result<()> ) - -> Result<()> { + pub fn download( + _url: &Url, + _resume_from: u64, + _callback: &Fn(Event) -> Result<()>, + ) -> Result<()> { Err(ErrorKind::BackendUnavailable("reqwest").into()) } } diff --git a/src/download/tests/download-curl-resume.rs b/src/download/tests/download-curl-resume.rs index a3aaf50112..778eafe64e 100644 --- a/src/download/tests/download-curl-resume.rs +++ b/src/download/tests/download-curl-resume.rs @@ -10,7 +10,7 @@ use url::Url; use download::*; mod support; -use support::{tmp_dir, write_file, file_contents, serve_file}; +use support::{file_contents, serve_file, tmp_dir, write_file}; #[test] fn partially_downloaded_file_gets_resumed_from_byte_offset() { @@ -22,13 +22,8 @@ fn partially_downloaded_file_gets_resumed_from_byte_offset() { write_file(&target_path, "123"); let from_url = Url::from_file_path(&from_path).unwrap(); - download_to_path_with_backend( - Backend::Curl, - &from_url, - &target_path, - true, - None) - .expect("Test download failed"); + download_to_path_with_backend(Backend::Curl, &from_url, &target_path, true, None) + .expect("Test download failed"); assert_eq!(file_contents(&target_path), "12345"); } @@ -47,33 +42,31 @@ fn callback_gets_all_data_as_if_the_download_happened_all_at_once() { let callback_len = Mutex::new(None); let received_in_callback = Mutex::new(Vec::new()); - download_to_path_with_backend(Backend::Curl, - &from_url, - &target_path, - true, - Some(&|msg| { - match msg { - Event::ResumingPartialDownload => { - let mut flag = callback_partial.lock().unwrap(); - assert!(!*flag); - *flag = true; - }, - Event::DownloadContentLengthReceived(len) => { - let mut flag = callback_len.lock().unwrap(); - assert!(flag.is_none()); - *flag = Some(len); - } - Event::DownloadDataReceived(data) => { - for b in data.iter() { - received_in_callback.lock().unwrap().push(b.clone()); + download_to_path_with_backend( + Backend::Curl, + &from_url, + &target_path, + true, + Some(&|msg| { + match msg { + Event::ResumingPartialDownload => { + let mut flag = callback_partial.lock().unwrap(); + assert!(!*flag); + *flag = true; } + Event::DownloadContentLengthReceived(len) => { + let mut flag = callback_len.lock().unwrap(); + assert!(flag.is_none()); + *flag = Some(len); + } + Event::DownloadDataReceived(data) => for b in data.iter() { + received_in_callback.lock().unwrap().push(b.clone()); + }, } - } - - Ok(()) - })) - .expect("Test download failed"); + Ok(()) + }), + ).expect("Test download failed"); assert!(*callback_partial.lock().unwrap()); assert_eq!(*callback_len.lock().unwrap(), Some(5)); diff --git a/src/download/tests/download-reqwest-resume.rs b/src/download/tests/download-reqwest-resume.rs index bbe03e245f..6049bb9afb 100644 --- a/src/download/tests/download-reqwest-resume.rs +++ b/src/download/tests/download-reqwest-resume.rs @@ -10,7 +10,7 @@ use url::Url; use download::*; mod support; -use support::{tmp_dir, write_file, file_contents, serve_file}; +use support::{file_contents, serve_file, tmp_dir, write_file}; #[test] fn resume_partial_from_file_url() { @@ -21,15 +21,9 @@ fn resume_partial_from_file_url() { let target_path = tmpdir.path().join("downloaded"); write_file(&target_path, "123"); - let from_url = Url::from_file_path(&from_path).unwrap(); - download_to_path_with_backend( - Backend::Reqwest, - &from_url, - &target_path, - true, - None) - .expect("Test download failed"); + download_to_path_with_backend(Backend::Reqwest, &from_url, &target_path, true, None) + .expect("Test download failed"); assert_eq!(file_contents(&target_path), "12345"); } @@ -48,33 +42,31 @@ fn callback_gets_all_data_as_if_the_download_happened_all_at_once() { let callback_len = Mutex::new(None); let received_in_callback = Mutex::new(Vec::new()); - download_to_path_with_backend(Backend::Reqwest, - &from_url, - &target_path, - true, - Some(&|msg| { - match msg { - Event::ResumingPartialDownload => { - let mut flag = callback_partial.lock().unwrap(); - assert!(!*flag); - *flag = true; - }, - Event::DownloadContentLengthReceived(len) => { - let mut flag = callback_len.lock().unwrap(); - assert!(flag.is_none()); - *flag = Some(len); - } - Event::DownloadDataReceived(data) => { - for b in data.iter() { - received_in_callback.lock().unwrap().push(b.clone()); + download_to_path_with_backend( + Backend::Reqwest, + &from_url, + &target_path, + true, + Some(&|msg| { + match msg { + Event::ResumingPartialDownload => { + let mut flag = callback_partial.lock().unwrap(); + assert!(!*flag); + *flag = true; + } + Event::DownloadContentLengthReceived(len) => { + let mut flag = callback_len.lock().unwrap(); + assert!(flag.is_none()); + *flag = Some(len); } + Event::DownloadDataReceived(data) => for b in data.iter() { + received_in_callback.lock().unwrap().push(b.clone()); + }, } - } - - Ok(()) - })) - .expect("Test download failed"); + Ok(()) + }), + ).expect("Test download failed"); assert!(*callback_partial.lock().unwrap()); assert_eq!(*callback_len.lock().unwrap(), Some(5)); diff --git a/src/download/tests/support/mod.rs b/src/download/tests/support/mod.rs index 7882fadb81..380211cf86 100644 --- a/src/download/tests/support/mod.rs +++ b/src/download/tests/support/mod.rs @@ -16,11 +16,13 @@ pub fn tmp_dir() -> TempDir { pub fn file_contents(path: &Path) -> String { let mut result = String::new(); - File::open(&path).unwrap().read_to_string(&mut result).expect("reading test result file"); + File::open(&path) + .unwrap() + .read_to_string(&mut result) + .expect("reading test result file"); result } - pub fn write_file(path: &Path, contents: &str) { let mut file = fs::OpenOptions::new() .write(true) @@ -34,7 +36,6 @@ pub fn write_file(path: &Path, contents: &str) { file.sync_data().expect("writing test data"); } - type Shutdown = oneshot::Sender<()>; pub fn serve_file(contents: Vec) -> (SocketAddr, Shutdown) { @@ -47,13 +48,11 @@ pub fn serve_file(contents: Vec) -> (SocketAddr, Shutdown) { let (addr_tx, addr_rx) = oneshot::channel(); let (tx, rx) = oneshot::channel(); thread::spawn(move || { - let server = http.bind(&addr, move || Ok(ServeFile(contents.clone()))) .expect("server setup failed"); let addr = server.local_addr().expect("local addr failed"); addr_tx.send(addr).unwrap(); - server.run_until(rx.map_err(|_| ())) - .expect("server failed"); + server.run_until(rx.map_err(|_| ())).expect("server failed"); }); let addr = addr_rx.wait().unwrap(); (addr, tx) @@ -79,13 +78,16 @@ impl hyper::server::Service for ServeFile { hyper::header::ContentRangeSpec::Bytes { range: Some((start, self.0.len() as u64)), instance_length: Some(self.0.len() as u64), - } + }, )); - (hyper::StatusCode::PartialContent, self.0[start as usize..].to_vec()) - }, + ( + hyper::StatusCode::PartialContent, + self.0[start as usize..].to_vec(), + ) + } _ => panic!("unexpected Range header"), } - }, + } _ => panic!("unexpected Range header"), } } else { diff --git a/src/rustup-cli/common.rs b/src/rustup-cli/common.rs index f4e9b4dca9..e37253a888 100644 --- a/src/rustup-cli/common.rs +++ b/src/rustup-cli/common.rs @@ -6,7 +6,7 @@ use errors::*; use rustup_utils::utils; use rustup_utils::notify::NotificationLevel; use self_update; -use std::io::{Write, BufRead, BufReader}; +use std::io::{BufRead, BufReader, Write}; use std::process::{Command, Stdio}; use std::path::Path; use std::{cmp, iter}; @@ -19,7 +19,7 @@ use wait_timeout::ChildExt; pub fn confirm(question: &str, default: bool) -> Result { print!("{} ", question); let _ = std::io::stdout().flush(); - let input = try!(read_line()); + let input = read_line()?; let r = match &*input { "y" | "Y" => true, @@ -34,7 +34,9 @@ pub fn confirm(question: &str, default: bool) -> Result { } pub enum Confirm { - Yes, No, Advanced + Yes, + No, + Advanced, } pub fn confirm_advanced() -> Result { @@ -44,10 +46,10 @@ pub fn confirm_advanced() -> Result { println!("3) Cancel installation"); let _ = std::io::stdout().flush(); - let input = try!(read_line()); + let input = read_line()?; let r = match &*input { - "1"|"" => Confirm::Yes, + "1" | "" => Confirm::Yes, "2" => Confirm::Advanced, _ => Confirm::No, }; @@ -60,7 +62,7 @@ pub fn confirm_advanced() -> Result { pub fn question_str(question: &str, default: &str) -> Result { println!("{}", question); let _ = std::io::stdout().flush(); - let input = try!(read_line()); + let input = read_line()?; println!(""); @@ -75,7 +77,7 @@ pub fn question_bool(question: &str, default: bool) -> Result { println!("{}", question); let _ = std::io::stdout().flush(); - let input = try!(read_line()); + let input = read_line()?; println!(""); @@ -85,18 +87,19 @@ pub fn question_bool(question: &str, default: bool) -> Result { match &*input { "y" | "Y" | "yes" => Ok(true), "n" | "N" | "no" => Ok(false), - _ => Ok(default) + _ => Ok(default), } } - } pub fn read_line() -> Result { let stdin = std::io::stdin(); let stdin = stdin.lock(); let mut lines = stdin.lines(); - lines.next().and_then(|l| l.ok()).ok_or( - "unable to read from stdin for confirmation".into()) + lines + .next() + .and_then(|l| l.ok()) + .ok_or("unable to read from stdin for confirmation".into()) } pub fn set_globals(verbose: bool) -> Result { @@ -105,8 +108,8 @@ pub fn set_globals(verbose: bool) -> Result { let download_tracker = RefCell::new(DownloadTracker::new()); - Ok(try!(Cfg::from_env(Arc::new(move |n: Notification| { - if download_tracker.borrow_mut().handle_notification(&n) { + Ok(Cfg::from_env(Arc::new(move |n: Notification| { + if download_tracker.borrow_mut().handle_notification(&n) { return; } @@ -126,16 +129,21 @@ pub fn set_globals(verbose: bool) -> Result { err!("{}", n); } } - })))) - + }))?) } -pub fn show_channel_update(cfg: &Cfg, name: &str, - updated: rustup::Result) -> Result<()> { +pub fn show_channel_update( + cfg: &Cfg, + name: &str, + updated: rustup::Result, +) -> Result<()> { show_channel_updates(cfg, vec![(name.to_string(), updated)]) } -fn show_channel_updates(cfg: &Cfg, toolchains: Vec<(String, rustup::Result)>) -> Result<()> { +fn show_channel_updates( + cfg: &Cfg, + 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); @@ -169,7 +177,8 @@ fn show_channel_updates(cfg: &Cfg, toolchains: Vec<(String, rustup::Result = data.collect(); - let max_width = data.iter().fold(0, |a, &(_, _, width, _, _)| cmp::max(a, width)); + let max_width = data.iter() + .fold(0, |a, &(_, _, width, _, _)| cmp::max(a, width)); for (name, banner, width, color, version) in data { let padding = max_width - width; @@ -190,15 +199,14 @@ fn show_channel_updates(cfg: &Cfg, toolchains: Vec<(String, rustup::Result Result<()> { - - let toolchains = try!(cfg.update_all_channels()); + let toolchains = cfg.update_all_channels()?; if toolchains.is_empty() { info!("no updatable toolchains installed"); } let setup_path = if self_update { - try!(self_update::prepare_update()) + self_update::prepare_update()? } else { None }; @@ -206,11 +214,11 @@ pub fn update_all_channels(cfg: &Cfg, self_update: bool) -> Result<()> { if !toolchains.is_empty() { println!(""); - try!(show_channel_updates(cfg, toolchains)); + show_channel_updates(cfg, toolchains)?; } if let Some(ref setup_path) = setup_path { - try!(self_update::run_update(setup_path)); + self_update::run_update(setup_path)?; unreachable!(); // update exits on success } else if self_update { @@ -241,7 +249,9 @@ pub fn rustc_version(toolchain: &Toolchain) -> String { let timeout = Duration::new(3, 0); match child.wait_timeout(timeout) { Ok(Some(status)) if status.success() => { - let out = child.stdout.expect("Child::stdout requested but not present"); + let out = child + .stdout + .expect("Child::stdout requested but not present"); let mut line = String::new(); if BufReader::new(out).read_line(&mut line).is_ok() { let lineend = line.trim_right_matches(&['\r', '\n'][..]).len(); @@ -251,7 +261,7 @@ pub fn rustc_version(toolchain: &Toolchain) -> String { } Ok(None) => { let _ = child.kill(); - return String::from("(timeout reading rustc version)") + return String::from("(timeout reading rustc version)"); } Ok(Some(_)) | Err(_) => {} } @@ -272,9 +282,13 @@ pub fn rustc_version(toolchain: &Toolchain) -> String { pub fn list_targets(toolchain: &Toolchain) -> Result<()> { let mut t = term2::stdout(); - for component in try!(toolchain.list_components()) { + for component in toolchain.list_components()? { if component.component.pkg == "rust-std" { - let target = component.component.target.as_ref().expect("rust-std should have a target"); + let target = component + .component + .target + .as_ref() + .expect("rust-std should have a target"); if component.required { let _ = t.attr(term2::Attr::Bold); let _ = writeln!(t, "{} (default)", target); @@ -294,7 +308,7 @@ pub fn list_targets(toolchain: &Toolchain) -> Result<()> { pub fn list_components(toolchain: &Toolchain) -> Result<()> { let mut t = term2::stdout(); - for component in try!(toolchain.list_components()) { + for component in toolchain.list_components()? { let name = component.component.name(); if component.required { let _ = t.attr(term2::Attr::Bold); @@ -313,7 +327,7 @@ pub fn list_components(toolchain: &Toolchain) -> Result<()> { } pub fn list_toolchains(cfg: &Cfg) -> Result<()> { - let toolchains = try!(cfg.list_toolchains()); + let toolchains = cfg.list_toolchains()?; if toolchains.is_empty() { println!("no installed toolchains"); @@ -327,7 +341,6 @@ pub fn list_toolchains(cfg: &Cfg) -> Result<()> { }; println!("{}{}", &toolchain, if_default); } - } else { for toolchain in toolchains { println!("{}", &toolchain); @@ -338,7 +351,7 @@ pub fn list_toolchains(cfg: &Cfg) -> Result<()> { } pub fn list_overrides(cfg: &Cfg) -> Result<()> { - let overrides = try!(cfg.settings_file.with(|s| Ok(s.overrides.clone()))); + let overrides = cfg.settings_file.with(|s| Ok(s.overrides.clone()))?; if overrides.is_empty() { println!("no overrides"); @@ -349,30 +362,34 @@ pub fn list_overrides(cfg: &Cfg) -> Result<()> { if !dir_exists { any_not_exist = true; } - println!("{:<40}\t{:<20}", - utils::format_path_for_display(&k) + - if dir_exists { - "" - } else { - " (not a directory)" - }, - v) + println!( + "{:<40}\t{:<20}", + utils::format_path_for_display(&k) + if dir_exists { + "" + } else { + " (not a directory)" + }, + v + ) } if any_not_exist { println!(""); - info!("you may remove overrides for non-existent directories with -`rustup override unset --nonexistent`"); + info!( + "you may remove overrides for non-existent directories with +`rustup override unset --nonexistent`" + ); } } Ok(()) } - pub fn version() -> &'static str { - concat!(env!("CARGO_PKG_VERSION"), include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))) + concat!( + env!("CARGO_PKG_VERSION"), + include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt")) + ) } - pub fn report_error(e: &Error) { err!("{}", e); diff --git a/src/rustup-cli/download_tracker.rs b/src/rustup-cli/download_tracker.rs index e6e61b7cf6..6673d9c26f 100644 --- a/src/rustup-cli/download_tracker.rs +++ b/src/rustup-cli/download_tracker.rs @@ -67,7 +67,7 @@ impl DownloadTracker { self.download_finished(); true } - _ => false + _ => false, } } @@ -94,7 +94,8 @@ impl DownloadTracker { if self.downloaded_last_few_secs.len() == DOWNLOAD_TRACK_COUNT { self.downloaded_last_few_secs.pop_back(); } - self.downloaded_last_few_secs.push_front(self.downloaded_this_sec); + self.downloaded_last_few_secs + .push_front(self.downloaded_this_sec); self.downloaded_this_sec = 0; } } @@ -123,14 +124,10 @@ impl DownloadTracker { fn display(&mut self) { let total_h = HumanReadable(self.total_downloaded as f64); let sum = self.downloaded_last_few_secs - .iter() - .fold(0., |a, &v| a + v as f64); + .iter() + .fold(0., |a, &v| a + v as f64); let len = self.downloaded_last_few_secs.len(); - let speed = if len > 0 { - sum / len as f64 - } else { - 0. - }; + let speed = if len > 0 { sum / len as f64 } else { 0. }; let speed_h = HumanReadable(speed); match self.content_len { @@ -140,17 +137,23 @@ impl DownloadTracker { let content_len_h = HumanReadable(content_len); let remaining = content_len - self.total_downloaded as f64; let eta_h = HumanReadable(remaining / speed); - let _ = write!(self.term.as_mut().unwrap(), - "{} / {} ({:3.0} %) {}/s ETA: {:#}", - total_h, - content_len_h, - percent, - speed_h, - eta_h); + let _ = write!( + self.term.as_mut().unwrap(), + "{} / {} ({:3.0} %) {}/s ETA: {:#}", + total_h, + content_len_h, + percent, + speed_h, + eta_h + ); } None => { - let _ = write!(self.term.as_mut().unwrap(), - "Total: {} Speed: {}/s", total_h, speed_h); + let _ = write!( + self.term.as_mut().unwrap(), + "Total: {} Speed: {}/s", + total_h, + speed_h + ); } } // delete_line() doesn't seem to clear the line properly. @@ -167,7 +170,8 @@ struct HumanReadable(f64); impl fmt::Display for HumanReadable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if f.alternate() { // repurposing the alternate mode for ETA + if f.alternate() { + // repurposing the alternate mode for ETA let sec = self.0; if sec.is_infinite() { @@ -177,9 +181,9 @@ impl fmt::Display for HumanReadable { let min = sec / 60; let sec = sec % 60; - write!(f, "{:3} min {:2} s", min, sec) // XYZ min PQ s + write!(f, "{:3} min {:2} s", min, sec) // XYZ min PQ s } else { - write!(f, "{:3.0} s", self.0) // XYZ s + write!(f, "{:3.0} s", self.0) // XYZ s } } else { const KIB: f64 = 1024.0; @@ -187,7 +191,7 @@ impl fmt::Display for HumanReadable { let size = self.0; if size >= MIB { - write!(f, "{:5.1} MiB", size / MIB) // XYZ.P MiB + write!(f, "{:5.1} MiB", size / MIB) // XYZ.P MiB } else if size >= KIB { write!(f, "{:5.1} KiB", size / KIB) } else { diff --git a/src/rustup-cli/help.rs b/src/rustup-cli/help.rs index da1d9a15f7..696ad9c408 100644 --- a/src/rustup-cli/help.rs +++ b/src/rustup-cli/help.rs @@ -1,5 +1,4 @@ -pub static RUSTUP_HELP: &'static str = -r"DISCUSSION: +pub static RUSTUP_HELP: &'static str = r"DISCUSSION: rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between stable, beta, and nightly compilers and keep them updated. It makes @@ -9,8 +8,7 @@ r"DISCUSSION: If you are new to Rust consider running `rustup doc --book` to learn Rust."; -pub static SHOW_HELP: &'static str = -r"DISCUSSION: +pub static SHOW_HELP: &'static str = r"DISCUSSION: Shows the name of the active toolchain and the version of `rustc`. If the active toolchain has installed support for additional @@ -19,8 +17,7 @@ r"DISCUSSION: If there are multiple toolchains installed then all installed toolchains are listed as well."; -pub static UPDATE_HELP: &'static str = -r"DISCUSSION: +pub static UPDATE_HELP: &'static str = r"DISCUSSION: With no toolchain specified, the `update` command updates each of the installed toolchains from the official release channels, then updates rustup itself. @@ -28,19 +25,16 @@ r"DISCUSSION: If given a toolchain argument then `update` updates that toolchain, the same as `rustup toolchain install`."; -pub static INSTALL_HELP: &'static str = -r"DISCUSSION: +pub static INSTALL_HELP: &'static str = r"DISCUSSION: Installs a specific rust toolchain. The 'install' command is an alias for 'rustup update '."; -pub static DEFAULT_HELP: &'static str = -r"DISCUSSION: +pub static DEFAULT_HELP: &'static str = r"DISCUSSION: Sets the default toolchain to the one specified. If the toolchain is not already installed then it is installed first."; -pub static TOOLCHAIN_HELP: &'static str = -r"DISCUSSION: +pub static TOOLCHAIN_HELP: &'static str = r"DISCUSSION: Many `rustup` commands deal with *toolchains*, a single installation of the Rust compiler. `rustup` supports multiple types of toolchains. The most basic track the official release @@ -77,8 +71,7 @@ r"DISCUSSION: often used to for developing Rust itself. For more information see `rustup toolchain help link`."; -pub static TOOLCHAIN_LINK_HELP: &'static str = -r"DISCUSSION: +pub static TOOLCHAIN_LINK_HELP: &'static str = r"DISCUSSION: 'toolchain' is the custom name to be assigned to the new toolchain. Any name is permitted as long as it does not fully match an initial substring of a standard release channel. For example, you can use @@ -97,8 +90,7 @@ r"DISCUSSION: If you now compile a crate in the current directory, the custom toolchain 'latest-stage1' will be used."; -pub static OVERRIDE_HELP: &'static str = -r"DISCUSSION: +pub static OVERRIDE_HELP: &'static str = r"DISCUSSION: Overrides configure rustup to use a specific toolchain when running in a specific directory. @@ -119,16 +111,14 @@ r"DISCUSSION: override and use the default toolchain again, `rustup override unset`."; -pub static OVERRIDE_UNSET_HELP: &'static str = -r"DISCUSSION: +pub static OVERRIDE_UNSET_HELP: &'static str = r"DISCUSSION: If `--path` argument is present, removes the override toolchain for the specified directory. If `--nonexistent` argument is present, removes the override toolchain for all nonexistent directories. Otherwise, removes the override toolchain for the current directory."; -pub static RUN_HELP: &'static str = -r"DISCUSSION: +pub static RUN_HELP: &'static str = r"DISCUSSION: Configures an environment to use the given toolchain and then runs the specified program. The command may be any program, not just rustc or cargo. This can be used for testing arbitrary toolchains @@ -143,8 +133,7 @@ r"DISCUSSION: $ rustup run nightly cargo build"; -pub static DOC_HELP: &'static str = -r"DISCUSSION: +pub static DOC_HELP: &'static str = r"DISCUSSION: Opens the documentation for the currently active toolchain with the default browser. @@ -253,7 +242,6 @@ r"DISCUSSION: PS C:\> rustup completions powershell >> %USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"; -pub static TOOLCHAIN_ARG_HELP: &'static str = - "Toolchain name, such as 'stable', 'nightly', \ - or '1.8.0'. For more information see `rustup \ - help toolchain`"; +pub static TOOLCHAIN_ARG_HELP: &'static str = "Toolchain name, such as 'stable', 'nightly', \ + or '1.8.0'. For more information see `rustup \ + help toolchain`"; diff --git a/src/rustup-cli/job.rs b/src/rustup-cli/job.rs index fb11936493..48cabc486c 100644 --- a/src/rustup-cli/job.rs +++ b/src/rustup-cli/job.rs @@ -35,8 +35,8 @@ mod imp { #[cfg(windows)] mod imp { extern crate kernel32; - extern crate winapi; extern crate psapi; + extern crate winapi; use std::ffi::OsString; use std::io; @@ -67,7 +67,7 @@ mod imp { let job = kernel32::CreateJobObjectW(0 as *mut _, 0 as *const _); if job.is_null() { - return None + return None; } let job = Handle { inner: job }; @@ -77,14 +77,15 @@ mod imp { // our children will reside in the job once we spawn a process. let mut info: winapi::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; info = mem::zeroed(); - info.BasicLimitInformation.LimitFlags = - winapi::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - let r = kernel32::SetInformationJobObject(job.inner, - winapi::JobObjectExtendedLimitInformation, - &mut info as *mut _ as winapi::LPVOID, - mem::size_of_val(&info) as winapi::DWORD); + info.BasicLimitInformation.LimitFlags = winapi::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let r = kernel32::SetInformationJobObject( + job.inner, + winapi::JobObjectExtendedLimitInformation, + &mut info as *mut _ as winapi::LPVOID, + mem::size_of_val(&info) as winapi::DWORD, + ); if r == 0 { - return None + return None; } // Assign our process to this job object, meaning that our children will @@ -92,7 +93,7 @@ mod imp { let me = kernel32::GetCurrentProcess(); let r = kernel32::AssignProcessToJobObject(job.inner, me); if r == 0 { - return None + return None; } Some(Setup { job: job }) @@ -121,13 +122,13 @@ mod imp { let mut info: winapi::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; info = mem::zeroed(); let r = kernel32::SetInformationJobObject( - self.job.inner, - winapi::JobObjectExtendedLimitInformation, - &mut info as *mut _ as winapi::LPVOID, - mem::size_of_val(&info) as winapi::DWORD); + self.job.inner, + winapi::JobObjectExtendedLimitInformation, + &mut info as *mut _ as winapi::LPVOID, + mem::size_of_val(&info) as winapi::DWORD, + ); if r == 0 { - info!("failed to configure job object to defaults: {}", - last_err()); + info!("failed to configure job object to defaults: {}", last_err()); } } } @@ -143,62 +144,64 @@ mod imp { let mut jobs: Jobs = mem::zeroed(); let r = kernel32::QueryInformationJobObject( - self.job.inner, - winapi::JobObjectBasicProcessIdList, - &mut jobs as *mut _ as winapi::LPVOID, - mem::size_of_val(&jobs) as winapi::DWORD, - 0 as *mut _); + self.job.inner, + winapi::JobObjectBasicProcessIdList, + &mut jobs as *mut _ as winapi::LPVOID, + mem::size_of_val(&jobs) as winapi::DWORD, + 0 as *mut _, + ); if r == 0 { info!("failed to query job object: {}", last_err()); - return false + return false; } let mut killed = false; let list = &jobs.list[..jobs.header.NumberOfProcessIdsInList as usize]; assert!(list.len() > 0); - let list = list.iter().filter(|&&id| { - // let's not kill ourselves - id as winapi::DWORD != kernel32::GetCurrentProcessId() - }).filter_map(|&id| { - // Open the process with the necessary rights, and if this - // fails then we probably raced with the process exiting so we - // ignore the problem. - let flags = winapi::PROCESS_QUERY_INFORMATION | - winapi::PROCESS_TERMINATE | - winapi::SYNCHRONIZE; - let p = kernel32::OpenProcess(flags, - winapi::FALSE, - id as winapi::DWORD); - if p.is_null() { - None - } else { - Some(Handle { inner: p }) - } - }).filter(|p| { - // Test if this process was actually in the job object or not. - // If it's not then we likely raced with something else - // recycling this PID, so we just skip this step. - let mut res = 0; - let r = kernel32::IsProcessInJob(p.inner, self.job.inner, &mut res); - if r == 0 { - info!("failed to test is process in job: {}", last_err()); - return false - } - res == winapi::TRUE - }); - + let list = list.iter() + .filter(|&&id| { + // let's not kill ourselves + id as winapi::DWORD != kernel32::GetCurrentProcessId() + }) + .filter_map(|&id| { + // Open the process with the necessary rights, and if this + // fails then we probably raced with the process exiting so we + // ignore the problem. + let flags = winapi::PROCESS_QUERY_INFORMATION | winapi::PROCESS_TERMINATE + | winapi::SYNCHRONIZE; + let p = kernel32::OpenProcess(flags, winapi::FALSE, id as winapi::DWORD); + if p.is_null() { + None + } else { + Some(Handle { inner: p }) + } + }) + .filter(|p| { + // Test if this process was actually in the job object or not. + // If it's not then we likely raced with something else + // recycling this PID, so we just skip this step. + let mut res = 0; + let r = kernel32::IsProcessInJob(p.inner, self.job.inner, &mut res); + if r == 0 { + info!("failed to test is process in job: {}", last_err()); + return false; + } + res == winapi::TRUE + }); for p in list { // Load the file which this process was spawned from. We then // later use this for identification purposes. let mut buf = [0; 1024]; - let r = psapi::GetProcessImageFileNameW(p.inner, - buf.as_mut_ptr(), - buf.len() as winapi::DWORD); + let r = psapi::GetProcessImageFileNameW( + p.inner, + buf.as_mut_ptr(), + buf.len() as winapi::DWORD, + ); if r == 0 { info!("failed to get image name: {}", last_err()); - continue + continue; } let s = OsString::from_wide(&buf[..r as usize]); info!("found remaining: {:?}", s); @@ -217,7 +220,7 @@ mod imp { if let Some(s) = s.to_str() { if s.contains("mspdbsrv") { info!("\toops, this is mspdbsrv"); - continue + continue; } } @@ -234,18 +237,20 @@ mod imp { let r = kernel32::WaitForSingleObject(p.inner, winapi::INFINITE); if r != 0 { info!("failed to wait for process to die: {}", last_err()); - return false + return false; } killed = true; } - return killed + return killed; } } impl Drop for Handle { fn drop(&mut self) { - unsafe { kernel32::CloseHandle(self.inner); } + unsafe { + kernel32::CloseHandle(self.inner); + } } } } diff --git a/src/rustup-cli/main.rs b/src/rustup-cli/main.rs index e0ebd70911..2b317afb3d 100644 --- a/src/rustup-cli/main.rs +++ b/src/rustup-cli/main.rs @@ -14,36 +14,36 @@ #![recursion_limit = "1024"] -extern crate rustup_dist; -extern crate rustup_utils; #[macro_use] extern crate error_chain; +extern crate rustup_dist; +extern crate rustup_utils; extern crate clap; -extern crate regex; -extern crate rustup; -extern crate term; extern crate itertools; -extern crate time; +extern crate markdown; extern crate rand; +extern crate regex; +extern crate rustup; extern crate scopeguard; -extern crate tempdir; extern crate sha2; -extern crate markdown; +extern crate tempdir; +extern crate term; +extern crate time; extern crate toml; extern crate wait_timeout; #[cfg(windows)] extern crate gcc; #[cfg(windows)] -extern crate winapi; -#[cfg(windows)] -extern crate winreg; +extern crate kernel32; +extern crate libc; #[cfg(windows)] extern crate user32; #[cfg(windows)] -extern crate kernel32; -extern crate libc; +extern crate winapi; +#[cfg(windows)] +extern crate winreg; #[macro_use] mod log; @@ -86,12 +86,11 @@ fn run_rustup() -> Result<()> { .and_then(|a| a.to_str()); match name { - Some("rustup") => { - rustup_mode::main() - } - Some(n) if n.starts_with("multirust-setup")|| - n.starts_with("rustup-setup") || - n.starts_with("rustup-init") => { + Some("rustup") => rustup_mode::main(), + Some(n) + if n.starts_with("multirust-setup") || n.starts_with("rustup-setup") + || n.starts_with("rustup-init") => + { // NB: The above check is only for the prefix of the file // name. Browsers rename duplicates to // e.g. rustup-setup(2), and this allows all variations @@ -121,9 +120,7 @@ fn run_rustup() -> Result<()> { self_update::install(true, false, opts) } } - Some(_) => { - proxy_mode::main() - } + Some(_) => proxy_mode::main(), None => { // Weird case. No arg0, or it's unparsable. Err(ErrorKind::NoExeName.into()) @@ -132,8 +129,10 @@ fn run_rustup() -> Result<()> { } fn do_recursion_guard() -> Result<()> { - let recursion_count = env::var("RUST_RECURSION_COUNT").ok() - .and_then(|s| s.parse().ok()).unwrap_or(0); + let recursion_count = env::var("RUST_RECURSION_COUNT") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); if recursion_count > RUST_RECURSION_COUNT_MAX { return Err(ErrorKind::InfiniteRecursion.into()); } @@ -161,7 +160,7 @@ fn make_environment_compatible() { env::set_var(rvar, mval); warn!("environment variable {} is deprecated. Use {}.", mvar, rvar); } - _ => () + _ => (), } } } @@ -183,7 +182,9 @@ fn fix_windows_reg_key() { let mut path = if let Ok(p) = path { p } else { return }; - if path.vtype == RegType::REG_EXPAND_SZ { return } + if path.vtype == RegType::REG_EXPAND_SZ { + return; + } path.vtype = RegType::REG_EXPAND_SZ; @@ -191,7 +192,7 @@ fn fix_windows_reg_key() { } #[cfg(not(windows))] -fn fix_windows_reg_key() { } +fn fix_windows_reg_key() {} // rustup used to be called 'multirust'. This deletes the old bin. fn delete_multirust_bin() { diff --git a/src/rustup-cli/proxy_mode.rs b/src/rustup-cli/proxy_mode.rs index f865d927f7..9b9c174b52 100644 --- a/src/rustup-cli/proxy_mode.rs +++ b/src/rustup-cli/proxy_mode.rs @@ -1,5 +1,5 @@ use common::set_globals; -use rustup::{Cfg}; +use rustup::Cfg; use errors::*; use rustup_utils::utils; use rustup::command::run_command_for_dir; @@ -9,7 +9,7 @@ use std::path::PathBuf; use job; pub fn main() -> Result<()> { - try!(::self_update::cleanup_self_updater()); + ::self_update::cleanup_self_updater()?; let _setup = job::setup(); @@ -19,18 +19,17 @@ pub fn main() -> Result<()> { let arg0 = arg0.as_ref() .and_then(|a| a.file_name()) .and_then(|a| a.to_str()); - let ref arg0 = try!(arg0.ok_or(ErrorKind::NoExeName)); + let ref arg0 = arg0.ok_or(ErrorKind::NoExeName)?; // Check for a toolchain specifier. let arg1 = args.next(); - let toolchain = arg1.as_ref() - .and_then(|arg1| { - if arg1.starts_with('+') { - Some(&arg1[1..]) - } else { - None - } - }); + let toolchain = arg1.as_ref().and_then(|arg1| { + if arg1.starts_with('+') { + Some(&arg1[1..]) + } else { + None + } + }); // Build command args now while we know whether or not to skip arg 1. let cmd_args: Vec<_> = if toolchain.is_none() { @@ -39,17 +38,17 @@ pub fn main() -> Result<()> { env::args_os().skip(2).collect() }; - let cfg = try!(set_globals(false)); - try!(cfg.check_metadata_version()); - try!(direct_proxy(&cfg, arg0, toolchain, &cmd_args)); + let cfg = set_globals(false)?; + cfg.check_metadata_version()?; + direct_proxy(&cfg, arg0, toolchain, &cmd_args)?; Ok(()) } fn direct_proxy(cfg: &Cfg, arg0: &str, toolchain: Option<&str>, args: &[OsString]) -> Result<()> { let cmd = match toolchain { - None => try!(cfg.create_command_for_dir(&try!(utils::current_dir()), arg0)), - Some(tc) => try!(cfg.create_command_for_toolchain(tc, false, arg0)), + None => cfg.create_command_for_dir(&utils::current_dir()?, arg0)?, + Some(tc) => cfg.create_command_for_toolchain(tc, false, arg0)?, }; - Ok(try!(run_command_for_dir(cmd, arg0, args, &cfg))) + Ok(run_command_for_dir(cmd, arg0, args, &cfg)?) } diff --git a/src/rustup-cli/rustup_mode.rs b/src/rustup-cli/rustup_mode.rs index 21524e1b5a..05568e1899 100644 --- a/src/rustup-cli/rustup_mode.rs +++ b/src/rustup-cli/rustup_mode.rs @@ -1,10 +1,10 @@ -use clap::{App, Arg, ArgGroup, AppSettings, SubCommand, ArgMatches, Shell}; +use clap::{App, AppSettings, Arg, ArgGroup, ArgMatches, Shell, SubCommand}; use common; -use rustup::{Cfg, Toolchain, command}; +use rustup::{command, Cfg, Toolchain}; use rustup::settings::TelemetryMode; use errors::*; use rustup_dist::manifest::Component; -use rustup_dist::dist::{TargetTriple, PartialToolchainDesc, PartialTargetTriple}; +use rustup_dist::dist::{PartialTargetTriple, PartialToolchainDesc, TargetTriple}; use rustup_utils::utils; use self_update; use std::path::Path; @@ -16,85 +16,75 @@ use std::io::{self, Write}; use help::*; pub fn main() -> Result<()> { - try!(::self_update::cleanup_self_updater()); + ::self_update::cleanup_self_updater()?; let ref matches = cli().get_matches(); let verbose = matches.is_present("verbose"); - let ref cfg = try!(common::set_globals(verbose)); + let ref cfg = common::set_globals(verbose)?; - if try!(maybe_upgrade_data(cfg, matches)) { - return Ok(()) + if maybe_upgrade_data(cfg, matches)? { + return Ok(()); } - try!(cfg.check_metadata_version()); + cfg.check_metadata_version()?; match matches.subcommand() { - ("show", Some(_)) => try!(show(cfg)), - ("install", Some(m)) => try!(update(cfg, m)), - ("update", Some(m)) => try!(update(cfg, m)), - ("uninstall", Some(m)) => try!(toolchain_remove(cfg, m)), - ("default", Some(m)) => try!(default_(cfg, m)), - ("toolchain", Some(c)) => { - match c.subcommand() { - ("install", Some(m)) => try!(update(cfg, m)), - ("list", Some(_)) => try!(common::list_toolchains(cfg)), - ("link", Some(m)) => try!(toolchain_link(cfg, m)), - ("uninstall", Some(m)) => try!(toolchain_remove(cfg, m)), - (_, _) => unreachable!(), - } - } - ("target", Some(c)) => { - match c.subcommand() { - ("list", Some(m)) => try!(target_list(cfg, m)), - ("add", Some(m)) => try!(target_add(cfg, m)), - ("remove", Some(m)) => try!(target_remove(cfg, m)), - (_, _) => unreachable!(), - } - } - ("component", Some(c)) => { - match c.subcommand() { - ("list", Some(m)) => try!(component_list(cfg, m)), - ("add", Some(m)) => try!(component_add(cfg, m)), - ("remove", Some(m)) => try!(component_remove(cfg, m)), - (_, _) => unreachable!(), - } - } - ("override", Some(c)) => { - match c.subcommand() { - ("list", Some(_)) => try!(common::list_overrides(cfg)), - ("set", Some(m)) => try!(override_add(cfg, m)), - ("unset", Some(m)) => try!(override_remove(cfg, m)), - (_ ,_) => unreachable!(), - } - } - ("run", Some(m)) => try!(run(cfg, m)), - ("which", Some(m)) => try!(which(cfg, m)), - ("doc", Some(m)) => try!(doc(cfg, m)), - ("man", Some(m)) => try!(man(cfg,m)), - ("self", Some(c)) => { - match c.subcommand() { - ("update", Some(_)) => try!(self_update::update()), - ("uninstall", Some(m)) => try!(self_uninstall(m)), - (_ ,_) => unreachable!(), - } - } - ("telemetry", Some(c)) => { - match c.subcommand() { - ("enable", Some(_)) => try!(set_telemetry(&cfg, TelemetryMode::On)), - ("disable", Some(_)) => try!(set_telemetry(&cfg, TelemetryMode::Off)), - ("analyze", Some(_)) => try!(analyze_telemetry(&cfg)), - (_, _) => unreachable!(), - } - } - ("set", Some(c)) => { - match c.subcommand() { - ("default-host", Some(m)) => try!(set_default_host_triple(&cfg, m)), - (_, _) => unreachable!(), - } - } + ("show", Some(_)) => show(cfg)?, + ("install", Some(m)) => update(cfg, m)?, + ("update", Some(m)) => update(cfg, m)?, + ("uninstall", Some(m)) => toolchain_remove(cfg, m)?, + ("default", Some(m)) => default_(cfg, m)?, + ("toolchain", Some(c)) => match c.subcommand() { + ("install", Some(m)) => update(cfg, m)?, + ("list", Some(_)) => common::list_toolchains(cfg)?, + ("link", Some(m)) => toolchain_link(cfg, m)?, + ("uninstall", Some(m)) => toolchain_remove(cfg, m)?, + (_, _) => unreachable!(), + }, + ("target", Some(c)) => match c.subcommand() { + ("list", Some(m)) => target_list(cfg, m)?, + ("add", Some(m)) => target_add(cfg, m)?, + ("remove", Some(m)) => target_remove(cfg, m)?, + (_, _) => unreachable!(), + }, + ("component", Some(c)) => match c.subcommand() { + ("list", Some(m)) => component_list(cfg, m)?, + ("add", Some(m)) => component_add(cfg, m)?, + ("remove", Some(m)) => component_remove(cfg, m)?, + (_, _) => unreachable!(), + }, + ("override", Some(c)) => match c.subcommand() { + ("list", Some(_)) => common::list_overrides(cfg)?, + ("set", Some(m)) => override_add(cfg, m)?, + ("unset", Some(m)) => override_remove(cfg, m)?, + (_, _) => unreachable!(), + }, + ("run", Some(m)) => run(cfg, m)?, + ("which", Some(m)) => which(cfg, m)?, + ("doc", Some(m)) => doc(cfg, m)?, + ("man", Some(m)) => man(cfg, m)?, + ("self", Some(c)) => match c.subcommand() { + ("update", Some(_)) => self_update::update()?, + ("uninstall", Some(m)) => self_uninstall(m)?, + (_, _) => unreachable!(), + }, + ("telemetry", Some(c)) => match c.subcommand() { + ("enable", Some(_)) => set_telemetry(&cfg, TelemetryMode::On)?, + ("disable", Some(_)) => set_telemetry(&cfg, TelemetryMode::Off)?, + ("analyze", Some(_)) => analyze_telemetry(&cfg)?, + (_, _) => unreachable!(), + }, + ("set", Some(c)) => match c.subcommand() { + ("default-host", Some(m)) => set_default_host_triple(&cfg, m)?, + (_, _) => unreachable!(), + }, ("completions", Some(c)) => { if let Some(shell) = c.value_of("shell") { - cli().gen_completions_to("rustup", shell.parse::().unwrap(), &mut io::stdout()); + cli().gen_completions_to( + "rustup", + shell.parse::().unwrap(), + &mut io::stdout(), + ); } } (_, _) => unreachable!(), @@ -111,271 +101,352 @@ pub fn cli() -> App<'static, 'static> { .setting(AppSettings::VersionlessSubcommands) .setting(AppSettings::DeriveDisplayOrder) .setting(AppSettings::SubcommandRequiredElseHelp) - .arg(Arg::with_name("verbose") - .help("Enable verbose output") - .short("v") - .long("verbose")) - .subcommand(SubCommand::with_name("show") - .about("Show the active and installed toolchains") - .after_help(SHOW_HELP)) - .subcommand(SubCommand::with_name("install") + .arg( + Arg::with_name("verbose") + .help("Enable verbose output") + .short("v") + .long("verbose"), + ) + .subcommand( + SubCommand::with_name("show") + .about("Show the active and installed toolchains") + .after_help(SHOW_HELP), + ) + .subcommand( + SubCommand::with_name("install") .about("Update Rust toolchains") .after_help(INSTALL_HELP) .setting(AppSettings::Hidden) // synonym for 'toolchain install' .arg(Arg::with_name("toolchain") .help(TOOLCHAIN_ARG_HELP) .required(true) - .multiple(true))) - .subcommand(SubCommand::with_name("uninstall") + .multiple(true)), + ) + .subcommand( + SubCommand::with_name("uninstall") .about("Uninstall Rust toolchains") .setting(AppSettings::Hidden) // synonym for 'toolchain uninstall' .arg(Arg::with_name("toolchain") .help(TOOLCHAIN_ARG_HELP) .required(true) - .multiple(true))) - .subcommand(SubCommand::with_name("update") - .about("Update Rust toolchains and rustup") - .after_help(UPDATE_HELP) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .required(false) - .multiple(true)) - .arg(Arg::with_name("no-self-update") - .help("Don't perform self update when running the `rustup` command") - .long("no-self-update") - .takes_value(false) - .hidden(true))) - .subcommand(SubCommand::with_name("default") - .about("Set the default toolchain") - .after_help(DEFAULT_HELP) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .required(true))) - .subcommand(SubCommand::with_name("toolchain") - .about("Modify or query the installed toolchains") - .after_help(TOOLCHAIN_HELP) - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list") - .about("List installed toolchains")) - .subcommand(SubCommand::with_name("install") - .about("Install or update a given toolchain") - .aliases(&["update", "add"]) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .required(true) - .multiple(true))) - .subcommand(SubCommand::with_name("uninstall") - .about("Uninstall a toolchain") - .alias("remove") - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .required(true) - .multiple(true))) - .subcommand(SubCommand::with_name("link") - .about("Create a custom toolchain by symlinking to a directory") - .after_help(TOOLCHAIN_LINK_HELP) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .required(true)) - .arg(Arg::with_name("path") - .required(true)))) - .subcommand(SubCommand::with_name("target") - .about("Modify a toolchain's supported targets") - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list") - .about("List installed and available targets") - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("add") - .about("Add a target to a Rust toolchain") - .alias("install") - .arg(Arg::with_name("target") - .required(true) - .multiple(true)) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("remove") - .about("Remove a target from a Rust toolchain") - .alias("uninstall") - .arg(Arg::with_name("target") - .required(true) - .multiple(true)) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .long("toolchain") - .takes_value(true)))) - .subcommand(SubCommand::with_name("component") - .about("Modify a toolchain's installed components") - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list") - .about("List installed and available components") - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .long("toolchain") - .takes_value(true))) - .subcommand(SubCommand::with_name("add") - .about("Add a component to a Rust toolchain") - .arg(Arg::with_name("component") - .required(true) - .multiple(true)) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .long("toolchain") - .takes_value(true)) - .arg(Arg::with_name("target") - .long("target") - .takes_value(true))) - .subcommand(SubCommand::with_name("remove") - .about("Remove a component from a Rust toolchain") - .arg(Arg::with_name("component") - .required(true) - .multiple(true)) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .long("toolchain") - .takes_value(true)) - .arg(Arg::with_name("target") - .long("target") - .takes_value(true)))) - .subcommand(SubCommand::with_name("override") - .about("Modify directory toolchain overrides") - .after_help(OVERRIDE_HELP) + .multiple(true)), + ) + .subcommand( + SubCommand::with_name("update") + .about("Update Rust toolchains and rustup") + .after_help(UPDATE_HELP) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .required(false) + .multiple(true), + ) + .arg( + Arg::with_name("no-self-update") + .help("Don't perform self update when running the `rustup` command") + .long("no-self-update") + .takes_value(false) + .hidden(true), + ), + ) + .subcommand( + SubCommand::with_name("default") + .about("Set the default toolchain") + .after_help(DEFAULT_HELP) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .required(true), + ), + ) + .subcommand( + SubCommand::with_name("toolchain") + .about("Modify or query the installed toolchains") + .after_help(TOOLCHAIN_HELP) + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(SubCommand::with_name("list").about("List installed toolchains")) + .subcommand( + SubCommand::with_name("install") + .about("Install or update a given toolchain") + .aliases(&["update", "add"]) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .required(true) + .multiple(true), + ), + ) + .subcommand( + SubCommand::with_name("uninstall") + .about("Uninstall a toolchain") + .alias("remove") + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .required(true) + .multiple(true), + ), + ) + .subcommand( + SubCommand::with_name("link") + .about("Create a custom toolchain by symlinking to a directory") + .after_help(TOOLCHAIN_LINK_HELP) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .required(true), + ) + .arg(Arg::with_name("path").required(true)), + ), + ) + .subcommand( + SubCommand::with_name("target") + .about("Modify a toolchain's supported targets") + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("list") + .about("List installed and available targets") + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("add") + .about("Add a target to a Rust toolchain") + .alias("install") + .arg(Arg::with_name("target").required(true).multiple(true)) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("remove") + .about("Remove a target from a Rust toolchain") + .alias("uninstall") + .arg(Arg::with_name("target").required(true).multiple(true)) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .long("toolchain") + .takes_value(true), + ), + ), + ) + .subcommand( + SubCommand::with_name("component") + .about("Modify a toolchain's installed components") + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("list") + .about("List installed and available components") + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .long("toolchain") + .takes_value(true), + ), + ) + .subcommand( + SubCommand::with_name("add") + .about("Add a component to a Rust toolchain") + .arg(Arg::with_name("component").required(true).multiple(true)) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .long("toolchain") + .takes_value(true), + ) + .arg(Arg::with_name("target").long("target").takes_value(true)), + ) + .subcommand( + SubCommand::with_name("remove") + .about("Remove a component from a Rust toolchain") + .arg(Arg::with_name("component").required(true).multiple(true)) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .long("toolchain") + .takes_value(true), + ) + .arg(Arg::with_name("target").long("target").takes_value(true)), + ), + ) + .subcommand( + SubCommand::with_name("override") + .about("Modify directory toolchain overrides") + .after_help(OVERRIDE_HELP) + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("list").about("List directory toolchain overrides"), + ) + .subcommand( + SubCommand::with_name("set") + .about("Set the override toolchain for a directory") + .alias("add") + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .required(true), + ), + ) + .subcommand( + SubCommand::with_name("unset") + .about("Remove the override toolchain for a directory") + .after_help(OVERRIDE_UNSET_HELP) + .alias("remove") + .arg( + Arg::with_name("path") + .long("path") + .takes_value(true) + .help("Path to the directory"), + ) + .arg( + Arg::with_name("nonexistent") + .long("nonexistent") + .takes_value(false) + .help("Remove override toolchain for all nonexistent directories"), + ), + ), + ) + .subcommand( + SubCommand::with_name("run") + .about("Run a command with an environment configured for a given toolchain") + .after_help(RUN_HELP) + .setting(AppSettings::TrailingVarArg) + .arg( + Arg::with_name("install") + .help("Install the requested toolchain if needed") + .long("install"), + ) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .required(true), + ) + .arg( + Arg::with_name("command") + .required(true) + .multiple(true) + .use_delimiter(false), + ), + ) + .subcommand( + SubCommand::with_name("which") + .about("Display which binary will be run for a given command") + .arg(Arg::with_name("command").required(true)), + ) + .subcommand( + SubCommand::with_name("doc") + .alias("docs") + .about("Open the documentation for the current toolchain") + .after_help(DOC_HELP) + .arg( + Arg::with_name("book") + .long("book") + .help("The Rust Programming Language book"), + ) + .arg( + Arg::with_name("std") + .long("std") + .help("Standard library API documentation"), + ) + .group(ArgGroup::with_name("page").args(&["book", "std"])), + ); + + if cfg!(not(target_os = "windows")) { + app = app.subcommand( + SubCommand::with_name("man") + .about("View the man page for a given command") + .arg(Arg::with_name("command").required(true)) + .arg( + Arg::with_name("toolchain") + .help(TOOLCHAIN_ARG_HELP) + .long("toolchain") + .takes_value(true), + ), + ); + } + + app.subcommand( + SubCommand::with_name("self") + .about("Modify the rustup installation") .setting(AppSettings::VersionlessSubcommands) .setting(AppSettings::DeriveDisplayOrder) .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("list") - .about("List directory toolchain overrides")) - .subcommand(SubCommand::with_name("set") - .about("Set the override toolchain for a directory") - .alias("add") - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .required(true))) - .subcommand(SubCommand::with_name("unset") - .about("Remove the override toolchain for a directory") - .after_help(OVERRIDE_UNSET_HELP) - .alias("remove") - .arg(Arg::with_name("path") - .long("path") - .takes_value(true) - .help("Path to the directory")) - .arg(Arg::with_name("nonexistent") - .long("nonexistent") - .takes_value(false) - .help("Remove override toolchain for all nonexistent directories")))) - .subcommand(SubCommand::with_name("run") - .about("Run a command with an environment configured for a given toolchain") - .after_help(RUN_HELP) - .setting(AppSettings::TrailingVarArg) - .arg(Arg::with_name("install") - .help("Install the requested toolchain if needed") - .long("install")) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .required(true)) - .arg(Arg::with_name("command") - .required(true).multiple(true).use_delimiter(false))) - .subcommand(SubCommand::with_name("which") - .about("Display which binary will be run for a given command") - .arg(Arg::with_name("command") - .required(true))) - .subcommand(SubCommand::with_name("doc") - .alias("docs") - .about("Open the documentation for the current toolchain") - .after_help(DOC_HELP) - .arg(Arg::with_name("book") - .long("book") - .help("The Rust Programming Language book")) - .arg(Arg::with_name("std") - .long("std") - .help("Standard library API documentation")) - .group(ArgGroup::with_name("page") - .args(&["book", "std"]))); - - if cfg!(not(target_os = "windows")) { - app = app - .subcommand(SubCommand::with_name("man") - .about("View the man page for a given command") - .arg(Arg::with_name("command") - .required(true)) - .arg(Arg::with_name("toolchain") - .help(TOOLCHAIN_ARG_HELP) - .long("toolchain") - .takes_value(true))); - } - - app.subcommand(SubCommand::with_name("self") - .about("Modify the rustup installation") - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("update") - .about("Download and install updates to rustup")) - .subcommand(SubCommand::with_name("uninstall") - .about("Uninstall rustup.") - .arg(Arg::with_name("no-prompt") - .short("y"))) - .subcommand(SubCommand::with_name("upgrade-data") - .about("Upgrade the internal data format."))) - .subcommand(SubCommand::with_name("telemetry") - .about("rustup telemetry commands") - .setting(AppSettings::Hidden) - .setting(AppSettings::VersionlessSubcommands) - .setting(AppSettings::DeriveDisplayOrder) - .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("enable") - .about("Enable rustup telemetry")) - .subcommand(SubCommand::with_name("disable") - .about("Disable rustup telemetry")) - .subcommand(SubCommand::with_name("analyze") - .about("Analyze stored telemetry"))) - .subcommand(SubCommand::with_name("set") - .about("Alter rustup settings") - .setting(AppSettings::SubcommandRequiredElseHelp) - .subcommand(SubCommand::with_name("default-host") - .about("The triple used to identify toolchains when not specified") - .arg(Arg::with_name("host_triple") - .required(true)))) - .subcommand(SubCommand::with_name("completions") - .about("Generate completion scripts for your shell") - .after_help(COMPLETIONS_HELP) - .setting(AppSettings::ArgRequiredElseHelp) - .arg(Arg::with_name("shell") - .possible_values(&Shell::variants()))) + .subcommand( + SubCommand::with_name("update").about("Download and install updates to rustup"), + ) + .subcommand( + SubCommand::with_name("uninstall") + .about("Uninstall rustup.") + .arg(Arg::with_name("no-prompt").short("y")), + ) + .subcommand( + SubCommand::with_name("upgrade-data").about("Upgrade the internal data format."), + ), + ).subcommand( + SubCommand::with_name("telemetry") + .about("rustup telemetry commands") + .setting(AppSettings::Hidden) + .setting(AppSettings::VersionlessSubcommands) + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand(SubCommand::with_name("enable").about("Enable rustup telemetry")) + .subcommand(SubCommand::with_name("disable").about("Disable rustup telemetry")) + .subcommand(SubCommand::with_name("analyze").about("Analyze stored telemetry")), + ) + .subcommand( + SubCommand::with_name("set") + .about("Alter rustup settings") + .setting(AppSettings::SubcommandRequiredElseHelp) + .subcommand( + SubCommand::with_name("default-host") + .about("The triple used to identify toolchains when not specified") + .arg(Arg::with_name("host_triple").required(true)), + ), + ) + .subcommand( + SubCommand::with_name("completions") + .about("Generate completion scripts for your shell") + .after_help(COMPLETIONS_HELP) + .setting(AppSettings::ArgRequiredElseHelp) + .arg(Arg::with_name("shell").possible_values(&Shell::variants())), + ) } fn maybe_upgrade_data(cfg: &Cfg, m: &ArgMatches) -> Result { match m.subcommand() { - ("self", Some(c)) => { - match c.subcommand() { - ("upgrade-data", Some(_)) => { - try!(cfg.upgrade_data()); - Ok(true) - } - _ => Ok(false), + ("self", Some(c)) => match c.subcommand() { + ("upgrade-data", Some(_)) => { + cfg.upgrade_data()?; + Ok(true) } - } - _ => Ok(false) + _ => Ok(false), + }, + _ => Ok(false), } } fn update_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 installed_toolchains = try!(cfg.list_toolchains()); - let default = try!(cfg.find_default()); - let default_name = default.map(|t| t.name().to_string()) - .unwrap_or("".into()); + 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 mut candidates = vec![]; for t in installed_toolchains { if t == default_name { @@ -386,10 +457,18 @@ fn update_bare_triple_check(cfg: &Cfg, name: &str) -> Result<()> { from_desc.map_or(false, |s| *s == *given) } - let triple_matches = - triple.arch.as_ref().map_or(true, |s| triple_comp_eq(s, desc.target.arch.as_ref())) - && triple.os.as_ref().map_or(true, |s| triple_comp_eq(s, desc.target.os.as_ref())) - && triple.env.as_ref().map_or(true, |s| triple_comp_eq(s, desc.target.env.as_ref())); + let triple_matches = triple + .arch + .as_ref() + .map_or(true, |s| triple_comp_eq(s, desc.target.arch.as_ref())) + && triple + .os + .as_ref() + .map_or(true, |s| triple_comp_eq(s, desc.target.os.as_ref())) + && triple + .env + .as_ref() + .map_or(true, |s| triple_comp_eq(s, desc.target.env.as_ref())); if triple_matches { candidates.push(t); } @@ -414,17 +493,22 @@ fn update_bare_triple_check(cfg: &Cfg, name: &str) -> Result<()> { 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 = try!(cfg.find_default()); - let default_name = default.map(|t| t.name().to_string()) - .unwrap_or("".into()); + let default = cfg.find_default()?; + let default_name = default.map(|t| t.name().to_string()).unwrap_or("".into()); if let Ok(mut desc) = PartialToolchainDesc::from_str(&default_name) { desc.target = triple; let maybe_toolchain = format!("{}", desc); - let ref toolchain = try!(cfg.get_toolchain(maybe_toolchain.as_ref(), false)); + let ref 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", name); + warn!( + "(partial) triple '{}' resolves to a toolchain that is already default", + name + ); } else { - println!("\nyou may use the following toolchain: {}\n", toolchain.name()); + println!( + "\nyou may use the following toolchain: {}\n", + toolchain.name() + ); } return Err(ErrorKind::ToolchainNotInstalled(name.to_string()).into()); } @@ -434,22 +518,22 @@ fn default_bare_triple_check(cfg: &Cfg, name: &str) -> Result<()> { fn default_(cfg: &Cfg, m: &ArgMatches) -> Result<()> { let ref toolchain = m.value_of("toolchain").expect(""); - try!(default_bare_triple_check(cfg, toolchain)); - let ref toolchain = try!(cfg.get_toolchain(toolchain, false)); + default_bare_triple_check(cfg, toolchain)?; + let ref toolchain = cfg.get_toolchain(toolchain, false)?; let status = if !toolchain.is_custom() { - Some(try!(toolchain.install_from_dist_if_not_installed())) + Some(toolchain.install_from_dist_if_not_installed()?) } else if !toolchain.exists() { return Err(ErrorKind::ToolchainNotInstalled(toolchain.name().to_string()).into()); } else { None }; - try!(toolchain.make_default()); + toolchain.make_default()?; if let Some(status) = status { println!(""); - try!(common::show_channel_update(cfg, toolchain.name(), Ok(status))); + common::show_channel_update(cfg, toolchain.name(), Ok(status))?; } Ok(()) @@ -458,11 +542,11 @@ fn default_(cfg: &Cfg, m: &ArgMatches) -> Result<()> { fn update(cfg: &Cfg, m: &ArgMatches) -> Result<()> { if let Some(names) = m.values_of("toolchain") { for name in names { - try!(update_bare_triple_check(cfg, name)); - let toolchain = try!(cfg.get_toolchain(name, false)); + update_bare_triple_check(cfg, name)?; + let toolchain = cfg.get_toolchain(name, false)?; let status = if !toolchain.is_custom() { - Some(try!(toolchain.install_from_dist())) + Some(toolchain.install_from_dist()?) } else if !toolchain.exists() { return Err(ErrorKind::ToolchainNotInstalled(toolchain.name().to_string()).into()); } else { @@ -471,11 +555,14 @@ fn update(cfg: &Cfg, m: &ArgMatches) -> Result<()> { if let Some(status) = status { println!(""); - try!(common::show_channel_update(cfg, toolchain.name(), Ok(status))); + common::show_channel_update(cfg, toolchain.name(), Ok(status))?; } } } else { - try!(common::update_all_channels(cfg, !m.is_present("no-self-update") && !self_update::NEVER_SELF_UPDATE)); + common::update_all_channels( + cfg, + !m.is_present("no-self-update") && !self_update::NEVER_SELF_UPDATE, + )?; } Ok(()) @@ -485,18 +572,23 @@ fn run(cfg: &Cfg, m: &ArgMatches) -> Result<()> { let ref toolchain = m.value_of("toolchain").expect(""); let args = m.values_of("command").unwrap(); let args: Vec<_> = args.collect(); - let cmd = try!(cfg.create_command_for_toolchain(toolchain, m.is_present("install"), args[0])); - - Ok(try!(command::run_command_for_dir(cmd, args[0], &args[1..], &cfg))) + let cmd = cfg.create_command_for_toolchain(toolchain, m.is_present("install"), args[0])?; + + Ok(command::run_command_for_dir( + cmd, + args[0], + &args[1..], + &cfg, + )?) } fn which(cfg: &Cfg, m: &ArgMatches) -> Result<()> { let binary = m.value_of("command").expect(""); - let binary_path = try!(cfg.which_binary(&try!(utils::current_dir()), binary)) - .expect("binary not found"); + let binary_path = cfg.which_binary(&utils::current_dir()?, binary)? + .expect("binary not found"); - try!(utils::assert_is_file(&binary_path)); + utils::assert_is_file(&binary_path)?; println!("{}", binary_path.display()); @@ -510,12 +602,12 @@ fn show(cfg: &Cfg) -> Result<()> { let _ = t.attr(term2::Attr::Bold); let _ = write!(t, "Default host: "); let _ = t.reset(); - println!("{}", try!(cfg.get_default_host_triple())); + println!("{}", cfg.get_default_host_triple()?); println!(""); } - let ref cwd = try!(utils::current_dir()); - let installed_toolchains = try!(cfg.list_toolchains()); + let ref cwd = utils::current_dir()?; + let installed_toolchains = cfg.list_toolchains()?; let active_toolchain = cfg.find_override_toolchain_or_default(cwd); // active_toolchain will carry the reason we don't have one in its detail. @@ -527,7 +619,7 @@ fn show(cfg: &Cfg) -> Result<()> { .filter(|c| c.component.pkg == "rust-std") .filter(|c| c.installed) .collect(), - Err(_) => vec![] + Err(_) => vec![], } } else { vec![] @@ -544,12 +636,16 @@ fn show(cfg: &Cfg) -> Result<()> { let show_headers = [ show_installed_toolchains, show_active_targets, - show_active_toolchain - ].iter().filter(|x| **x).count() > 1; + show_active_toolchain, + ].iter() + .filter(|x| **x) + .count() > 1; if show_installed_toolchains { - if show_headers { print_header("installed toolchains") } - let default_name = try!(cfg.get_default()); + if show_headers { + print_header("installed toolchains") + } + let default_name = cfg.get_default()?; for t in installed_toolchains { if default_name == t { println!("{} (default)", t); @@ -557,7 +653,9 @@ fn show(cfg: &Cfg) -> Result<()> { println!("{}", t); } } - if show_headers { println!("") }; + if show_headers { + println!("") + }; } if show_active_targets { @@ -565,30 +663,38 @@ fn show(cfg: &Cfg) -> Result<()> { print_header("installed targets for active toolchain"); } for t in active_targets { - println!("{}", t.component.target.as_ref().expect("rust-std should have a target")); + println!( + "{}", + t.component + .target + .as_ref() + .expect("rust-std should have a target") + ); } - if show_headers { println!("") }; + if show_headers { + println!("") + }; } if show_active_toolchain { - if show_headers { print_header("active toolchain") } + if show_headers { + print_header("active toolchain") + } match active_toolchain { - Ok(atc) => { - match atc { - Some((ref toolchain, Some(ref reason))) => { - println!("{} ({})", toolchain.name(), reason); - println!("{}", common::rustc_version(toolchain)); - } - Some((ref toolchain, None)) => { - println!("{} (default)", toolchain.name()); - println!("{}", common::rustc_version(toolchain)); - } - None => { - println!("no active toolchain"); - } + Ok(atc) => match atc { + Some((ref toolchain, Some(ref reason))) => { + println!("{} ({})", toolchain.name(), reason); + println!("{}", common::rustc_version(toolchain)); } - } + Some((ref toolchain, None)) => { + println!("{} (default)", toolchain.name()); + println!("{}", common::rustc_version(toolchain)); + } + None => { + println!("no active toolchain"); + } + }, Err(err) => { if let Some(cause) = err.cause() { println!("(error: {}, {})", err, cause); @@ -598,7 +704,9 @@ fn show(cfg: &Cfg) -> Result<()> { } } - if show_headers { println!("") }; + if show_headers { + println!("") + }; } fn print_header(s: &str) { @@ -614,13 +722,13 @@ fn show(cfg: &Cfg) -> Result<()> { } fn target_list(cfg: &Cfg, m: &ArgMatches) -> Result<()> { - let toolchain = try!(explicit_or_dir_toolchain(cfg, m)); + let toolchain = explicit_or_dir_toolchain(cfg, m)?; common::list_targets(&toolchain) } fn target_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { - let toolchain = try!(explicit_or_dir_toolchain(cfg, m)); + let toolchain = explicit_or_dir_toolchain(cfg, m)?; for target in m.values_of("target").expect("") { let new_component = Component { @@ -628,14 +736,14 @@ fn target_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { target: Some(TargetTriple::from_str(target)), }; - try!(toolchain.add_component(new_component)); + toolchain.add_component(new_component)?; } Ok(()) } fn target_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { - let toolchain = try!(explicit_or_dir_toolchain(cfg, m)); + let toolchain = explicit_or_dir_toolchain(cfg, m)?; for target in m.values_of("target").expect("") { let new_component = Component { @@ -643,23 +751,29 @@ fn target_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { target: Some(TargetTriple::from_str(target)), }; - try!(toolchain.remove_component(new_component)); + toolchain.remove_component(new_component)?; } Ok(()) } fn component_list(cfg: &Cfg, m: &ArgMatches) -> Result<()> { - let toolchain = try!(explicit_or_dir_toolchain(cfg, m)); + let toolchain = explicit_or_dir_toolchain(cfg, m)?; common::list_components(&toolchain) } fn component_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { - let toolchain = try!(explicit_or_dir_toolchain(cfg, m)); - let target = m.value_of("target").map(TargetTriple::from_str).or_else(|| { - toolchain.desc().as_ref().ok().map(|desc| desc.target.clone()) - }); + let toolchain = explicit_or_dir_toolchain(cfg, m)?; + let target = m.value_of("target") + .map(TargetTriple::from_str) + .or_else(|| { + toolchain + .desc() + .as_ref() + .ok() + .map(|desc| desc.target.clone()) + }); for component in m.values_of("component").expect("") { let new_component = Component { @@ -667,17 +781,23 @@ fn component_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { target: target.clone(), }; - try!(toolchain.add_component(new_component)); + toolchain.add_component(new_component)?; } Ok(()) } fn component_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { - let toolchain = try!(explicit_or_dir_toolchain(cfg, m)); - let target = m.value_of("target").map(TargetTriple::from_str).or_else(|| { - toolchain.desc().as_ref().ok().map(|desc| desc.target.clone()) - }); + let toolchain = explicit_or_dir_toolchain(cfg, m)?; + let target = m.value_of("target") + .map(TargetTriple::from_str) + .or_else(|| { + toolchain + .desc() + .as_ref() + .ok() + .map(|desc| desc.target.clone()) + }); for component in m.values_of("component").expect("") { let new_component = Component { @@ -685,7 +805,7 @@ fn component_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { target: target.clone(), }; - try!(toolchain.remove_component(new_component)); + toolchain.remove_component(new_component)?; } Ok(()) @@ -694,12 +814,12 @@ fn component_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { fn explicit_or_dir_toolchain<'a>(cfg: &'a Cfg, m: &ArgMatches) -> Result> { let toolchain = m.value_of("toolchain"); if let Some(toolchain) = toolchain { - let toolchain = try!(cfg.get_toolchain(toolchain, false)); + let toolchain = cfg.get_toolchain(toolchain, false)?; return Ok(toolchain); } - let ref cwd = try!(utils::current_dir()); - let (toolchain, _) = try!(cfg.toolchain_for_dir(cwd)); + let ref cwd = utils::current_dir()?; + let (toolchain, _) = cfg.toolchain_for_dir(cwd)?; Ok(toolchain) } @@ -707,36 +827,36 @@ 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 = try!(cfg.get_toolchain(toolchain, true)); + let toolchain = cfg.get_toolchain(toolchain, true)?; - Ok(try!(toolchain.install_from_dir(Path::new(path), true))) + Ok(toolchain.install_from_dir(Path::new(path), true)?) } fn toolchain_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { for toolchain in m.values_of("toolchain").expect("") { - let toolchain = try!(cfg.get_toolchain(toolchain, false)); - try!(toolchain.remove()); + let toolchain = cfg.get_toolchain(toolchain, false)?; + toolchain.remove()?; } Ok(()) } fn override_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { let ref toolchain = m.value_of("toolchain").expect(""); - let toolchain = try!(cfg.get_toolchain(toolchain, false)); + let toolchain = cfg.get_toolchain(toolchain, false)?; let status = if !toolchain.is_custom() { - Some(try!(toolchain.install_from_dist_if_not_installed())) + Some(toolchain.install_from_dist_if_not_installed()?) } else if !toolchain.exists() { return Err(ErrorKind::ToolchainNotInstalled(toolchain.name().to_string()).into()); } else { None }; - try!(toolchain.make_override(&try!(utils::current_dir()))); + toolchain.make_override(&utils::current_dir()?)?; if let Some(status) = status { println!(""); - try!(common::show_channel_update(cfg, toolchain.name(), Ok(status))); + common::show_channel_update(cfg, toolchain.name(), Ok(status))?; } Ok(()) @@ -744,13 +864,18 @@ fn override_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { fn override_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { let paths = if m.is_present("nonexistent") { - let list: Vec<_> = try!(cfg.settings_file.with(|s| Ok(s.overrides.iter().filter_map(|(k, _)| - if Path::new(k).is_dir() { - None - } else { - Some(k.clone()) - } - ).collect()))); + let list: Vec<_> = cfg.settings_file.with(|s| { + Ok(s.overrides + .iter() + .filter_map(|(k, _)| { + if Path::new(k).is_dir() { + None + } else { + Some(k.clone()) + } + }) + .collect()) + })?; if list.is_empty() { info!("no nonexistent paths detected"); } @@ -759,20 +884,22 @@ fn override_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { if m.is_present("path") { vec![m.value_of("path").unwrap().to_string()] } else { - vec![try!(utils::current_dir()).to_str().unwrap().to_string()] + vec![utils::current_dir()?.to_str().unwrap().to_string()] } }; for path in paths { - if try!(cfg.settings_file.with_mut(|s| { - Ok(s.remove_override(&Path::new(&path), cfg.notify_handler.as_ref())) - })) { + if cfg.settings_file + .with_mut(|s| Ok(s.remove_override(&Path::new(&path), cfg.notify_handler.as_ref())))? + { info!("override toolchain for '{}' removed", path); } else { info!("no override toolchain for '{}'", path); if !m.is_present("path") && !m.is_present("nonexistent") { - info!("you may use `--path ` option to remove override toolchain \ - for a specific path"); + info!( + "you may use `--path ` option to remove override toolchain \ + for a specific path" + ); } } } @@ -788,18 +915,18 @@ fn doc(cfg: &Cfg, m: &ArgMatches) -> Result<()> { "index.html" }; - Ok(try!(cfg.open_docs_for_dir(&try!(utils::current_dir()), doc_url))) + Ok(cfg.open_docs_for_dir(&utils::current_dir()?, doc_url)?) } fn man(cfg: &Cfg, m: &ArgMatches) -> Result<()> { let manpage = m.value_of("command").expect(""); - let toolchain = try!(explicit_or_dir_toolchain(cfg, m)); + let toolchain = explicit_or_dir_toolchain(cfg, m)?; let mut man_path = toolchain.path().to_path_buf(); man_path.push("share"); man_path.push("man"); man_path.push("man1"); man_path.push(manpage.to_owned() + ".1"); - try!(utils::assert_is_file(&man_path)); + utils::assert_is_file(&man_path)?; Command::new("man") .arg(man_path) .status() @@ -815,17 +942,17 @@ fn self_uninstall(m: &ArgMatches) -> Result<()> { fn set_telemetry(cfg: &Cfg, t: TelemetryMode) -> Result<()> { match t { - TelemetryMode::On => Ok(try!(cfg.set_telemetry(true))), - TelemetryMode::Off => Ok(try!(cfg.set_telemetry(false))), + TelemetryMode::On => Ok(cfg.set_telemetry(true)?), + TelemetryMode::Off => Ok(cfg.set_telemetry(false)?), } } fn analyze_telemetry(cfg: &Cfg) -> Result<()> { - let analysis = try!(cfg.analyze_telemetry()); + let analysis = cfg.analyze_telemetry()?; common::show_telemetry(analysis) } fn set_default_host_triple(cfg: &Cfg, m: &ArgMatches) -> Result<()> { - try!(cfg.set_default_host_triple(m.value_of("host_triple").expect(""))); + cfg.set_default_host_triple(m.value_of("host_triple").expect(""))?; Ok(()) } diff --git a/src/rustup-cli/self_update.rs b/src/rustup-cli/self_update.rs index 35f7904930..97da1a4427 100644 --- a/src/rustup-cli/self_update.rs +++ b/src/rustup-cli/self_update.rs @@ -36,7 +36,7 @@ use rustup_dist::dist; use rustup_utils::utils; use std::env; use std::env::consts::EXE_SUFFIX; -use std::path::{Path, PathBuf, Component}; +use std::path::{Component, Path, PathBuf}; use std::process::{self, Command}; use std::fs; use tempdir::TempDir; @@ -165,8 +165,7 @@ This will uninstall all Rust toolchains and data, and remove } } -static MSVC_MESSAGE: &'static str = -r#"# Rust Visual C++ prerequisites +static MSVC_MESSAGE: &'static str = r#"# Rust Visual C++ prerequisites Rust requires the Microsoft C++ build tools for Visual Studio 2013 or later, but they don't seem to be installed. @@ -189,24 +188,25 @@ doing then it is fine to continue installation without the build tools, but otherwise, install the C++ build tools before proceeding. "#; -static TOOLS: &'static [&'static str] - = &["rustc", "rustdoc", "cargo", "rust-lldb", "rust-gdb", "rls"]; +static TOOLS: &'static [&'static str] = + &["rustc", "rustdoc", "cargo", "rust-lldb", "rust-gdb", "rls"]; // Tools which are commonly installed by Cargo as well as rustup. We take a bit // more care with these to ensure we don't overwrite the user's previous // installation. static DUP_TOOLS: &'static [&'static str] = &["rustfmt", "cargo-fmt"]; -static UPDATE_ROOT: &'static str - = "https://static.rust-lang.org/rustup"; +static UPDATE_ROOT: &'static str = "https://static.rust-lang.org/rustup"; /// `CARGO_HOME` suitable for display, possibly with $HOME /// substituted for the directory prefix fn canonical_cargo_home() -> Result { - let path = try!(utils::cargo_home()); + let path = utils::cargo_home()?; let mut path_str = path.to_string_lossy().to_string(); - let default_cargo_home = utils::home_dir().unwrap_or(PathBuf::from(".")).join(".cargo"); + let default_cargo_home = utils::home_dir() + .unwrap_or(PathBuf::from(".")) + .join(".cargo"); if default_cargo_home == path { if cfg!(unix) { path_str = String::from("$HOME/.cargo"); @@ -221,19 +221,17 @@ fn canonical_cargo_home() -> Result { /// Installing is a simple matter of coping the running binary to /// `CARGO_HOME`/bin, hardlinking the various Rust tools to it, /// and adding `CARGO_HOME`/bin to PATH. -pub fn install(no_prompt: bool, verbose: bool, - mut opts: InstallOpts) -> Result<()> { +pub fn install(no_prompt: bool, verbose: bool, mut opts: InstallOpts) -> Result<()> { + do_pre_install_sanity_checks()?; + check_existence_of_rustc_or_cargo_in_path(no_prompt)?; + do_anti_sudo_check(no_prompt)?; - try!(do_pre_install_sanity_checks()); - try!(check_existence_of_rustc_or_cargo_in_path(no_prompt)); - try!(do_anti_sudo_check(no_prompt)); - - if !try!(do_msvc_check(&opts)) { + if !do_msvc_check(&opts)? { if no_prompt { warn!("installing msvc toolchain without its prerequisites"); } else { term2::stdout().md(MSVC_MESSAGE); - if !try!(common::confirm("\nContinue? (Y/n)", true)) { + if !common::confirm("\nContinue? (Y/n)", true)? { info!("aborting installation"); return Ok(()); } @@ -241,51 +239,48 @@ pub fn install(no_prompt: bool, verbose: bool, } if !no_prompt { - let ref msg = try!(pre_install_msg(opts.no_modify_path)); + let ref msg = pre_install_msg(opts.no_modify_path)?; term2::stdout().md(msg); loop { term2::stdout().md(current_install_opts(&opts)); - match try!(common::confirm_advanced()) { + match common::confirm_advanced()? { Confirm::No => { info!("aborting installation"); return Ok(()); - }, + } Confirm::Yes => { break; - }, + } Confirm::Advanced => { - opts = try!(customize_install(opts)); + opts = customize_install(opts)?; } } } } let install_res: Result<()> = (|| { - try!(cleanup_legacy()); - try!(install_bins()); + cleanup_legacy()?; + install_bins()?; if !opts.no_modify_path { - try!(do_add_to_path(&get_add_path_methods())); + do_add_to_path(&get_add_path_methods())?; } // Create ~/.rustup and a compatibility ~/.multirust symlink. // FIXME: Someday we can stop setting up the symlink, and when // we do that we can stop creating ~/.rustup as well. - try!(utils::create_rustup_home()); - try!(maybe_install_rust(&opts.default_toolchain, &opts.default_host_triple, verbose)); + utils::create_rustup_home()?; + maybe_install_rust(&opts.default_toolchain, &opts.default_host_triple, verbose)?; if cfg!(unix) { - let ref env_file = try!(utils::cargo_home()).join("env"); - let ref env_str = format!( - "{}\n", - try!(shell_export_string())); - try!(utils::write_file("env", env_file, env_str)); + 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)?; } Ok(()) })(); - if let Err(ref e) = install_res { common::report_error(e); @@ -296,7 +291,7 @@ pub fn install(no_prompt: bool, verbose: bool, if cfg!(windows) && !no_prompt { println!(""); println!("Press the Enter key to continue."); - try!(common::read_line()); + common::read_line()?; } process::exit(1); @@ -304,22 +299,24 @@ pub fn install(no_prompt: bool, verbose: bool, // More helpful advice, skip if -y if !no_prompt { - let cargo_home = try!(canonical_cargo_home()); + let cargo_home = canonical_cargo_home()?; let msg = if !opts.no_modify_path { if cfg!(unix) { - format!(post_install_msg_unix!(), - cargo_home = cargo_home) + format!(post_install_msg_unix!(), cargo_home = cargo_home) } else { - format!(post_install_msg_win!(), - cargo_home = cargo_home) + 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) + 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); @@ -330,7 +327,7 @@ pub fn install(no_prompt: bool, verbose: bool, if cfg!(windows) { println!(""); println!("Press the Enter key to continue."); - try!(common::read_line()); + common::read_line()?; } } @@ -340,8 +337,10 @@ pub fn install(no_prompt: bool, verbose: bool, fn rustc_or_cargo_exists_in_path() -> Result<()> { // Ignore rustc and cargo if present in $HOME/.cargo/bin or a few other directories fn ignore_paths(path: &PathBuf) -> bool { - !path.components().any(|c| c == Component::Normal(".cargo".as_ref())) && - !path.components().any(|c| c == Component::Normal(".multirust".as_ref())) + !path.components() + .any(|c| c == Component::Normal(".cargo".as_ref())) + && !path.components() + .any(|c| c == Component::Normal(".multirust".as_ref())) } if let Some(paths) = env::var_os("PATH") { @@ -380,27 +379,19 @@ fn check_existence_of_rustc_or_cargo_in_path(no_prompt: bool) -> Result<()> { } fn do_pre_install_sanity_checks() -> Result<()> { - let multirust_manifest_path - = PathBuf::from("/usr/local/lib/rustlib/manifest-multirust"); - let rustc_manifest_path - = PathBuf::from("/usr/local/lib/rustlib/manifest-rustc"); - let uninstaller_path - = PathBuf::from("/usr/local/lib/rustlib/uninstall.sh"); - let multirust_meta_path - = env::home_dir().map(|d| d.join(".multirust")); - let multirust_version_path - = multirust_meta_path.as_ref().map(|p| p.join("version")); - let rustup_sh_path - = env::home_dir().map(|d| d.join(".rustup")); + let multirust_manifest_path = PathBuf::from("/usr/local/lib/rustlib/manifest-multirust"); + let rustc_manifest_path = PathBuf::from("/usr/local/lib/rustlib/manifest-rustc"); + let uninstaller_path = PathBuf::from("/usr/local/lib/rustlib/uninstall.sh"); + let multirust_meta_path = env::home_dir().map(|d| d.join(".multirust")); + let multirust_version_path = multirust_meta_path.as_ref().map(|p| p.join("version")); + let rustup_sh_path = env::home_dir().map(|d| d.join(".rustup")); let rustup_sh_version_path = rustup_sh_path.as_ref().map(|p| p.join("rustup-version")); - let multirust_exists = - multirust_manifest_path.exists() && uninstaller_path.exists(); - let rustc_exists = - rustc_manifest_path.exists() && uninstaller_path.exists(); - let rustup_sh_exists = - rustup_sh_version_path.map(|p| p.exists()) == Some(true); - let old_multirust_meta_exists = if let Some(ref multirust_version_path) = multirust_version_path { + let multirust_exists = multirust_manifest_path.exists() && uninstaller_path.exists(); + let rustc_exists = rustc_manifest_path.exists() && uninstaller_path.exists(); + let rustup_sh_exists = rustup_sh_version_path.map(|p| p.exists()) == Some(true); + let old_multirust_meta_exists = if let Some(ref multirust_version_path) = multirust_version_path + { multirust_version_path.exists() && { let version = utils::read_file("old-multirust", multirust_version_path); let version = version.unwrap_or(String::new()); @@ -417,35 +408,51 @@ fn do_pre_install_sanity_checks() -> Result<()> { (true, false) => { warn!("it looks like you have an existing installation of multirust"); warn!("rustup cannot be installed alongside multirust"); - warn!("run `{}` as root to uninstall multirust before installing rustup", uninstaller_path.display()); + warn!( + "run `{}` as root to uninstall multirust before installing rustup", + uninstaller_path.display() + ); return Err("cannot install while multirust is installed".into()); } (false, true) => { warn!("it looks like you have existing multirust metadata"); warn!("rustup cannot be installed alongside multirust"); - warn!("delete `{}` before installing rustup", multirust_meta_path.expect("").display()); + warn!( + "delete `{}` before installing rustup", + multirust_meta_path.expect("").display() + ); return Err("cannot install while multirust is installed".into()); } (true, true) => { warn!("it looks like you have an existing installation of multirust"); warn!("rustup cannot be installed alongside multirust"); - warn!("run `{}` as root and delete `{}` before installing rustup", uninstaller_path.display(), multirust_meta_path.expect("").display()); + warn!( + "run `{}` as root and delete `{}` before installing rustup", + uninstaller_path.display(), + multirust_meta_path.expect("").display() + ); return Err("cannot install while multirust is installed".into()); } - (false, false) => () + (false, false) => (), } if rustc_exists { warn!("it looks like you have an existing installation of Rust"); warn!("rustup cannot be installed alongside Rust. Please uninstall first"); - warn!("run `{}` as root to uninstall Rust", uninstaller_path.display()); + warn!( + "run `{}` as root to uninstall Rust", + uninstaller_path.display() + ); return Err("cannot install while Rust is installed".into()); } if rustup_sh_exists { warn!("it looks like you have existing rustup.sh metadata"); warn!("rustup cannot be installed while rustup.sh metadata exists"); - warn!("delete `{}` to remove rustup.sh", rustup_sh_path.expect("").display()); + warn!( + "delete `{}` to remove rustup.sh", + rustup_sh_path.expect("").display() + ); warn!("or, if you already rustup installed, you can run"); warn!("`rustup self update` and `rustup toolchain list` to upgrade"); warn!("your directory structure"); @@ -471,13 +478,25 @@ fn do_anti_sudo_check(no_prompt: bool) -> Result<()> { use std::ptr; // test runner should set this, nothing else - if env::var("RUSTUP_INIT_SKIP_SUDO_CHECK").as_ref().map(Deref::deref).ok() == Some("yes") { + if env::var("RUSTUP_INIT_SKIP_SUDO_CHECK") + .as_ref() + .map(Deref::deref) + .ok() == Some("yes") + { return false; } let mut buf = [0u8; 1024]; let mut pwd = unsafe { mem::uninitialized::() }; let mut pwdp: *mut c::passwd = ptr::null_mut(); - let rv = unsafe { c::getpwuid_r(c::geteuid(), &mut pwd, mem::transmute(&mut buf), buf.len(), &mut pwdp) }; + let rv = unsafe { + c::getpwuid_r( + c::geteuid(), + &mut pwd, + mem::transmute(&mut buf), + buf.len(), + &mut pwdp, + ) + }; if rv != 0 || pwdp.is_null() { warn!("getpwuid_r: couldn't get user data"); return false; @@ -487,7 +506,7 @@ fn do_anti_sudo_check(no_prompt: bool) -> Result<()> { let env_home = env_home.as_ref().map(Deref::deref); match (env_home, pw_dir) { (None, _) | (_, None) => false, - (Some(eh), Some(pd)) => eh != pd + (Some(eh), Some(pd)) => eh != pd, } } @@ -502,7 +521,7 @@ fn do_anti_sudo_check(no_prompt: bool) -> Result<()> { err!("$HOME differs from euid-obtained home directory: you may be using sudo"); err!("if this is what you want, restart the installation with `-y'"); process::exit(1); - }, + } (true, true) => { warn!("$HOME differs from euid-obtained home directory: you may be using sudo"); } @@ -536,34 +555,45 @@ fn do_msvc_check(_opts: &InstallOpts) -> Result { } fn pre_install_msg(no_modify_path: bool) -> Result { - let cargo_home = try!(utils::cargo_home()); + let cargo_home = utils::cargo_home()?; let cargo_home_bin = cargo_home.join("bin"); if !no_modify_path { if cfg!(unix) { let add_path_methods = get_add_path_methods(); - let rcfiles = add_path_methods.into_iter() + let rcfiles = add_path_methods + .into_iter() .filter_map(|m| { if let PathUpdateMethod::RcFile(path) = m { Some(format!("{}", path.display())) } else { None } - }).collect::>(); + }) + .collect::>(); let plural = if rcfiles.len() > 1 { "s" } else { "" }; - let rcfiles = rcfiles.into_iter().map(|f| format!(" {}", f)).collect::>(); + let rcfiles = rcfiles + .into_iter() + .map(|f| format!(" {}", f)) + .collect::>(); let rcfiles = rcfiles.join("\n"); - Ok(format!(pre_install_msg_unix!(), - cargo_home_bin = cargo_home_bin.display(), - plural = plural, - rcfiles = rcfiles)) + Ok(format!( + pre_install_msg_unix!(), + cargo_home_bin = cargo_home_bin.display(), + plural = plural, + rcfiles = rcfiles + )) } else { - Ok(format!(pre_install_msg_win!(), - cargo_home_bin = cargo_home_bin.display())) + Ok(format!( + pre_install_msg_win!(), + cargo_home_bin = cargo_home_bin.display() + )) } } else { - Ok(format!(pre_install_msg_no_modify_path!(), - cargo_home_bin = cargo_home_bin.display())) + Ok(format!( + pre_install_msg_no_modify_path!(), + cargo_home_bin = cargo_home_bin.display() + )) } } @@ -583,24 +613,23 @@ fn current_install_opts(opts: &InstallOpts) -> String { // Interactive editing of the install options fn customize_install(mut opts: InstallOpts) -> Result { - println!( "I'm going to ask you the value of each these installation options.\n\ - You may simply press the Enter key to leave unchanged."); + You may simply press the Enter key to leave unchanged." + ); println!(""); - opts.default_host_triple = try!(common::question_str( - "Default host triple?", - &opts.default_host_triple)); + opts.default_host_triple = + common::question_str("Default host triple?", &opts.default_host_triple)?; - opts.default_toolchain = try!(common::question_str( + opts.default_toolchain = common::question_str( "Default toolchain? (stable/beta/nightly/none)", - &opts.default_toolchain)); + &opts.default_toolchain, + )?; - opts.no_modify_path = !try!(common::question_bool( - "Modify PATH variable? (y/n)", - !opts.no_modify_path)); + opts.no_modify_path = + !common::question_bool("Modify PATH variable? (y/n)", !opts.no_modify_path)?; Ok(opts) } @@ -610,12 +639,12 @@ fn customize_install(mut opts: InstallOpts) -> Result { // upgrade and are on the $PATH, it would cause major confusion. This // method silently deletes them. fn cleanup_legacy() -> Result<()> { - let legacy_bin_dir = try!(legacy_multirust_home_dir()).join("bin"); + let legacy_bin_dir = legacy_multirust_home_dir()?.join("bin"); for tool in TOOLS.iter().cloned().chain(vec!["multirust", "rustup"]) { let ref file = legacy_bin_dir.join(&format!("{}{}", tool, EXE_SUFFIX)); if file.exists() { - try!(utils::remove_file("legacy-bin", file)); + utils::remove_file("legacy-bin", file)?; } } @@ -623,14 +652,12 @@ fn cleanup_legacy() -> Result<()> { #[cfg(unix)] fn legacy_multirust_home_dir() -> Result { - Ok(try!(utils::legacy_multirust_home())) + Ok(utils::legacy_multirust_home()?) } #[cfg(windows)] fn legacy_multirust_home_dir() -> Result { - use rustup_utils::raw::windows::{ - get_special_folder, FOLDERID_LocalAppData - }; + use rustup_utils::raw::windows::{get_special_folder, FOLDERID_LocalAppData}; // FIXME: This looks bogus. Where is the .multirust dir? Ok(get_special_folder(&FOLDERID_LocalAppData).unwrap_or(PathBuf::from("."))) @@ -638,23 +665,23 @@ fn cleanup_legacy() -> Result<()> { } fn install_bins() -> Result<()> { - let ref bin_path = try!(utils::cargo_home()).join("bin"); - let ref this_exe_path = try!(utils::current_exe()); + 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)); - try!(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() { - try!(utils::remove_file("rustup-bin", rustup_path)); + utils::remove_file("rustup-bin", rustup_path)?; } - try!(utils::copy_file(this_exe_path, rustup_path)); - try!(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 = try!(utils::cargo_home()).join("bin"); + let ref bin_path = utils::cargo_home()?.join("bin"); let ref rustup_path = bin_path.join(&format!("rustup{}", EXE_SUFFIX)); // Record the size of the known links, then when we get files which may or @@ -668,17 +695,20 @@ pub fn install_proxies() -> Result<()> { if tool_path.exists() { file_size = utils::file_size(tool_path)?; } - try!(utils::hard_or_symlink_file(rustup_path, tool_path)); + utils::hard_or_symlink_file(rustup_path, tool_path)?; } for tool in DUP_TOOLS { let ref tool_path = bin_path.join(&format!("{}{}", tool, EXE_SUFFIX)); if tool_path.exists() && (file_size == 0 || utils::file_size(tool_path)? != file_size) { - warn!("tool `{}` is already installed, remove it from `{}`, then run `rustup update` \ - to have rustup manage this tool.", - tool, bin_path.to_string_lossy()); + warn!( + "tool `{}` is already installed, remove it from `{}`, then run `rustup update` \ + to have rustup manage this tool.", + tool, + bin_path.to_string_lossy() + ); } else { - try!(utils::hard_or_symlink_file(rustup_path, tool_path)); + utils::hard_or_symlink_file(rustup_path, tool_path)?; } } @@ -686,7 +716,7 @@ pub fn install_proxies() -> Result<()> { } fn maybe_install_rust(toolchain_str: &str, default_host_triple: &str, verbose: bool) -> Result<()> { - let ref cfg = try!(common::set_globals(verbose)); + let ref 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: @@ -695,14 +725,14 @@ fn maybe_install_rust(toolchain_str: &str, default_host_triple: &str, verbose: b if toolchain_str == "none" { info!("skipping toolchain installation"); println!(""); - } else if try!(cfg.find_default()).is_none() { + } else if cfg.find_default()?.is_none() { // Set host triple first as it will affect resolution of toolchain_str - try!(cfg.set_default_host_triple(default_host_triple)); - let toolchain = try!(cfg.get_toolchain(toolchain_str, false)); - let status = try!(toolchain.install_from_dist()); - try!(cfg.set_default(toolchain_str)); + cfg.set_default_host_triple(default_host_triple)?; + let toolchain = cfg.get_toolchain(toolchain_str, false)?; + let status = toolchain.install_from_dist()?; + cfg.set_default(toolchain_str)?; println!(""); - try!(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!(""); @@ -721,27 +751,29 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { if cfg!(feature = "msi-installed") { // Get the product code of the MSI installer from the registry // and spawn `msiexec /x`, then exit immediately - let product_code = try!(get_msi_product_code()); - try!(Command::new("msiexec") - .arg("/x") - .arg(product_code) - .spawn() - .chain_err(|| ErrorKind::WindowsUninstallMadness)); + let product_code = get_msi_product_code()?; + Command::new("msiexec") + .arg("/x") + .arg(product_code) + .spawn() + .chain_err(|| ErrorKind::WindowsUninstallMadness)?; process::exit(0); } - let ref cargo_home = try!(utils::cargo_home()); + let ref cargo_home = utils::cargo_home()?; - if !cargo_home.join(&format!("bin/rustup{}", EXE_SUFFIX)).exists() { + if !cargo_home + .join(&format!("bin/rustup{}", EXE_SUFFIX)) + .exists() + { return Err(ErrorKind::NotSelfInstalled(cargo_home.clone()).into()); } if !no_prompt { println!(""); - let ref msg = format!(pre_uninstall_msg!(), - cargo_home = try!(canonical_cargo_home())); + let ref msg = format!(pre_uninstall_msg!(), cargo_home = canonical_cargo_home()?); term2::stdout().md(msg); - if !try!(common::confirm("\nContinue? (y/N)", false)) { + if !common::confirm("\nContinue? (y/N)", false)? { info!("aborting uninstallation"); return Ok(()); } @@ -749,12 +781,12 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { info!("removing rustup home"); - try!(utils::delete_legacy_multirust_symlink()); + utils::delete_legacy_multirust_symlink()?; // Delete RUSTUP_HOME - let ref rustup_dir = try!(utils::rustup_home()); + let ref rustup_dir = utils::rustup_home()?; if rustup_dir.exists() { - try!(utils::remove_dir("rustup_home", rustup_dir, &|_| {})); + utils::remove_dir("rustup_home", rustup_dir, &|_| {})?; } let read_dir_err = "failure reading directory"; @@ -762,36 +794,39 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { info!("removing cargo home"); // Remove CARGO_HOME/bin from PATH - let ref remove_path_methods = try!(get_remove_path_methods()); - try!(do_remove_from_path(remove_path_methods)); + let ref 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 try!(fs::read_dir(cargo_home).chain_err(|| read_dir_err)) { - let dirent = try!(dirent.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() { - try!(utils::remove_dir("cargo_home", &dirent.path(), &|_| {})); + utils::remove_dir("cargo_home", &dirent.path(), &|_| {})?; } else { - try!(utils::remove_file("cargo_home", &dirent.path())); + utils::remove_file("cargo_home", &dirent.path())?; } } } // Then everything in bin except rustup and tools. These can't be unlinked // until this process exits (on windows). - let tools = TOOLS.iter().chain(DUP_TOOLS.iter()).map(|t| format!("{}{}", t, EXE_SUFFIX)); + let tools = TOOLS + .iter() + .chain(DUP_TOOLS.iter()) + .map(|t| format!("{}{}", t, EXE_SUFFIX)); let tools: Vec<_> = tools.chain(vec![format!("rustup{}", EXE_SUFFIX)]).collect(); - for dirent in try!(fs::read_dir(&cargo_home.join("bin")).chain_err(|| read_dir_err)) { - let dirent = try!(dirent.chain_err(|| read_dir_err)); + for dirent in fs::read_dir(&cargo_home.join("bin")).chain_err(|| read_dir_err)? { + let dirent = dirent.chain_err(|| read_dir_err)?; let name = dirent.file_name(); let file_is_tool = name.to_str().map(|n| tools.iter().any(|t| *t == n)); if file_is_tool == Some(false) { if dirent.path().is_dir() { - try!(utils::remove_dir("cargo_home", &dirent.path(), &|_| {})); + utils::remove_dir("cargo_home", &dirent.path(), &|_| {})?; } else { - try!(utils::remove_file("cargo_home", &dirent.path())); + utils::remove_file("cargo_home", &dirent.path())?; } } } @@ -801,7 +836,7 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { // Delete rustup. This is tricky because this is *probably* // the running executable and on Windows can't be unlinked until // the process exits. - try!(delete_rustup_and_cargo_home()); + delete_rustup_and_cargo_home()?; info!("rustup is uninstalled"); @@ -822,26 +857,18 @@ fn get_msi_product_code() -> Result { let environment = root.open_subkey_with_flags("SOFTWARE\\rustup", KEY_READ); match environment { - Ok(env) => { - match env.get_value("InstalledProductCode") { - Ok(val) => { - Ok(val) - } - Err(e) => { - Err(e).chain_err(|| ErrorKind::WindowsUninstallMadness) - } - } - } - Err(e) => { - Err(e).chain_err(|| ErrorKind::WindowsUninstallMadness) - } + Ok(env) => match env.get_value("InstalledProductCode") { + Ok(val) => Ok(val), + Err(e) => Err(e).chain_err(|| ErrorKind::WindowsUninstallMadness), + }, + Err(e) => Err(e).chain_err(|| ErrorKind::WindowsUninstallMadness), } } #[cfg(unix)] fn delete_rustup_and_cargo_home() -> Result<()> { - let ref cargo_home = try!(utils::cargo_home()); - try!(utils::remove_dir("cargo_home", cargo_home, &|_| ())); + let ref cargo_home = utils::cargo_home()?; + utils::remove_dir("cargo_home", cargo_home, &|_| ())?; Ok(()) } @@ -884,23 +911,23 @@ fn delete_rustup_and_cargo_home() -> Result<()> { use std::time::Duration; // CARGO_HOME, hopefully empty except for bin/rustup.exe - let ref cargo_home = try!(utils::cargo_home()); + let ref cargo_home = utils::cargo_home()?; // The rustup.exe bin let ref rustup_path = cargo_home.join(&format!("bin/rustup{}", EXE_SUFFIX)); // The directory containing CARGO_HOME - let work_path = cargo_home.parent().expect("CARGO_HOME doesn't have a parent?"); + let work_path = cargo_home + .parent() + .expect("CARGO_HOME doesn't have a parent?"); // Generate a unique name for the files we're about to move out // of CARGO_HOME. let numbah: u32 = rand::random(); let gc_exe = work_path.join(&format!("rustup-gc-{:x}.exe", numbah)); - use winapi::{FILE_SHARE_DELETE, FILE_SHARE_READ, - INVALID_HANDLE_VALUE, FILE_FLAG_DELETE_ON_CLOSE, - DWORD, SECURITY_ATTRIBUTES, OPEN_EXISTING, - GENERIC_READ}; - use kernel32::{CreateFileW, CloseHandle}; + use winapi::{DWORD, FILE_FLAG_DELETE_ON_CLOSE, FILE_SHARE_DELETE, FILE_SHARE_READ, + GENERIC_READ, INVALID_HANDLE_VALUE, OPEN_EXISTING, SECURITY_ATTRIBUTES}; + use kernel32::{CloseHandle, CreateFileW}; use std::os::windows::ffi::OsStrExt; use std::ptr; use std::io; @@ -908,7 +935,7 @@ fn delete_rustup_and_cargo_home() -> Result<()> { unsafe { // Copy rustup (probably this process's exe) to the gc exe - try!(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); @@ -920,23 +947,28 @@ fn delete_rustup_and_cargo_home() -> Result<()> { sa.nLength = mem::size_of::() as DWORD; sa.bInheritHandle = 1; - let gc_handle = CreateFileW(gc_exe_win.as_ptr(), - GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_DELETE, - &mut sa, - OPEN_EXISTING, - FILE_FLAG_DELETE_ON_CLOSE, - ptr::null_mut()); + let gc_handle = CreateFileW( + gc_exe_win.as_ptr(), + GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_DELETE, + &mut sa, + OPEN_EXISTING, + FILE_FLAG_DELETE_ON_CLOSE, + ptr::null_mut(), + ); if gc_handle == INVALID_HANDLE_VALUE { let err = io::Error::last_os_error(); return Err(err).chain_err(|| ErrorKind::WindowsUninstallMadness); } - let _g = scopeguard::guard(gc_handle, |h| { let _ = CloseHandle(*h); }); + let _g = scopeguard::guard(gc_handle, |h| { + let _ = CloseHandle(*h); + }); - try!(Command::new(gc_exe).spawn() - .chain_err(|| ErrorKind::WindowsUninstallMadness)); + Command::new(gc_exe) + .spawn() + .chain_err(|| ErrorKind::WindowsUninstallMadness)?; // The catch 22 article says we must sleep here to give // Windows a chance to bump the processes file reference @@ -957,34 +989,33 @@ pub fn complete_windows_uninstall() -> Result<()> { use std::ffi::OsStr; use std::process::Stdio; - try!(wait_for_parent()); + wait_for_parent()?; // Now that the parent has exited there are hopefully no more files open in CARGO_HOME - let ref cargo_home = try!(utils::cargo_home()); - try!(utils::remove_dir("cargo_home", cargo_home, &|_| ())); + let ref 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 // exe when it exits. let rm_gc_exe = OsStr::new("net"); - try!(Command::new(rm_gc_exe) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - .chain_err(|| ErrorKind::WindowsUninstallMadness)); + Command::new(rm_gc_exe) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .chain_err(|| ErrorKind::WindowsUninstallMadness)?; process::exit(0); } #[cfg(windows)] fn wait_for_parent() -> Result<()> { - use kernel32::{Process32First, Process32Next, - CreateToolhelp32Snapshot, CloseHandle, OpenProcess, - GetCurrentProcessId, WaitForSingleObject}; - use winapi::{PROCESSENTRY32, INVALID_HANDLE_VALUE, DWORD, INFINITE, - TH32CS_SNAPPROCESS, SYNCHRONIZE, WAIT_OBJECT_0}; + use kernel32::{CloseHandle, CreateToolhelp32Snapshot, GetCurrentProcessId, OpenProcess, + Process32First, Process32Next, WaitForSingleObject}; + use winapi::{PROCESSENTRY32, TH32CS_SNAPPROCESS, WAIT_OBJECT_0, DWORD, INFINITE, + INVALID_HANDLE_VALUE, SYNCHRONIZE}; use std::io; use std::mem; use std::ptr; @@ -999,7 +1030,9 @@ fn wait_for_parent() -> Result<()> { return Err(err).chain_err(|| ErrorKind::WindowsUninstallMadness); } - let _g = scopeguard::guard(snapshot, |h| { let _ = CloseHandle(*h); }); + let _g = scopeguard::guard(snapshot, |h| { + let _ = CloseHandle(*h); + }); let mut entry: PROCESSENTRY32 = mem::zeroed(); entry.dwSize = mem::size_of::() as DWORD; @@ -1032,7 +1065,9 @@ fn wait_for_parent() -> Result<()> { return Ok(()); } - let _g = scopeguard::guard(parent, |h| { let _ = CloseHandle(*h); }); + let _g = scopeguard::guard(parent, |h| { + let _ = CloseHandle(*h); + }); // Wait for our parent to exit let res = WaitForSingleObject(parent, INFINITE); @@ -1086,12 +1121,12 @@ fn get_add_path_methods() -> Vec { } } - let rcfiles = profiles.into_iter().filter_map(|f|f); + let rcfiles = profiles.into_iter().filter_map(|f| f); rcfiles.map(PathUpdateMethod::RcFile).collect() } fn shell_export_string() -> Result { - let path = format!("{}/bin", try!(canonical_cargo_home())); + let path = format!("{}/bin", canonical_cargo_home()?); // The path is *prepended* in case there are system-installed // rustc's that need to be overridden. Ok(format!(r#"export PATH="{}:$PATH""#, path)) @@ -1099,17 +1134,16 @@ fn shell_export_string() -> Result { #[cfg(unix)] fn do_add_to_path(methods: &[PathUpdateMethod]) -> Result<()> { - for method in methods { if let PathUpdateMethod::RcFile(ref rcpath) = *method { let file = if rcpath.exists() { - try!(utils::read_file("rcfile", rcpath)) + utils::read_file("rcfile", rcpath)? } else { String::new() }; - let ref addition = format!("\n{}", try!(shell_export_string())); + let ref addition = format!("\n{}", shell_export_string()?); if !file.contains(addition) { - try!(utils::append_file("rcfile", rcpath, addition)); + utils::append_file("rcfile", rcpath, addition)?; } } else { unreachable!() @@ -1129,14 +1163,17 @@ fn do_add_to_path(methods: &[PathUpdateMethod]) -> Result<()> { use user32::*; use std::ptr; - let old_path = if let Some(s) = try!(get_windows_path_var()) { + let old_path = if let Some(s) = get_windows_path_var()? { s } else { // Non-unicode path return Ok(()); }; - let mut new_path = try!(utils::cargo_home()).join("bin").to_string_lossy().to_string(); + let mut new_path = utils::cargo_home()? + .join("bin") + .to_string_lossy() + .to_string(); if old_path.contains(&new_path) { return Ok(()); } @@ -1147,24 +1184,27 @@ fn do_add_to_path(methods: &[PathUpdateMethod]) -> Result<()> { } let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = try!(root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) - .chain_err(|| ErrorKind::PermissionDenied)); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .chain_err(|| ErrorKind::PermissionDenied)?; let reg_value = RegValue { bytes: utils::string_to_winreg_bytes(&new_path), vtype: RegType::REG_EXPAND_SZ, }; - try!(environment.set_raw_value("PATH", ®_value) - .chain_err(|| ErrorKind::PermissionDenied)); + environment + .set_raw_value("PATH", ®_value) + .chain_err(|| ErrorKind::PermissionDenied)?; // Tell other processes to update their environment unsafe { - SendMessageTimeoutA(HWND_BROADCAST, - WM_SETTINGCHANGE, - 0 as WPARAM, - "Environment\0".as_ptr() as LPARAM, - SMTO_ABORTIFHUNG, - 5000, - ptr::null_mut()); + SendMessageTimeoutA( + HWND_BROADCAST, + WM_SETTINGCHANGE, + 0 as WPARAM, + "Environment\0".as_ptr() as LPARAM, + SMTO_ABORTIFHUNG, + 5000, + ptr::null_mut(), + ); } Ok(()) @@ -1180,8 +1220,8 @@ fn get_windows_path_var() -> Result> { use std::io; let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = try!(root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) - .chain_err(|| ErrorKind::PermissionDenied)); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .chain_err(|| ErrorKind::PermissionDenied)?; let reg_value = environment.get_raw_value("PATH"); match reg_value { @@ -1194,12 +1234,8 @@ fn get_windows_path_var() -> Result> { return Ok(None); } } - Err(ref e) if e.kind() == io::ErrorKind::NotFound => { - Ok(Some(String::new())) - } - Err(e) => { - Err(e).chain_err(|| ErrorKind::WindowsUninstallMadness) - } + Err(ref e) if e.kind() == io::ErrorKind::NotFound => Ok(Some(String::new())), + Err(e) => Err(e).chain_err(|| ErrorKind::WindowsUninstallMadness), } } @@ -1214,17 +1250,14 @@ fn get_remove_path_methods() -> Result> { let bash_profile = utils::home_dir().map(|p| p.join(".bash_profile")); let rcfiles = vec![profile, bash_profile]; - let existing_rcfiles = rcfiles.into_iter() - .filter_map(|f|f) - .filter(|f| f.exists()); - - let export_str = try!(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 existing_rcfiles = rcfiles.into_iter().filter_map(|f| f).filter(|f| f.exists()); + + 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) + }); Ok(matching_rcfiles.map(PathUpdateMethod::RcFile).collect()) } @@ -1239,14 +1272,17 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { use user32::*; use std::ptr; - let old_path = if let Some(s) = try!(get_windows_path_var()) { + let old_path = if let Some(s) = get_windows_path_var()? { s } else { // Non-unicode path return Ok(()); }; - let ref path_str = try!(utils::cargo_home()).join("bin").to_string_lossy().to_string(); + let ref path_str = utils::cargo_home()? + .join("bin") + .to_string_lossy() + .to_string(); let idx = if let Some(i) = old_path.find(path_str) { i } else { @@ -1261,32 +1297,36 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { } let mut new_path = old_path[..idx].to_string(); - new_path.push_str(&old_path[idx + len ..]); + new_path.push_str(&old_path[idx + len..]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = try!(root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) - .chain_err(|| ErrorKind::PermissionDenied)); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .chain_err(|| ErrorKind::PermissionDenied)?; if new_path.is_empty() { - try!(environment.delete_value("PATH") - .chain_err(|| ErrorKind::PermissionDenied)); + environment + .delete_value("PATH") + .chain_err(|| ErrorKind::PermissionDenied)?; } else { let reg_value = RegValue { bytes: utils::string_to_winreg_bytes(&new_path), vtype: RegType::REG_EXPAND_SZ, }; - try!(environment.set_raw_value("PATH", ®_value) - .chain_err(|| ErrorKind::PermissionDenied)); + environment + .set_raw_value("PATH", ®_value) + .chain_err(|| ErrorKind::PermissionDenied)?; } // Tell other processes to update their environment unsafe { - SendMessageTimeoutA(HWND_BROADCAST, - WM_SETTINGCHANGE, - 0 as WPARAM, - "Environment\0".as_ptr() as LPARAM, - SMTO_ABORTIFHUNG, - 5000, - ptr::null_mut()); + SendMessageTimeoutA( + HWND_BROADCAST, + WM_SETTINGCHANGE, + 0 as WPARAM, + "Environment\0".as_ptr() as LPARAM, + SMTO_ABORTIFHUNG, + 5000, + ptr::null_mut(), + ); } Ok(()) @@ -1296,19 +1336,20 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { for method in methods { if let PathUpdateMethod::RcFile(ref rcpath) = *method { - let file = try!(utils::read_file("rcfile", rcpath)); - let addition = format!("\n{}\n", try!(shell_export_string())); + let file = utils::read_file("rcfile", rcpath)?; + let addition = format!("\n{}\n", shell_export_string()?); let file_bytes = file.into_bytes(); let addition_bytes = addition.into_bytes(); - let idx = file_bytes.windows(addition_bytes.len()) + let idx = file_bytes + .windows(addition_bytes.len()) .position(|w| w == &*addition_bytes); 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(); - try!(utils::write_file("rcfile", rcpath, new_file)); + utils::write_file("rcfile", rcpath, new_file)?; } else { // Weird case. rcfile no longer needs to be modified? } @@ -1341,7 +1382,7 @@ pub fn update() -> Result<()> { err!("you should probably use your system package manager to update rustup"); process::exit(1); } - let setup_path = try!(prepare_update()); + let setup_path = prepare_update()?; if let Some(ref p) = setup_path { let version = match get_new_rustup_version(p) { Some(new_version) => parse_new_rustup_version(new_version), @@ -1352,7 +1393,7 @@ pub fn update() -> Result<()> { }; info!("rustup updated successfully to {}", version); - try!(run_update(p)); + run_update(p)?; } else { // Try again in case we emitted "tool `{}` is already installed" last time. install_proxies()? @@ -1366,8 +1407,8 @@ fn get_new_rustup_version(path: &Path) -> Option { Err(_) => None, Ok(output) => match String::from_utf8(output.stdout) { Ok(version) => Some(version), - Err(_) => None - } + Err(_) => None, + }, } } @@ -1376,7 +1417,7 @@ fn parse_new_rustup_version(version: String) -> String { let capture = re.captures(&version); let matched_version = match capture { Some(cap) => cap.get(0).unwrap().as_str(), - None => "(unknown)" + None => "(unknown)", }; String::from(matched_version) } @@ -1384,7 +1425,7 @@ fn parse_new_rustup_version(version: String) -> String { pub fn prepare_update() -> Result> { use toml; - let ref cargo_home = try!(utils::cargo_home()); + 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)); @@ -1393,17 +1434,15 @@ pub fn prepare_update() -> Result> { } if setup_path.exists() { - try!(utils::remove_file("setup", setup_path)); + utils::remove_file("setup", setup_path)?; } // Get build triple let triple = dist::TargetTriple::from_build(); - let update_root = env::var("RUSTUP_UPDATE_ROOT") - .unwrap_or(String::from(UPDATE_ROOT)); + let update_root = env::var("RUSTUP_UPDATE_ROOT").unwrap_or(String::from(UPDATE_ROOT)); - let tempdir = try!(TempDir::new("rustup-update") - .chain_err(|| "error creating temp directory")); + let tempdir = TempDir::new("rustup-update").chain_err(|| "error creating temp directory")?; // Get current version let current_version = env!("CARGO_PKG_VERSION"); @@ -1411,23 +1450,30 @@ pub fn prepare_update() -> Result> { // Download available version info!("checking for self-updates"); let release_file_url = format!("{}/release-stable.toml", update_root); - let release_file_url = try!(utils::parse_url(&release_file_url)); + let release_file_url = utils::parse_url(&release_file_url)?; let release_file = tempdir.path().join("release-stable.toml"); - try!(utils::download_file(&release_file_url, &release_file, None, &|_| ())); - let release_toml_str = try!(utils::read_file("rustup release", &release_file)); - let release_toml: toml::Value = try!(toml::from_str(&release_toml_str) - .map_err(|_| Error::from("unable to parse rustup release file"))); - let schema = try!(release_toml.get("schema-version") - .ok_or(Error::from("no schema key in rustup release file"))); - let schema = try!(schema.as_str() - .ok_or(Error::from("invalid schema key in rustup release file"))); - let available_version = try!(release_toml.get("version") - .ok_or(Error::from("no version key in rustup release file"))); - let available_version = try!(available_version.as_str() - .ok_or(Error::from("invalid version key in rustup release file"))); + utils::download_file(&release_file_url, &release_file, None, &|_| ())?; + let release_toml_str = utils::read_file("rustup release", &release_file)?; + let release_toml: toml::Value = toml::from_str(&release_toml_str) + .map_err(|_| Error::from("unable to parse rustup release file"))?; + let schema = release_toml + .get("schema-version") + .ok_or(Error::from("no schema key in rustup release file"))?; + let schema = schema + .as_str() + .ok_or(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"))?; + let available_version = available_version + .as_str() + .ok_or(Error::from("invalid version key in rustup release file"))?; if schema != "1" { - return Err(Error::from(&*format!("unknown schema version '{}' in rustup release file", schema))); + return Err(Error::from(&*format!( + "unknown schema version '{}' in rustup release file", + schema + ))); } // If up-to-date @@ -1436,21 +1482,20 @@ pub fn prepare_update() -> Result> { } // Get download URL - let url = format!("{}/archive/{}/{}/rustup-init{}", update_root, - available_version, triple, EXE_SUFFIX); + let url = format!( + "{}/archive/{}/{}/rustup-init{}", + update_root, available_version, triple, EXE_SUFFIX + ); // Get download path - let download_url = try!(utils::parse_url(&url)); + let download_url = utils::parse_url(&url)?; // Download new version info!("downloading self-update"); - try!(utils::download_file(&download_url, - &setup_path, - None, - &|_| ())); + utils::download_file(&download_url, &setup_path, None, &|_| ())?; // Mark as executable - try!(utils::make_executable(setup_path)); + utils::make_executable(setup_path)?; Ok(Some(setup_path.to_owned())) } @@ -1465,9 +1510,10 @@ pub fn prepare_update() -> Result> { /// considered successful. #[cfg(unix)] pub fn run_update(setup_path: &Path) -> Result<()> { - let status = try!(Command::new(setup_path) + let status = Command::new(setup_path) .arg("--self-replace") - .status().chain_err(|| "unable to run updater")); + .status() + .chain_err(|| "unable to run updater")?; if !status.success() { return Err("self-updated failed to replace rustup executable".into()); @@ -1478,9 +1524,10 @@ pub fn run_update(setup_path: &Path) -> Result<()> { #[cfg(windows)] pub fn run_update(setup_path: &Path) -> Result<()> { - try!(Command::new(setup_path) + Command::new(setup_path) .arg("--self-replace") - .spawn().chain_err(|| "unable to run updater")); + .spawn() + .chain_err(|| "unable to run updater")?; process::exit(0); } @@ -1491,32 +1538,32 @@ pub fn run_update(setup_path: &Path) -> Result<()> { /// rustup process exits. #[cfg(unix)] pub fn self_replace() -> Result<()> { - try!(install_bins()); + install_bins()?; Ok(()) } #[cfg(windows)] pub fn self_replace() -> Result<()> { - try!(wait_for_parent()); - try!(install_bins()); + wait_for_parent()?; + install_bins()?; Ok(()) } pub fn cleanup_self_updater() -> Result<()> { - let cargo_home = try!(utils::cargo_home()); + let cargo_home = utils::cargo_home()?; let ref setup = cargo_home.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); if setup.exists() { - try!(utils::remove_file("setup", setup)); + utils::remove_file("setup", setup)?; } // Transitional let ref old_setup = cargo_home.join(&format!("bin/multirust-setup{}", EXE_SUFFIX)); if old_setup.exists() { - try!(utils::remove_file("setup", old_setup)); + utils::remove_file("setup", old_setup)?; } Ok(()) diff --git a/src/rustup-cli/setup_mode.rs b/src/rustup-cli/setup_mode.rs index f309d104cc..98288ba6c4 100644 --- a/src/rustup-cli/setup_mode.rs +++ b/src/rustup-cli/setup_mode.rs @@ -1,7 +1,7 @@ use std::env; use self_update::{self, InstallOpts}; use errors::*; -use clap::{App, Arg, AppSettings}; +use clap::{App, AppSettings, Arg}; use rustup_dist::dist::TargetTriple; use common; @@ -18,31 +18,42 @@ pub fn main() -> Result<()> { .version(common::version()) .about("The installer for rustup") .setting(AppSettings::DeriveDisplayOrder) - .arg(Arg::with_name("verbose") - .short("v") - .long("verbose") - .help("Enable verbose output")) - .arg(Arg::with_name("no-prompt") - .short("y") - .help("Disable confirmation prompt.")) - .arg(Arg::with_name("default-host") - .long("default-host") - .takes_value(true) - .help("Choose a default host triple")) - .arg(Arg::with_name("default-toolchain") - .long("default-toolchain") - .takes_value(true) - .help("Choose a default toolchain to install")) - .arg(Arg::with_name("no-modify-path") - .long("no-modify-path") - .help("Don't configure the PATH environment variable")); + .arg( + Arg::with_name("verbose") + .short("v") + .long("verbose") + .help("Enable verbose output"), + ) + .arg( + Arg::with_name("no-prompt") + .short("y") + .help("Disable confirmation prompt."), + ) + .arg( + Arg::with_name("default-host") + .long("default-host") + .takes_value(true) + .help("Choose a default host triple"), + ) + .arg( + Arg::with_name("default-toolchain") + .long("default-toolchain") + .takes_value(true) + .help("Choose a default toolchain to install"), + ) + .arg( + Arg::with_name("no-modify-path") + .long("no-modify-path") + .help("Don't configure the PATH environment variable"), + ); let matches = cli.get_matches(); let no_prompt = matches.is_present("no-prompt"); let verbose = matches.is_present("verbose"); - let default_host = matches.value_of("default-host").map(|s| s.to_owned()).unwrap_or_else(|| { - TargetTriple::from_host_or_build().to_string() - }); + let default_host = matches + .value_of("default-host") + .map(|s| s.to_owned()) + .unwrap_or_else(|| TargetTriple::from_host_or_build().to_string()); let default_toolchain = matches.value_of("default-toolchain").unwrap_or("stable"); let no_modify_path = matches.is_present("no-modify-path"); @@ -52,7 +63,7 @@ pub fn main() -> Result<()> { no_modify_path: no_modify_path, }; - try!(self_update::install(no_prompt, verbose, opts)); + self_update::install(no_prompt, verbose, opts)?; Ok(()) } diff --git a/src/rustup-cli/term2.rs b/src/rustup-cli/term2.rs index 60daa15efe..4034bb8824 100644 --- a/src/rustup-cli/term2.rs +++ b/src/rustup-cli/term2.rs @@ -5,7 +5,7 @@ use std::io; use term; use rustup_utils::tty; -use markdown::{Block, Span, ListItem}; +use markdown::{Block, ListItem, Span}; use markdown::tokenize; pub use term::color; @@ -16,11 +16,15 @@ pub trait Instantiable { } impl Instantiable for io::Stdout { - fn instance() -> Self { io::stdout() } + fn instance() -> Self { + io::stdout() + } } impl Instantiable for io::Stderr { - fn instance() -> Self { io::stderr() } + fn instance() -> Self { + io::stderr() + } } pub trait Isatty { @@ -40,7 +44,8 @@ impl Isatty for io::Stderr { } pub struct Terminal(Option + Send>>) - where T: Instantiable + Isatty + io::Write; +where + T: Instantiable + Isatty + io::Write; pub type StdoutTerminal = Terminal; pub type StderrTerminal = Terminal; @@ -57,7 +62,7 @@ struct LineWrapper<'a, T: io::Write + 'a> { indent: u32, margin: u32, pos: u32, - pub w: &'a mut T + pub w: &'a mut T, } impl<'a, T: io::Write + 'a> LineWrapper<'a, T> { @@ -125,7 +130,7 @@ impl<'a, T: io::Write + 'a> LineWrapper<'a, T> { indent: indent, margin: margin, pos: indent, - w: w + w: w, } } } @@ -133,14 +138,14 @@ impl<'a, T: io::Write + 'a> LineWrapper<'a, T> { // Handles the formatting of text struct LineFormatter<'a, T: Instantiable + Isatty + io::Write + 'a> { wrapper: LineWrapper<'a, Terminal>, - attrs: Vec + attrs: Vec, } impl<'a, T: Instantiable + Isatty + io::Write + 'a> LineFormatter<'a, T> { fn new(w: &'a mut Terminal, indent: u32, margin: u32) -> Self { LineFormatter { wrapper: LineWrapper::new(w, indent, margin), - attrs: Vec::new() + attrs: Vec::new(), } } fn push_attr(&mut self, attr: Attr) { @@ -157,15 +162,15 @@ impl<'a, T: Instantiable + Isatty + io::Write + 'a> LineFormatter<'a, T> { fn do_spans(&mut self, spans: Vec) { for span in spans { match span { - Span::Break => {}, + Span::Break => {} Span::Text(text) => { self.wrapper.write_span(&text); - }, + } Span::Code(code) => { self.push_attr(Attr::Bold); self.wrapper.write_word(&code); self.pop_attr(); - }, + } Span::Emphasis(spans) => { self.push_attr(Attr::ForegroundColor(color::BRIGHT_RED)); self.do_spans(spans); @@ -183,7 +188,7 @@ impl<'a, T: Instantiable + Isatty + io::Write + 'a> LineFormatter<'a, T> { self.do_spans(spans); self.wrapper.write_line(); self.pop_attr(); - }, + } Block::CodeBlock(code) => { self.wrapper.write_line(); self.wrapper.indent += 2; @@ -193,12 +198,12 @@ impl<'a, T: Instantiable + Isatty + io::Write + 'a> LineFormatter<'a, T> { self.wrapper.write_line(); } self.wrapper.indent -= 2; - }, + } Block::Paragraph(spans) => { self.wrapper.write_line(); self.do_spans(spans); self.wrapper.write_line(); - }, + } Block::UnorderedList(items) => { self.wrapper.write_line(); for item in items { @@ -206,12 +211,10 @@ impl<'a, T: Instantiable + Isatty + io::Write + 'a> LineFormatter<'a, T> { match item { ListItem::Simple(spans) => { self.do_spans(spans); - }, - ListItem::Paragraph(blocks) => { - for block in blocks { - self.do_block(block); - } } + ListItem::Paragraph(blocks) => for block in blocks { + self.do_block(block); + }, } self.wrapper.write_line(); self.wrapper.indent -= 2; @@ -244,7 +247,9 @@ impl io::Write for Terminal { impl Terminal { pub fn fg(&mut self, color: color::Color) -> Result<(), term::Error> { - if !T::isatty() { return Ok(()) } + if !T::isatty() { + return Ok(()); + } if let Some(ref mut t) = self.0 { t.fg(color) @@ -254,14 +259,16 @@ impl Terminal { } pub fn attr(&mut self, attr: Attr) -> Result<(), term::Error> { - if !T::isatty() { return Ok(()) } + if !T::isatty() { + return Ok(()); + } if let Some(ref mut t) = self.0 { if let Err(e) = t.attr(attr) { // If `attr` is not supported, try to emulate it match attr { Attr::Bold => t.fg(color::BRIGHT_WHITE), - _ => Err(e) + _ => Err(e), } } else { Ok(()) @@ -272,7 +279,9 @@ impl Terminal { } pub fn reset(&mut self) -> Result<(), term::Error> { - if !T::isatty() { return Ok(()) } + if !T::isatty() { + return Ok(()); + } if let Some(ref mut t) = self.0 { t.reset() diff --git a/src/rustup-dist/build.rs b/src/rustup-dist/build.rs index c3ea28b8ab..2f3dbd8988 100644 --- a/src/rustup-dist/build.rs +++ b/src/rustup-dist/build.rs @@ -7,6 +7,9 @@ fn main() { let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); let target = env::var("TARGET").unwrap(); - File::create(out_dir.join("target.txt")).unwrap().write_all(target.as_bytes()).unwrap(); + File::create(out_dir.join("target.txt")) + .unwrap() + .write_all(target.as_bytes()) + .unwrap(); println!("cargo:rerun-if-changed=build.rs"); } diff --git a/src/rustup-dist/src/component/components.rs b/src/rustup-dist/src/component/components.rs index 9185f6e0c0..491aedba9b 100644 --- a/src/rustup-dist/src/component/components.rs +++ b/src/rustup-dist/src/component/components.rs @@ -24,7 +24,7 @@ impl Components { let c = Components { prefix: prefix }; // Validate that the metadata uses a format we know - if let Some(v) = try!(c.read_version()) { + if let Some(v) = c.read_version()? { if v != INSTALLER_VERSION { return Err(ErrorKind::BadInstalledMetadataVersion(v).into()); } @@ -41,16 +41,18 @@ impl Components { fn read_version(&self) -> Result> { let p = self.prefix.manifest_file(VERSION_FILE); if utils::is_file(&p) { - Ok(Some(try!(utils::read_file(VERSION_FILE, &p)).trim().to_string())) + Ok(Some(utils::read_file(VERSION_FILE, &p)?.trim().to_string())) } else { Ok(None) } } fn write_version(&self, tx: &mut Transaction) -> Result<()> { - try!(tx.modify_file(self.prefix.rel_manifest_file(VERSION_FILE))); - try!(utils::write_file(VERSION_FILE, - &self.prefix.manifest_file(VERSION_FILE), - INSTALLER_VERSION)); + tx.modify_file(self.prefix.rel_manifest_file(VERSION_FILE))?; + utils::write_file( + VERSION_FILE, + &self.prefix.manifest_file(VERSION_FILE), + INSTALLER_VERSION, + )?; Ok(()) } @@ -59,15 +61,14 @@ impl Components { if !utils::is_file(&path) { return Ok(Vec::new()); } - let content = try!(utils::read_file("components", &path)); - Ok(content.lines() - .map(|s| { - Component { - components: self.clone(), - name: s.to_owned(), - } - }) - .collect()) + let content = utils::read_file("components", &path)?; + Ok(content + .lines() + .map(|s| Component { + components: self.clone(), + name: s.to_owned(), + }) + .collect()) } pub fn add<'a>(&self, name: &str, tx: Transaction<'a>) -> ComponentBuilder<'a> { ComponentBuilder { @@ -78,7 +79,7 @@ impl Components { } } pub fn find(&self, name: &str) -> Result> { - let result = try!(self.list()); + let result = self.list()?; Ok(result.into_iter().filter(|c| (c.name() == name)).next()) } pub fn prefix(&self) -> InstallPrefix { @@ -90,20 +91,23 @@ pub struct ComponentBuilder<'a> { components: Components, name: String, parts: Vec, - tx: Transaction<'a> + tx: Transaction<'a>, } impl<'a> ComponentBuilder<'a> { pub fn add_file(&mut self, path: PathBuf) -> Result { - self.parts.push(ComponentPart("file".to_owned(), path.clone())); + self.parts + .push(ComponentPart("file".to_owned(), path.clone())); self.tx.add_file(&self.name, path) } pub fn copy_file(&mut self, path: PathBuf, src: &Path) -> Result<()> { - self.parts.push(ComponentPart("file".to_owned(), path.clone())); + self.parts + .push(ComponentPart("file".to_owned(), path.clone())); self.tx.copy_file(&self.name, path, src) } pub fn copy_dir(&mut self, path: PathBuf, src: &Path) -> Result<()> { - self.parts.push(ComponentPart("dir".to_owned(), path.clone())); + self.parts + .push(ComponentPart("dir".to_owned(), path.clone())); self.tx.copy_dir(&self.name, path, src) } @@ -111,21 +115,21 @@ impl<'a> ComponentBuilder<'a> { // Write component manifest let path = self.components.rel_component_manifest(&self.name); let abs_path = self.components.prefix.abs_path(&path); - let mut file = try!(self.tx.add_file(&self.name, path)); + let mut file = self.tx.add_file(&self.name, path)?; for part in self.parts { // FIXME: This writes relative paths to the component manifest, // but rust-installer writes absolute paths. - try!(utils::write_line("component", &mut file, &abs_path, &part.encode())); + utils::write_line("component", &mut file, &abs_path, &part.encode())?; } // Add component to components file let path = self.components.rel_components_file(); let abs_path = self.components.prefix.abs_path(&path); - try!(self.tx.modify_file(path)); - try!(utils::append_file("components", &abs_path, &self.name)); + self.tx.modify_file(path)?; + utils::append_file("components", &abs_path, &self.name)?; // Drop in the version file for future use - try!(self.components.write_version(&mut self.tx)); + self.components.write_version(&mut self.tx)?; Ok(self.tx) } @@ -140,8 +144,7 @@ impl ComponentPart { } pub fn decode(line: &str) -> Option { line.find(":") - .map(|pos| ComponentPart(line[0..pos].to_owned(), - PathBuf::from(&line[(pos + 1)..]))) + .map(|pos| ComponentPart(line[0..pos].to_owned(), PathBuf::from(&line[(pos + 1)..]))) } } @@ -159,16 +162,18 @@ impl Component { self.components.prefix.manifest_file(&self.manifest_name()) } pub fn rel_manifest_file(&self) -> PathBuf { - self.components.prefix.rel_manifest_file(&self.manifest_name()) + self.components + .prefix + .rel_manifest_file(&self.manifest_name()) } pub fn name(&self) -> &str { &self.name } pub fn parts(&self) -> Result> { let mut result = Vec::new(); - for line in try!(utils::read_file("component", &self.manifest_file())).lines() { - result.push(try!(ComponentPart::decode(line) - .ok_or_else(|| ErrorKind::CorruptComponent(self.name.clone())))); + for line in utils::read_file("component", &self.manifest_file())?.lines() { + result.push(ComponentPart::decode(line) + .ok_or_else(|| ErrorKind::CorruptComponent(self.name.clone()))?); } Ok(result) } @@ -176,10 +181,12 @@ impl Component { // Update components file let path = self.components.rel_components_file(); let abs_path = self.components.prefix.abs_path(&path); - let temp = try!(tx.temp().new_file()); - try!(utils::filter_file("components", &abs_path, &temp, |l| (l != self.name))); - try!(tx.modify_file(path)); - try!(utils::rename_file("components", &temp, &abs_path)); + let temp = tx.temp().new_file()?; + utils::filter_file("components", &abs_path, &temp, |l| { + (l != self.name) + })?; + tx.modify_file(path)?; + utils::rename_file("components", &temp, &abs_path)?; // TODO: If this is the last component remove the components file // and the version file. @@ -251,10 +258,14 @@ impl Component { Some(_) => { let mut path_buf = self.path_buf.take().unwrap(); match path_buf.file_name() { - Some(_) => if path_buf.pop() { Some(path_buf) } else { None }, + Some(_) => if path_buf.pop() { + Some(path_buf) + } else { + None + }, None => self.iter.next(), } - }, + } }; if self.path_buf.is_none() { return None; @@ -280,20 +291,20 @@ impl Component { ancestors: HashSet::new(), prefix: self.components.prefix.abs_path(""), }; - for part in try!(self.parts()).into_iter().rev() { + for part in self.parts()?.into_iter().rev() { match &*part.0 { - "file" => try!(tx.remove_file(&self.name, part.1.clone())), - "dir" => try!(tx.remove_dir(&self.name, part.1.clone())), + "file" => tx.remove_file(&self.name, part.1.clone())?, + "dir" => tx.remove_dir(&self.name, part.1.clone())?, _ => return Err(ErrorKind::CorruptComponent(self.name.clone()).into()), } pset.seen(part.1); } for empty_dir in pset { - try!(tx.remove_dir(&self.name, empty_dir)); + tx.remove_dir(&self.name, empty_dir)?; } // Remove component manifest - try!(tx.remove_file(&self.name, self.rel_manifest_file())); + tx.remove_file(&self.name, self.rel_manifest_file())?; Ok(tx) } diff --git a/src/rustup-dist/src/component/mod.rs b/src/rustup-dist/src/component/mod.rs index 6d5442a1cf..1c15c3aac3 100644 --- a/src/rustup-dist/src/component/mod.rs +++ b/src/rustup-dist/src/component/mod.rs @@ -12,4 +12,3 @@ mod transaction; mod package; // The representation of *installed* components, and uninstallation mod components; - diff --git a/src/rustup-dist/src/component/package.rs b/src/rustup-dist/src/component/package.rs index 8aa63db97a..106d2c079a 100644 --- a/src/rustup-dist/src/component/package.rs +++ b/src/rustup-dist/src/component/package.rs @@ -2,8 +2,8 @@ //! for installing from a directory or tarball to an installation //! prefix, represented by a `Components` instance. -extern crate tar; extern crate flate2; +extern crate tar; extern crate xz2; use component::components::*; @@ -25,12 +25,13 @@ pub const VERSION_FILE: &'static str = "rust-installer-version"; pub trait Package: fmt::Debug { fn contains(&self, component: &str, short_name: Option<&str>) -> bool; - fn install<'a>(&self, - target: &Components, - component: &str, - short_name: Option<&str>, - tx: Transaction<'a>) - -> Result>; + fn install<'a>( + &self, + target: &Components, + component: &str, + short_name: Option<&str>, + tx: Transaction<'a>, + ) -> Result>; fn components(&self) -> Vec; } @@ -42,9 +43,9 @@ pub struct DirectoryPackage { impl DirectoryPackage { pub fn new(path: PathBuf) -> Result { - try!(validate_installer_version(&path)); + validate_installer_version(&path)?; - let content = try!(utils::read_file("package components", &path.join("components"))); + let content = utils::read_file("package components", &path.join("components"))?; let components = content.lines().map(|l| l.to_owned()).collect(); Ok(DirectoryPackage { path: path, @@ -54,7 +55,7 @@ impl DirectoryPackage { } fn validate_installer_version(path: &Path) -> Result<()> { - let file = try!(utils::read_file("installer version", &path.join(VERSION_FILE))); + let file = utils::read_file("installer version", &path.join(VERSION_FILE))?; let v = file.trim(); if v == INSTALLER_VERSION { Ok(()) @@ -65,19 +66,19 @@ fn validate_installer_version(path: &Path) -> Result<()> { impl Package for DirectoryPackage { fn contains(&self, component: &str, short_name: Option<&str>) -> bool { - self.components.contains(component) || - if let Some(n) = short_name { + self.components.contains(component) || if let Some(n) = short_name { self.components.contains(n) } else { false } } - fn install<'a>(&self, - target: &Components, - name: &str, - short_name: Option<&str>, - tx: Transaction<'a>) - -> Result> { + fn install<'a>( + &self, + target: &Components, + name: &str, + short_name: Option<&str>, + tx: Transaction<'a>, + ) -> Result> { let actual_name = if self.components.contains(name) { name } else if let Some(n) = short_name { @@ -88,26 +89,26 @@ impl Package for DirectoryPackage { let root = self.path.join(actual_name); - let manifest = try!(utils::read_file("package manifest", &root.join("manifest.in"))); + let manifest = utils::read_file("package manifest", &root.join("manifest.in"))?; let mut builder = target.add(name, tx); for l in manifest.lines() { - let part = try!(ComponentPart::decode(l) - .ok_or_else(|| ErrorKind::CorruptComponent(name.to_owned()))); + let part = ComponentPart::decode(l) + .ok_or_else(|| ErrorKind::CorruptComponent(name.to_owned()))?; let path = part.1; let src_path = root.join(&path); match &*part.0 { - "file" => try!(builder.copy_file(path.clone(), &src_path)), - "dir" => try!(builder.copy_dir(path.clone(), &src_path)), + "file" => builder.copy_file(path.clone(), &src_path)?, + "dir" => builder.copy_dir(path.clone(), &src_path)?, _ => return Err(ErrorKind::CorruptComponent(name.to_owned()).into()), } - try!(set_file_perms(&target.prefix().path().join(path), &src_path)); + set_file_perms(&target.prefix().path().join(path), &src_path)?; } - let tx = try!(builder.finish()); + let tx = builder.finish()?; Ok(tx) } @@ -145,17 +146,25 @@ fn set_file_perms(dest_path: &Path, src_path: &Path) -> Result<()> { if is_dir { // Walk the directory setting everything for entry in WalkDir::new(dest_path) { - let entry = try!(entry.chain_err(|| ErrorKind::ComponentDirPermissionsFailed)); - let meta = try!(entry.metadata().chain_err(|| ErrorKind::ComponentDirPermissionsFailed)); + let entry = entry.chain_err(|| ErrorKind::ComponentDirPermissionsFailed)?; + let meta = entry + .metadata() + .chain_err(|| ErrorKind::ComponentDirPermissionsFailed)?; let mut perm = meta.permissions(); perm.set_mode(if needs_x(&meta) { 0o755 } else { 0o644 }); - try!(fs::set_permissions(entry.path(), perm).chain_err(|| ErrorKind::ComponentFilePermissionsFailed)); + fs::set_permissions(entry.path(), perm) + .chain_err(|| ErrorKind::ComponentFilePermissionsFailed)?; } } else { - let meta = try!(fs::metadata(dest_path).chain_err(|| ErrorKind::ComponentFilePermissionsFailed)); + let meta = fs::metadata(dest_path).chain_err(|| ErrorKind::ComponentFilePermissionsFailed)?; let mut perm = meta.permissions(); - perm.set_mode(if is_bin || needs_x(&meta) { 0o755 } else { 0o644 }); - try!(fs::set_permissions(dest_path, perm).chain_err(|| ErrorKind::ComponentFilePermissionsFailed)); + perm.set_mode(if is_bin || needs_x(&meta) { + 0o755 + } else { + 0o644 + }); + fs::set_permissions(dest_path, perm) + .chain_err(|| ErrorKind::ComponentFilePermissionsFailed)?; } Ok(()) @@ -171,24 +180,29 @@ pub struct TarPackage<'a>(DirectoryPackage, temp::Dir<'a>); impl<'a> TarPackage<'a> { pub fn new(stream: R, temp_cfg: &'a temp::Cfg) -> Result { - let temp_dir = try!(temp_cfg.new_directory()); + let temp_dir = temp_cfg.new_directory()?; let mut archive = tar::Archive::new(stream); // The rust-installer packages unpack to a directory called // $pkgname-$version-$target. Skip that directory when // unpacking. - try!(unpack_without_first_dir(&mut archive, &*temp_dir)); + unpack_without_first_dir(&mut archive, &*temp_dir)?; - Ok(TarPackage(try!(DirectoryPackage::new(temp_dir.to_owned())), temp_dir)) + Ok(TarPackage( + DirectoryPackage::new(temp_dir.to_owned())?, + temp_dir, + )) } } fn unpack_without_first_dir(archive: &mut tar::Archive, path: &Path) -> Result<()> { - let entries = try!(archive.entries().chain_err(|| ErrorKind::ExtractingPackage)); + let entries = archive + .entries() + .chain_err(|| ErrorKind::ExtractingPackage)?; for entry in entries { - let mut entry = try!(entry.chain_err(|| ErrorKind::ExtractingPackage)); + let mut entry = entry.chain_err(|| ErrorKind::ExtractingPackage)?; let relpath = { let path = entry.path(); - let path = try!(path.chain_err(|| ErrorKind::ExtractingPackage)); + let path = path.chain_err(|| ErrorKind::ExtractingPackage)?; path.into_owned() }; let mut components = relpath.components(); @@ -198,12 +212,15 @@ fn unpack_without_first_dir(archive: &mut tar::Archive, path: &Path) // Create the full path to the entry if it does not exist already match full_path.parent() { - Some(parent) if !parent.exists() => - try!(::std::fs::create_dir_all(&parent).chain_err(|| ErrorKind::ExtractingPackage)), + Some(parent) if !parent.exists() => { + ::std::fs::create_dir_all(&parent).chain_err(|| ErrorKind::ExtractingPackage)? + } _ => (), }; - try!(entry.unpack(&full_path).chain_err(|| ErrorKind::ExtractingPackage)); + entry + .unpack(&full_path) + .chain_err(|| ErrorKind::ExtractingPackage)?; } Ok(()) @@ -213,12 +230,13 @@ impl<'a> Package for TarPackage<'a> { fn contains(&self, component: &str, short_name: Option<&str>) -> bool { self.0.contains(component, short_name) } - fn install<'b>(&self, - target: &Components, - component: &str, - short_name: Option<&str>, - tx: Transaction<'b>) - -> Result> { + fn install<'b>( + &self, + target: &Components, + component: &str, + short_name: Option<&str>, + tx: Transaction<'b>, + ) -> Result> { self.0.install(target, component, short_name, tx) } fn components(&self) -> Vec { @@ -231,12 +249,13 @@ pub struct TarGzPackage<'a>(TarPackage<'a>); impl<'a> TarGzPackage<'a> { pub fn new(stream: R, temp_cfg: &'a temp::Cfg) -> Result { - let stream = try!(flate2::read::GzDecoder::new(stream).chain_err(|| ErrorKind::ExtractingPackage)); + let stream = + flate2::read::GzDecoder::new(stream).chain_err(|| ErrorKind::ExtractingPackage)?; - Ok(TarGzPackage(try!(TarPackage::new(stream, temp_cfg)))) + Ok(TarGzPackage(TarPackage::new(stream, temp_cfg)?)) } pub fn new_file(path: &Path, temp_cfg: &'a temp::Cfg) -> Result { - let file = try!(File::open(path).chain_err(|| ErrorKind::ExtractingPackage)); + let file = File::open(path).chain_err(|| ErrorKind::ExtractingPackage)?; Self::new(file, temp_cfg) } } @@ -245,12 +264,13 @@ impl<'a> Package for TarGzPackage<'a> { fn contains(&self, component: &str, short_name: Option<&str>) -> bool { self.0.contains(component, short_name) } - fn install<'b>(&self, - target: &Components, - component: &str, - short_name: Option<&str>, - tx: Transaction<'b>) - -> Result> { + fn install<'b>( + &self, + target: &Components, + component: &str, + short_name: Option<&str>, + tx: Transaction<'b>, + ) -> Result> { self.0.install(target, component, short_name, tx) } fn components(&self) -> Vec { @@ -265,10 +285,10 @@ impl<'a> TarXzPackage<'a> { pub fn new(stream: R, temp_cfg: &'a temp::Cfg) -> Result { let stream = xz2::read::XzDecoder::new(stream); - Ok(TarXzPackage(try!(TarPackage::new(stream, temp_cfg)))) + Ok(TarXzPackage(TarPackage::new(stream, temp_cfg)?)) } pub fn new_file(path: &Path, temp_cfg: &'a temp::Cfg) -> Result { - let file = try!(File::open(path).chain_err(|| ErrorKind::ExtractingPackage)); + let file = File::open(path).chain_err(|| ErrorKind::ExtractingPackage)?; Self::new(file, temp_cfg) } } @@ -277,12 +297,13 @@ impl<'a> Package for TarXzPackage<'a> { fn contains(&self, component: &str, short_name: Option<&str>) -> bool { self.0.contains(component, short_name) } - fn install<'b>(&self, - target: &Components, - component: &str, - short_name: Option<&str>, - tx: Transaction<'b>) - -> Result> { + fn install<'b>( + &self, + target: &Components, + component: &str, + short_name: Option<&str>, + tx: Transaction<'b>, + ) -> Result> { self.0.install(target, component, short_name, tx) } fn components(&self) -> Vec { diff --git a/src/rustup-dist/src/component/transaction.rs b/src/rustup-dist/src/component/transaction.rs index d1b3595cff..00251ab1de 100644 --- a/src/rustup-dist/src/component/transaction.rs +++ b/src/rustup-dist/src/component/transaction.rs @@ -40,10 +40,11 @@ pub struct Transaction<'a> { } impl<'a> Transaction<'a> { - pub fn new(prefix: InstallPrefix, - temp_cfg: &'a temp::Cfg, - notify_handler: &'a Fn(Notification)) - -> Self { + pub fn new( + prefix: InstallPrefix, + temp_cfg: &'a temp::Cfg, + notify_handler: &'a Fn(Notification), + ) -> Self { Transaction { prefix: prefix, changes: Vec::new(), @@ -68,7 +69,7 @@ impl<'a> Transaction<'a> { /// contents. pub fn add_file(&mut self, component: &str, relpath: PathBuf) -> Result { assert!(relpath.is_relative()); - let (item, file) = try!(ChangedItem::add_file(&self.prefix, component, relpath)); + let (item, file) = ChangedItem::add_file(&self.prefix, component, relpath)?; self.change(item); Ok(file) } @@ -76,7 +77,7 @@ impl<'a> Transaction<'a> { /// Copy a file to a relative path of the install prefix. pub fn copy_file(&mut self, component: &str, relpath: PathBuf, src: &Path) -> Result<()> { assert!(relpath.is_relative()); - let item = try!(ChangedItem::copy_file(&self.prefix, component, relpath, src)); + let item = ChangedItem::copy_file(&self.prefix, component, relpath, src)?; self.change(item); Ok(()) } @@ -84,7 +85,7 @@ impl<'a> Transaction<'a> { /// Recursively copy a directory to a relative path of the install prefix. pub fn copy_dir(&mut self, component: &str, relpath: PathBuf, src: &Path) -> Result<()> { assert!(relpath.is_relative()); - let item = try!(ChangedItem::copy_dir(&self.prefix, component, relpath, src)); + let item = ChangedItem::copy_dir(&self.prefix, component, relpath, src)?; self.change(item); Ok(()) } @@ -92,7 +93,7 @@ impl<'a> Transaction<'a> { /// Remove a file from a relative path to the install prefix. pub fn remove_file(&mut self, component: &str, relpath: PathBuf) -> Result<()> { assert!(relpath.is_relative()); - let item = try!(ChangedItem::remove_file(&self.prefix, component, relpath, &self.temp_cfg)); + let item = ChangedItem::remove_file(&self.prefix, component, relpath, &self.temp_cfg)?; self.change(item); Ok(()) } @@ -101,7 +102,7 @@ impl<'a> Transaction<'a> { /// install prefix. pub fn remove_dir(&mut self, component: &str, relpath: PathBuf) -> Result<()> { assert!(relpath.is_relative()); - let item = try!(ChangedItem::remove_dir(&self.prefix, component, relpath, &self.temp_cfg)); + let item = ChangedItem::remove_dir(&self.prefix, component, relpath, &self.temp_cfg)?; self.change(item); Ok(()) } @@ -110,9 +111,14 @@ impl<'a> Transaction<'a> { /// the install prefix. pub fn write_file(&mut self, component: &str, relpath: PathBuf, content: String) -> Result<()> { assert!(relpath.is_relative()); - let (item, mut file) = try!(ChangedItem::add_file(&self.prefix, component, relpath.clone())); + let (item, mut file) = ChangedItem::add_file(&self.prefix, component, relpath.clone())?; self.change(item); - try!(utils::write_str("component", &mut file, &self.prefix.abs_path(&relpath), &content)); + utils::write_str( + "component", + &mut file, + &self.prefix.abs_path(&relpath), + &content, + )?; Ok(()) } @@ -122,7 +128,7 @@ impl<'a> Transaction<'a> { /// This is used for arbitrarily manipulating a file. pub fn modify_file(&mut self, relpath: PathBuf) -> Result<()> { assert!(relpath.is_relative()); - let item = try!(ChangedItem::modify_file(&self.prefix, relpath, &self.temp_cfg)); + let item = ChangedItem::modify_file(&self.prefix, relpath, &self.temp_cfg)?; self.change(item); Ok(()) } @@ -172,22 +178,18 @@ impl<'a> ChangedItem<'a> { fn roll_back(&self, prefix: &InstallPrefix) -> Result<()> { use self::ChangedItem::*; match *self { - AddedFile(ref path) => try!(utils::remove_file("component", &prefix.abs_path(path))), - AddedDir(ref path) => { - try!(utils::remove_dir("component", - &prefix.abs_path(path), - &|_| ())) - } + AddedFile(ref path) => utils::remove_file("component", &prefix.abs_path(path))?, + AddedDir(ref path) => utils::remove_dir("component", &prefix.abs_path(path), &|_| ())?, RemovedFile(ref path, ref tmp) | ModifiedFile(ref path, Some(ref tmp)) => { - try!(utils::rename_file("component", &tmp, &prefix.abs_path(path))) + utils::rename_file("component", &tmp, &prefix.abs_path(path))? } RemovedDir(ref path, ref tmp) => { - try!(utils::rename_dir("component", &tmp.join("bk"), &prefix.abs_path(path))) + utils::rename_dir("component", &tmp.join("bk"), &prefix.abs_path(path))? } ModifiedFile(ref path, None) => { let abs_path = prefix.abs_path(path); if utils::is_file(&abs_path) { - try!(utils::remove_file("component", &abs_path)); + utils::remove_file("component", &abs_path)?; } } } @@ -202,18 +204,19 @@ impl<'a> ChangedItem<'a> { }.into()) } else { if let Some(p) = abs_path.parent() { - try!(utils::ensure_dir_exists("component", p, &|_| ())); + utils::ensure_dir_exists("component", p, &|_| ())?; } - let file = try!(File::create(&abs_path) - .chain_err(|| format!("error creating file '{}'", abs_path.display()))); + let file = File::create(&abs_path) + .chain_err(|| format!("error creating file '{}'", abs_path.display()))?; Ok((ChangedItem::AddedFile(relpath), file)) } } - fn copy_file(prefix: &InstallPrefix, - component: &str, - relpath: PathBuf, - src: &Path) - -> Result { + fn copy_file( + prefix: &InstallPrefix, + component: &str, + relpath: PathBuf, + src: &Path, + ) -> Result { let abs_path = prefix.abs_path(&relpath); if utils::path_exists(&abs_path) { Err(ErrorKind::ComponentConflict { @@ -222,13 +225,18 @@ impl<'a> ChangedItem<'a> { }.into()) } else { if let Some(p) = abs_path.parent() { - try!(utils::ensure_dir_exists("component", p, &|_| ())); + utils::ensure_dir_exists("component", p, &|_| ())?; } - try!(utils::copy_file(src, &abs_path)); + utils::copy_file(src, &abs_path)?; Ok(ChangedItem::AddedFile(relpath)) } } - fn copy_dir(prefix: &InstallPrefix, component: &str, relpath: PathBuf, src: &Path) -> Result { + fn copy_dir( + prefix: &InstallPrefix, + component: &str, + relpath: PathBuf, + src: &Path, + ) -> Result { let abs_path = prefix.abs_path(&relpath); if utils::path_exists(&abs_path) { Err(ErrorKind::ComponentConflict { @@ -237,52 +245,64 @@ impl<'a> ChangedItem<'a> { }.into()) } else { if let Some(p) = abs_path.parent() { - try!(utils::ensure_dir_exists("component", p, &|_| ())); + utils::ensure_dir_exists("component", p, &|_| ())?; } - try!(utils::copy_dir(src, &abs_path, &|_| ())); + utils::copy_dir(src, &abs_path, &|_| ())?; Ok(ChangedItem::AddedDir(relpath)) } } - fn remove_file(prefix: &InstallPrefix, component: &str, relpath: PathBuf, temp_cfg: &'a temp::Cfg) -> Result { + fn remove_file( + prefix: &InstallPrefix, + component: &str, + relpath: PathBuf, + temp_cfg: &'a temp::Cfg, + ) -> Result { let abs_path = prefix.abs_path(&relpath); - let backup = try!(temp_cfg.new_file()); + let backup = temp_cfg.new_file()?; if !utils::path_exists(&abs_path) { Err(ErrorKind::ComponentMissingFile { name: component.to_owned(), path: relpath.clone(), }.into()) } else { - try!(utils::rename_file("component", &abs_path, &backup)); + utils::rename_file("component", &abs_path, &backup)?; Ok(ChangedItem::RemovedFile(relpath, backup)) } } - fn remove_dir(prefix: &InstallPrefix, component: &str, relpath: PathBuf, temp_cfg: &'a temp::Cfg) -> Result { + fn remove_dir( + prefix: &InstallPrefix, + component: &str, + relpath: PathBuf, + temp_cfg: &'a temp::Cfg, + ) -> Result { let abs_path = prefix.abs_path(&relpath); - let backup = try!(temp_cfg.new_directory()); + let backup = temp_cfg.new_directory()?; if !utils::path_exists(&abs_path) { Err(ErrorKind::ComponentMissingDir { name: component.to_owned(), path: relpath.clone(), }.into()) } else { - try!(utils::rename_dir("component", &abs_path, &backup.join("bk"))); + utils::rename_dir("component", &abs_path, &backup.join("bk"))?; Ok(ChangedItem::RemovedDir(relpath, backup)) } } - fn modify_file(prefix: &InstallPrefix, relpath: PathBuf, temp_cfg: &'a temp::Cfg) -> Result { + fn modify_file( + prefix: &InstallPrefix, + relpath: PathBuf, + temp_cfg: &'a temp::Cfg, + ) -> Result { let abs_path = prefix.abs_path(&relpath); if utils::is_file(&abs_path) { - let backup = try!(temp_cfg.new_file()); - try!(utils::copy_file(&abs_path, &backup)); + let backup = temp_cfg.new_file()?; + utils::copy_file(&abs_path, &backup)?; Ok(ChangedItem::ModifiedFile(relpath, Some(backup))) } else { if let Some(p) = abs_path.parent() { - try!(utils::ensure_dir_exists("component", p, &|_| {})); + utils::ensure_dir_exists("component", p, &|_| {})?; } Ok(ChangedItem::ModifiedFile(relpath, None)) } } } - - diff --git a/src/rustup-dist/src/config.rs b/src/rustup-dist/src/config.rs index 53908586e3..dca4b684f4 100644 --- a/src/rustup-dist/src/config.rs +++ b/src/rustup-dist/src/config.rs @@ -15,14 +15,14 @@ pub struct Config { impl Config { pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { - let version = try!(get_string(&mut table, "config_version", path)); + let version = get_string(&mut table, "config_version", path)?; if !SUPPORTED_CONFIG_VERSIONS.contains(&&*version) { return Err(ErrorKind::UnsupportedVersion(version).into()); } - let components = try!(get_array(&mut table, "components", path)); - let components = try!(Self::toml_to_components(components, - &format!("{}{}.", path, "components"))); + let components = get_array(&mut table, "components", path)?; + let components = + Self::toml_to_components(components, &format!("{}{}.", path, "components"))?; Ok(Config { config_version: version, @@ -31,8 +31,10 @@ impl Config { } pub fn to_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); - result.insert("config_version".to_owned(), - toml::Value::String(self.config_version)); + result.insert( + "config_version".to_owned(), + toml::Value::String(self.config_version), + ); let components = Self::components_to_toml(self.components); if !components.is_empty() { result.insert("components".to_owned(), toml::Value::Array(components)); @@ -55,7 +57,7 @@ impl Config { for (i, v) in arr.into_iter().enumerate() { if let toml::Value::Table(t) = v { let path = format!("{}[{}]", path, i); - result.push(try!(Component::from_toml(t, &path))); + result.push(Component::from_toml(t, &path)?); } } diff --git a/src/rustup-dist/src/dist.rs b/src/rustup-dist/src/dist.rs index a1375ad898..dc52b7f92e 100644 --- a/src/rustup-dist/src/dist.rs +++ b/src/rustup-dist/src/dist.rs @@ -1,4 +1,3 @@ - use temp; use errors::*; use notifications::*; @@ -6,8 +5,8 @@ use rustup_utils::{self, utils}; use prefix::InstallPrefix; use manifest::Component; use manifest::Manifest as ManifestV2; -use manifestation::{Manifestation, UpdateStatus, Changes}; -use download::{DownloadCfg}; +use manifestation::{Changes, Manifestation, UpdateStatus}; +use download::DownloadCfg; use std::path::Path; use std::fmt; @@ -57,32 +56,44 @@ pub struct TargetTriple(String); // These lists contain the targets known to rustup, and used to build // the PartialTargetTriple. -static LIST_ARCHS: &'static [&'static str] = &["i386", - "i586", - "i686", - "x86_64", - "arm", - "armv7", - "armv7s", - "aarch64", - "mips", - "mipsel", - "mips64", - "mips64el", - "powerpc", - "powerpc64", - "powerpc64le", - "s390x"]; -static LIST_OSES: &'static [&'static str] = &["pc-windows", - "unknown-linux", - "apple-darwin", - "unknown-netbsd", - "apple-ios", - "linux", - "rumprun-netbsd", - "unknown-freebsd"]; -static LIST_ENVS: &'static [&'static str] = - &["gnu", "msvc", "gnueabi", "gnueabihf", "gnuabi64", "androideabi", "android", "musl"]; +static LIST_ARCHS: &'static [&'static str] = &[ + "i386", + "i586", + "i686", + "x86_64", + "arm", + "armv7", + "armv7s", + "aarch64", + "mips", + "mipsel", + "mips64", + "mips64el", + "powerpc", + "powerpc64", + "powerpc64le", + "s390x", +]; +static LIST_OSES: &'static [&'static str] = &[ + "pc-windows", + "unknown-linux", + "apple-darwin", + "unknown-netbsd", + "apple-ios", + "linux", + "rumprun-netbsd", + "unknown-freebsd", +]; +static LIST_ENVS: &'static [&'static str] = &[ + "gnu", + "msvc", + "gnueabi", + "gnueabihf", + "gnuabi64", + "androideabi", + "android", + "musl", +]; // MIPS platforms don't indicate endianness in uname, however binaries only // run on boxes with the same endianness, as expected. @@ -94,11 +105,9 @@ const TRIPLE_MIPS_UNKNOWN_LINUX_GNU: &'static str = "mips-unknown-linux-gnu"; const TRIPLE_MIPS_UNKNOWN_LINUX_GNU: &'static 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: &'static 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: &'static str = "mips64el-unknown-linux-gnuabi64"; impl TargetTriple { pub fn from_str(name: &str) -> Self { @@ -153,8 +162,10 @@ impl TargetTriple { return None; } - (CStr::from_ptr(sys_info.sysname.as_ptr()).to_bytes(), - CStr::from_ptr(sys_info.machine.as_ptr()).to_bytes()) + ( + CStr::from_ptr(sys_info.sysname.as_ptr()).to_bytes(), + CStr::from_ptr(sys_info.machine.as_ptr()).to_bytes(), + ) }; let host_triple = match (sysname, machine) { @@ -213,10 +224,12 @@ impl PartialTargetTriple { // we can count on all triple components being // delineated by it. let name = format!("-{}", name); - let pattern = format!(r"^(?:-({}))?(?:-({}))?(?:-({}))?$", - LIST_ARCHS.join("|"), - LIST_OSES.join("|"), - LIST_ENVS.join("|")); + let pattern = format!( + r"^(?:-({}))?(?:-({}))?(?:-({}))?$", + LIST_ARCHS.join("|"), + LIST_OSES.join("|"), + LIST_ENVS.join("|") + ); let re = Regex::new(&pattern).unwrap(); re.captures(&name).map(|c| { @@ -239,12 +252,18 @@ impl PartialTargetTriple { impl PartialToolchainDesc { pub fn from_str(name: &str) -> Result { - let channels = - ["nightly", "beta", "stable", r"\d{1}\.\d{1}\.\d{1}", r"\d{1}\.\d{2}\.\d{1}"]; - - let pattern = format!(r"^({})(?:-(\d{{4}}-\d{{2}}-\d{{2}}))?(?:-(.*))?$", - channels.join("|")); + let channels = [ + "nightly", + "beta", + "stable", + r"\d{1}\.\d{1}\.\d{1}", + r"\d{1}\.\d{2}\.\d{1}", + ]; + let pattern = format!( + r"^({})(?:-(\d{{4}}-\d{{2}}-\d{{2}}))?(?:-(.*))?$", + channels.join("|") + ); let re = Regex::new(&pattern).unwrap(); let d = re.captures(name).map(|c| { @@ -258,12 +277,10 @@ impl PartialToolchainDesc { let trip = c.get(3).map(|c| c.as_str()).unwrap_or(""); let trip = PartialTargetTriple::from_str(&trip); - trip.map(|t| { - PartialToolchainDesc { - channel: c.get(1).unwrap().as_str().to_owned(), - date: c.get(2).map(|s| s.as_str()).and_then(fn_map), - target: t, - } + trip.map(|t| PartialToolchainDesc { + channel: c.get(1).unwrap().as_str().to_owned(), + date: c.get(2).map(|s| s.as_str()).and_then(fn_map), + target: t, }) }); @@ -311,13 +328,18 @@ impl PartialToolchainDesc { impl ToolchainDesc { pub fn from_str(name: &str) -> Result { - let channels = - ["nightly", "beta", "stable", r"\d{1}\.\d{1}\.\d{1}", r"\d{1}\.\d{2}\.\d{1}"]; + let channels = [ + "nightly", + "beta", + "stable", + r"\d{1}\.\d{1}\.\d{1}", + r"\d{1}\.\d{2}\.\d{1}", + ]; let pattern = format!( r"^({})(?:-(\d{{4}}-\d{{2}}-\d{{2}}))?-(.*)?$", channels.join("|"), - ); + ); let re = Regex::new(&pattern).unwrap(); re.captures(name) @@ -395,19 +417,20 @@ pub fn validate_channel_name(name: &str) -> Result<()> { pub struct Manifest<'a>(temp::File<'a>, String); impl<'a> Manifest<'a> { - pub fn package_url(&self, - package: &str, - target_triple: &str, - ext: &str) - -> Result> { + pub fn package_url( + &self, + package: &str, + target_triple: &str, + ext: &str, + ) -> Result> { let suffix = target_triple.to_owned() + ext; - Ok(try!(utils::match_file("manifest", &self.0, |line| { + Ok(utils::match_file("manifest", &self.0, |line| { if line.starts_with(package) && line.ends_with(&suffix) { Some(format!("{}/{}", &self.1, line)) } else { None } - }))) + })?) } } @@ -419,19 +442,19 @@ impl fmt::Display for TargetTriple { impl fmt::Display for PartialToolchainDesc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", &self.channel)); + write!(f, "{}", &self.channel)?; if let Some(ref date) = self.date { - try!(write!(f, "-{}", date)); + write!(f, "-{}", date)?; } if let Some(ref arch) = self.target.arch { - try!(write!(f, "-{}", arch)); + write!(f, "-{}", arch)?; } if let Some(ref os) = self.target.os { - try!(write!(f, "-{}", os)); + write!(f, "-{}", os)?; } if let Some(ref env) = self.target.env { - try!(write!(f, "-{}", env)); + write!(f, "-{}", env)?; } Ok(()) @@ -440,60 +463,55 @@ impl fmt::Display for PartialToolchainDesc { impl fmt::Display for ToolchainDesc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", &self.channel)); + write!(f, "{}", &self.channel)?; if let Some(ref date) = self.date { - try!(write!(f, "-{}", date)); + write!(f, "-{}", date)?; } - try!(write!(f, "-{}", self.target)); + write!(f, "-{}", self.target)?; Ok(()) } } - // Installs or updates a toolchain from a dist server. If an initial // install then it will be installed with the default components. If // an upgrade then all the existing components will be upgraded. // // Returns the manifest's hash if anything changed. -pub fn update_from_dist<'a>(download: DownloadCfg<'a>, - update_hash: Option<&Path>, - toolchain: &ToolchainDesc, - prefix: &InstallPrefix, - add: &[Component], - remove: &[Component]) - -> Result> { - +pub fn update_from_dist<'a>( + download: DownloadCfg<'a>, + update_hash: Option<&Path>, + toolchain: &ToolchainDesc, + prefix: &InstallPrefix, + add: &[Component], + remove: &[Component], +) -> Result> { let fresh_install = !prefix.path().exists(); - let res = update_from_dist_(download, - update_hash, - toolchain, - prefix, - add, - remove); + let res = update_from_dist_(download, update_hash, toolchain, prefix, add, remove); // Don't leave behind an empty / broken installation directory if res.is_err() && fresh_install { // FIXME Ignoring cascading errors - let _ = utils::remove_dir("toolchain", prefix.path(), - &|n| (download.notify_handler)(n.into())); + let _ = utils::remove_dir("toolchain", prefix.path(), &|n| { + (download.notify_handler)(n.into()) + }); } res } -pub fn update_from_dist_<'a>(download: DownloadCfg<'a>, - update_hash: Option<&Path>, - toolchain: &ToolchainDesc, - prefix: &InstallPrefix, - add: &[Component], - remove: &[Component]) - -> Result> { - +pub fn update_from_dist_<'a>( + download: DownloadCfg<'a>, + update_hash: Option<&Path>, + toolchain: &ToolchainDesc, + prefix: &InstallPrefix, + add: &[Component], + remove: &[Component], +) -> Result> { let toolchain_str = toolchain.to_string(); - let manifestation = try!(Manifestation::open(prefix.clone(), toolchain.target.clone())); + let manifestation = Manifestation::open(prefix.clone(), toolchain.target.clone())?; let changes = Changes { add_extensions: add.to_owned(), @@ -504,23 +522,26 @@ pub fn update_from_dist_<'a>(download: DownloadCfg<'a>, (download.notify_handler)(Notification::DownloadingManifest(&toolchain_str)); match dl_v2_manifest(download, update_hash, toolchain) { Ok(Some((m, hash))) => { - (download.notify_handler)(Notification::DownloadedManifest(&m.date, m.get_rust_version().ok())); - return match try!(manifestation.update(&m, - changes, - &download, - download.notify_handler.clone())) { + (download.notify_handler)(Notification::DownloadedManifest( + &m.date, + m.get_rust_version().ok(), + )); + return match manifestation.update( + &m, + changes, + &download, + download.notify_handler.clone(), + )? { UpdateStatus::Unchanged => Ok(None), UpdateStatus::Changed => Ok(Some(hash)), - } + }; } Ok(None) => return Ok(None), Err(Error(ErrorKind::Utils(::rustup_utils::ErrorKind::DownloadNotExists { .. }), _)) => { // Proceed to try v1 as a fallback (download.notify_handler)(Notification::DownloadingLegacyManifest); } - Err(Error(ErrorKind::ChecksumFailed { .. }, _)) => { - return Ok(None) - } + Err(Error(ErrorKind::ChecksumFailed { .. }, _)) => return Ok(None), Err(e) => return Err(e), } @@ -535,31 +556,38 @@ pub fn update_from_dist_<'a>(download: DownloadCfg<'a>, } Err(e) => { return Err(e).chain_err(|| { - format!("failed to download manifest for '{}'", - toolchain.manifest_name()) + format!( + "failed to download manifest for '{}'", + toolchain.manifest_name() + ) }); } }; - match manifestation.update_v1(&manifest, - update_hash, - &download.temp_cfg, - download.notify_handler.clone()) { + match manifestation.update_v1( + &manifest, + update_hash, + &download.temp_cfg, + download.notify_handler.clone(), + ) { Ok(None) => Ok(None), Ok(Some(hash)) => Ok(Some(hash)), e @ Err(Error(ErrorKind::Utils(rustup_utils::ErrorKind::DownloadNotExists { .. }), _)) => { e.chain_err(|| { - format!("could not download nonexistent rust version `{}`", - toolchain_str) + format!( + "could not download nonexistent rust version `{}`", + toolchain_str + ) }) } Err(e) => Err(e), } } -fn dl_v2_manifest<'a>(download: DownloadCfg<'a>, - update_hash: Option<&Path>, - toolchain: &ToolchainDesc) - -> Result> { +fn dl_v2_manifest<'a>( + download: DownloadCfg<'a>, + update_hash: Option<&Path>, + toolchain: &ToolchainDesc, +) -> Result> { let manifest_url = toolchain.manifest_v2_url(download.dist_root); let manifest_dl_res = download.download_and_check(&manifest_url, update_hash, ".toml"); @@ -570,8 +598,8 @@ fn dl_v2_manifest<'a>(download: DownloadCfg<'a>, } else { return Ok(None); }; - let manifest_str = try!(utils::read_file("manifest", &manifest_file)); - let manifest = try!(ManifestV2::parse(&manifest_str)); + let manifest_str = utils::read_file("manifest", &manifest_file)?; + let manifest = ManifestV2::parse(&manifest_str)?; Ok(Some((manifest, manifest_hash))) } else { @@ -584,7 +612,6 @@ fn dl_v2_manifest<'a>(download: DownloadCfg<'a>, } Err(manifest_dl_res.unwrap_err()) } - } fn dl_v1_manifest<'a>(download: DownloadCfg<'a>, toolchain: &ToolchainDesc) -> Result> { @@ -593,18 +620,21 @@ fn dl_v1_manifest<'a>(download: DownloadCfg<'a>, toolchain: &ToolchainDesc) -> R if !["nightly", "beta", "stable"].contains(&&*toolchain.channel) { // This is an explicit version. In v1 there was no manifest, // you just know the file to download, so synthesize one. - let installer_name = format!("{}/rust-{}-{}.tar.gz", - root_url, - toolchain.channel, - toolchain.target); + let installer_name = format!( + "{}/rust-{}-{}.tar.gz", + root_url, toolchain.channel, toolchain.target + ); return Ok(vec![installer_name]); } let manifest_url = toolchain.manifest_v1_url(download.dist_root); - let manifest_dl = try!(download.download_and_check(&manifest_url, None, "")); + let manifest_dl = download.download_and_check(&manifest_url, None, "")?; let (manifest_file, _) = manifest_dl.unwrap(); - let manifest_str = try!(utils::read_file("manifest", &manifest_file)); - let urls = manifest_str.lines().map(|s| format!("{}/{}", root_url, s)).collect(); + let manifest_str = utils::read_file("manifest", &manifest_file)?; + let urls = manifest_str + .lines() + .map(|s| format!("{}/{}", root_url, s)) + .collect(); Ok(urls) } diff --git a/src/rustup-dist/src/download.rs b/src/rustup-dist/src/download.rs index 8e31568ddb..ef1f039c30 100644 --- a/src/rustup-dist/src/download.rs +++ b/src/rustup-dist/src/download.rs @@ -1,11 +1,10 @@ -use rustup_utils::{utils}; +use rustup_utils::utils; use errors::*; use temp; use notifications::*; -use sha2::{Sha256, Digest}; +use sha2::{Digest, Sha256}; use url::Url; - use std::path::{Path, PathBuf}; use std::fs; use std::ops; @@ -20,7 +19,6 @@ pub struct DownloadCfg<'a> { pub notify_handler: &'a Fn(Notification), } - pub struct File { path: PathBuf, } @@ -33,46 +31,46 @@ impl ops::Deref for File { } } - impl<'a> DownloadCfg<'a> { - /// Downloads a file, validating its hash, and resuming interrupted downloads /// Partial downloads are stored in `self.download_dir`, keyed by hash. If the /// target file already exists, then the hash is checked and it is returned - /// immediately without re-downloading. + /// immediately without re-downloading. pub fn download(&self, url: &Url, hash: &str) -> Result { - - try!(utils::ensure_dir_exists("Download Directory", &self.download_dir, &|n| (self.notify_handler)(n.into()))); + utils::ensure_dir_exists("Download Directory", &self.download_dir, &|n| { + (self.notify_handler)(n.into()) + })?; let target_file = self.download_dir.join(Path::new(hash)); if target_file.exists() { - let cached_result = try!(file_hash(&target_file)); + let cached_result = file_hash(&target_file)?; if hash == cached_result { (self.notify_handler)(Notification::FileAlreadyDownloaded); (self.notify_handler)(Notification::ChecksumValid(&url.to_string())); - return Ok(File { path: target_file, }); + return Ok(File { path: target_file }); } else { (self.notify_handler)(Notification::CachedFileChecksumFailed); - try!(fs::remove_file(&target_file).chain_err(|| "cleaning up previous download")); + fs::remove_file(&target_file).chain_err(|| "cleaning up previous download")?; } } - - let partial_file_path = - target_file.with_file_name( - target_file.file_name().map(|s| { - s.to_str().unwrap_or("_")}) - .unwrap_or("_") - .to_owned() - + ".partial"); + let partial_file_path = target_file.with_file_name( + target_file + .file_name() + .map(|s| s.to_str().unwrap_or("_")) + .unwrap_or("_") + .to_owned() + ".partial", + ); let mut hasher = Sha256::new(); - try!(utils::download_file_with_resume(&url, - &partial_file_path, - Some(&mut hasher), - true, - &|n| (self.notify_handler)(n.into()))); + utils::download_file_with_resume( + &url, + &partial_file_path, + Some(&mut hasher), + true, + &|n| (self.notify_handler)(n.into()), + )?; let actual_hash = format!("{:x}", hasher.result()); @@ -85,7 +83,7 @@ impl<'a> DownloadCfg<'a> { }.into()); } else { (self.notify_handler)(Notification::ChecksumValid(&url.to_string())); - try!(fs::rename(&partial_file_path, &target_file)); + fs::rename(&partial_file_path, &target_file)?; return Ok(File { path: target_file }); } } @@ -94,37 +92,36 @@ impl<'a> DownloadCfg<'a> { for hash in hashes.iter() { let used_file = self.download_dir.join(hash); if self.download_dir.join(&used_file).exists() { - try!(fs::remove_file(used_file).chain_err(|| "cleaning up cached downloads")); + fs::remove_file(used_file).chain_err(|| "cleaning up cached downloads")?; } } Ok(()) } fn download_hash(&self, url: &str) -> Result { - let hash_url = try!(utils::parse_url(&(url.to_owned() + ".sha256"))); - let hash_file = try!(self.temp_cfg.new_file()); + let hash_url = utils::parse_url(&(url.to_owned() + ".sha256"))?; + let hash_file = self.temp_cfg.new_file()?; - try!(utils::download_file(&hash_url, - &hash_file, - None, - &|n| (self.notify_handler)(n.into()))); + utils::download_file(&hash_url, &hash_file, None, &|n| { + (self.notify_handler)(n.into()) + })?; - Ok(try!(utils::read_file("hash", &hash_file).map(|s| s[0..64].to_owned()))) + Ok(utils::read_file("hash", &hash_file).map(|s| s[0..64].to_owned())?) } /// Downloads a file, sourcing its hash from the same url with a `.sha256` suffix. /// If `update_hash` is present, then that will be compared to the downloaded hash, - /// and if they match, the download is skipped. - pub fn download_and_check(&self, - url_str: &str, - update_hash: Option<&Path>, - ext: &str) - -> Result, String)>> { - let hash = try!(self.download_hash(url_str)); + /// and if they match, the download is skipped. + pub fn download_and_check( + &self, + url_str: &str, + update_hash: Option<&Path>, + ext: &str, + ) -> Result, String)>> { + let hash = self.download_hash(url_str)?; let partial_hash: String = hash.chars().take(UPDATE_HASH_LEN).collect(); if let Some(hash_file) = update_hash { - if utils::is_file(hash_file) { if let Ok(contents) = utils::read_file("update hash", hash_file) { if contents == partial_hash { @@ -139,24 +136,22 @@ impl<'a> DownloadCfg<'a> { } } - let url = try!(utils::parse_url(url_str)); - let file = try!(self.temp_cfg.new_file_with_ext("", ext)); + let url = utils::parse_url(url_str)?; + let file = self.temp_cfg.new_file_with_ext("", ext)?; let mut hasher = Sha256::new(); - try!(utils::download_file(&url, - &file, - Some(&mut hasher), - &|n| (self.notify_handler)(n.into()))); + utils::download_file(&url, &file, Some(&mut hasher), &|n| { + (self.notify_handler)(n.into()) + })?; let actual_hash = format!("{:x}", hasher.result()); if hash != actual_hash { // Incorrect hash return Err(ErrorKind::ChecksumFailed { - url: url_str.to_owned(), - expected: hash, - calculated: actual_hash, - } - .into()); + url: url_str.to_owned(), + expected: hash, + calculated: actual_hash, + }.into()); } else { (self.notify_handler)(Notification::ChecksumValid(url_str)); } @@ -167,15 +162,16 @@ impl<'a> DownloadCfg<'a> { } } - fn file_hash(path: &Path) -> Result { let mut hasher = Sha256::new(); use std::io::Read; - let mut downloaded = try!(fs::File::open(&path).chain_err(|| "opening already downloaded file")); + 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; } + if n == 0 { + break; + } hasher.input(&buf[..n]); } else { break; diff --git a/src/rustup-dist/src/errors.rs b/src/rustup-dist/src/errors.rs index b878b1ef8f..f193c4288f 100644 --- a/src/rustup-dist/src/errors.rs +++ b/src/rustup-dist/src/errors.rs @@ -128,20 +128,23 @@ fn component_unavailable_msg(cs: &[Component]) -> String { } if cs.len() == 1 { - let _ = write!(buf, "component {} is unavailable for download", format_component(&cs[0])); + let _ = write!( + buf, + "component {} is unavailable for download", + format_component(&cs[0]) + ); } else { use itertools::Itertools; - let same_target = cs.iter().all(|c| c.target == cs[0].target || c.target.is_none()); + let same_target = cs.iter() + .all(|c| c.target == cs[0].target || c.target.is_none()); if same_target { let mut cs_strs = cs.iter().map(|c| format!("'{}'", c.pkg)); let cs_str = cs_strs.join(", "); - let _ = write!(buf, "some components unavailable for download: {}", - cs_str); + let _ = write!(buf, "some components unavailable for download: {}", cs_str); } else { let mut cs_strs = cs.iter().map(format_component); let cs_str = cs_strs.join(", "); - let _ = write!(buf, "some components unavailable for download: {}", - cs_str); + let _ = write!(buf, "some components unavailable for download: {}", cs_str); } } diff --git a/src/rustup-dist/src/lib.rs b/src/rustup-dist/src/lib.rs index ae26f47873..a748dd57f1 100644 --- a/src/rustup-dist/src/lib.rs +++ b/src/rustup-dist/src/lib.rs @@ -1,30 +1,30 @@ #![recursion_limit = "1024"] -extern crate regex; -extern crate itertools; -extern crate walkdir; -extern crate toml; -extern crate flate2; -extern crate tar; -extern crate url; -extern crate rustup_utils; #[macro_use] extern crate error_chain; +extern crate flate2; +extern crate itertools; +extern crate regex; +extern crate rustup_utils; extern crate sha2; +extern crate tar; +extern crate toml; +extern crate url; +extern crate walkdir; -#[cfg(windows)] -extern crate winapi; -#[cfg(windows)] -extern crate winreg; -#[cfg(windows)] -extern crate user32; #[cfg(windows)] extern crate kernel32; #[cfg(not(windows))] extern crate libc; +#[cfg(windows)] +extern crate user32; +#[cfg(windows)] +extern crate winapi; +#[cfg(windows)] +extern crate winreg; pub use errors::*; -pub use notifications::{Notification}; +pub use notifications::Notification; pub mod temp; diff --git a/src/rustup-dist/src/manifest.rs b/src/rustup-dist/src/manifest.rs index 5e149984cd..81f85c781a 100644 --- a/src/rustup-dist/src/manifest.rs +++ b/src/rustup-dist/src/manifest.rs @@ -37,7 +37,7 @@ pub struct Package { #[derive(Clone, Debug, PartialEq)] pub enum PackageTargets { Wildcard(TargetedPackage), - Targeted(HashMap) + Targeted(HashMap), } #[derive(Clone, Debug, PartialEq)] @@ -65,7 +65,7 @@ impl Manifest { pub fn parse(data: &str) -> Result { let value = toml::from_str(data).map_err(ErrorKind::Parsing)?; let manifest = Self::from_toml(value, "")?; - try!(manifest.validate()); + manifest.validate()?; Ok(manifest) } @@ -74,23 +74,25 @@ impl Manifest { } pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { - let version = try!(get_string(&mut table, "manifest-version", path)); + let version = get_string(&mut table, "manifest-version", path)?; if !SUPPORTED_MANIFEST_VERSIONS.contains(&&*version) { return Err(ErrorKind::UnsupportedVersion(version).into()); } Ok(Manifest { manifest_version: version, - date: try!(get_string(&mut table, "date", path)), - packages: try!(Self::table_to_packages(&mut table, path)), - renames: try!(Self::table_to_renames(table, path)), + date: get_string(&mut table, "date", path)?, + packages: Self::table_to_packages(&mut table, path)?, + renames: Self::table_to_renames(table, path)?, }) } pub fn to_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); result.insert("date".to_owned(), toml::Value::String(self.date)); - result.insert("manifest-version".to_owned(), - toml::Value::String(self.manifest_version)); + result.insert( + "manifest-version".to_owned(), + toml::Value::String(self.manifest_version), + ); let renames = Self::renames_to_table(self.renames); result.insert("rename".to_owned(), toml::Value::Table(renames)); @@ -101,13 +103,16 @@ impl Manifest { result } - fn table_to_packages(table: &mut toml::value::Table, path: &str) -> Result> { + fn table_to_packages( + table: &mut toml::value::Table, + path: &str, + ) -> Result> { let mut result = HashMap::new(); - let pkg_table = try!(get_table(table, "pkg", path)); + let pkg_table = get_table(table, "pkg", path)?; for (k, v) in pkg_table { if let toml::Value::Table(t) = v { - result.insert(k, try!(Package::from_toml(t, &path))); + result.insert(k, Package::from_toml(t, &path)?); } } @@ -121,9 +126,12 @@ impl Manifest { result } - fn table_to_renames(mut table: toml::value::Table, path: &str) -> Result> { + fn table_to_renames( + mut table: toml::value::Table, + path: &str, + ) -> Result> { let mut result = HashMap::new(); - let rename_table = try!(get_table(&mut table, "rename", path)); + let rename_table = get_table(&mut table, "rename", path)?; for (k, v) in rename_table { if let toml::Value::Table(mut t) = v { @@ -144,8 +152,9 @@ impl Manifest { } pub fn get_package(&self, name: &str) -> Result<&Package> { - self.packages.get(name).ok_or_else( - || format!("package not found: '{}'", name).into()) + self.packages + .get(name) + .ok_or_else(|| format!("package not found: '{}'", name).into()) } pub fn get_rust_version(&self) -> Result<&str> { @@ -154,8 +163,10 @@ impl Manifest { fn validate_targeted_package(&self, tpkg: &TargetedPackage) -> Result<()> { for c in tpkg.components.iter().chain(tpkg.extensions.iter()) { - let cpkg = try!(self.get_package(&c.pkg).chain_err(|| ErrorKind::MissingPackageForComponent(c.clone()))); - let _ctpkg = try!(cpkg.get_target(c.target.as_ref()).chain_err(|| ErrorKind::MissingPackageForComponent(c.clone()))); + let cpkg = self.get_package(&c.pkg) + .chain_err(|| ErrorKind::MissingPackageForComponent(c.clone()))?; + let _ctpkg = cpkg.get_target(c.target.as_ref()) + .chain_err(|| ErrorKind::MissingPackageForComponent(c.clone()))?; } Ok(()) } @@ -165,13 +176,11 @@ impl Manifest { for (_, pkg) in &self.packages { match pkg.targets { PackageTargets::Wildcard(ref tpkg) => { - try!(self.validate_targeted_package(tpkg)); - }, - PackageTargets::Targeted(ref tpkgs) => { - for (_, tpkg) in tpkgs { - try!(self.validate_targeted_package(tpkg)); - } + self.validate_targeted_package(tpkg)?; } + PackageTargets::Targeted(ref tpkgs) => for (_, tpkg) in tpkgs { + self.validate_targeted_package(tpkg)?; + }, } } @@ -190,8 +199,8 @@ impl Manifest { impl Package { pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { Ok(Package { - version: try!(get_string(&mut table, "version", path)), - targets: try!(Self::toml_to_targets(table, path)), + version: get_string(&mut table, "version", path)?, + targets: Self::toml_to_targets(table, path)?, }) } pub fn to_toml(self) -> toml::value::Table { @@ -206,15 +215,21 @@ impl Package { } fn toml_to_targets(mut table: toml::value::Table, path: &str) -> Result { - let mut target_table = try!(get_table(&mut table, "target", path)); + let mut target_table = get_table(&mut table, "target", path)?; if let Some(toml::Value::Table(t)) = target_table.remove("*") { - Ok(PackageTargets::Wildcard(try!(TargetedPackage::from_toml(t, &path)))) + Ok(PackageTargets::Wildcard(TargetedPackage::from_toml( + t, + &path, + )?)) } else { let mut result = HashMap::new(); for (k, v) in target_table { if let toml::Value::Table(t) = v { - result.insert(TargetTriple::from_str(&k), try!(TargetedPackage::from_toml(t, &path))); + result.insert( + TargetTriple::from_str(&k), + TargetedPackage::from_toml(t, &path)?, + ); } } Ok(PackageTargets::Targeted(result)) @@ -225,12 +240,10 @@ impl Package { match targets { PackageTargets::Wildcard(tpkg) => { result.insert("*".to_owned(), toml::Value::Table(tpkg.to_toml())); - }, - PackageTargets::Targeted(tpkgs) => { - for (k, v) in tpkgs { - result.insert(k.to_string(), toml::Value::Table(v.to_toml())); - } } + PackageTargets::Targeted(tpkgs) => for (k, v) in tpkgs { + result.insert(k.to_string(), toml::Value::Table(v.to_toml())); + }, } result } @@ -240,8 +253,9 @@ impl Package { PackageTargets::Wildcard(ref tpkg) => Ok(tpkg), PackageTargets::Targeted(ref tpkgs) => { if let Some(t) = target { - tpkgs.get(t).ok_or_else( - || format!("target not found: '{}'", t).into()) + tpkgs + .get(t) + .ok_or_else(|| format!("target not found: '{}'", t).into()) } else { Err("no target specified".into()) } @@ -254,34 +268,38 @@ impl PackageTargets { pub fn get<'a>(&'a self, target: &TargetTriple) -> Option<&'a TargetedPackage> { match *self { PackageTargets::Wildcard(ref tpkg) => Some(tpkg), - PackageTargets::Targeted(ref tpkgs) => tpkgs.get(target) + PackageTargets::Targeted(ref tpkgs) => tpkgs.get(target), } } pub fn get_mut<'a>(&'a mut self, target: &TargetTriple) -> Option<&'a mut TargetedPackage> { match *self { PackageTargets::Wildcard(ref mut tpkg) => Some(tpkg), - PackageTargets::Targeted(ref mut tpkgs) => tpkgs.get_mut(target) + PackageTargets::Targeted(ref mut tpkgs) => tpkgs.get_mut(target), } } } impl TargetedPackage { pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { - let components = try!(get_array(&mut table, "components", path)); - let extensions = try!(get_array(&mut table, "extensions", path)); + let components = get_array(&mut table, "components", path)?; + let extensions = get_array(&mut table, "extensions", path)?; - if try!(get_bool(&mut table, "available", path)) { + if get_bool(&mut table, "available", path)? { Ok(TargetedPackage { bins: Some(PackageBins { - url: try!(get_string(&mut table, "url", path)), - hash: try!(get_string(&mut table, "hash", path)), + url: get_string(&mut table, "url", path)?, + hash: get_string(&mut table, "hash", path)?, xz_url: get_string(&mut table, "xz_url", path).ok(), xz_hash: get_string(&mut table, "xz_hash", path).ok(), }), - components: try!(Self::toml_to_components(components, - &format!("{}{}.", path, "components"))), - extensions: try!(Self::toml_to_components(extensions, - &format!("{}{}.", path, "extensions"))), + components: Self::toml_to_components( + components, + &format!("{}{}.", path, "components"), + )?, + extensions: Self::toml_to_components( + extensions, + &format!("{}{}.", path, "extensions"), + )?, }) } else { Ok(TargetedPackage { @@ -325,7 +343,7 @@ impl TargetedPackage { for (i, v) in arr.into_iter().enumerate() { if let toml::Value::Table(t) = v { let path = format!("{}[{}]", path, i); - result.push(try!(Component::from_toml(t, &path))); + result.push(Component::from_toml(t, &path)?); } } @@ -343,21 +361,26 @@ impl TargetedPackage { impl Component { pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { Ok(Component { - pkg: try!(get_string(&mut table, "pkg", path)), - target: try!(get_string(&mut table, "target", path).map(|s| { + pkg: get_string(&mut table, "pkg", path)?, + target: get_string(&mut table, "target", path).map(|s| { if s == "*" { None } else { Some(TargetTriple::from_str(&s)) } - })), + })?, }) } pub fn to_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); - result.insert("target".to_owned(), toml::Value::String( - self.target.map(|t| t.to_string()).unwrap_or_else(||"*".to_owned()) - )); + result.insert( + "target".to_owned(), + toml::Value::String( + self.target + .map(|t| t.to_string()) + .unwrap_or_else(|| "*".to_owned()), + ), + ); result.insert("pkg".to_owned(), toml::Value::String(self.pkg)); result } diff --git a/src/rustup-dist/src/manifestation.rs b/src/rustup-dist/src/manifestation.rs index d48e13e299..f55d3b9abc 100644 --- a/src/rustup-dist/src/manifestation.rs +++ b/src/rustup-dist/src/manifestation.rs @@ -4,7 +4,7 @@ use config::Config; use manifest::{Component, Manifest, TargetedPackage}; use dist::{TargetTriple, DEFAULT_DIST_SERVER}; -use component::{Components, Transaction, TarGzPackage, TarXzPackage, Package}; +use component::{Components, Package, TarGzPackage, TarXzPackage, Transaction}; use temp; use errors::*; use notifications::*; @@ -24,7 +24,7 @@ enum Format { #[derive(Debug)] pub struct Manifestation { installation: Components, - target_triple: TargetTriple + target_triple: TargetTriple, } #[derive(Debug)] @@ -43,7 +43,10 @@ impl Changes { } #[derive(PartialEq, Debug)] -pub enum UpdateStatus { Changed, Unchanged } +pub enum UpdateStatus { + Changed, + Unchanged, +} impl Manifestation { /// Open the install prefix for updates from a distribution @@ -55,7 +58,7 @@ impl Manifestation { // TODO: validate the triple with the existing install as well // as the metadata format of the existing install Ok(Manifestation { - installation: try!(Components::open(prefix)), + installation: Components::open(prefix)?, target_triple: triple, }) } @@ -75,33 +78,38 @@ impl Manifestation { /// distribution manifest to "rustlib/rustup-dist.toml" and a /// configuration containing the component name-target pairs to /// "rustlib/rustup-config.toml". - pub fn update(&self, - new_manifest: &Manifest, - changes: Changes, - download_cfg: &DownloadCfg, - notify_handler: &Fn(Notification)) -> Result { - + pub fn update( + &self, + new_manifest: &Manifest, + changes: Changes, + download_cfg: &DownloadCfg, + notify_handler: &Fn(Notification), + ) -> Result { // 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 rust_package = try!(new_manifest.get_package("rust")); - let rust_target_package = try!(rust_package.get_target(Some(&self.target_triple))); + let rust_package = new_manifest.get_package("rust")?; + let rust_target_package = rust_package.get_target(Some(&self.target_triple))?; // Load the previous dist manifest - let ref old_manifest = try!(self.load_manifest()); + let ref old_manifest = self.load_manifest()?; // Load the configuration and list of installed components. - let ref config = try!(self.read_config()); + let ref config = self.read_config()?; // Create the lists of components needed for installation - let component_lists = try!(build_update_component_lists(new_manifest, old_manifest, config, - changes, &rust_target_package, - notify_handler)); - let (components_to_uninstall, - components_to_install, - final_component_list) = component_lists; + let component_lists = build_update_component_lists( + new_manifest, + old_manifest, + config, + changes, + &rust_target_package, + notify_handler, + )?; + let (components_to_uninstall, components_to_install, final_component_list) = + component_lists; if components_to_uninstall.is_empty() && components_to_install.is_empty() { return Ok(UpdateStatus::Unchanged); @@ -110,26 +118,35 @@ impl Manifestation { // Make sure we don't accidentally uninstall the essential components! (see #1297) let missing_essential_components = ["rustc", "cargo"] .iter() - .filter_map(|pkg| if final_component_list.iter().any(|c| &c.pkg == pkg) { - None - } else { - Some(Component { - pkg: pkg.to_string(), - target: Some(self.target_triple.clone()), - }) + .filter_map(|pkg| { + if final_component_list.iter().any(|c| &c.pkg == pkg) { + None + } else { + Some(Component { + pkg: pkg.to_string(), + target: Some(self.target_triple.clone()), + }) + } }) .collect::>(); if !missing_essential_components.is_empty() { - return Err(ErrorKind::RequestedComponentsUnavailable(missing_essential_components).into()); + return Err( + ErrorKind::RequestedComponentsUnavailable(missing_essential_components).into(), + ); } // Validate that the requested components are available - let unavailable_components: Vec = components_to_install.iter().filter(|c| { - use manifest::*; - let pkg: Option<&Package> = new_manifest.get_package(&c.pkg).ok(); - let target_pkg: Option<&TargetedPackage> = pkg.and_then(|p| p.get_target(c.target.as_ref()).ok()); - target_pkg.map(|tp| tp.available()) != Some(true) - }).cloned().collect(); + let unavailable_components: Vec = components_to_install + .iter() + .filter(|c| { + use manifest::*; + let pkg: Option<&Package> = new_manifest.get_package(&c.pkg).ok(); + let target_pkg: Option<&TargetedPackage> = + pkg.and_then(|p| p.get_target(c.target.as_ref()).ok()); + target_pkg.map(|tp| tp.available()) != Some(true) + }) + .cloned() + .collect(); if !unavailable_components.is_empty() { return Err(ErrorKind::RequestedComponentsUnavailable(unavailable_components).into()); @@ -138,17 +155,16 @@ impl Manifestation { // Map components to urls and hashes let mut components_urls_and_hashes: Vec<(Component, Format, String, String)> = Vec::new(); for component in components_to_install { - let package = try!(new_manifest.get_package(&component.pkg)); - let target_package = try!(package.get_target(component.target.as_ref())); + let package = new_manifest.get_package(&component.pkg)?; + let target_package = package.get_target(component.target.as_ref())?; let bins = target_package.bins.as_ref().expect("components available"); - let c_u_h = - if let (Some(url), Some(hash)) = (bins.xz_url.clone(), - bins.xz_hash.clone()) { - (component, Format::Xz, url, hash) - } else { - (component, Format::Gz, bins.url.clone(), bins.hash.clone()) - }; + let c_u_h = if let (Some(url), Some(hash)) = (bins.xz_url.clone(), bins.xz_hash.clone()) + { + (component, Format::Xz, url, hash) + } else { + (component, Format::Gz, bins.url.clone(), bins.hash.clone()) + }; components_urls_and_hashes.push(c_u_h); } @@ -158,21 +174,22 @@ impl Manifestation { let mut things_to_install: Vec<(Component, Format, File)> = Vec::new(); let mut things_downloaded: Vec = Vec::new(); for (component, format, url, hash) in components_urls_and_hashes { - - notify_handler(Notification::DownloadingComponent(&component.pkg, - &self.target_triple, - component.target.as_ref())); + notify_handler(Notification::DownloadingComponent( + &component.pkg, + &self.target_triple, + component.target.as_ref(), + )); let url = if altered { url.replace(DEFAULT_DIST_SERVER, temp_cfg.dist_server.as_str()) } else { url }; - let url_url = try!(utils::parse_url(&url)); + let url_url = utils::parse_url(&url)?; - let dowloaded_file = try!(download_cfg.download(&url_url, &hash).chain_err(|| { - ErrorKind::ComponentDownloadFailed(component.clone()) - })); + let dowloaded_file = download_cfg + .download(&url_url, &hash) + .chain_err(|| ErrorKind::ComponentDownloadFailed(component.clone()))?; things_downloaded.push(hash); things_to_install.push((component, format, dowloaded_file)); @@ -183,34 +200,36 @@ impl Manifestation { // If the previous installation was from a v1 manifest we need // to uninstall it first. - tx = try!(self.maybe_handle_v2_upgrade(config, tx)); + tx = self.maybe_handle_v2_upgrade(config, tx)?; // Uninstall components for component in components_to_uninstall { + notify_handler(Notification::RemovingComponent( + &component.pkg, + &self.target_triple, + component.target.as_ref(), + )); - notify_handler(Notification::RemovingComponent(&component.pkg, - &self.target_triple, - component.target.as_ref())); - - tx = try!(self.uninstall_component(&component, tx, notify_handler.clone())); + tx = self.uninstall_component(&component, tx, notify_handler.clone())?; } // Install components for (component, format, installer_file) in things_to_install { - - notify_handler(Notification::InstallingComponent(&component.pkg, - &self.target_triple, - component.target.as_ref())); + notify_handler(Notification::InstallingComponent( + &component.pkg, + &self.target_triple, + component.target.as_ref(), + )); let gz; let xz; let package: &Package = match format { Format::Gz => { - gz = try!(TarGzPackage::new_file(&installer_file, temp_cfg)); + gz = TarGzPackage::new_file(&installer_file, temp_cfg)?; &gz } Format::Xz => { - xz = try!(TarXzPackage::new_file(&installer_file, temp_cfg)); + xz = TarXzPackage::new_file(&installer_file, temp_cfg)?; &xz } }; @@ -228,15 +247,13 @@ impl Manifestation { return Err(ErrorKind::CorruptComponent(component.pkg.clone()).into()); } - tx = try!(package.install(&self.installation, - name, Some(short_name), - tx)); + tx = package.install(&self.installation, name, Some(short_name), tx)?; } // Install new distribution manifest let ref new_manifest_str = new_manifest.clone().stringify(); - try!(tx.modify_file(rel_installed_manifest_path.to_owned())); - try!(utils::write_file("manifest", installed_manifest_path, new_manifest_str)); + tx.modify_file(rel_installed_manifest_path.to_owned())?; + utils::write_file("manifest", installed_manifest_path, new_manifest_str)?; // Write configuration. // @@ -249,13 +266,13 @@ impl Manifestation { 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); - try!(tx.modify_file(rel_config_path.to_owned())); - try!(utils::write_file("dist config", config_path, config_str)); + tx.modify_file(rel_config_path.to_owned())?; + utils::write_file("dist config", config_path, config_str)?; // End transaction tx.commit(); - try!(download_cfg.clean(&things_downloaded)); + download_cfg.clean(&things_downloaded)?; Ok(UpdateStatus::Changed) } @@ -267,30 +284,35 @@ impl Manifestation { // Read configuration and delete it let rel_config_path = prefix.rel_manifest_file(CONFIG_FILE); - let ref config_str = try!(utils::read_file("dist config", &prefix.path().join(&rel_config_path))); - let config = try!(Config::parse(config_str)); - try!(tx.remove_file("dist config", rel_config_path)); + let ref 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 { - tx = try!(self.uninstall_component(&component, tx, notify_handler)); + tx = self.uninstall_component(&component, tx, notify_handler)?; } tx.commit(); Ok(()) } - fn uninstall_component<'a>(&self, component: &Component, mut tx: Transaction<'a>, - notify_handler: &Fn(Notification)) -> Result> { + fn uninstall_component<'a>( + &self, + component: &Component, + mut tx: Transaction<'a>, + notify_handler: &Fn(Notification), + ) -> Result> { // For historical reasons, the rust-installer component // 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(); let ref short_name = format!("{}", component.pkg); - if let Some(c) = try!(self.installation.find(&name)) { - tx = try!(c.uninstall(tx)); - } else if let Some(c) = try!(self.installation.find(&short_name)) { - tx = try!(c.uninstall(tx)); + if let Some(c) = self.installation.find(&name)? { + tx = c.uninstall(tx)?; + } else if let Some(c) = self.installation.find(&short_name)? { + tx = c.uninstall(tx)?; } else { notify_handler(Notification::MissingInstalledComponent(&name)); } @@ -305,8 +327,8 @@ impl Manifestation { 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 = try!(utils::read_file("dist config", config_path)); - Ok(Some(try!(Config::parse(config_str)))) + let ref config_str = utils::read_file("dist config", config_path)?; + Ok(Some(Config::parse(config_str)?)) } else { Ok(None) } @@ -316,35 +338,47 @@ impl Manifestation { 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 = try!(utils::read_file("installed manifest", old_manifest_path)); - Ok(Some(try!(Manifest::parse(manifest_str)))) + let ref manifest_str = utils::read_file("installed manifest", old_manifest_path)?; + Ok(Some(Manifest::parse(manifest_str)?)) } else { Ok(None) } } /// Installation using the legacy v1 manifest format - pub fn update_v1(&self, - new_manifest: &[String], - update_hash: Option<&Path>, - temp_cfg: &temp::Cfg, - notify_handler: &Fn(Notification)) -> Result> { + pub fn update_v1( + &self, + new_manifest: &[String], + update_hash: Option<&Path>, + temp_cfg: &temp::Cfg, + notify_handler: &Fn(Notification), + ) -> Result> { // If there's already a v2 installation then something has gone wrong - if try!(self.read_config()).is_some() { - return Err("the server unexpectedly provided an obsolete version of the distribution manifest".into()); + if self.read_config()?.is_some() { + return Err( + "the server unexpectedly provided an obsolete version of the distribution manifest" + .into(), + ); } - let url = new_manifest.iter().find(|u| u.contains(&format!("{}{}", self.target_triple, ".tar.gz"))); + let url = new_manifest + .iter() + .find(|u| u.contains(&format!("{}{}", self.target_triple, ".tar.gz"))); if url.is_none() { - return Err(format!("binary package was not provided for '{}'", - self.target_triple.to_string()).into()); + return Err(format!( + "binary package was not provided for '{}'", + self.target_triple.to_string() + ).into()); } // Only replace once. The cost is inexpensive. - let url = url.unwrap().replace(DEFAULT_DIST_SERVER, temp_cfg.dist_server.as_str()); + let url = url.unwrap() + .replace(DEFAULT_DIST_SERVER, temp_cfg.dist_server.as_str()); - notify_handler(Notification::DownloadingComponent("rust", - &self.target_triple, - Some(&self.target_triple))); + notify_handler(Notification::DownloadingComponent( + "rust", + &self.target_triple, + Some(&self.target_triple), + )); use std::path::PathBuf; let dld_dir = PathBuf::from("bogus"); @@ -352,10 +386,10 @@ impl Manifestation { dist_root: "bogus", download_dir: &dld_dir, temp_cfg: temp_cfg, - notify_handler: notify_handler + notify_handler: notify_handler, }; - let dl = try!(dlcfg.download_and_check(&url, update_hash, ".tar.gz")); + let dl = dlcfg.download_and_check(&url, update_hash, ".tar.gz")?; if dl.is_none() { return Ok(None); }; @@ -363,25 +397,25 @@ impl Manifestation { let prefix = self.installation.prefix(); - notify_handler(Notification::InstallingComponent("rust", - &self.target_triple, - Some(&self.target_triple))); + notify_handler(Notification::InstallingComponent( + "rust", + &self.target_triple, + Some(&self.target_triple), + )); // Begin transaction let mut tx = Transaction::new(prefix.clone(), temp_cfg, notify_handler); // Uninstall components - for component in try!(self.installation.list()) { - tx = try!(component.uninstall(tx)); + for component in self.installation.list()? { + tx = component.uninstall(tx)?; } // Install all the components in the installer - let package = try!(TarGzPackage::new_file(&installer_file, temp_cfg)); + let package = TarGzPackage::new_file(&installer_file, temp_cfg)?; for component in package.components() { - tx = try!(package.install(&self.installation, - &component, None, - tx)); + tx = package.install(&self.installation, &component, None, tx)?; } // End transaction @@ -394,16 +428,20 @@ impl Manifestation { // doesn't have a configuration or manifest-derived list of // component/target pairs. Uninstall it using the intaller's // component list before upgrading. - fn maybe_handle_v2_upgrade<'a>(&self, - config: &Option, - mut tx: Transaction<'a>) -> Result> { - let installed_components = try!(self.installation.list()); + fn maybe_handle_v2_upgrade<'a>( + &self, + config: &Option, + mut tx: Transaction<'a>, + ) -> Result> { + let installed_components = self.installation.list()?; let looks_like_v1 = config.is_none() && !installed_components.is_empty(); - if !looks_like_v1 { return Ok(tx) } + if !looks_like_v1 { + return Ok(tx); + } for component in installed_components { - tx = try!(component.uninstall(tx)); + tx = component.uninstall(tx)?; } Ok(tx) @@ -419,25 +457,37 @@ fn build_update_component_lists( changes: Changes, rust_target_package: &TargetedPackage, notify_handler: &Fn(Notification), - ) -> Result<(Vec, Vec, Vec)> { - +) -> Result<(Vec, Vec, Vec)> { // Check some invariantns for component_to_add in &changes.add_extensions { - assert!(rust_target_package.extensions.contains(component_to_add), - "package must contain extension to add"); - assert!(!changes.remove_extensions.contains(component_to_add), - "can't both add and remove extensions"); + assert!( + rust_target_package.extensions.contains(component_to_add), + "package must contain extension to add" + ); + assert!( + !changes.remove_extensions.contains(component_to_add), + "can't both add and remove extensions" + ); } for component_to_remove in &changes.remove_extensions { - assert!(rust_target_package.extensions.contains(component_to_remove), - "package must contain extension to remove"); - let config = config.as_ref().expect("removing extension on fresh install?"); - assert!(config.components.contains(component_to_remove), - "removing package that isn't installed"); + assert!( + rust_target_package.extensions.contains(component_to_remove), + "package must contain extension to remove" + ); + let config = config + .as_ref() + .expect("removing extension on fresh install?"); + assert!( + config.components.contains(component_to_remove), + "removing package that isn't installed" + ); } // The list of components already installed, empty if a new install - let starting_list = config.as_ref().map(|c| c.components.clone()).unwrap_or(Vec::new()); + let starting_list = config + .as_ref() + .map(|c| c.components.clone()) + .unwrap_or(Vec::new()); // The list of components we'll have installed at the end let mut final_component_list = Vec::new(); @@ -513,5 +563,9 @@ fn build_update_component_lists( } } - Ok((components_to_uninstall, components_to_install, final_component_list)) + Ok(( + components_to_uninstall, + components_to_install, + final_component_list, + )) } diff --git a/src/rustup-dist/src/notifications.rs b/src/rustup-dist/src/notifications.rs index 4ad534dc29..53470f1449 100644 --- a/src/rustup-dist/src/notifications.rs +++ b/src/rustup-dist/src/notifications.rs @@ -2,7 +2,7 @@ use std::path::Path; use std::fmt::{self, Display}; use temp; use rustup_utils; -use rustup_utils::notify::{NotificationLevel}; +use rustup_utils::notify::NotificationLevel; use manifest::Component; use dist::TargetTriple; use errors::*; @@ -51,19 +51,24 @@ impl<'a> Notification<'a> { match *self { Temp(ref n) => n.level(), Utils(ref n) => n.level(), - ChecksumValid(_) | NoUpdateHash(_) | - FileAlreadyDownloaded | - DownloadingLegacyManifest => NotificationLevel::Verbose, - Extracting(_, _) | SignatureValid(_) | - DownloadingComponent(_, _, _) | - InstallingComponent(_, _, _) | - RemovingComponent(_, _, _) | - ComponentAlreadyInstalled(_) | - ManifestChecksumFailedHack | - RollingBack | DownloadingManifest(_) | - DownloadedManifest(_, _) => NotificationLevel::Info, - CantReadUpdateHash(_) | ExtensionNotInstalled(_) | - MissingInstalledComponent(_) | CachedFileChecksumFailed => NotificationLevel::Warn, + ChecksumValid(_) + | NoUpdateHash(_) + | FileAlreadyDownloaded + | DownloadingLegacyManifest => NotificationLevel::Verbose, + Extracting(_, _) + | SignatureValid(_) + | DownloadingComponent(_, _, _) + | InstallingComponent(_, _, _) + | RemovingComponent(_, _, _) + | ComponentAlreadyInstalled(_) + | ManifestChecksumFailedHack + | RollingBack + | DownloadingManifest(_) + | DownloadedManifest(_, _) => NotificationLevel::Info, + CantReadUpdateHash(_) + | ExtensionNotInstalled(_) + | MissingInstalledComponent(_) + | CachedFileChecksumFailed => NotificationLevel::Warn, NonFatalError(_) => NotificationLevel::Error, } } @@ -79,22 +84,22 @@ impl<'a> Display for Notification<'a> { ComponentAlreadyInstalled(ref c) => { write!(f, "component {} is up to date", c.description()) } - CantReadUpdateHash(path) => { - write!(f, - "can't read update hash file: '{}', can't skip update...", - path.display()) - } + CantReadUpdateHash(path) => write!( + f, + "can't read update hash file: '{}', can't skip update...", + path.display() + ), NoUpdateHash(path) => write!(f, "no update hash at: '{}'", path.display()), ChecksumValid(_) => write!(f, "checksum passed"), SignatureValid(_) => write!(f, "signature valid"), FileAlreadyDownloaded => write!(f, "reusing previously downloaded file"), CachedFileChecksumFailed => write!(f, "bad checksum for cached download"), RollingBack => write!(f, "rolling back changes"), - ExtensionNotInstalled(c) => { - write!(f, "extension '{}' was not installed", c.name()) - } + ExtensionNotInstalled(c) => write!(f, "extension '{}' was not installed", c.name()), NonFatalError(e) => write!(f, "{}", e), - MissingInstalledComponent(c) => write!(f, "during uninstall component {} was not found", c), + MissingInstalledComponent(c) => { + write!(f, "during uninstall component {} was not found", c) + } DownloadingComponent(c, h, t) => { if Some(h) == t || t.is_none() { write!(f, "downloading component '{}'", c) @@ -117,10 +122,16 @@ impl<'a> Display for Notification<'a> { } } DownloadingManifest(t) => write!(f, "syncing channel updates for '{}'", t), - DownloadedManifest(date, Some(version)) => write!(f, "latest update on {}, rust version {}", date, version), - DownloadedManifest(date, None) => write!(f, "latest update on {}, no rust version", date), + DownloadedManifest(date, Some(version)) => { + write!(f, "latest update on {}, rust version {}", date, version) + } + DownloadedManifest(date, None) => { + write!(f, "latest update on {}, no rust version", date) + } DownloadingLegacyManifest => write!(f, "manifest not found. trying legacy manifest"), - ManifestChecksumFailedHack => write!(f, "update not yet available, sorry! try again later"), + ManifestChecksumFailedHack => { + write!(f, "update not yet available, sorry! try again later") + } } } } diff --git a/src/rustup-dist/src/prefix.rs b/src/rustup-dist/src/prefix.rs index 8b8bd0dd6b..b6a80d4f6e 100644 --- a/src/rustup-dist/src/prefix.rs +++ b/src/rustup-dist/src/prefix.rs @@ -8,9 +8,7 @@ pub struct InstallPrefix { } impl InstallPrefix { pub fn from(path: PathBuf) -> Self { - InstallPrefix { - path: path, - } + InstallPrefix { path: path } } pub fn path(&self) -> &Path { &self.path diff --git a/src/rustup-dist/src/temp.rs b/src/rustup-dist/src/temp.rs index b69d5c7c21..f457fe0057 100644 --- a/src/rustup-dist/src/temp.rs +++ b/src/rustup-dist/src/temp.rs @@ -12,18 +12,9 @@ use rustup_utils::notify::NotificationLevel; #[derive(Debug)] pub enum Error { - CreatingRoot { - path: PathBuf, - error: io::Error, - }, - CreatingFile { - path: PathBuf, - error: io::Error, - }, - CreatingDirectory { - path: PathBuf, - error: io::Error, - }, + CreatingRoot { path: PathBuf, error: io::Error }, + CreatingFile { path: PathBuf, error: io::Error }, + CreatingDirectory { path: PathBuf, error: io::Error }, } pub type Result = ::std::result::Result; @@ -100,18 +91,18 @@ impl error::Error for Error { fn description(&self) -> &str { use self::Error::*; match *self { - CreatingRoot {..} => "could not create temp root", - CreatingFile {..} => "could not create temp file", - CreatingDirectory {..} => "could not create temp directory", + CreatingRoot { .. } => "could not create temp root", + CreatingFile { .. } => "could not create temp file", + CreatingDirectory { .. } => "could not create temp directory", } } fn cause(&self) -> Option<&error::Error> { use self::Error::*; match *self { - CreatingRoot { ref error, .. } | - CreatingFile { ref error, .. } | - CreatingDirectory { ref error, .. } => Some(error), + CreatingRoot { ref error, .. } + | CreatingFile { ref error, .. } + | CreatingDirectory { ref error, .. } => Some(error), } } } @@ -134,7 +125,11 @@ impl Display for Error { } impl Cfg { - pub fn new(root_directory: PathBuf, dist_server: &str, notify_handler: Box) -> Self { + pub fn new( + root_directory: PathBuf, + dist_server: &str, + notify_handler: Box, + ) -> Self { Cfg { root_directory: root_directory, dist_server: dist_server.to_owned(), @@ -145,17 +140,14 @@ impl Cfg { pub fn create_root(&self) -> Result { raw::ensure_dir_exists(&self.root_directory, |p| { (self.notify_handler)(Notification::CreatingRoot(p)); + }).map_err(|e| Error::CreatingRoot { + path: PathBuf::from(&self.root_directory), + error: e, }) - .map_err(|e| { - Error::CreatingRoot { - path: PathBuf::from(&self.root_directory), - error: e, - } - }) } pub fn new_directory(&self) -> Result { - try!(self.create_root()); + self.create_root()?; loop { let temp_name = raw::random_string(16) + "_dir"; @@ -166,12 +158,10 @@ impl Cfg { // random names at exactly the same time is... low. if !raw::path_exists(&temp_dir) { (self.notify_handler)(Notification::CreatingDirectory(&temp_dir)); - try!(fs::create_dir(&temp_dir).map_err(|e| { - Error::CreatingDirectory { - path: PathBuf::from(&temp_dir), - error: e, - } - })); + fs::create_dir(&temp_dir).map_err(|e| Error::CreatingDirectory { + path: PathBuf::from(&temp_dir), + error: e, + })?; return Ok(Dir { cfg: self, path: temp_dir, @@ -185,7 +175,7 @@ impl Cfg { } pub fn new_file_with_ext(&self, prefix: &str, ext: &str) -> Result { - try!(self.create_root()); + self.create_root()?; loop { let temp_name = prefix.to_owned() + &raw::random_string(16) + "_file" + ext; @@ -196,12 +186,10 @@ impl Cfg { // random names at exactly the same time is... low. if !raw::path_exists(&temp_file) { (self.notify_handler)(Notification::CreatingFile(&temp_file)); - try!(fs::File::create(&temp_file).map_err(|e| { - Error::CreatingFile { - path: PathBuf::from(&temp_file), - error: e, - } - })); + fs::File::create(&temp_file).map_err(|e| Error::CreatingFile { + path: PathBuf::from(&temp_file), + error: e, + })?; return Ok(File { cfg: self, path: temp_file, @@ -214,9 +202,9 @@ impl Cfg { impl fmt::Debug for Cfg { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Cfg") - .field("root_directory", &self.root_directory) - .field("notify_handler", &"...") - .finish() + .field("root_directory", &self.root_directory) + .field("notify_handler", &"...") + .finish() } } @@ -239,7 +227,10 @@ impl<'a> ops::Deref for File<'a> { impl<'a> Drop for Dir<'a> { fn drop(&mut self) { if raw::is_directory(&self.path) { - let n = Notification::DirectoryDeletion(&self.path, remove_dir_all::remove_dir_all(&self.path)); + let n = Notification::DirectoryDeletion( + &self.path, + remove_dir_all::remove_dir_all(&self.path), + ); (self.cfg.notify_handler)(n); } } diff --git a/src/rustup-dist/tests/dist.rs b/src/rustup-dist/tests/dist.rs index c66ad1dd52..a03e5a4e8d 100644 --- a/src/rustup-dist/tests/dist.rs +++ b/src/rustup-dist/tests/dist.rs @@ -1,30 +1,30 @@ // Tests of installation and updates from a v2 Rust distribution // server (mocked on the file system) +extern crate flate2; +extern crate itertools; extern crate rustup_dist; -extern crate rustup_utils; extern crate rustup_mock; -extern crate tempdir; +extern crate rustup_utils; extern crate tar; +extern crate tempdir; extern crate toml; -extern crate flate2; -extern crate walkdir; -extern crate itertools; extern crate url; +extern crate walkdir; use rustup_mock::dist::*; -use rustup_mock::{MockFile, MockInstallerBuilder, MockComponentBuilder}; +use rustup_mock::{MockComponentBuilder, MockFile, MockInstallerBuilder}; use rustup_dist::prefix::InstallPrefix; use rustup_dist::ErrorKind; use rustup_dist::errors::Result; -use rustup_dist::dist::{ToolchainDesc, TargetTriple, DEFAULT_DIST_SERVER}; +use rustup_dist::dist::{TargetTriple, ToolchainDesc, DEFAULT_DIST_SERVER}; use rustup_dist::download::DownloadCfg; use rustup_dist::Notification; use rustup_utils::utils; use rustup_utils::raw as utils_raw; use rustup_dist::temp; -use rustup_dist::manifestation::{Manifestation, UpdateStatus, Changes}; -use rustup_dist::manifest::{Manifest, Component}; +use rustup_dist::manifestation::{Changes, Manifestation, UpdateStatus}; +use rustup_dist::manifest::{Component, Manifest}; use url::Url; use std::cell::Cell; use std::collections::HashMap; @@ -35,19 +35,24 @@ use std::sync::Arc; use tempdir::TempDir; // Creates a mock dist server populated with some test data -pub fn create_mock_dist_server(path: &Path, - edit: Option<&Fn(&str, &mut MockPackage)>) -> MockDistServer { +pub fn create_mock_dist_server( + path: &Path, + edit: Option<&Fn(&str, &mut MockPackage)>, +) -> MockDistServer { MockDistServer { path: path.to_owned(), channels: vec![ create_mock_channel("nightly", "2016-02-01", edit), create_mock_channel("nightly", "2016-02-02", edit), - ] + ], } } -pub fn create_mock_channel(channel: &str, date: &str, - edit: Option<&Fn(&str, &mut MockPackage)>) -> MockChannel { +pub fn create_mock_channel( + channel: &str, + date: &str, + edit: Option<&Fn(&str, &mut MockPackage)>, +) -> MockChannel { // Put the date in the files so they can be differentiated let contents = Arc::new(date.as_bytes().to_vec()); @@ -73,7 +78,7 @@ pub fn create_mock_channel(channel: &str, date: &str, name: "rust-std".to_string(), target: "x86_64-apple-darwin".to_string(), }, - ], + ], extensions: vec![ MockComponent { name: "rust-std".to_string(), @@ -83,10 +88,8 @@ pub fn create_mock_channel(channel: &str, date: &str, name: "rust-std".to_string(), target: "i686-unknown-linux-gnu".to_string(), }, - ], - installer: MockInstallerBuilder { - components: vec![] - } + ], + installer: MockInstallerBuilder { components: vec![] }, }, MockTargetedPackage { target: "i686-apple-darwin".to_string(), @@ -104,13 +107,11 @@ pub fn create_mock_channel(channel: &str, date: &str, name: "rust-std".to_string(), target: "i686-apple-darwin".to_string(), }, - ], + ], extensions: vec![], - installer: MockInstallerBuilder { - components: vec![] - } - } - ] + installer: MockInstallerBuilder { components: vec![] }, + }, + ], }); for bin in &["bin/rustc", "bin/cargo"] { @@ -125,22 +126,20 @@ pub fn create_mock_channel(channel: &str, date: &str, components: vec![], extensions: vec![], installer: MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: pkg.to_string(), - files: vec![ - MockFile::new_arc(*bin, contents.clone()), - ], - }], - } + components: vec![ + MockComponentBuilder { + name: pkg.to_string(), + files: vec![MockFile::new_arc(*bin, contents.clone())], + }, + ], + }, }, MockTargetedPackage { target: "i686-apple-darwin".to_string(), available: true, components: vec![], extensions: vec![], - installer: MockInstallerBuilder { - components: vec![] - } + installer: MockInstallerBuilder { components: vec![] }, }, ], }); @@ -156,13 +155,13 @@ pub fn create_mock_channel(channel: &str, date: &str, components: vec![], extensions: vec![], installer: MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: "rust-std-x86_64-apple-darwin".to_string(), - files: vec![ - MockFile::new_arc("lib/libstd.rlib", contents.clone()), - ], - }], - } + components: vec![ + MockComponentBuilder { + name: "rust-std-x86_64-apple-darwin".to_string(), + files: vec![MockFile::new_arc("lib/libstd.rlib", contents.clone())], + }, + ], + }, }, MockTargetedPackage { target: "i686-apple-darwin".to_string(), @@ -170,13 +169,18 @@ pub fn create_mock_channel(channel: &str, date: &str, components: vec![], extensions: vec![], installer: MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: "rust-std-i686-apple-darwin".to_string(), - files: vec![ - MockFile::new_arc("lib/i686-apple-darwin/libstd.rlib", contents.clone()), - ], - }], - } + components: vec![ + MockComponentBuilder { + name: "rust-std-i686-apple-darwin".to_string(), + files: vec![ + MockFile::new_arc( + "lib/i686-apple-darwin/libstd.rlib", + contents.clone(), + ), + ], + }, + ], + }, }, MockTargetedPackage { target: "i686-unknown-linux-gnu".to_string(), @@ -184,15 +188,20 @@ pub fn create_mock_channel(channel: &str, date: &str, components: vec![], extensions: vec![], installer: MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: "rust-std-i686-unknown-linux-gnu".to_string(), - files: vec![ - MockFile::new_arc("lib/i686-unknown-linux-gnu/libstd.rlib", contents.clone()), - ], - }], - } + components: vec![ + MockComponentBuilder { + name: "rust-std-i686-unknown-linux-gnu".to_string(), + files: vec![ + MockFile::new_arc( + "lib/i686-unknown-linux-gnu/libstd.rlib", + contents.clone(), + ), + ], + }, + ], + }, }, - ] + ], }); // An extra package that can be used as a component of the other packages @@ -222,15 +231,15 @@ fn bonus_component(name: &'static str, contents: Arc>) -> MockPackage { components: vec![], extensions: vec![], installer: MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: format!("{}-x86_64-apple-darwin", name), - files: vec![ - MockFile::new_arc(&*format!("bin/{}", name), contents), - ], - }], - } + components: vec![ + MockComponentBuilder { + name: format!("{}-x86_64-apple-darwin", name), + files: vec![MockFile::new_arc(&*format!("bin/{}", name), contents)], + }, + ], + }, }, - ] + ], } } @@ -241,16 +250,36 @@ fn mock_dist_server_smoke_test() { create_mock_dist_server(&path, None).write(&[ManifestVersion::V2], false); - assert!(utils::path_exists(path.join("dist/2016-02-01/rustc-nightly-x86_64-apple-darwin.tar.gz"))); - assert!(utils::path_exists(path.join("dist/2016-02-01/rustc-nightly-i686-apple-darwin.tar.gz"))); - assert!(utils::path_exists(path.join("dist/2016-02-01/rust-std-nightly-x86_64-apple-darwin.tar.gz"))); - assert!(utils::path_exists(path.join("dist/2016-02-01/rust-std-nightly-i686-apple-darwin.tar.gz"))); - assert!(utils::path_exists(path.join("dist/2016-02-01/rustc-nightly-x86_64-apple-darwin.tar.gz.sha256"))); - assert!(utils::path_exists(path.join("dist/2016-02-01/rustc-nightly-i686-apple-darwin.tar.gz.sha256"))); - assert!(utils::path_exists(path.join("dist/2016-02-01/rust-std-nightly-x86_64-apple-darwin.tar.gz.sha256"))); - assert!(utils::path_exists(path.join("dist/2016-02-01/rust-std-nightly-i686-apple-darwin.tar.gz.sha256"))); - assert!(utils::path_exists(path.join("dist/channel-rust-nightly.toml"))); - assert!(utils::path_exists(path.join("dist/channel-rust-nightly.toml.sha256"))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rustc-nightly-x86_64-apple-darwin.tar.gz" + ))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rustc-nightly-i686-apple-darwin.tar.gz" + ))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rust-std-nightly-x86_64-apple-darwin.tar.gz" + ))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rust-std-nightly-i686-apple-darwin.tar.gz" + ))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rustc-nightly-x86_64-apple-darwin.tar.gz.sha256" + ))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rustc-nightly-i686-apple-darwin.tar.gz.sha256" + ))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rust-std-nightly-x86_64-apple-darwin.tar.gz.sha256" + ))); + assert!(utils::path_exists(path.join( + "dist/2016-02-01/rust-std-nightly-i686-apple-darwin.tar.gz.sha256" + ))); + assert!(utils::path_exists(path.join( + "dist/channel-rust-nightly.toml" + ))); + assert!(utils::path_exists(path.join( + "dist/channel-rust-nightly.toml.sha256" + ))); } // Test that a standard rename works - the component is installed with the old name, then renamed @@ -261,14 +290,20 @@ fn rename_component() { let ref url = Url::parse(&format!("file://{}", dist_tempdir.path().to_string_lossy())).unwrap(); let edit_1 = &|_: &str, pkg: &mut MockPackage| { - let tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.components.push(MockComponent { name: "bonus".to_string(), target: "x86_64-apple-darwin".to_string(), }); }; let edit_2 = &|_: &str, pkg: &mut MockPackage| { - let tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.components.push(MockComponent { name: "bobo".to_string(), target: "x86_64-apple-darwin".to_string(), @@ -278,26 +313,32 @@ fn rename_component() { let date_2 = "2016-02-02"; let mut channel_2 = create_mock_channel("nightly", date_2, Some(edit_2)); channel_2.packages[4] = bonus_component("bobo", Arc::new(date_2.as_bytes().to_vec())); - channel_2.renames.insert("bonus".to_owned(), "bobo".to_owned()); + channel_2 + .renames + .insert("bonus".to_owned(), "bobo".to_owned()); let mock_dist_server = MockDistServer { path: dist_tempdir.path().to_owned(), channels: vec![ create_mock_channel("nightly", "2016-02-01", Some(edit_1)), channel_2, - ] + ], }; - setup_from_dist_server(mock_dist_server, url, false, - &|url, toolchain, prefix, download_cfg, temp_cfg| { - change_channel_date(url, "nightly", "2016-02-01"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); - assert!(!utils::path_exists(&prefix.path().join("bin/bobo"))); - change_channel_date(url, "nightly", "2016-02-02"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); - assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); - }); + setup_from_dist_server( + mock_dist_server, + url, + false, + &|url, toolchain, prefix, download_cfg, temp_cfg| { + change_channel_date(url, "nightly", "2016-02-01"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); + assert!(!utils::path_exists(&prefix.path().join("bin/bobo"))); + change_channel_date(url, "nightly", "2016-02-02"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); + assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); + }, + ); } // Test that a rename is ignored if the component with the new name is already installed. @@ -307,7 +348,10 @@ fn rename_component_ignore() { let ref url = Url::parse(&format!("file://{}", dist_tempdir.path().to_string_lossy())).unwrap(); let edit = &|_: &str, pkg: &mut MockPackage| { - let tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.components.push(MockComponent { name: "bobo".to_string(), target: "x86_64-apple-darwin".to_string(), @@ -320,26 +364,29 @@ fn rename_component_ignore() { let date_2 = "2016-02-02"; let mut channel_2 = create_mock_channel("nightly", date_2, Some(edit)); channel_2.packages[4] = bonus_component("bobo", Arc::new(date_2.as_bytes().to_vec())); - channel_2.renames.insert("bonus".to_owned(), "bobo".to_owned()); + channel_2 + .renames + .insert("bonus".to_owned(), "bobo".to_owned()); let mock_dist_server = MockDistServer { path: dist_tempdir.path().to_owned(), - channels: vec![ - channel_1, - channel_2, - ] + channels: vec![channel_1, channel_2], }; - setup_from_dist_server(mock_dist_server, url, false, - &|url, toolchain, prefix, download_cfg, temp_cfg| { - change_channel_date(url, "nightly", "2016-02-01"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); - assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); - change_channel_date(url, "nightly", "2016-02-02"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); - assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); - }); + setup_from_dist_server( + mock_dist_server, + url, + false, + &|url, toolchain, prefix, download_cfg, temp_cfg| { + change_channel_date(url, "nightly", "2016-02-01"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); + assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); + change_channel_date(url, "nightly", "2016-02-02"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); + assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); + }, + ); } // Test that a rename is ignored if the component with the old name was never installed. @@ -349,7 +396,10 @@ fn rename_component_new() { let ref url = Url::parse(&format!("file://{}", dist_tempdir.path().to_string_lossy())).unwrap(); let edit_2 = &|_: &str, pkg: &mut MockPackage| { - let tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.components.push(MockComponent { name: "bobo".to_string(), target: "x86_64-apple-darwin".to_string(), @@ -359,94 +409,121 @@ fn rename_component_new() { let date_2 = "2016-02-02"; let mut channel_2 = create_mock_channel("nightly", date_2, Some(edit_2)); channel_2.packages[4] = bonus_component("bobo", Arc::new(date_2.as_bytes().to_vec())); - channel_2.renames.insert("bonus".to_owned(), "bobo".to_owned()); + channel_2 + .renames + .insert("bonus".to_owned(), "bobo".to_owned()); let mock_dist_server = MockDistServer { path: dist_tempdir.path().to_owned(), channels: vec![ create_mock_channel("nightly", "2016-02-01", None), channel_2, - ] + ], }; - setup_from_dist_server(mock_dist_server, url, false, - &|url, toolchain, prefix, download_cfg, temp_cfg| { - change_channel_date(url, "nightly", "2016-02-01"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); - assert!(!utils::path_exists(&prefix.path().join("bin/bobo"))); - change_channel_date(url, "nightly", "2016-02-02"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); - assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); - }); + setup_from_dist_server( + mock_dist_server, + url, + false, + &|url, toolchain, prefix, download_cfg, temp_cfg| { + change_channel_date(url, "nightly", "2016-02-01"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); + assert!(!utils::path_exists(&prefix.path().join("bin/bobo"))); + change_channel_date(url, "nightly", "2016-02-02"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); + assert!(utils::path_exists(&prefix.path().join("bin/bobo"))); + }, + ); } // Installs or updates a toolchain from a dist server. If an initial // install then it will be installed with the default components. If // an upgrade then all the existing components will be upgraded. // FIXME: Unify this with dist::update_from_dist -fn update_from_dist(dist_server: &Url, - toolchain: &ToolchainDesc, - prefix: &InstallPrefix, - add: &[Component], - remove: &[Component], - download_cfg: &DownloadCfg, - temp_cfg: &temp::Cfg) -> Result { - +fn update_from_dist( + dist_server: &Url, + toolchain: &ToolchainDesc, + prefix: &InstallPrefix, + add: &[Component], + remove: &[Component], + download_cfg: &DownloadCfg, + temp_cfg: &temp::Cfg, +) -> Result { // Download the dist manifest and place it into the installation prefix - let ref manifest_url = try!(make_manifest_url(dist_server, toolchain)); - let manifest_file = try!(temp_cfg.new_file()); - try!(utils::download_file(manifest_url, &manifest_file, None, &|_| {})); - let manifest_str = try!(utils::read_file("manifest", &manifest_file)); - let manifest = try!(Manifest::parse(&manifest_str)); + let ref manifest_url = make_manifest_url(dist_server, toolchain)?; + let manifest_file = temp_cfg.new_file()?; + utils::download_file(manifest_url, &manifest_file, None, &|_| {})?; + let manifest_str = utils::read_file("manifest", &manifest_file)?; + let manifest = Manifest::parse(&manifest_str)?; // Read the manifest to update the components let trip = toolchain.target.clone(); - let manifestation = try!(Manifestation::open(prefix.clone(), trip)); + let manifestation = Manifestation::open(prefix.clone(), trip)?; let changes = Changes { add_extensions: add.to_owned(), remove_extensions: remove.to_owned(), }; - manifestation.update(&manifest, changes, download_cfg, download_cfg.notify_handler.clone()) + manifestation.update( + &manifest, + changes, + download_cfg, + download_cfg.notify_handler.clone(), + ) } fn make_manifest_url(dist_server: &Url, toolchain: &ToolchainDesc) -> Result { - let url = format!("{}/dist/channel-rust-{}.toml", dist_server, toolchain.channel); + let url = format!( + "{}/dist/channel-rust-{}.toml", + dist_server, toolchain.channel + ); Ok(Url::parse(&url).unwrap()) } -fn uninstall(toolchain: &ToolchainDesc, prefix: &InstallPrefix, temp_cfg: &temp::Cfg, - notify_handler: &Fn(Notification)) -> Result<()> { +fn uninstall( + toolchain: &ToolchainDesc, + prefix: &InstallPrefix, + temp_cfg: &temp::Cfg, + notify_handler: &Fn(Notification), +) -> Result<()> { let trip = toolchain.target.clone(); - let manifestation = try!(Manifestation::open(prefix.clone(), trip)); + let manifestation = Manifestation::open(prefix.clone(), trip)?; - try!(manifestation.uninstall(temp_cfg, notify_handler.clone())); + manifestation.uninstall(temp_cfg, notify_handler.clone())?; Ok(()) } -fn setup(edit: Option<&Fn(&str, &mut MockPackage)>, enable_xz: bool, - f: &Fn(&Url, &ToolchainDesc, &InstallPrefix, &DownloadCfg, &temp::Cfg)) { +fn setup( + edit: Option<&Fn(&str, &mut MockPackage)>, + enable_xz: bool, + f: &Fn(&Url, &ToolchainDesc, &InstallPrefix, &DownloadCfg, &temp::Cfg), +) { let dist_tempdir = TempDir::new("rustup").unwrap(); let mock_dist_server = create_mock_dist_server(dist_tempdir.path(), edit); let ref url = Url::parse(&format!("file://{}", dist_tempdir.path().to_string_lossy())).unwrap(); setup_from_dist_server(mock_dist_server, url, enable_xz, f); } - -fn setup_from_dist_server(server: MockDistServer, url: &Url, enable_xz: bool, - f: &Fn(&Url, &ToolchainDesc, &InstallPrefix, &DownloadCfg, &temp::Cfg)) { +fn setup_from_dist_server( + server: MockDistServer, + url: &Url, + enable_xz: bool, + f: &Fn(&Url, &ToolchainDesc, &InstallPrefix, &DownloadCfg, &temp::Cfg), +) { server.write(&[ManifestVersion::V2], enable_xz); let prefix_tempdir = TempDir::new("rustup").unwrap(); let work_tempdir = TempDir::new("rustup").unwrap(); - let ref temp_cfg = temp::Cfg::new(work_tempdir.path().to_owned(), - DEFAULT_DIST_SERVER, - Box::new(|_| ())); + let ref temp_cfg = temp::Cfg::new( + work_tempdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let ref toolchain = ToolchainDesc::from_str("nightly-x86_64-apple-darwin").unwrap(); let ref prefix = InstallPrefix::from(prefix_tempdir.path().to_owned()); @@ -454,7 +531,7 @@ fn setup_from_dist_server(server: MockDistServer, url: &Url, enable_xz: bool, dist_root: "phony", temp_cfg: temp_cfg, download_dir: &prefix.path().to_owned().join("downloads"), - notify_handler: &|_|{} + notify_handler: &|_| {}, }; f(url, toolchain, prefix, download_cfg, temp_cfg); @@ -462,7 +539,11 @@ fn setup_from_dist_server(server: MockDistServer, url: &Url, enable_xz: bool, #[test] fn initial_install() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); assert!(utils::path_exists(&prefix.path().join("bin/rustc"))); @@ -472,7 +553,11 @@ fn initial_install() { #[test] fn initial_install_xz() { - setup(None, true, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, true, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); assert!(utils::path_exists(&prefix.path().join("bin/rustc"))); @@ -482,7 +567,11 @@ fn initial_install_xz() { #[test] fn test_uninstall() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); uninstall(toolchain, prefix, temp_cfg, &|_| ()).unwrap(); @@ -493,23 +582,39 @@ fn test_uninstall() { #[test] fn uninstall_removes_config_file() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.manifest_file("multirust-config.toml"))); + assert!(utils::path_exists(&prefix + .manifest_file("multirust-config.toml"))); uninstall(toolchain, prefix, temp_cfg, &|_| ()).unwrap(); - assert!(!utils::path_exists(&prefix.manifest_file("multirust-config.toml"))); + assert!(!utils::path_exists(&prefix + .manifest_file("multirust-config.toml"))); }); } #[test] fn upgrade() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { change_channel_date(url, "nightly", "2016-02-01"); update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert_eq!("2016-02-01", utils_raw::read_file(&prefix.path().join("bin/rustc")).unwrap()); + assert_eq!( + "2016-02-01", + utils_raw::read_file(&prefix.path().join("bin/rustc")).unwrap() + ); change_channel_date(url, "nightly", "2016-02-02"); update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert_eq!("2016-02-02", utils_raw::read_file(&prefix.path().join("bin/rustc")).unwrap()); + assert_eq!( + "2016-02-02", + utils_raw::read_file(&prefix.path().join("bin/rustc")).unwrap() + ); }); } @@ -518,46 +623,67 @@ fn update_removes_components_that_dont_exist() { // On day 1 install the 'bonus' component, on day 2 its no londer a component let edit = &|date: &str, pkg: &mut MockPackage| { if date == "2016-02-01" { - let mut tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let mut tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.components.push(MockComponent { name: "bonus".to_string(), target: "x86_64-apple-darwin".to_string(), }); } }; - setup(Some(edit), false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - change_channel_date(url, "nightly", "2016-02-01"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); - change_channel_date(url, "nightly", "2016-02-02"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); - }); + setup( + Some(edit), + false, + &|url, toolchain, prefix, download_cfg, temp_cfg| { + change_channel_date(url, "nightly", "2016-02-01"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); + change_channel_date(url, "nightly", "2016-02-02"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(!utils::path_exists(&prefix.path().join("bin/bonus"))); + }, + ); } #[test] fn update_preserves_extensions() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) - } - ]; + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), + }, + ]; change_channel_date(url, "nightly", "2016-02-01"); update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); change_channel_date(url, "nightly", "2016-02-02"); update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } @@ -565,118 +691,169 @@ fn update_preserves_extensions() { fn update_preserves_extensions_that_became_components() { let edit = &|date: &str, pkg: &mut MockPackage| { if date == "2016-02-01" { - let mut tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let mut tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.extensions.push(MockComponent { name: "bonus".to_string(), target: "x86_64-apple-darwin".to_string(), }); } if date == "2016-02-02" { - let mut tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let mut tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.components.push(MockComponent { name: "bonus".to_string(), target: "x86_64-apple-darwin".to_string(), }); } }; - setup(Some(edit), false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - let ref adds = vec![ - Component { - pkg: "bonus".to_string(), target: Some(TargetTriple::from_str("x86_64-apple-darwin")) - }, + setup( + Some(edit), + false, + &|url, toolchain, prefix, download_cfg, temp_cfg| { + let ref adds = vec![ + Component { + pkg: "bonus".to_string(), + target: Some(TargetTriple::from_str("x86_64-apple-darwin")), + }, ]; - change_channel_date(url, "nightly", "2016-02-01"); - update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); + change_channel_date(url, "nightly", "2016-02-01"); + update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); + assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); - change_channel_date(url, "nightly", "2016-02-02"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); - }); + change_channel_date(url, "nightly", "2016-02-02"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); + }, + ); } #[test] fn update_preserves_components_that_became_extensions() { let edit = &|date: &str, pkg: &mut MockPackage| { if date == "2016-02-01" { - let mut tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let mut tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.components.push(MockComponent { name: "bonus".to_string(), target: "x86_64-apple-darwin".to_string(), }); } if date == "2016-02-02" { - let mut tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let mut tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.extensions.push(MockComponent { name: "bonus".to_string(), target: "x86_64-apple-darwin".to_string(), }); } }; - setup(Some(edit), false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - change_channel_date(url, "nightly", "2016-02-01"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); - change_channel_date(url, "nightly", "2016-02-02"); - update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); - }); + setup( + Some(edit), + false, + &|url, toolchain, prefix, download_cfg, temp_cfg| { + change_channel_date(url, "nightly", "2016-02-01"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); + change_channel_date(url, "nightly", "2016-02-02"); + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); + }, + ); } #[test] fn update_makes_no_changes_for_identical_manifest() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - let status = update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { + let status = + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); assert_eq!(status, UpdateStatus::Changed); - let status = update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); + let status = + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); assert_eq!(status, UpdateStatus::Unchanged); }); } #[test] fn add_extensions_for_initial_install() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) - } + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), + }, ]; update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } #[test] fn add_extensions_for_same_manifest() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) - } + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), + }, ]; update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } #[test] fn add_extensions_for_upgrade() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { change_channel_date(url, "nightly", "2016-02-01"); update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); @@ -685,27 +862,38 @@ fn add_extensions_for_upgrade() { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) - } + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), + }, ]; update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } #[test] #[should_panic] fn add_extension_not_in_manifest() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref adds = vec![ Component { - pkg: "rust-bogus".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-bogus".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; @@ -716,10 +904,15 @@ fn add_extension_not_in_manifest() { #[test] #[should_panic] fn add_extension_that_is_required_component() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref adds = vec![ Component { - pkg: "rustc".to_string(), target: Some(TargetTriple::from_str("x86_64-apple-darwin")) + pkg: "rustc".to_string(), + target: Some(TargetTriple::from_str("x86_64-apple-darwin")), }, ]; @@ -729,22 +922,25 @@ fn add_extension_that_is_required_component() { #[test] #[ignore] -fn add_extensions_for_same_manifest_does_not_reinstall_other_components() { -} +fn add_extensions_for_same_manifest_does_not_reinstall_other_components() {} #[test] #[ignore] -fn add_extensions_for_same_manifest_when_extension_already_installed() { -} +fn add_extensions_for_same_manifest_when_extension_already_installed() {} #[test] fn add_extensions_does_not_remove_other_components() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; @@ -758,10 +954,15 @@ fn add_extensions_does_not_remove_other_components() { #[test] #[should_panic] fn remove_extensions_for_initial_install() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref removes = vec![ Component { - pkg: "rustc".to_string(), target: Some(TargetTriple::from_str("x86_64-apple-darwin")) + pkg: "rustc".to_string(), + target: Some(TargetTriple::from_str("x86_64-apple-darwin")), }, ]; @@ -771,43 +972,60 @@ fn remove_extensions_for_initial_install() { #[test] fn remove_extensions_for_same_manifest() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) - } + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), + }, ]; update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); let ref removes = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, - ]; + ]; update_from_dist(url, toolchain, prefix, &[], removes, download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + assert!(!utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } #[test] fn remove_extensions_for_upgrade() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { change_channel_date(url, "nightly", "2016-02-01"); let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) - } + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), + }, ]; update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); @@ -816,21 +1034,30 @@ fn remove_extensions_for_upgrade() { let ref removes = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; update_from_dist(url, toolchain, prefix, &[], removes, download_cfg, temp_cfg).unwrap(); - assert!(!utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + assert!(!utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } #[test] #[should_panic] fn remove_extension_not_in_manifest() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { change_channel_date(url, "nightly", "2016-02-01"); update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); @@ -839,7 +1066,8 @@ fn remove_extension_not_in_manifest() { let ref removes = vec![ Component { - pkg: "rust-bogus".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-bogus".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; @@ -855,44 +1083,58 @@ fn remove_extension_not_in_manifest() { fn remove_extension_not_in_manifest_but_is_already_installed() { let edit = &|date: &str, pkg: &mut MockPackage| { if date == "2016-02-01" { - let mut tpkg = pkg.targets.iter_mut().find(|p| p.target == "x86_64-apple-darwin").unwrap(); + let mut tpkg = pkg.targets + .iter_mut() + .find(|p| p.target == "x86_64-apple-darwin") + .unwrap(); tpkg.extensions.push(MockComponent { name: "bonus".to_string(), target: "x86_64-apple-darwin".to_string(), }); } }; - setup(Some(edit), false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - change_channel_date(url, "nightly", "2016-02-01"); - - let ref adds = vec![ - Component { - pkg: "bonus".to_string(), target: Some(TargetTriple::from_str("x86_64-apple-darwin")) - }, - ]; - update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); - assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); + setup( + Some(edit), + false, + &|url, toolchain, prefix, download_cfg, temp_cfg| { + change_channel_date(url, "nightly", "2016-02-01"); + + let ref adds = vec![ + Component { + pkg: "bonus".to_string(), + target: Some(TargetTriple::from_str("x86_64-apple-darwin")), + }, + ]; + update_from_dist(url, toolchain, prefix, adds, &[], download_cfg, temp_cfg).unwrap(); + assert!(utils::path_exists(&prefix.path().join("bin/bonus"))); - change_channel_date(url, "nightly", "2016-02-02"); + change_channel_date(url, "nightly", "2016-02-02"); - let ref removes = vec![ - Component { - pkg: "bonus".to_string(), target: Some(TargetTriple::from_str("x86_64-apple-darwin")) - }, - ]; - update_from_dist(url, toolchain, prefix, &[], removes, download_cfg, temp_cfg).unwrap(); - }); + let ref removes = vec![ + Component { + pkg: "bonus".to_string(), + target: Some(TargetTriple::from_str("x86_64-apple-darwin")), + }, + ]; + update_from_dist(url, toolchain, prefix, &[], removes, download_cfg, temp_cfg).unwrap(); + }, + ); } #[test] #[should_panic] fn remove_extension_that_is_required_component() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); let ref removes = vec![ Component { - pkg: "rustc".to_string(), target: Some(TargetTriple::from_str("x86_64-apple-darwin")) + pkg: "rustc".to_string(), + target: Some(TargetTriple::from_str("x86_64-apple-darwin")), }, ]; @@ -903,12 +1145,17 @@ fn remove_extension_that_is_required_component() { #[test] #[should_panic] fn remove_extension_not_installed() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); let ref removes = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; @@ -918,15 +1165,19 @@ fn remove_extension_not_installed() { #[test] #[ignore] -fn remove_extensions_for_same_manifest_does_not_reinstall_other_components() { -} +fn remove_extensions_for_same_manifest_does_not_reinstall_other_components() {} #[test] fn remove_extensions_does_not_remove_other_components() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; @@ -934,7 +1185,8 @@ fn remove_extensions_does_not_remove_other_components() { let ref removes = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; @@ -946,12 +1198,17 @@ fn remove_extensions_does_not_remove_other_components() { #[test] fn add_and_remove_for_upgrade() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { change_channel_date(url, "nightly", "2016-02-01"); let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), }, ]; @@ -961,29 +1218,48 @@ fn add_and_remove_for_upgrade() { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; let ref removes = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), }, ]; - update_from_dist(url, toolchain, prefix, adds, removes, download_cfg, temp_cfg).unwrap(); - - assert!(utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(!utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + update_from_dist( + url, + toolchain, + prefix, + adds, + removes, + download_cfg, + temp_cfg, + ).unwrap(); + + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(!utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } #[test] fn add_and_remove() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), }, ]; @@ -991,79 +1267,117 @@ fn add_and_remove() { let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; let ref removes = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-unknown-linux-gnu")), }, ]; - update_from_dist(url, toolchain, prefix, adds, removes, download_cfg, temp_cfg).unwrap(); - - assert!(utils::path_exists(&prefix.path().join("lib/i686-apple-darwin/libstd.rlib"))); - assert!(!utils::path_exists(&prefix.path().join("lib/i686-unknown-linux-gnu/libstd.rlib"))); + update_from_dist( + url, + toolchain, + prefix, + adds, + removes, + download_cfg, + temp_cfg, + ).unwrap(); + + assert!(utils::path_exists(&prefix + .path() + .join("lib/i686-apple-darwin/libstd.rlib"))); + assert!(!utils::path_exists(&prefix + .path() + .join("lib/i686-unknown-linux-gnu/libstd.rlib"))); }); } #[test] #[should_panic] fn add_and_remove_same_component() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap(); let ref adds = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple-darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple-darwin")), }, ]; let ref removes = vec![ Component { - pkg: "rust-std".to_string(), target: Some(TargetTriple::from_str("i686-apple_darwin")) + pkg: "rust-std".to_string(), + target: Some(TargetTriple::from_str("i686-apple_darwin")), }, ]; - update_from_dist(url, toolchain, prefix, adds, removes, download_cfg, temp_cfg).unwrap(); + update_from_dist( + url, + toolchain, + prefix, + adds, + removes, + download_cfg, + temp_cfg, + ).unwrap(); }); } #[test] fn bad_component_hash() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let path = url.to_file_path().unwrap(); let path = path.join("dist/2016-02-02/rustc-nightly-x86_64-apple-darwin.tar.gz"); utils_raw::write_file(&path, "bogus").unwrap(); - let err = update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap_err(); + let err = + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap_err(); match *err.kind() { ErrorKind::ComponentDownloadFailed(_) => (), - _ => panic!() + _ => panic!(), } }); } #[test] fn unable_to_download_component() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let path = url.to_file_path().unwrap(); let path = path.join("dist/2016-02-02/rustc-nightly-x86_64-apple-darwin.tar.gz"); fs::remove_file(&path).unwrap(); - let err = update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap_err(); + let err = + update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap_err(); match *err.kind() { ErrorKind::ComponentDownloadFailed(..) => (), - _ => panic!() + _ => panic!(), } }); } fn prevent_installation(prefix: &InstallPrefix) { - utils::ensure_dir_exists("installation path", &prefix.path().join("lib"), &|_|{}).unwrap(); + utils::ensure_dir_exists("installation path", &prefix.path().join("lib"), &|_| {}).unwrap(); let install_blocker = prefix.path().join("lib").join("rustlib"); utils::write_file("install-blocker", &install_blocker, "fail-installation").unwrap(); } @@ -1075,8 +1389,11 @@ fn allow_installation(prefix: &InstallPrefix) { #[test] fn reuse_downloaded_file() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { prevent_installation(prefix); let reuse_notification_fired = Arc::new(Cell::new(false)); @@ -1089,7 +1406,7 @@ fn reuse_downloaded_file() { if let Notification::FileAlreadyDownloaded = n { reuse_notification_fired.set(true); } - } + }, }; update_from_dist(url, toolchain, prefix, &[], &[], &download_cfg, temp_cfg).unwrap_err(); @@ -1105,12 +1422,19 @@ fn reuse_downloaded_file() { #[test] fn checks_files_hashes_before_reuse() { - setup(None, false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - + setup(None, false, &|url, + toolchain, + prefix, + download_cfg, + temp_cfg| { let path = url.to_file_path().unwrap(); - let target_hash = utils::read_file("target hash", &path.join("dist/2016-02-02/rustc-nightly-x86_64-apple-darwin.tar.gz.sha256")).unwrap()[.. 64].to_owned(); + let target_hash = utils::read_file( + "target hash", + &path.join("dist/2016-02-02/rustc-nightly-x86_64-apple-darwin.tar.gz.sha256"), + ).unwrap()[..64] + .to_owned(); let prev_download = download_cfg.download_dir.join(target_hash); - utils::ensure_dir_exists("download dir", &download_cfg.download_dir, &|_|{}).unwrap(); + utils::ensure_dir_exists("download dir", &download_cfg.download_dir, &|_| {}).unwrap(); utils::write_file("bad previous download", &prev_download, "bad content").unwrap(); println!("wrote previous download to {}", prev_download.display()); @@ -1123,7 +1447,7 @@ fn checks_files_hashes_before_reuse() { if let Notification::CachedFileChecksumFailed = n { noticed_bad_checksum.set(true); } - } + }, }; update_from_dist(url, toolchain, prefix, &[], &[], &download_cfg, temp_cfg).unwrap(); diff --git a/src/rustup-dist/tests/install.rs b/src/rustup-dist/tests/install.rs index 04571b511f..306a863633 100644 --- a/src/rustup-dist/tests/install.rs +++ b/src/rustup-dist/tests/install.rs @@ -1,6 +1,6 @@ extern crate rustup_dist; -extern crate rustup_utils; extern crate rustup_mock; +extern crate rustup_utils; extern crate tempdir; use rustup_dist::component::Components; @@ -15,7 +15,7 @@ use rustup_dist::prefix::InstallPrefix; use std::fs::File; use std::io::Write; use tempdir::TempDir; -use rustup_mock::{MockInstallerBuilder, MockComponentBuilder, MockFile}; +use rustup_mock::{MockComponentBuilder, MockFile, MockInstallerBuilder}; // Just testing that the mocks work #[test] @@ -29,17 +29,12 @@ fn mock_smoke_test() { files: vec![ MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), - MockFile::new_dir("doc/stuff", &[ - ("doc1", b"", false), - ("doc2", b"", false), - ]), + MockFile::new_dir("doc/stuff", &[("doc1", b"", false), ("doc2", b"", false)]), ], }, MockComponentBuilder { name: "mycomponent2".to_string(), - files: vec![ - MockFile::new("bin/quux", b"quux"), - ], + files: vec![MockFile::new("bin/quux", b"quux")], }, ], }; @@ -112,10 +107,7 @@ fn basic_install() { files: vec![ MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), - MockFile::new_dir("doc/stuff", &[ - ("doc1", b"", false), - ("doc2", b"", false), - ]), + MockFile::new_dir("doc/stuff", &[("doc1", b"", false), ("doc2", b"", false)]), ], }, ], @@ -127,7 +119,11 @@ fn basic_install() { let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + tmpdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); @@ -169,7 +165,11 @@ fn multiple_component_install() { let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + tmpdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); @@ -199,10 +199,7 @@ fn uninstall() { files: vec![ MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), - MockFile::new_dir("doc/stuff", &[ - ("doc1", b"", false), - ("doc2", b"", false), - ]), + MockFile::new_dir("doc/stuff", &[("doc1", b"", false), ("doc2", b"", false)]), ], }, MockComponentBuilder { @@ -218,7 +215,11 @@ fn uninstall() { let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + tmpdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); @@ -273,7 +274,11 @@ fn component_bad_version() { let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + tmpdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); @@ -289,7 +294,10 @@ fn component_bad_version() { // Can't open components now let e = Components::open(prefix.clone()).unwrap_err(); - if let ErrorKind::BadInstalledMetadataVersion(_) = *e.kind() { } else { panic!() } + if let ErrorKind::BadInstalledMetadataVersion(_) = *e.kind() { + } else { + panic!() + } } // Directories should be 0755, normal files 0644, files that come @@ -310,11 +318,14 @@ fn unix_permissions() { MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), MockFile::new("lib/foobar", b"foobar").executable(true), - MockFile::new_dir("doc/stuff", &[ - ("doc1", b"", false), - ("morestuff/doc2", b"", false), - ("morestuff/tool", b"", true), - ]), + MockFile::new_dir( + "doc/stuff", + &[ + ("doc1", b"", false), + ("morestuff/doc2", b"", false), + ("morestuff/tool", b"", true), + ], + ), ], }, ], @@ -326,7 +337,11 @@ fn unix_permissions() { let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + tmpdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); @@ -337,21 +352,53 @@ fn unix_permissions() { let tx = pkg.install(&components, "mycomponent", None, tx).unwrap(); tx.commit(); - let m = 0o777 & fs::metadata(instdir.path().join("bin/foo")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("bin/foo")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o755); - let m = 0o777 & fs::metadata(instdir.path().join("lib/bar")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("lib/bar")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o644); - let m = 0o777 & fs::metadata(instdir.path().join("lib/foobar")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("lib/foobar")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o755); - let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("doc/stuff/")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o755); - let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/doc1")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("doc/stuff/doc1")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o644); - let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/morestuff")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("doc/stuff/morestuff")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o755); - let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/morestuff/doc2")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("doc/stuff/morestuff/doc2")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o644); - let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/morestuff/tool")).unwrap().permissions().mode(); + let m = 0o777 + & fs::metadata(instdir.path().join("doc/stuff/morestuff/tool")) + .unwrap() + .permissions() + .mode(); assert_eq!(m, 0o755); } @@ -377,7 +424,11 @@ fn install_to_prefix_that_does_not_exist() { let prefix = InstallPrefix::from(does_not_exist.clone()); let tmpdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + tmpdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); diff --git a/src/rustup-dist/tests/manifest.rs b/src/rustup-dist/tests/manifest.rs index 0c2e4e469e..1a91630398 100644 --- a/src/rustup-dist/tests/manifest.rs +++ b/src/rustup-dist/tests/manifest.rs @@ -25,7 +25,9 @@ fn parse_smoke_test() { let rust_pkg = pkg.get_package("rust").unwrap(); assert!(rust_pkg.version.contains("1.3.0")); - let rust_target_pkg = rust_pkg.get_target(Some(&x86_64_unknown_linux_gnu)).unwrap(); + let rust_target_pkg = rust_pkg + .get_target(Some(&x86_64_unknown_linux_gnu)) + .unwrap(); assert_eq!(rust_target_pkg.available(), true); assert_eq!(rust_target_pkg.bins.clone().unwrap().url, "example.com"); assert_eq!(rust_target_pkg.bins.clone().unwrap().hash, "..."); @@ -39,7 +41,9 @@ fn parse_smoke_test() { assert_eq!(component.target.as_ref(), Some(&x86_64_unknown_linux_musl)); let docs_pkg = pkg.get_package("rust-docs").unwrap(); - let docs_target_pkg = docs_pkg.get_target(Some(&x86_64_unknown_linux_gnu)).unwrap(); + let docs_target_pkg = docs_pkg + .get_target(Some(&x86_64_unknown_linux_gnu)) + .unwrap(); assert_eq!(docs_target_pkg.bins.clone().unwrap().url, "example.com"); } @@ -84,7 +88,7 @@ date = "2015-10-10" let err = Manifest::parse(manifest).unwrap_err(); match *err.kind() { - ErrorKind::MissingPackageForComponent(_) => {}, + ErrorKind::MissingPackageForComponent(_) => {} _ => panic!(), } } diff --git a/src/rustup-dist/tests/transactions.rs b/src/rustup-dist/tests/transactions.rs index 4fca7990e5..a055755f26 100644 --- a/src/rustup-dist/tests/transactions.rs +++ b/src/rustup-dist/tests/transactions.rs @@ -22,7 +22,11 @@ fn add_file() { let prefix = InstallPrefix::from(prefixdir.path().to_owned()); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let mut tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); @@ -33,8 +37,10 @@ fn add_file() { tx.commit(); drop(file); - assert_eq!(utils_raw::read_file(&prefix.path().join("foo/bar")).unwrap(), - "test"); + assert_eq!( + utils_raw::read_file(&prefix.path().join("foo/bar")).unwrap(), + "test" + ); } #[test] @@ -44,7 +50,11 @@ fn add_file_then_rollback() { let prefix = InstallPrefix::from(prefixdir.path().to_owned()); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let notify = |_: Notification| (); let mut tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); @@ -60,7 +70,11 @@ fn add_file_that_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -77,7 +91,7 @@ fn add_file_that_exists() { assert_eq!(name, "c"); assert_eq!(path, PathBuf::from("foo/bar")); } - _ => panic!() + _ => panic!(), } } @@ -87,7 +101,11 @@ fn copy_file() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -97,7 +115,8 @@ fn copy_file() { let srcpath = srcdir.path().join("bar"); utils::write_file("", &srcpath, "").unwrap(); - tx.copy_file("c", PathBuf::from("foo/bar"), &srcpath).unwrap(); + tx.copy_file("c", PathBuf::from("foo/bar"), &srcpath) + .unwrap(); tx.commit(); assert!(utils::is_file(prefix.path().join("foo/bar"))); @@ -109,7 +128,11 @@ fn copy_file_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -119,7 +142,8 @@ fn copy_file_then_rollback() { let srcpath = srcdir.path().join("bar"); utils::write_file("", &srcpath, "").unwrap(); - tx.copy_file("c", PathBuf::from("foo/bar"), &srcpath).unwrap(); + tx.copy_file("c", PathBuf::from("foo/bar"), &srcpath) + .unwrap(); drop(tx); assert!(!utils::is_file(prefix.path().join("foo/bar"))); @@ -131,7 +155,11 @@ fn copy_file_that_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -144,14 +172,15 @@ fn copy_file_that_exists() { fs::create_dir_all(&prefixdir.path().join("foo")).unwrap(); utils::write_file("", &prefixdir.path().join("foo/bar"), "").unwrap(); - let err = tx.copy_file("c", PathBuf::from("foo/bar"), &srcpath).unwrap_err(); + let err = tx.copy_file("c", PathBuf::from("foo/bar"), &srcpath) + .unwrap_err(); match err.0 { ErrorKind::ComponentConflict { name, path } => { assert_eq!(name, "c"); assert_eq!(path, PathBuf::from("foo/bar")); } - _ => panic!() + _ => panic!(), } } @@ -161,7 +190,11 @@ fn copy_dir() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -191,7 +224,11 @@ fn copy_dir_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -221,7 +258,11 @@ fn copy_dir_that_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -230,14 +271,15 @@ fn copy_dir_that_exists() { fs::create_dir_all(prefix.path().join("a")).unwrap(); - let err = tx.copy_dir("c", PathBuf::from("a"), srcdir.path()).unwrap_err(); + let err = tx.copy_dir("c", PathBuf::from("a"), srcdir.path()) + .unwrap_err(); match err.0 { ErrorKind::ComponentConflict { name, path } => { assert_eq!(name, "c"); assert_eq!(path, PathBuf::from("a")); } - _ => panic!() + _ => panic!(), } } @@ -246,7 +288,11 @@ fn remove_file() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -267,7 +313,11 @@ fn remove_file_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -288,7 +338,11 @@ fn remove_file_that_not_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -302,7 +356,7 @@ fn remove_file_that_not_exists() { assert_eq!(name, "c"); assert_eq!(path, PathBuf::from("foo")); } - _ => panic!() + _ => panic!(), } } @@ -311,7 +365,11 @@ fn remove_dir() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -333,7 +391,11 @@ fn remove_dir_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -355,7 +417,11 @@ fn remove_dir_that_not_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -369,7 +435,7 @@ fn remove_dir_that_not_exists() { assert_eq!(name, "c"); assert_eq!(path, PathBuf::from("foo")); } - _ => panic!() + _ => panic!(), } } @@ -378,7 +444,11 @@ fn write_file() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -386,7 +456,8 @@ fn write_file() { let mut tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); let content = "hi".to_string(); - tx.write_file("c", PathBuf::from("foo/bar"), content.clone()).unwrap(); + tx.write_file("c", PathBuf::from("foo/bar"), content.clone()) + .unwrap(); tx.commit(); let path = prefix.path().join("foo/bar"); @@ -400,7 +471,11 @@ fn write_file_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -408,7 +483,8 @@ fn write_file_then_rollback() { let mut tx = Transaction::new(prefix.clone(), &tmpcfg, ¬ify); let content = "hi".to_string(); - tx.write_file("c", PathBuf::from("foo/bar"), content.clone()).unwrap(); + tx.write_file("c", PathBuf::from("foo/bar"), content.clone()) + .unwrap(); drop(tx); assert!(!utils::is_file(&prefix.path().join("foo/bar"))); @@ -419,7 +495,11 @@ fn write_file_that_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -428,14 +508,15 @@ fn write_file_that_exists() { let content = "hi".to_string(); utils_raw::write_file(&prefix.path().join("a"), &content).unwrap(); - let err = tx.write_file("c", PathBuf::from("a"), content.clone()).unwrap_err(); + let err = tx.write_file("c", PathBuf::from("a"), content.clone()) + .unwrap_err(); match err.0 { ErrorKind::ComponentConflict { name, path } => { assert_eq!(name, "c"); assert_eq!(path, PathBuf::from("a")); } - _ => panic!() + _ => panic!(), } } @@ -446,7 +527,11 @@ fn modify_file_that_not_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -466,7 +551,11 @@ fn modify_file_that_exists() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -486,7 +575,11 @@ fn modify_file_that_not_exists_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -504,7 +597,11 @@ fn modify_file_that_exists_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -527,7 +624,11 @@ fn modify_twice_then_rollback() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -550,7 +651,11 @@ fn do_multiple_op_transaction(rollback: bool) { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -591,7 +696,8 @@ fn do_multiple_op_transaction(rollback: bool) { let ref srcpath4 = srcdir.path().join(&relpath4); fs::create_dir_all(srcpath4.parent().unwrap()).unwrap(); utils_raw::write_file(srcpath4, "").unwrap(); - tx.copy_dir("", PathBuf::from("doc"), &srcdir.path().join("doc")).unwrap(); + tx.copy_dir("", PathBuf::from("doc"), &srcdir.path().join("doc")) + .unwrap(); tx.modify_file(relpath5).unwrap(); utils_raw::write_file(path5, "").unwrap(); @@ -646,7 +752,11 @@ fn rollback_failure_keeps_going() { let prefixdir = TempDir::new("rustup").unwrap(); let txdir = TempDir::new("rustup").unwrap(); - let tmpcfg = temp::Cfg::new(txdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ())); + let tmpcfg = temp::Cfg::new( + txdir.path().to_owned(), + DEFAULT_DIST_SERVER, + Box::new(|_| ()), + ); let prefix = InstallPrefix::from(prefixdir.path().to_owned()); @@ -669,5 +779,4 @@ fn rollback_failure_keeps_going() { // they are deleted during rollback. #[test] #[ignore] -fn intermediate_dir_rollback() { -} +fn intermediate_dir_rollback() {} diff --git a/src/rustup-mock/src/clitools.rs b/src/rustup-mock/src/clitools.rs index 4dcb70e9c1..4182ac42b4 100644 --- a/src/rustup-mock/src/clitools.rs +++ b/src/rustup-mock/src/clitools.rs @@ -8,15 +8,14 @@ use std::env; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::mem; -use std::path::{PathBuf, Path}; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::Arc; use std::time::Duration; use tempdir::TempDir; -use {MockInstallerBuilder, MockFile, MockComponentBuilder}; -use dist::{MockDistServer, MockChannel, MockPackage, - MockTargetedPackage, MockComponent, change_channel_date, - ManifestVersion}; +use {MockComponentBuilder, MockFile, MockInstallerBuilder}; +use dist::{change_channel_date, ManifestVersion, MockChannel, MockComponent, MockDistServer, + MockPackage, MockTargetedPackage}; use url::Url; use wait_timeout::ChildExt; @@ -44,13 +43,13 @@ pub struct Config { // Building the mock server is slow, so use simple scenario when possible. #[derive(PartialEq, Copy, Clone)] pub enum Scenario { - Full, // Two dates, two manifests - ArchivesV2, // Two dates, v2 manifests - ArchivesV1, // Two dates, v1 manifests - SimpleV2, // One date, v2 manifests - SimpleV1, // One date, v1 manifests - MultiHost, // One date, v2 manifests, MULTI_ARCH1 host - Unavailable, // Two dates, v2 manifests, everything unavailable in second date. + Full, // Two dates, two manifests + ArchivesV2, // Two dates, v2 manifests + ArchivesV1, // Two dates, v1 manifests + SimpleV2, // One date, v2 manifests + SimpleV1, // One date, v1 manifests + MultiHost, // One date, v2 manifests, MULTI_ARCH1 host + Unavailable, // Two dates, v2 manifests, everything unavailable in second date. } pub static CROSS_ARCH1: &'static str = "x86_64-unknown-linux-musl"; @@ -122,7 +121,12 @@ pub fn setup(s: Scenario, f: &Fn(&mut Config)) { // Make sure the host triple matches the build triple. Otherwise testing a 32-bit build of // rustup on a 64-bit machine will fail, because the tests do not have the host detection // functionality built in. - run(&config, "rustup", &["set", "host", &this_host_triple()], &[]); + run( + &config, + "rustup", + &["set", "host", &this_host_triple()], + &[], + ); // Create some custom toolchains create_custom_toolchains(&config.customdir); @@ -142,7 +146,8 @@ impl Config { } pub fn change_dir(&self, path: &Path, mut f: F) - where F: FnMut() + where + F: FnMut(), { self._change_dir(path, &mut f) } @@ -211,8 +216,7 @@ pub fn expect_stderr_ok(config: &Config, args: &[&str], expected: &str) { } } -pub fn expect_ok_ex(config: &Config, args: &[&str], - stdout: &str, stderr: &str) { +pub fn expect_ok_ex(config: &Config, args: &[&str], stdout: &str, stderr: &str) { let out = run(config, args[0], &args[1..], &[]); if !out.ok || out.stdout != stdout || out.stderr != stderr { print_command(args, &out); @@ -223,8 +227,7 @@ pub fn expect_ok_ex(config: &Config, args: &[&str], } } -pub fn expect_err_ex(config: &Config, args: &[&str], - stdout: &str, stderr: &str) { +pub fn expect_err_ex(config: &Config, args: &[&str], stdout: &str, stderr: &str) { let out = run(config, args[0], &args[1..], &[]); if out.ok || out.stdout != stdout || out.stderr != stderr { print_command(args, &out); @@ -239,7 +242,8 @@ pub fn expect_timeout_ok(config: &Config, timeout: Duration, args: &[&str]) { let mut child = cmd(config, args[0], &args[1..]) .stdout(Stdio::null()) .stderr(Stdio::null()) - .spawn().unwrap(); + .spawn() + .unwrap(); match child.wait_timeout(timeout).unwrap() { Some(status) => { @@ -297,8 +301,14 @@ pub fn env(config: &Config, cmd: &mut Command) { new_path.push(p); } cmd.env("PATH", new_path); - cmd.env("RUSTUP_HOME", config.rustupdir.to_string_lossy().to_string()); - cmd.env("RUSTUP_DIST_SERVER", format!("file://{}", config.distdir.to_string_lossy())); + cmd.env( + "RUSTUP_HOME", + config.rustupdir.to_string_lossy().to_string(), + ); + cmd.env( + "RUSTUP_DIST_SERVER", + format!("file://{}", config.distdir.to_string_lossy()), + ); cmd.env("CARGO_HOME", config.cargodir.to_string_lossy().to_string()); cmd.env("RUSTUP_OVERRIDE_HOST_TRIPLE", this_host_triple()); @@ -358,8 +368,9 @@ fn create_mock_dist_server(path: &Path, s: Scenario) { let ref vs = match s { Scenario::Full => vec![ManifestVersion::V1, ManifestVersion::V2], Scenario::SimpleV1 | Scenario::ArchivesV1 => vec![ManifestVersion::V1], - Scenario::SimpleV2 | Scenario::ArchivesV2 | - Scenario::MultiHost | Scenario::Unavailable => vec![ManifestVersion::V2], + Scenario::SimpleV2 | Scenario::ArchivesV2 | Scenario::MultiHost | Scenario::Unavailable => { + vec![ManifestVersion::V2] + } }; MockDistServer { @@ -369,32 +380,66 @@ fn create_mock_dist_server(path: &Path, s: Scenario) { // Also create the manifests for stable releases by version if dates_count > 1 { - let _ = hard_link(path.join("dist/2015-01-01/channel-rust-stable.toml"), - path.join("dist/channel-rust-1.0.0.toml")); - let _ = hard_link(path.join("dist/2015-01-01/channel-rust-stable.toml.sha256"), - path.join("dist/channel-rust-1.0.0.toml.sha256")); - } - let _ = hard_link(path.join("dist/2015-01-02/channel-rust-stable.toml"), - path.join("dist/channel-rust-1.1.0.toml")); - let _ = hard_link(path.join("dist/2015-01-02/channel-rust-stable.toml.sha256"), - path.join("dist/channel-rust-1.1.0.toml.sha256")); + let _ = hard_link( + path.join("dist/2015-01-01/channel-rust-stable.toml"), + path.join("dist/channel-rust-1.0.0.toml"), + ); + let _ = hard_link( + path.join("dist/2015-01-01/channel-rust-stable.toml.sha256"), + path.join("dist/channel-rust-1.0.0.toml.sha256"), + ); + } + let _ = hard_link( + path.join("dist/2015-01-02/channel-rust-stable.toml"), + path.join("dist/channel-rust-1.1.0.toml"), + ); + let _ = hard_link( + path.join("dist/2015-01-02/channel-rust-stable.toml.sha256"), + path.join("dist/channel-rust-1.1.0.toml.sha256"), + ); // Same for v1 manifests. These are just the installers. let host_triple = this_host_triple(); if dates_count > 1 { - hard_link(path.join(format!("dist/2015-01-01/rust-stable-{}.tar.gz", host_triple)), - path.join(format!("dist/rust-1.0.0-{}.tar.gz", host_triple))).unwrap(); - hard_link(path.join(format!("dist/2015-01-01/rust-stable-{}.tar.gz.sha256", host_triple)), - path.join(format!("dist/rust-1.0.0-{}.tar.gz.sha256", host_triple))).unwrap(); - } - hard_link(path.join(format!("dist/2015-01-02/rust-stable-{}.tar.gz", host_triple)), - path.join(format!("dist/rust-1.1.0-{}.tar.gz", host_triple))).unwrap(); - hard_link(path.join(format!("dist/2015-01-02/rust-stable-{}.tar.gz.sha256", host_triple)), - path.join(format!("dist/rust-1.1.0-{}.tar.gz.sha256", host_triple))).unwrap(); -} - -fn build_mock_channel(s: Scenario, channel: &str, date: &str, - version: &'static str, version_hash: &str, rename_rls: bool) -> MockChannel { + hard_link( + path.join(format!( + "dist/2015-01-01/rust-stable-{}.tar.gz", + host_triple + )), + path.join(format!("dist/rust-1.0.0-{}.tar.gz", host_triple)), + ).unwrap(); + hard_link( + path.join(format!( + "dist/2015-01-01/rust-stable-{}.tar.gz.sha256", + host_triple + )), + path.join(format!("dist/rust-1.0.0-{}.tar.gz.sha256", host_triple)), + ).unwrap(); + } + hard_link( + path.join(format!( + "dist/2015-01-02/rust-stable-{}.tar.gz", + host_triple + )), + path.join(format!("dist/rust-1.1.0-{}.tar.gz", host_triple)), + ).unwrap(); + hard_link( + path.join(format!( + "dist/2015-01-02/rust-stable-{}.tar.gz.sha256", + host_triple + )), + path.join(format!("dist/rust-1.1.0-{}.tar.gz.sha256", host_triple)), + ).unwrap(); +} + +fn build_mock_channel( + s: Scenario, + channel: &str, + date: &str, + version: &'static str, + version_hash: &str, + rename_rls: bool, +) -> MockChannel { // Build the mock installers let ref host_triple = this_host_triple(); let std = build_mock_std_installer(host_triple); @@ -409,11 +454,18 @@ fn build_mock_channel(s: Scenario, channel: &str, date: &str, // Convert the mock installers to mock package definitions for the // mock dist server - let mut all = vec![("rust-std", vec![(std, host_triple.clone()), - (cross_std1, CROSS_ARCH1.to_string()), - (cross_std2, CROSS_ARCH2.to_string())]), - ("rustc", vec![(rustc, host_triple.clone())]), - ("cargo", vec![(cargo, host_triple.clone())])]; + let mut all = vec![ + ( + "rust-std", + vec![ + (std, host_triple.clone()), + (cross_std1, CROSS_ARCH1.to_string()), + (cross_std2, CROSS_ARCH2.to_string()), + ], + ), + ("rustc", vec![(rustc, host_triple.clone())]), + ("cargo", vec![(cargo, host_triple.clone())]), + ]; if rename_rls { let rls = build_mock_rls_installer(version, version_hash, false); @@ -423,10 +475,12 @@ fn build_mock_channel(s: Scenario, channel: &str, date: &str, all.push(("rls-preview", vec![(rls_preview, host_triple.clone())])); } - let more = vec![("rust-docs", vec![(rust_docs, host_triple.clone())]), - ("rust-src", vec![(rust_src, "*".to_string())]), - ("rust-analysis", vec![(rust_analysis, "*".to_string())]), - ("rust", vec![(rust, host_triple.clone())])]; + let more = vec![ + ("rust-docs", vec![(rust_docs, host_triple.clone())]), + ("rust-src", vec![(rust_src, "*".to_string())]), + ("rust-analysis", vec![(rust_analysis, "*".to_string())]), + ("rust", vec![(rust, host_triple.clone())]), + ]; all.extend(more); if s == Scenario::MultiHost { @@ -440,11 +494,18 @@ fn build_mock_channel(s: Scenario, channel: &str, date: &str, let rust_src = build_mock_rust_src_installer(); let triple = MULTI_ARCH1.to_string(); - let more = vec![("rust-std", vec![(std, triple.clone()), - (cross_std1, CROSS_ARCH1.to_string()), - (cross_std2, CROSS_ARCH2.to_string())]), - ("rustc", vec![(rustc, triple.clone())]), - ("cargo", vec![(cargo, triple.clone())])]; + let more = vec![ + ( + "rust-std", + vec![ + (std, triple.clone()), + (cross_std1, CROSS_ARCH1.to_string()), + (cross_std2, CROSS_ARCH2.to_string()), + ], + ), + ("rustc", vec![(rustc, triple.clone())]), + ("cargo", vec![(cargo, triple.clone())]), + ]; all.extend(more); if rename_rls { @@ -455,28 +516,30 @@ fn build_mock_channel(s: Scenario, channel: &str, date: &str, all.push(("rls-preview", vec![(rls_preview, triple.clone())])); } - let more = vec![("rust-docs", vec![(rust_docs, triple.clone())]), - ("rust-src", vec![(rust_src, "*".to_string())]), - ("rust", vec![(rust, triple.clone())])]; + let more = vec![ + ("rust-docs", vec![(rust_docs, triple.clone())]), + ("rust-src", vec![(rust_src, "*".to_string())]), + ("rust", vec![(rust, triple.clone())]), + ]; all.extend(more); } let packages = all.into_iter().map(|(name, target_pkgs)| { - let target_pkgs = target_pkgs.into_iter().map(|(installer, triple)| { - MockTargetedPackage { + let target_pkgs = target_pkgs + .into_iter() + .map(|(installer, triple)| MockTargetedPackage { target: triple, available: true, components: vec![], extensions: vec![], installer: installer, - } - }); + }); MockPackage { name: name, version: version, - targets: target_pkgs.collect() + targets: target_pkgs.collect(), } }); let mut packages: Vec<_> = packages.collect(); @@ -488,29 +551,29 @@ fn build_mock_channel(s: Scenario, channel: &str, date: &str, let ref target = target_pkg.target; target_pkg.components.push(MockComponent { name: "rust-std".to_string(), - target: target.to_string() + target: target.to_string(), }); target_pkg.components.push(MockComponent { name: "rustc".to_string(), - target: target.to_string() + target: target.to_string(), }); target_pkg.components.push(MockComponent { name: "cargo".to_string(), - target: target.to_string() + target: target.to_string(), }); target_pkg.components.push(MockComponent { name: "rust-docs".to_string(), - target: target.to_string() + target: target.to_string(), }); if rename_rls { target_pkg.extensions.push(MockComponent { name: "rls".to_string(), - target: target.to_string() + target: target.to_string(), }); } else { target_pkg.extensions.push(MockComponent { name: "rls-preview".to_string(), - target: target.to_string() + target: target.to_string(), }); } target_pkg.extensions.push(MockComponent { @@ -557,19 +620,22 @@ fn build_mock_unavailable_channel(channel: &str, date: &str, version: &'static s "rls-preview", "rust-analysis", ]; - let packages = packages.iter().map(|name| MockPackage { - name, - version, - targets: vec![MockTargetedPackage { - target: host_triple.clone(), - available: false, - components: vec![], - extensions: vec![], - installer: MockInstallerBuilder { - components: vec![], - }, - }], - }).collect(); + let packages = packages + .iter() + .map(|name| MockPackage { + name, + version, + targets: vec![ + MockTargetedPackage { + target: host_triple.clone(), + available: false, + components: vec![], + extensions: vec![], + installer: MockInstallerBuilder { components: vec![] }, + }, + ], + }) + .collect(); MockChannel { name: channel.to_string(), @@ -583,16 +649,29 @@ pub fn this_host_triple() -> String { if let Some(triple) = option_env!("RUSTUP_OVERRIDE_BUILD_TRIPLE") { triple.to_owned() } else { - let arch = if cfg!(target_arch = "x86") { "i686" } - else if cfg!(target_arch = "x86_64") { "x86_64" } - else { unimplemented!() }; - let os = if cfg!(target_os = "linux") { "unknown-linux" } - else if cfg!(target_os = "windows") { "pc-windows" } - else if cfg!(target_os = "macos") { "apple-darwin" } - else { unimplemented!() }; - let env = if cfg!(target_env = "gnu") { Some("gnu") } - else if cfg!(target_env = "msvc") { Some("msvc") } - else { None }; + let arch = if cfg!(target_arch = "x86") { + "i686" + } else if cfg!(target_arch = "x86_64") { + "x86_64" + } else { + unimplemented!() + }; + let os = if cfg!(target_os = "linux") { + "unknown-linux" + } else if cfg!(target_os = "windows") { + "pc-windows" + } else if cfg!(target_os = "macos") { + "apple-darwin" + } else { + unimplemented!() + }; + let env = if cfg!(target_env = "gnu") { + Some("gnu") + } else if cfg!(target_env = "msvc") { + Some("msvc") + } else { + None + }; if let Some(env) = env { format!("{}-{}-{}", arch, os, env) @@ -604,28 +683,36 @@ pub fn this_host_triple() -> String { fn build_mock_std_installer(trip: &str) -> MockInstallerBuilder { MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: format!("rust-std-{}", trip.clone()), - files: vec![ - MockFile::new(format!("lib/rustlib/{}/libstd.rlib", trip), b""), - ], - }], + components: vec![ + MockComponentBuilder { + name: format!("rust-std-{}", trip.clone()), + files: vec![ + MockFile::new(format!("lib/rustlib/{}/libstd.rlib", trip), b""), + ], + }, + ], } } fn build_mock_cross_std_installer(target: &str, date: &str) -> MockInstallerBuilder { MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: format!("rust-std-{}", target.clone()), - files: vec![ - MockFile::new(format!("lib/rustlib/{}/lib/libstd.rlib", target), b""), - MockFile::new(format!("lib/rustlib/{}/lib/{}", target, date), b""), - ], - }], + components: vec![ + MockComponentBuilder { + name: format!("rust-std-{}", target.clone()), + files: vec![ + MockFile::new(format!("lib/rustlib/{}/lib/libstd.rlib", target), b""), + MockFile::new(format!("lib/rustlib/{}/lib/{}", target, date), b""), + ], + }, + ], } } -fn build_mock_rustc_installer(target: &str, version: &str, version_hash_: &str) -> MockInstallerBuilder { +fn build_mock_rustc_installer( + target: &str, + version: &str, + version_hash_: &str, +) -> MockInstallerBuilder { // For cross-host rustc's modify the version_hash so they can be identified from // test cases. let this_host = this_host_triple(); @@ -637,72 +724,83 @@ fn build_mock_rustc_installer(target: &str, version: &str, version_hash_: &str) } MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: "rustc".to_string(), - files: mock_bin("rustc", version, &version_hash), - }], + components: vec![ + MockComponentBuilder { + name: "rustc".to_string(), + files: mock_bin("rustc", version, &version_hash), + }, + ], } } fn build_mock_cargo_installer(version: &str, version_hash: &str) -> MockInstallerBuilder { MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: "cargo".to_string(), - files: mock_bin("cargo", version, &version_hash), - }], + components: vec![ + MockComponentBuilder { + name: "cargo".to_string(), + files: mock_bin("cargo", version, &version_hash), + }, + ], } } -fn build_mock_rls_installer(version: &str, version_hash: &str, preview: bool) -> MockInstallerBuilder { - let name = if preview { - "rls-preview" - } else { - "rls" - }; +fn build_mock_rls_installer( + version: &str, + version_hash: &str, + preview: bool, +) -> MockInstallerBuilder { + let name = if preview { "rls-preview" } else { "rls" }; MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: name.to_string(), - files: mock_bin("rls", version, version_hash), - }], + components: vec![ + MockComponentBuilder { + name: name.to_string(), + files: mock_bin("rls", version, version_hash), + }, + ], } } fn build_mock_rust_doc_installer() -> MockInstallerBuilder { MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: "rust-docs".to_string(), - files: vec![ - MockFile::new("share/doc/rust/html/index.html", b""), - ], - }], + components: vec![ + MockComponentBuilder { + name: "rust-docs".to_string(), + files: vec![MockFile::new("share/doc/rust/html/index.html", b"")], + }, + ], } } fn build_mock_rust_analysis_installer(trip: &str) -> MockInstallerBuilder { MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: format!("rust-analysis-{}", trip), - files: vec![ - MockFile::new(format!("lib/rustlib/{}/analysis/libfoo.json", trip), b""), - ], - }], + components: vec![ + MockComponentBuilder { + name: format!("rust-analysis-{}", trip), + files: vec![ + MockFile::new(format!("lib/rustlib/{}/analysis/libfoo.json", trip), b""), + ], + }, + ], } } fn build_mock_rust_src_installer() -> MockInstallerBuilder { MockInstallerBuilder { - components: vec![MockComponentBuilder { - name: "rust-src".to_string(), - files: vec![ - MockFile::new("lib/rustlib/src/rust-src/foo.rs", b""), - ], - }], + components: vec![ + MockComponentBuilder { + name: "rust-src".to_string(), + files: vec![MockFile::new("lib/rustlib/src/rust-src/foo.rs", b"")], + }, + ], } } fn build_combined_installer(components: &[&MockInstallerBuilder]) -> MockInstallerBuilder { MockInstallerBuilder { - components: components.iter().flat_map(|m| m.components.clone()).collect() + components: components + .iter() + .flat_map(|m| m.components.clone()) + .collect(), } } @@ -775,8 +873,9 @@ fn create_custom_toolchains(customdir: &Path) { } pub fn hard_link(a: A, b: B) -> io::Result<()> - where A: AsRef, - B: AsRef, +where + A: AsRef, + B: AsRef, { drop(fs::remove_file(b.as_ref())); fs::hard_link(a, b).map(|_| ()) diff --git a/src/rustup-mock/src/dist.rs b/src/rustup-mock/src/dist.rs index 31f576e4ec..7834cdc2c2 100644 --- a/src/rustup-mock/src/dist.rs +++ b/src/rustup-mock/src/dist.rs @@ -6,10 +6,10 @@ use url::Url; use std::collections::HashMap; use std::fs::{self, File}; use std::io::{Read, Write}; -use std::path::{PathBuf, Path}; +use std::path::{Path, PathBuf}; use std::sync::Mutex; use tempdir::TempDir; -use sha2::{Sha256, Digest}; +use sha2::{Digest, Sha256}; use toml; use flate2; use xz2; @@ -115,7 +115,10 @@ pub struct MockHashes { pub xz: Option, } -pub enum ManifestVersion { V1, V2 } +pub enum ManifestVersion { + V1, + V2, +} impl MockDistServer { pub fn write(&self, vs: &[ManifestVersion], enable_xz: bool) { @@ -136,7 +139,12 @@ impl MockDistServer { } } - fn build_package(&self, channel: &MockChannel, package: &MockPackage, enable_xz: bool) -> HashMap { + fn build_package( + &self, + channel: &MockChannel, + package: &MockPackage, + enable_xz: bool, + ) -> HashMap { let mut hashes = HashMap::new(); for target_package in &package.targets { @@ -150,18 +158,26 @@ impl MockDistServer { name: package.name.to_string(), target: target_package.target.to_string(), }; - hashes.insert(component, MockHashes { gz: gz_hash, xz: xz_hash }); + hashes.insert( + component, + MockHashes { + gz: gz_hash, + xz: xz_hash, + }, + ); } return hashes; } // Returns the hash of the tarball - fn build_target_package(&self, - channel: &MockChannel, - package: &MockPackage, - target_package: &MockTargetedPackage, - format: &str) -> String { + fn build_target_package( + &self, + channel: &MockChannel, + package: &MockPackage, + target_package: &MockTargetedPackage, + format: &str, + ) -> String { // This is where the tarball, sums and sigs will go let ref dist_dir = self.path.join("dist"); let ref archive_dir = dist_dir.join(&channel.date); @@ -172,7 +188,10 @@ impl MockDistServer { let workdir = tmpdir.path().join("work"); let ref installer_name = if target_package.target != "*" { - format!("{}-{}-{}", package.name, channel.name, target_package.target) + format!( + "{}-{}-{}", + package.name, channel.name, target_package.target + ) } else { format!("{}-{}", package.name, channel.name) }; @@ -190,34 +209,49 @@ impl MockDistServer { Mutex::new(HashMap::new()); } - let key = (installer_name.to_string(), - target_package.clone(), - format.to_string()); + let key = ( + installer_name.to_string(), + target_package.clone(), + format.to_string(), + ); let tarballs = TARBALLS.lock().unwrap(); let hash = if tarballs.contains_key(&key) { let (ref contents, ref hash) = tarballs[&key]; - File::create(&installer_tarball).unwrap() - .write_all(contents).unwrap(); - File::create(&installer_hash).unwrap() - .write_all(hash.as_bytes()).unwrap(); + File::create(&installer_tarball) + .unwrap() + .write_all(contents) + .unwrap(); + File::create(&installer_hash) + .unwrap() + .write_all(hash.as_bytes()) + .unwrap(); hash.clone() } else { drop(tarballs); target_package.installer.build(installer_dir); - create_tarball(&PathBuf::from(installer_name), - installer_dir, installer_tarball); + create_tarball( + &PathBuf::from(installer_name), + installer_dir, + installer_tarball, + ); let mut contents = Vec::new(); - File::open(installer_tarball).unwrap() - .read_to_end(&mut contents).unwrap(); + File::open(installer_tarball) + .unwrap() + .read_to_end(&mut contents) + .unwrap(); let hash = create_hash(installer_tarball, installer_hash); - TARBALLS.lock().unwrap().insert(key, (contents, hash.clone())); + TARBALLS + .lock() + .unwrap() + .insert(key, (contents, hash.clone())); hash }; // Copy from the archive to the main dist directory if package.name == "rust" { let ref main_installer_tarball = dist_dir.join(format!("{}{}", installer_name, format)); - let ref main_installer_hash = dist_dir.join(format!("{}{}.sha256", installer_name, format)); + let ref main_installer_hash = + dist_dir.join(format!("{}{}.sha256", installer_name, format)); hard_link(installer_tarball, main_installer_tarball).unwrap(); hard_link(installer_hash, main_installer_hash).unwrap(); } @@ -254,30 +288,49 @@ impl MockDistServer { hard_link(hash_path, archive_hash_path).unwrap(); } - fn write_manifest_v2(&self, channel: &MockChannel, hashes: &HashMap) { + fn write_manifest_v2( + &self, + channel: &MockChannel, + hashes: &HashMap, + ) { let mut toml_manifest = toml::value::Table::new(); - toml_manifest.insert(String::from("manifest-version"), toml::Value::String(MOCK_MANIFEST_VERSION.to_owned())); - toml_manifest.insert(String::from("date"), toml::Value::String(channel.date.to_owned())); + toml_manifest.insert( + String::from("manifest-version"), + toml::Value::String(MOCK_MANIFEST_VERSION.to_owned()), + ); + toml_manifest.insert( + String::from("date"), + toml::Value::String(channel.date.to_owned()), + ); // [pkg.*] let mut toml_packages = toml::value::Table::new(); for package in &channel.packages { let mut toml_package = toml::value::Table::new(); - toml_package.insert(String::from("version"), toml::Value::String(package.version.to_owned())); + toml_package.insert( + String::from("version"), + toml::Value::String(package.version.to_owned()), + ); // [pkg.*.target.*] let mut toml_targets = toml::value::Table::new(); for target in &package.targets { let mut toml_target = toml::value::Table::new(); - toml_target.insert(String::from("available"), toml::Value::Boolean(target.available)); + toml_target.insert( + String::from("available"), + toml::Value::Boolean(target.available), + ); let package_file_name = if target.target != "*" { format!("{}-{}-{}.tar.gz", package.name, channel.name, target.target) } else { format!("{}-{}.tar.gz", package.name, channel.name) }; - let path = self.path.join("dist").join(&channel.date).join(package_file_name); + let path = self.path + .join("dist") + .join(&channel.date) + .join(package_file_name); let url = format!("file://{}", path.to_string_lossy()); toml_target.insert(String::from("url"), toml::Value::String(url.clone())); @@ -289,7 +342,10 @@ impl MockDistServer { toml_target.insert(String::from("hash"), toml::Value::String(hash.gz)); if let Some(xz_hash) = hash.xz { - toml_target.insert(String::from("xz_url"), toml::Value::String(url.replace(".tar.gz", ".tar.xz"))); + toml_target.insert( + String::from("xz_url"), + toml::Value::String(url.replace(".tar.gz", ".tar.xz")), + ); toml_target.insert(String::from("xz_hash"), toml::Value::String(xz_hash)); } @@ -297,21 +353,39 @@ impl MockDistServer { let mut toml_components = toml::value::Array::new(); for component in &target.components { let mut toml_component = toml::value::Table::new(); - toml_component.insert(String::from("pkg"), toml::Value::String(component.name.to_owned())); - toml_component.insert(String::from("target"), toml::Value::String(component.target.to_owned())); + toml_component.insert( + String::from("pkg"), + toml::Value::String(component.name.to_owned()), + ); + toml_component.insert( + String::from("target"), + toml::Value::String(component.target.to_owned()), + ); toml_components.push(toml::Value::Table(toml_component)); } - toml_target.insert(String::from("components"), toml::Value::Array(toml_components)); + toml_target.insert( + String::from("components"), + toml::Value::Array(toml_components), + ); // [pkg.*.target.*.extensions.*] let mut toml_extensions = toml::value::Array::new(); for extension in &target.extensions { let mut toml_extension = toml::value::Table::new(); - toml_extension.insert(String::from("pkg"), toml::Value::String(extension.name.to_owned())); - toml_extension.insert(String::from("target"), toml::Value::String(extension.target.to_owned())); + toml_extension.insert( + String::from("pkg"), + toml::Value::String(extension.name.to_owned()), + ); + toml_extension.insert( + String::from("target"), + toml::Value::String(extension.target.to_owned()), + ); toml_extensions.push(toml::Value::Table(toml_extension)); } - toml_target.insert(String::from("extensions"), toml::Value::Array(toml_extensions)); + toml_target.insert( + String::from("extensions"), + toml::Value::Array(toml_extensions), + ); toml_targets.insert(target.target.clone(), toml::Value::Table(toml_target)); } @@ -341,7 +415,8 @@ impl MockDistServer { let ref archive_manifest_path = self.path.join(format!("{}.toml", archive_manifest_name)); hard_link(manifest_path, archive_manifest_path).unwrap(); - let ref archive_hash_path = self.path.join(format!("{}.toml.sha256", archive_manifest_name)); + let ref archive_hash_path = self.path + .join(format!("{}.toml.sha256", archive_manifest_name)); hard_link(hash_path, archive_hash_path).unwrap(); } } @@ -400,5 +475,7 @@ pub fn create_hash(src: &Path, dst: &Path) -> String { fn write_file(dst: &Path, contents: &str) { drop(fs::remove_file(dst)); - File::create(dst).and_then(|mut f| f.write_all(contents.as_bytes())).unwrap(); + File::create(dst) + .and_then(|mut f| f.write_all(contents.as_bytes())) + .unwrap(); } diff --git a/src/rustup-mock/src/lib.rs b/src/rustup-mock/src/lib.rs index ba2761dc60..81fb8bec2f 100644 --- a/src/rustup-mock/src/lib.rs +++ b/src/rustup-mock/src/lib.rs @@ -1,16 +1,16 @@ //! Mocks for testing -extern crate url; +extern crate flate2; #[macro_use] extern crate lazy_static; -extern crate walkdir; -extern crate flate2; -extern crate xz2; -extern crate tempdir; +extern crate sha2; extern crate tar; +extern crate tempdir; extern crate toml; -extern crate sha2; +extern crate url; extern crate wait_timeout; +extern crate walkdir; +extern crate xz2; #[cfg(windows)] extern crate winapi; @@ -20,7 +20,7 @@ extern crate winreg; pub mod dist; pub mod clitools; -use std::fs::{self, OpenOptions, File}; +use std::fs::{self, File, OpenOptions}; use std::io::Write; use std::path::Path; use std::sync::Arc; @@ -60,8 +60,12 @@ impl MockInstallerBuilder { for component in &self.components { // Update the components file let comp_file = path.join("components"); - let ref mut comp_file = OpenOptions::new().write(true).append(true).create(true) - .open(comp_file.clone()).unwrap(); + let ref mut comp_file = OpenOptions::new() + .write(true) + .append(true) + .create(true) + .open(comp_file.clone()) + .unwrap(); writeln!(comp_file, "{}", component.name).unwrap(); // Create the component directory @@ -112,12 +116,20 @@ impl MockFile { pub fn new_dir(path: &str, files: &[(&'static str, &'static [u8], bool)]) -> MockFile { MockFile { path: path.to_string(), - contents: Contents::Dir(files.iter().map(|&(name, data, exe)| { - (name, MockContents { - contents: Arc::new(data.to_vec()), - executable: exe, - }) - }).collect()), + contents: Contents::Dir( + files + .iter() + .map(|&(name, data, exe)| { + ( + name, + MockContents { + contents: Arc::new(data.to_vec()), + executable: exe, + }, + ) + }) + .collect(), + ), } } @@ -132,12 +144,10 @@ impl MockFile { pub fn build(&self, path: &Path) { let path = path.join(&self.path); match self.contents { - Contents::Dir(ref files) => { - for &(ref name, ref contents) in files { - let fname = path.join(name); - contents.build(&fname); - } - } + Contents::Dir(ref files) => for &(ref name, ref contents) in files { + let fname = path.join(name); + contents.build(&fname); + }, Contents::File(ref contents) => contents.build(&path), } } @@ -147,8 +157,10 @@ impl MockContents { fn build(&self, path: &Path) { let dir_path = path.parent().unwrap().to_owned(); fs::create_dir_all(dir_path).unwrap(); - File::create(&path).unwrap() - .write_all(&self.contents).unwrap(); + File::create(&path) + .unwrap() + .write_all(&self.contents) + .unwrap(); #[cfg(unix)] { @@ -168,7 +180,8 @@ pub fn get_path() -> Option { use winapi::*; let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); environment.get_value("PATH").ok() } @@ -180,7 +193,8 @@ pub fn restore_path(p: &Option) { use winapi::*; let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); if let Some(p) = p.as_ref() { let reg_value = RegValue { @@ -201,8 +215,9 @@ pub fn restore_path(p: &Option) { } #[cfg(unix)] -pub fn get_path() -> Option { None } +pub fn get_path() -> Option { + None +} #[cfg(unix)] -pub fn restore_path(_: &Option) { } - +pub fn restore_path(_: &Option) {} diff --git a/src/rustup-utils/src/errors.rs b/src/rustup-utils/src/errors.rs index fd9d5b4fde..0ca59f2393 100644 --- a/src/rustup-utils/src/errors.rs +++ b/src/rustup-utils/src/errors.rs @@ -60,7 +60,8 @@ error_chain! { dest: PathBuf, } { description("could not rename file") - display("could not rename {} file from '{}' to '{}'", name, src.display(), dest.display()) + display("could not rename {} file from '{}' to '{}'", + name, src.display(), dest.display()) } RenamingDirectory { name: &'static str, @@ -68,7 +69,8 @@ error_chain! { dest: PathBuf, } { description("could not rename directory") - display("could not rename {} directory from '{}' to '{}'", name, src.display(), dest.display()) + display("could not rename {} directory from '{}' to '{}'", + name, src.display(), dest.display()) } DownloadingFile { url: Url, diff --git a/src/rustup-utils/src/lib.rs b/src/rustup-utils/src/lib.rs index 98973e6564..185522b595 100644 --- a/src/rustup-utils/src/lib.rs +++ b/src/rustup-utils/src/lib.rs @@ -1,29 +1,29 @@ #![recursion_limit = "1024"] // for error_chain! -extern crate rand; -extern crate scopeguard; +extern crate download; #[macro_use] extern crate error_chain; +extern crate rand; +extern crate scopeguard; +extern crate semver; extern crate sha2; -extern crate url; extern crate toml; -extern crate download; -extern crate semver; +extern crate url; #[cfg(windows)] -extern crate winapi; -#[cfg(windows)] -extern crate winreg; +extern crate advapi32; #[cfg(windows)] -extern crate shell32; +extern crate kernel32; #[cfg(windows)] extern crate ole32; #[cfg(windows)] -extern crate kernel32; -#[cfg(windows)] -extern crate advapi32; +extern crate shell32; #[cfg(windows)] extern crate userenv; +#[cfg(windows)] +extern crate winapi; +#[cfg(windows)] +extern crate winreg; #[cfg(unix)] extern crate libc; @@ -36,5 +36,5 @@ pub mod utils; pub mod toml_utils; pub use errors::*; -pub use notifications::{Notification}; +pub use notifications::Notification; pub mod notify; diff --git a/src/rustup-utils/src/notifications.rs b/src/rustup-utils/src/notifications.rs index 34589fa3fd..b9f906355c 100644 --- a/src/rustup-utils/src/notifications.rs +++ b/src/rustup-utils/src/notifications.rs @@ -30,16 +30,16 @@ impl<'a> Notification<'a> { use self::Notification::*; match *self { CreatingDirectory(_, _) | RemovingDirectory(_, _) => NotificationLevel::Verbose, - LinkingDirectory(_, _) | - CopyingDirectory(_, _) | - DownloadingFile(_, _) | - DownloadContentLengthReceived(_) | - DownloadDataReceived(_) | - DownloadFinished | - ResumingPartialDownload | - UsingCurl | UsingReqwest => NotificationLevel::Verbose, - UsingHyperDeprecated | - NoCanonicalPath(_) => NotificationLevel::Warn, + LinkingDirectory(_, _) + | CopyingDirectory(_, _) + | DownloadingFile(_, _) + | DownloadContentLengthReceived(_) + | DownloadDataReceived(_) + | DownloadFinished + | ResumingPartialDownload + | UsingCurl + | UsingReqwest => NotificationLevel::Verbose, + UsingHyperDeprecated | NoCanonicalPath(_) => NotificationLevel::Warn, } } } @@ -64,8 +64,10 @@ impl<'a> Display for Notification<'a> { ResumingPartialDownload => write!(f, "resuming partial download"), UsingCurl => write!(f, "downloading with curl"), UsingReqwest => write!(f, "downloading with reqwest"), - UsingHyperDeprecated => f.write_str("RUSTUP_USE_HYPER environment variable is deprecated, use RUSTUP_USE_REQWEST instead"), + UsingHyperDeprecated => f.write_str( + "RUSTUP_USE_HYPER environment variable is deprecated, \ + use RUSTUP_USE_REQWEST instead", + ), } } } - diff --git a/src/rustup-utils/src/raw.rs b/src/rustup-utils/src/raw.rs index 00ed137f6b..04f532399c 100644 --- a/src/rustup-utils/src/raw.rs +++ b/src/rustup-utils/src/raw.rs @@ -14,9 +14,10 @@ use std::str; use rand::random; -pub fn ensure_dir_exists, F: FnOnce(&Path)>(path: P, - callback: F) - -> io::Result { +pub fn ensure_dir_exists, F: FnOnce(&Path)>( + path: P, + callback: F, +) -> io::Result { if !is_directory(path.as_ref()) { callback(path.as_ref()); fs::create_dir_all(path.as_ref()).map(|()| true) @@ -39,7 +40,9 @@ 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()).collect() + (0..length) + .map(|_| from_u32(chars[random::() % chars.len()] as u32).unwrap()) + .collect() } pub fn if_not_empty>(s: S) -> Option { @@ -51,63 +54,62 @@ pub fn if_not_empty>(s: S) -> Option { } pub fn write_file(path: &Path, contents: &str) -> io::Result<()> { - let mut file = try!(fs::OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(path)); + let mut file = fs::OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(path)?; - try!(io::Write::write_all(&mut file, contents.as_bytes())); + io::Write::write_all(&mut file, contents.as_bytes())?; - try!(file.sync_data()); + file.sync_data()?; Ok(()) } pub fn read_file(path: &Path) -> io::Result { - let mut file = try!(fs::OpenOptions::new() - .read(true) - .open(path)); + let mut file = fs::OpenOptions::new().read(true).open(path)?; let mut contents = String::new(); - try!(io::Read::read_to_string(&mut file, &mut contents)); + io::Read::read_to_string(&mut file, &mut contents)?; Ok(contents) } -pub fn filter_file bool>(src: &Path, - dest: &Path, - mut filter: F) - -> io::Result { - let src_file = try!(fs::File::open(src)); - let dest_file = try!(fs::File::create(dest)); +pub fn filter_file bool>( + src: &Path, + dest: &Path, + mut filter: F, +) -> io::Result { + let src_file = fs::File::open(src)?; + let dest_file = fs::File::create(dest)?; let mut reader = io::BufReader::new(src_file); let mut writer = io::BufWriter::new(dest_file); let mut removed = 0; for result in io::BufRead::lines(&mut reader) { - let line = try!(result); + let line = result?; if filter(&line) { - try!(writeln!(&mut writer, "{}", &line)); + writeln!(&mut writer, "{}", &line)?; } else { removed += 1; } } - try!(writer.flush()); + writer.flush()?; Ok(removed) } pub fn match_file Option>(src: &Path, mut f: F) -> io::Result> { - let src_file = try!(fs::File::open(src)); + let src_file = fs::File::open(src)?; let mut reader = io::BufReader::new(src_file); for result in io::BufRead::lines(&mut reader) { - let line = try!(result); + let line = result?; if let Some(r) = f(&line) { return Ok(Some(r)); } @@ -117,32 +119,30 @@ pub fn match_file Option>(src: &Path, mut f: F) -> io::R } pub fn append_file(dest: &Path, line: &str) -> io::Result<()> { - let mut dest_file = try!(fs::OpenOptions::new() - .write(true) - .append(true) - .create(true) - .open(dest)); + let mut dest_file = fs::OpenOptions::new() + .write(true) + .append(true) + .create(true) + .open(dest)?; - try!(writeln!(&mut dest_file, "{}", line)); + writeln!(&mut dest_file, "{}", line)?; - try!(dest_file.sync_data()); + dest_file.sync_data()?; Ok(()) } pub fn tee_file(path: &Path, mut w: &mut W) -> io::Result<()> { - let mut file = try!(fs::OpenOptions::new() - .read(true) - .open(path)); + let mut file = fs::OpenOptions::new().read(true).open(path)?; let buffer_size = 0x10000; let mut buffer = vec![0u8; buffer_size]; loop { - let bytes_read = try!(io::Read::read(&mut file, &mut buffer)); + let bytes_read = io::Read::read(&mut file, &mut buffer)?; if bytes_read != 0 { - try!(io::Write::write_all(w, &mut buffer[0..bytes_read])); + io::Write::write_all(w, &mut buffer[0..bytes_read])?; } else { return Ok(()); } @@ -197,24 +197,25 @@ fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> { // We're using low-level APIs to create the junction, and these are more picky about paths. // For example, forward slashes cannot be used as a path separator, so we should try to // canonicalize the path first. - let target = try!(fs::canonicalize(target)); + let target = fs::canonicalize(target)?; - try!(fs::create_dir(junction)); + fs::create_dir(junction)?; - let path = try!(windows::to_u16s(junction)); + let path = windows::to_u16s(junction)?; unsafe { - let h = CreateFileW(path.as_ptr(), - GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - 0 as *mut _, - OPEN_EXISTING, - FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, - ptr::null_mut()); + let h = CreateFileW( + path.as_ptr(), + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + 0 as *mut _, + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, + ptr::null_mut(), + ); let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; - let mut db = data.as_mut_ptr() - as *mut REPARSE_MOUNTPOINT_DATA_BUFFER; + let mut db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER; let buf = &mut (*db).ReparseTarget as *mut _; let mut i = 0; // FIXME: this conversion is very hacky @@ -229,17 +230,19 @@ fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> { (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; (*db).ReparseTargetMaximumLength = (i * 2) as WORD; (*db).ReparseTargetLength = ((i - 1) * 2) as WORD; - (*db).ReparseDataLength = - (*db).ReparseTargetLength as DWORD + 12; + (*db).ReparseDataLength = (*db).ReparseTargetLength as DWORD + 12; let mut ret = 0; - let res = DeviceIoControl(h as *mut _, - FSCTL_SET_REPARSE_POINT, - data.as_ptr() as *mut _, - (*db).ReparseDataLength + 8, - ptr::null_mut(), 0, - &mut ret, - ptr::null_mut()); + let res = DeviceIoControl( + h as *mut _, + FSCTL_SET_REPARSE_POINT, + data.as_ptr() as *mut _, + (*db).ReparseDataLength + 8, + ptr::null_mut(), + 0, + &mut ret, + ptr::null_mut(), + ); if res == 0 { Err(io::Error::last_os_error()) @@ -300,7 +303,7 @@ pub fn cmd_status(cmd: &mut Command) -> CommandResult<()> { } pub fn remove_dir(path: &Path) -> io::Result<()> { - if try!(fs::symlink_metadata(path)).file_type().is_symlink() { + if fs::symlink_metadata(path)?.file_type().is_symlink() { if cfg!(windows) { fs::remove_dir(path) } else { @@ -316,16 +319,16 @@ pub fn remove_dir(path: &Path) -> io::Result<()> { } pub fn copy_dir(src: &Path, dest: &Path) -> io::Result<()> { - try!(fs::create_dir(dest)); - for entry in try!(src.read_dir()) { - let entry = try!(entry); - let kind = try!(entry.file_type()); + fs::create_dir(dest)?; + for entry in src.read_dir()? { + let entry = entry?; + let kind = entry.file_type()?; let src = entry.path(); let dest = dest.join(entry.file_name()); if kind.is_dir() { - try!(copy_dir(&src, &dest)); + copy_dir(&src, &dest)?; } else { - try!(fs::copy(&src, &dest)); + fs::copy(&src, &dest)?; } } Ok(()) @@ -340,11 +343,9 @@ 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()); - env::split_paths(&path).map(|p| { - p.join(&cmd) - }).any(|p| { - p.exists() - }) + env::split_paths(&path) + .map(|p| p.join(&cmd)) + .any(|p| p.exists()) } pub fn find_cmd<'a>(cmds: &[&'a str]) -> Option<&'a str> { @@ -356,7 +357,13 @@ pub fn open_browser(path: &Path) -> io::Result { fn inner(path: &Path) -> io::Result { use std::process::Stdio; - let commands = ["xdg-open", "open", "firefox", "chromium", "sensible-browser"]; + let commands = [ + "xdg-open", + "open", + "firefox", + "chromium", + "sensible-browser", + ]; if let Some(cmd) = find_cmd(&commands) { Command::new(cmd) .arg(path) @@ -376,25 +383,28 @@ pub fn open_browser(path: &Path) -> io::Result { // FIXME: When winapi has this function, use their version extern "system" { - pub fn ShellExecuteW(hwnd: winapi::HWND, - lpOperation: winapi::LPCWSTR, - lpFile: winapi::LPCWSTR, - lpParameters: winapi::LPCWSTR, - lpDirectory: winapi::LPCWSTR, - nShowCmd: winapi::c_int) - -> winapi::HINSTANCE; + pub fn ShellExecuteW( + hwnd: winapi::HWND, + lpOperation: winapi::LPCWSTR, + lpFile: winapi::LPCWSTR, + lpParameters: winapi::LPCWSTR, + lpDirectory: winapi::LPCWSTR, + nShowCmd: winapi::c_int, + ) -> winapi::HINSTANCE; } const SW_SHOW: winapi::c_int = 5; let path = windows::to_u16s(path)?; let operation = windows::to_u16s("open")?; let result = unsafe { - ShellExecuteW(ptr::null_mut(), - operation.as_ptr(), - path.as_ptr(), - ptr::null(), - ptr::null(), - SW_SHOW) + ShellExecuteW( + ptr::null_mut(), + operation.as_ptr(), + path.as_ptr(), + ptr::null(), + ptr::null(), + SW_SHOW, + ) }; Ok(result as usize > 32) } @@ -408,8 +418,8 @@ pub mod windows { use std::path::PathBuf; use std::ptr; use std::slice; - use std::ffi::{OsString, OsStr}; - use std::os::windows::ffi::{OsStringExt, OsStrExt}; + use std::ffi::{OsStr, OsString}; + use std::os::windows::ffi::{OsStrExt, OsStringExt}; use shell32; use ole32; @@ -429,8 +439,6 @@ pub mod windows { }; pub fn get_special_folder(id: &shtypes::KNOWNFOLDERID) -> io::Result { - - let mut path = ptr::null_mut(); let result; @@ -455,8 +463,10 @@ pub mod windows { fn inner(s: &OsStr) -> io::Result> { let mut maybe_result: Vec = s.encode_wide().collect(); if maybe_result.iter().any(|&u| u == 0) { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "strings passed to WinAPI cannot contain NULs")); + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "strings passed to WinAPI cannot contain NULs", + )); } maybe_result.push(0); Ok(maybe_result) diff --git a/src/rustup-utils/src/toml_utils.rs b/src/rustup-utils/src/toml_utils.rs index 5da9e6fde2..1ecc174185 100644 --- a/src/rustup-utils/src/toml_utils.rs +++ b/src/rustup-utils/src/toml_utils.rs @@ -2,8 +2,9 @@ use toml; use errors::*; pub fn get_value(table: &mut toml::value::Table, key: &str, path: &str) -> Result { - table.remove(key).ok_or_else( - || format!("missing key: '{}'", path.to_owned() + key).into()) + table + .remove(key) + .ok_or_else(|| format!("missing key: '{}'", path.to_owned() + key).into()) } pub fn get_string(table: &mut toml::value::Table, key: &str, path: &str) -> Result { @@ -16,7 +17,11 @@ pub fn get_string(table: &mut toml::value::Table, key: &str, path: &str) -> Resu }) } -pub fn get_opt_string(table: &mut toml::value::Table, key: &str, path: &str) -> Result> { +pub fn get_opt_string( + table: &mut toml::value::Table, + key: &str, + path: &str, +) -> Result> { if let Ok(v) = get_value(table, key, path) { if let toml::Value::String(s) = v { Ok(Some(s)) @@ -50,7 +55,11 @@ pub fn get_opt_bool(table: &mut toml::value::Table, key: &str, path: &str) -> Re } } -pub fn get_table(table: &mut toml::value::Table, key: &str, path: &str) -> Result { +pub fn get_table( + table: &mut toml::value::Table, + key: &str, + path: &str, +) -> Result { if let Some(v) = table.remove(key) { if let toml::Value::Table(t) = v { Ok(t) @@ -62,7 +71,11 @@ pub fn get_table(table: &mut toml::value::Table, key: &str, path: &str) -> Resul } } -pub fn get_array(table: &mut toml::value::Table, key: &str, path: &str) -> Result { +pub fn get_array( + table: &mut toml::value::Table, + key: &str, + path: &str, +) -> Result { if let Some(v) = table.remove(key) { if let toml::Value::Array(s) = v { Ok(s) diff --git a/src/rustup-utils/src/tty.rs b/src/rustup-utils/src/tty.rs index 0b23d759b6..c4af1d36bb 100644 --- a/src/rustup-utils/src/tty.rs +++ b/src/rustup-utils/src/tty.rs @@ -15,8 +15,7 @@ pub fn stderr_isatty() -> bool { const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD; extern "system" { fn GetStdHandle(which: DWORD) -> HANDLE; - fn GetConsoleMode(hConsoleHandle: HANDLE, - lpMode: *mut DWORD) -> BOOL; + fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL; } unsafe { let handle = GetStdHandle(STD_ERROR_HANDLE); @@ -39,8 +38,7 @@ pub fn stdout_isatty() -> bool { const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD; extern "system" { fn GetStdHandle(which: DWORD) -> HANDLE; - fn GetConsoleMode(hConsoleHandle: HANDLE, - lpMode: *mut DWORD) -> BOOL; + fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL; } unsafe { let handle = GetStdHandle(STD_OUTPUT_HANDLE); diff --git a/src/rustup-utils/src/utils.rs b/src/rustup-utils/src/utils.rs index fa4bd2822e..6c3cd9963a 100644 --- a/src/rustup-utils/src/utils.rs +++ b/src/rustup-utils/src/utils.rs @@ -5,9 +5,9 @@ use std::io::{self, Write}; use std::process::Command; use std::ffi::OsString; use std::env; -use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; +use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use sha2::Sha256; -use notifications::{Notification}; +use notifications::Notification; use raw; #[cfg(windows)] use winapi::DWORD; @@ -16,111 +16,94 @@ use winreg; use std::cmp::Ord; use url::Url; -pub use raw::{is_directory, is_file, path_exists, if_not_empty, random_string, prefix_arg, - has_cmd, find_cmd}; - -pub fn ensure_dir_exists(name: &'static str, - path: &Path, - notify_handler: &Fn(Notification)) - -> Result { - raw::ensure_dir_exists(path, - |p| notify_handler(Notification::CreatingDirectory(name, p))) - .chain_err(|| { - ErrorKind::CreatingDirectory { - name: name, - path: PathBuf::from(path), - } - }) +pub use raw::{find_cmd, has_cmd, if_not_empty, is_directory, is_file, path_exists, prefix_arg, + random_string}; + +pub fn ensure_dir_exists( + name: &'static str, + path: &Path, + notify_handler: &Fn(Notification), +) -> Result { + raw::ensure_dir_exists(path, |p| { + notify_handler(Notification::CreatingDirectory(name, p)) + }).chain_err(|| ErrorKind::CreatingDirectory { + 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, - path: PathBuf::from(path), - } + raw::read_file(path).chain_err(|| ErrorKind::ReadingFile { + 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, - path: PathBuf::from(path), - } + raw::write_file(path, contents).chain_err(|| ErrorKind::WritingFile { + 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, - path: PathBuf::from(path), - } + raw::append_file(path, line).chain_err(|| ErrorKind::WritingFile { + 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, - path: path.to_path_buf(), - } + writeln!(file, "{}", line).chain_err(|| ErrorKind::WritingFile { + 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, - path: path.to_path_buf(), - } + write!(file, "{}", s).chain_err(|| ErrorKind::WritingFile { + name: name, + path: path.to_path_buf(), }) } pub fn rename_file(name: &'static str, src: &Path, dest: &Path) -> Result<()> { - fs::rename(src, dest).chain_err(|| { - ErrorKind::RenamingFile { - name: name, - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } + fs::rename(src, dest).chain_err(|| ErrorKind::RenamingFile { + name: name, + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) } pub fn rename_dir(name: &'static str, src: &Path, dest: &Path) -> Result<()> { - fs::rename(src, dest).chain_err(|| { - ErrorKind::RenamingDirectory { - name: name, - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } + fs::rename(src, dest).chain_err(|| ErrorKind::RenamingDirectory { + name: name, + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) } -pub fn filter_file bool>(name: &'static str, - src: &Path, - dest: &Path, - filter: F) - -> Result { - raw::filter_file(src, dest, filter).chain_err(|| { - ErrorKind::FilteringFile { - name: name, - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } +pub fn filter_file bool>( + name: &'static str, + src: &Path, + dest: &Path, + filter: F, +) -> Result { + raw::filter_file(src, dest, filter).chain_err(|| ErrorKind::FilteringFile { + name: name, + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) } -pub fn match_file Option>(name: &'static str, - src: &Path, - f: F) - -> Result> { - raw::match_file(src, f).chain_err(|| { - ErrorKind::ReadingFile { - name: name, - path: PathBuf::from(src), - } +pub fn match_file Option>( + name: &'static str, + src: &Path, + f: F, +) -> Result> { + raw::match_file(src, f).chain_err(|| ErrorKind::ReadingFile { + name: name, + path: PathBuf::from(src), }) } @@ -132,46 +115,48 @@ pub fn canonicalize_path(path: &Path, notify_handler: &Fn(Notification)) -> Path } pub fn tee_file(name: &'static str, path: &Path, w: &mut W) -> Result<()> { - raw::tee_file(path, w).chain_err(|| { - ErrorKind::ReadingFile { - name: name, - path: PathBuf::from(path), - } + raw::tee_file(path, w).chain_err(|| ErrorKind::ReadingFile { + name: name, + path: PathBuf::from(path), }) } -pub fn download_file(url: &Url, - path: &Path, - hasher: Option<&mut Sha256>, - notify_handler: &Fn(Notification)) - -> Result<()> { - download_file_with_resume(&url, &path, hasher, false, ¬ify_handler) +pub fn download_file( + url: &Url, + path: &Path, + hasher: Option<&mut Sha256>, + notify_handler: &Fn(Notification), +) -> Result<()> { + download_file_with_resume(&url, &path, hasher, false, ¬ify_handler) } -pub fn download_file_with_resume(url: &Url, - path: &Path, - hasher: Option<&mut Sha256>, - resume_from_partial: bool, - notify_handler: &Fn(Notification)) - -> Result<()> { +pub fn download_file_with_resume( + url: &Url, + path: &Path, + hasher: Option<&mut Sha256>, + resume_from_partial: bool, + notify_handler: &Fn(Notification), +) -> Result<()> { use download::ErrorKind as DEK; match download_file_(url, path, hasher, resume_from_partial, notify_handler) { Ok(_) => Ok(()), Err(e) => { let is_client_error = match e.kind() { - &ErrorKind::Download(DEK::HttpStatus(400 ... 499)) => true, + &ErrorKind::Download(DEK::HttpStatus(400...499)) => true, &ErrorKind::Download(DEK::FileNotFound) => true, - _ => false + _ => false, }; - Err(e).chain_err(|| if is_client_error { - ErrorKind::DownloadNotExists { - url: url.clone(), - path: path.to_path_buf(), - } - } else { - ErrorKind::DownloadingFile { - url: url.clone(), - path: path.to_path_buf(), + Err(e).chain_err(|| { + if is_client_error { + ErrorKind::DownloadNotExists { + url: url.clone(), + path: path.to_path_buf(), + } + } else { + ErrorKind::DownloadingFile { + url: url.clone(), + path: path.to_path_buf(), + } } }) } @@ -180,17 +165,17 @@ pub fn download_file_with_resume(url: &Url, static DEPRECATED_HYPER_WARNED: AtomicBool = ATOMIC_BOOL_INIT; -fn download_file_(url: &Url, - path: &Path, - hasher: Option<&mut Sha256>, - resume_from_partial: bool, - notify_handler: &Fn(Notification)) - -> Result<()> { - +fn download_file_( + url: &Url, + path: &Path, + hasher: Option<&mut Sha256>, + resume_from_partial: bool, + notify_handler: &Fn(Notification), +) -> Result<()> { use sha2::Digest; use std::cell::RefCell; use download::download_to_path_with_backend; - use download::{self, Event, Backend}; + use download::{self, Backend, Event}; notify_handler(Notification::DownloadingFile(url, path)); @@ -205,7 +190,7 @@ fn download_file_(url: &Url, h.input(data); } } - _ => () + _ => (), } match msg { @@ -237,7 +222,7 @@ fn download_file_(url: &Url, (Backend::Curl, Notification::UsingCurl) }; notify_handler(notification); - try!(download_to_path_with_backend(backend, url, path, resume_from_partial, Some(callback))); + download_to_path_with_backend(backend, url, path, resume_from_partial, Some(callback))?; notify_handler(Notification::DownloadFinished); @@ -249,16 +234,16 @@ pub fn parse_url(url: &str) -> Result { } pub fn cmd_status(name: &'static str, cmd: &mut Command) -> Result<()> { - raw::cmd_status(cmd).chain_err(|| { - ErrorKind::RunningCommand { - name: OsString::from(name), - } + raw::cmd_status(cmd).chain_err(|| ErrorKind::RunningCommand { + name: OsString::from(name), }) } pub fn assert_is_file(path: &Path) -> Result<()> { if !is_file(path) { - Err(ErrorKind::NotAFile { path: PathBuf::from(path) }.into()) + Err(ErrorKind::NotAFile { + path: PathBuf::from(path), + }.into()) } else { Ok(()) } @@ -266,7 +251,9 @@ pub fn assert_is_file(path: &Path) -> Result<()> { pub fn assert_is_directory(path: &Path) -> Result<()> { if !is_directory(path) { - Err(ErrorKind::NotADirectory { path: PathBuf::from(path) }.into()) + Err(ErrorKind::NotADirectory { + path: PathBuf::from(path), + }.into()) } else { Ok(()) } @@ -274,11 +261,9 @@ pub fn assert_is_directory(path: &Path) -> Result<()> { pub fn symlink_dir(src: &Path, dest: &Path, notify_handler: &Fn(Notification)) -> Result<()> { notify_handler(Notification::LinkingDirectory(src, dest)); - raw::symlink_dir(src, dest).chain_err(|| { - ErrorKind::LinkingDirectory { - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } + raw::symlink_dir(src, dest).chain_err(|| ErrorKind::LinkingDirectory { + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) } @@ -290,21 +275,17 @@ pub fn hard_or_symlink_file(src: &Path, dest: &Path) -> Result<()> { } pub fn hardlink_file(src: &Path, dest: &Path) -> Result<()> { - raw::hardlink(src, dest).chain_err(|| { - ErrorKind::LinkingFile { - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } + raw::hardlink(src, dest).chain_err(|| ErrorKind::LinkingFile { + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) } #[cfg(unix)] pub fn symlink_file(src: &Path, dest: &Path) -> Result<()> { - ::std::os::unix::fs::symlink(src, dest).chain_err(|| { - ErrorKind::LinkingFile { - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } + ::std::os::unix::fs::symlink(src, dest).chain_err(|| ErrorKind::LinkingFile { + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) } @@ -312,58 +293,51 @@ pub fn symlink_file(src: &Path, dest: &Path) -> Result<()> { pub fn symlink_file(src: &Path, dest: &Path) -> Result<()> { // we are supposed to not use symlink on windows Err(ErrorKind::LinkingFile { - src: PathBuf::from(src), - dest: PathBuf::from(dest), - }.into() - ) + src: PathBuf::from(src), + dest: PathBuf::from(dest), + }.into()) } pub fn copy_dir(src: &Path, dest: &Path, notify_handler: &Fn(Notification)) -> Result<()> { notify_handler(Notification::CopyingDirectory(src, dest)); - raw::copy_dir(src, dest).chain_err(|| { - ErrorKind::CopyingDirectory { - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } + raw::copy_dir(src, dest).chain_err(|| ErrorKind::CopyingDirectory { + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) } pub fn copy_file(src: &Path, dest: &Path) -> Result<()> { fs::copy(src, dest) - .chain_err(|| { - ErrorKind::CopyingFile { - src: PathBuf::from(src), - dest: PathBuf::from(dest), - } + .chain_err(|| ErrorKind::CopyingFile { + src: PathBuf::from(src), + dest: PathBuf::from(dest), }) .map(|_| ()) } -pub fn remove_dir(name: &'static str, path: &Path, notify_handler: &Fn(Notification)) -> Result<()> { +pub fn remove_dir( + name: &'static str, + path: &Path, + notify_handler: &Fn(Notification), +) -> Result<()> { notify_handler(Notification::RemovingDirectory(name, path)); - raw::remove_dir(path).chain_err(|| { - ErrorKind::RemovingDirectory { - name: name, - path: PathBuf::from(path), - } + raw::remove_dir(path).chain_err(|| ErrorKind::RemovingDirectory { + 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, - path: PathBuf::from(path), - } + fs::remove_file(path).chain_err(|| ErrorKind::RemovingFile { + 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, - path: PathBuf::from(path), - } + fs::read_dir(path).chain_err(|| ErrorKind::ReadingDirectory { + name: name, + path: PathBuf::from(path), }) } @@ -371,24 +345,20 @@ pub fn open_browser(path: &Path) -> Result<()> { match raw::open_browser(path) { Ok(true) => Ok(()), Ok(false) => Err("no browser installed".into()), - Err(e) => Err(e).chain_err(|| "could not open browser") + Err(e) => Err(e).chain_err(|| "could not open browser"), } } pub fn set_permissions(path: &Path, perms: fs::Permissions) -> Result<()> { - fs::set_permissions(path, perms).chain_err(|| { - ErrorKind::SettingPermissions { - path: PathBuf::from(path), - } + fs::set_permissions(path, perms).chain_err(|| ErrorKind::SettingPermissions { + path: PathBuf::from(path), }) } pub fn file_size(path: &Path) -> Result { - let metadata = fs::metadata(path).chain_err(|| { - ErrorKind::ReadingFile { - name: "metadata for", - path: PathBuf::from(path), - } + let metadata = fs::metadata(path).chain_err(|| ErrorKind::ReadingFile { + name: "metadata for", + path: PathBuf::from(path), })?; Ok(metadata.len()) } @@ -402,11 +372,9 @@ pub fn make_executable(path: &Path) -> Result<()> { fn inner(path: &Path) -> Result<()> { use std::os::unix::fs::PermissionsExt; - let metadata = try!(fs::metadata(path).chain_err(|| { - ErrorKind::SettingPermissions { - path: PathBuf::from(path), - } - })); + let metadata = fs::metadata(path).chain_err(|| ErrorKind::SettingPermissions { + path: PathBuf::from(path), + })?; let mut perms = metadata.permissions(); let new_mode = (perms.mode() & !0o777) | 0o755; perms.set_mode(new_mode); @@ -438,28 +406,35 @@ pub fn to_absolute>(path: P) -> Result { #[cfg(windows)] pub fn home_dir() -> Option { use std::ptr; - use kernel32::{GetCurrentProcess, GetLastError, CloseHandle}; + use kernel32::{CloseHandle, GetCurrentProcess, GetLastError}; use advapi32::OpenProcessToken; use userenv::GetUserProfileDirectoryW; use winapi::ERROR_INSUFFICIENT_BUFFER; use winapi::winnt::TOKEN_READ; use scopeguard; - ::std::env::var_os("USERPROFILE").map(PathBuf::from).or_else(|| unsafe { - let me = GetCurrentProcess(); - let mut token = ptr::null_mut(); - if OpenProcessToken(me, TOKEN_READ, &mut token) == 0 { - return None; - } - let _g = scopeguard::guard(token, |h| { let _ = CloseHandle(*h); }); - fill_utf16_buf(|buf, mut sz| { - match GetUserProfileDirectoryW(token, buf, &mut sz) { - 0 if GetLastError() != ERROR_INSUFFICIENT_BUFFER => 0, - 0 => sz, - _ => sz - 1, // sz includes the null terminator + ::std::env::var_os("USERPROFILE") + .map(PathBuf::from) + .or_else(|| unsafe { + let me = GetCurrentProcess(); + let mut token = ptr::null_mut(); + if OpenProcessToken(me, TOKEN_READ, &mut token) == 0 { + return None; } - }, os2path).ok() - }) + let _g = scopeguard::guard(token, |h| { + let _ = CloseHandle(*h); + }); + fill_utf16_buf( + |buf, mut sz| { + match GetUserProfileDirectoryW(token, buf, &mut sz) { + 0 if GetLastError() != ERROR_INSUFFICIENT_BUFFER => 0, + 0 => sz, + _ => sz - 1, // sz includes the null terminator + } + }, + os2path, + ).ok() + }) } #[cfg(windows)] @@ -470,11 +445,12 @@ fn os2path(s: &[u16]) -> PathBuf { #[cfg(windows)] fn fill_utf16_buf(mut f1: F1, f2: F2) -> io::Result - where F1: FnMut(*mut u16, DWORD) -> DWORD, - F2: FnOnce(&[u16]) -> T +where + F1: FnMut(*mut u16, DWORD) -> DWORD, + F2: FnOnce(&[u16]) -> T, { use kernel32::{GetLastError, SetLastError}; - use winapi::{ERROR_INSUFFICIENT_BUFFER}; + use winapi::ERROR_INSUFFICIENT_BUFFER; // Start off with a stack buf but then spill over to the heap if we end up // needing more space. @@ -512,7 +488,7 @@ fn fill_utf16_buf(mut f1: F1, f2: F2) -> io::Result } else if k >= n { n = k; } else { - return Ok(f2(&buf[..k])) + return Ok(f2(&buf[..k])); } } } @@ -533,22 +509,20 @@ pub fn cargo_home() -> Result { // install to the wrong place. This check is to make the // multirust-rs to rustup upgrade seamless. let env_var = if let Some(v) = env_var { - let vv = v.to_string_lossy().to_string(); - if vv.contains(".multirust/cargo") || - vv.contains(r".multirust\cargo") || - vv.trim().is_empty() { - None - } else { - Some(v) - } + let vv = v.to_string_lossy().to_string(); + if vv.contains(".multirust/cargo") || vv.contains(r".multirust\cargo") + || vv.trim().is_empty() + { + None + } else { + Some(v) + } } else { None }; - let cwd = try!(env::current_dir().chain_err(|| ErrorKind::CargoHome)); - let cargo_home = env_var.clone().map(|home| { - cwd.join(home) - }); + let cwd = env::current_dir().chain_err(|| ErrorKind::CargoHome)?; + let cargo_home = env_var.clone().map(|home| cwd.join(home)); let user_home = home_dir().map(|p| p.join(".cargo")); cargo_home.or(user_home).ok_or(ErrorKind::CargoHome.into()) } @@ -556,7 +530,6 @@ pub fn cargo_home() -> Result { // Convert the ~/.multirust folder to ~/.rustup while dealing with rustup.sh // metadata, which used to also live in ~/.rustup, but now lives in ~/rustup.sh. pub fn do_rustup_home_upgrade() -> bool { - fn rustup_home_is_set() -> bool { env::var_os("RUSTUP_HOME").is_some() } @@ -593,8 +566,7 @@ pub fn do_rustup_home_upgrade() -> bool { fn delete_rustup_dir() -> Result<()> { if let Some(dir) = rustup_dir() { - raw::remove_dir(&dir) - .chain_err(|| "unable to delete rustup dir")?; + raw::remove_dir(&dir).chain_err(|| "unable to delete rustup dir")?; } Ok(()) @@ -603,8 +575,7 @@ pub fn do_rustup_home_upgrade() -> bool { fn rename_rustup_dir_to_rustup_sh() -> Result<()> { let dirs = (rustup_dir(), rustup_sh_dir()); if let (Some(rustup), Some(rustup_sh)) = dirs { - fs::rename(&rustup, &rustup_sh) - .chain_err(|| "unable to rename rustup dir")?; + fs::rename(&rustup, &rustup_sh).chain_err(|| "unable to rename rustup dir")?; } Ok(()) @@ -613,8 +584,7 @@ pub fn do_rustup_home_upgrade() -> bool { fn rename_multirust_dir_to_rustup() -> Result<()> { let dirs = (multirust_dir(), rustup_dir()); if let (Some(rustup), Some(rustup_sh)) = dirs { - fs::rename(&rustup, &rustup_sh) - .chain_err(|| "unable to rename multirust dir")?; + fs::rename(&rustup, &rustup_sh).chain_err(|| "unable to rename multirust dir")?; } Ok(()) @@ -622,7 +592,9 @@ pub fn do_rustup_home_upgrade() -> bool { // If RUSTUP_HOME is set then its default path doesn't matter, so we're // not going to risk doing any I/O work and making a mess. - if rustup_home_is_set() { return true } + if rustup_home_is_set() { + return true; + } // Now we are just trying to get a bogus, rustup.sh-created ~/.rustup out // of the way in the manner that is least likely to take time and generate @@ -679,11 +651,12 @@ pub fn create_rustup_home() -> Result<()> { // If RUSTUP_HOME is set then don't make any assumptions about where it's // ok to put ~/.multirust - if env::var_os("RUSTUP_HOME").is_some() { return Ok(()) } + if env::var_os("RUSTUP_HOME").is_some() { + return Ok(()); + } let home = rustup_home_in_user_dir()?; - fs::create_dir_all(&home) - .chain_err(|| "unable to create ~/.rustup")?; + fs::create_dir_all(&home).chain_err(|| "unable to create ~/.rustup")?; // This is a temporary compatibility symlink create_legacy_multirust_symlink()?; @@ -701,9 +674,13 @@ fn create_legacy_multirust_symlink() -> Result<()> { return Ok(()); } - raw::symlink_dir(&newhome, &oldhome) - .chain_err(|| format!("unable to symlink {} from {}", - newhome.display(), oldhome.display()))?; + raw::symlink_dir(&newhome, &oldhome).chain_err(|| { + format!( + "unable to symlink {} from {}", + newhome.display(), + oldhome.display() + ) + })?; Ok(()) } @@ -712,8 +689,8 @@ pub fn delete_legacy_multirust_symlink() -> Result<()> { let oldhome = legacy_multirust_home()?; if oldhome.exists() { - let meta = fs::symlink_metadata(&oldhome) - .chain_err(|| "unable to get metadata for ~/.multirust")?; + let meta = + fs::symlink_metadata(&oldhome).chain_err(|| "unable to get metadata for ~/.multirust")?; if meta.file_type().is_symlink() { // remove_dir handles unlinking symlinks raw::remove_dir(&oldhome) @@ -739,16 +716,16 @@ pub fn rustup_home_in_user_dir() -> Result { pub fn rustup_home() -> Result { let use_rustup_dir = do_rustup_home_upgrade(); - let cwd = try!(env::current_dir().chain_err(|| ErrorKind::RustupHome)); - let rustup_home = env::var_os("RUSTUP_HOME").map(|home| { - cwd.join(home) - }); + let cwd = env::current_dir().chain_err(|| ErrorKind::RustupHome)?; + let rustup_home = env::var_os("RUSTUP_HOME").map(|home| cwd.join(home)); let user_home = if use_rustup_dir { dot_dir(".rustup") } else { dot_dir(".multirust") }; - rustup_home.or(user_home).ok_or(ErrorKind::RustupHome.into()) + rustup_home + .or(user_home) + .ok_or(ErrorKind::RustupHome.into()) } pub fn format_path_for_display(path: &str) -> String { @@ -789,15 +766,17 @@ pub fn string_from_winreg_value(val: &winreg::RegValue) -> Option { } else { return None; }; - while s.ends_with('\u{0}') {s.pop();} + while s.ends_with('\u{0}') { + s.pop(); + } Some(s) } - _ => None + _ => None, } } pub fn toolchain_sort>(v: &mut Vec) { - use semver::{Version, Identifier}; + use semver::{Identifier, Version}; fn special_version(ord: u64, s: &str) -> Version { Version { @@ -830,7 +809,6 @@ pub fn toolchain_sort>(v: &mut Vec) { }); } - #[cfg(test)] mod tests { use super::*; diff --git a/src/rustup-win-installer/build.rs b/src/rustup-win-installer/build.rs index eb1bafcf1a..1af2175fe6 100644 --- a/src/rustup-win-installer/build.rs +++ b/src/rustup-win-installer/build.rs @@ -12,7 +12,8 @@ fn main() { println!("cargo:rustc-link-lib=static=wcautil"); println!("cargo:rustc-link-lib=static=dutil"); - let wix_path = env::var("WIX").expect("WIX must be installed, and 'WIX' environment variable must be set"); + let wix_path = + env::var("WIX").expect("WIX must be installed, and 'WIX' environment variable must be set"); // For the correct WIX library path, we need to know which VS version we are using. // We use the `gcc` crate's functionality to do this, which should always match what rustc is doing. @@ -21,18 +22,25 @@ fn main() { VsVers::Vs14 => "VS2015", VsVers::Vs15 => "VS2017", VsVers::Vs12 => panic!("Unsupported VS version: Vs12"), - _ => panic!("Unsupported VS version") // FIXME: should use {:?}, but `VsVers` does not yet implement `Debug` + _ => panic!("Unsupported VS version"), // FIXME: should use {:?}, but `VsVers` does not yet implement `Debug` }; - println!("cargo:warning=Using WIX libraries for VS version: {}", vs_version_string); + println!( + "cargo:warning=Using WIX libraries for VS version: {}", + vs_version_string + ); - let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("cannot read CARGO_CFG_TARGET_ARCH in build script"); + let target_arch = env::var("CARGO_CFG_TARGET_ARCH") + .expect("cannot read CARGO_CFG_TARGET_ARCH in build script"); let target_arch = match target_arch.as_str() { "x86" => "x86", "x86_64" => "x64", - other => panic!("Target architecture {} not supported by WIX.", other) + other => panic!("Target architecture {} not supported by WIX.", other), }; - + // Tell cargo about the WIX SDK path for `wcautil.lib` and `dutil.lib` - println!("cargo:rustc-link-search=native={}SDK\\{}\\lib\\{}", wix_path, vs_version_string, target_arch); -} \ No newline at end of file + println!( + "cargo:rustc-link-search=native={}SDK\\{}\\lib\\{}", + wix_path, vs_version_string, target_arch + ); +} diff --git a/src/rustup-win-installer/src/lib.rs b/src/rustup-win-installer/src/lib.rs index beee59f3f7..d524e08e97 100644 --- a/src/rustup-win-installer/src/lib.rs +++ b/src/rustup-win-installer/src/lib.rs @@ -1,12 +1,12 @@ #![allow(non_snake_case)] -extern crate winapi; extern crate rustup; +extern crate winapi; use std::ffi::CString; use std::path::PathBuf; use std::collections::HashMap; -use ::winapi::{HRESULT, PCSTR, UINT, LPCWSTR, LPWSTR, LPVOID}; +use winapi::{HRESULT, LPCWSTR, LPVOID, LPWSTR, PCSTR, UINT}; pub type MSIHANDLE = u32; @@ -15,8 +15,16 @@ pub const LOGMSG_VERBOSE: i32 = 1; pub const LOGMSG_STANDARD: i32 = 2; // TODO: share this with self_update.rs -static TOOLS: &'static [&'static str] - = &["rustc", "rustdoc", "cargo", "rust-lldb", "rust-gdb", "rls", "rustfmt", "cargo-fmt"]; +static TOOLS: &'static [&'static str] = &[ + "rustc", + "rustdoc", + "cargo", + "rust-lldb", + "rust-gdb", + "rls", + "rustfmt", + "cargo-fmt", +]; #[no_mangle] /// This is be run as a `deferred` action after `InstallFiles` on install and upgrade @@ -86,7 +94,9 @@ fn from_wide_ptr(ptr: *const u16) -> String { use std::os::windows::ffi::OsStringExt; unsafe { assert!(!ptr.is_null()); - let len = (0..std::isize::MAX).position(|i| *ptr.offset(i) == 0).unwrap(); + let len = (0..std::isize::MAX) + .position(|i| *ptr.offset(i) == 0) + .unwrap(); let slice = std::slice::from_raw_parts(ptr, len); OsString::from_wide(slice).to_string_lossy().into_owned() } @@ -95,7 +105,10 @@ fn from_wide_ptr(ptr: *const u16) -> String { fn to_wide_chars(s: &str) -> Vec { use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; - OsStr::new(s).encode_wide().chain(Some(0).into_iter()).collect::>() + OsStr::new(s) + .encode_wide() + .chain(Some(0).into_iter()) + .collect::>() } extern "system" { @@ -107,4 +120,4 @@ extern "system" { extern "cdecl" { fn WcaLog(llv: i32, fmt: PCSTR); -} \ No newline at end of file +} diff --git a/src/rustup/command.rs b/src/rustup/command.rs index d8a1f460cb..853ecf14ba 100644 --- a/src/rustup/command.rs +++ b/src/rustup/command.rs @@ -1,6 +1,6 @@ use std::ffi::OsStr; use std::fs::File; -use std::io::{self, Write, BufRead, BufReader, Seek, SeekFrom}; +use std::io::{self, BufRead, BufReader, Seek, SeekFrom, Write}; use std::process::{self, Command, Stdio}; use std::time::Instant; use regex::Regex; @@ -12,21 +12,25 @@ use notifications::*; use rustup_utils; use telemetry::{Telemetry, TelemetryEvent}; - -pub fn run_command_for_dir>(cmd: Command, - arg0: &str, - args: &[S], - cfg: &Cfg) -> Result<()> { - if (arg0 == "rustc" || arg0 == "rustc.exe") && try!(cfg.telemetry_enabled()) { +pub fn run_command_for_dir>( + cmd: Command, + arg0: &str, + args: &[S], + cfg: &Cfg, +) -> Result<()> { + if (arg0 == "rustc" || arg0 == "rustc.exe") && cfg.telemetry_enabled()? { return telemetry_rustc(cmd, arg0, args, cfg); } exec_command_for_dir_without_telemetry(cmd, arg0, args) } -fn telemetry_rustc>(mut cmd: Command, - arg0: &str, - args: &[S], cfg: &Cfg) -> Result<()> { +fn telemetry_rustc>( + mut cmd: Command, + arg0: &str, + args: &[S], + cfg: &Cfg, +) -> Result<()> { #[cfg(unix)] fn file_as_stdio(file: &File) -> Stdio { use std::os::unix::io::{AsRawFd, FromRawFd}; @@ -48,8 +52,7 @@ fn telemetry_rustc>(mut cmd: Command, e.starts_with("--color") }); - if stderr_isatty() && !has_color_args - { + if stderr_isatty() && !has_color_args { cmd.arg("--color"); cmd.arg("always"); } @@ -60,10 +63,10 @@ fn telemetry_rustc>(mut cmd: Command, // FIXME rust-lang/rust#32254. It's not clear to me // when and why this is needed. let mut cmd = cmd.stdin(Stdio::inherit()) - .stdout(Stdio::inherit()) - .stderr(cmd_err_stdio) - .spawn() - .unwrap(); + .stdout(Stdio::inherit()) + .stderr(cmd_err_stdio) + .spawn() + .unwrap(); let status = cmd.wait(); @@ -98,28 +101,41 @@ fn telemetry_rustc>(mut cmd: Command, if let Some(caps) = re.captures(&b) { if caps.len() > 0 { - errors.push(caps.name("error").map(|m| m.as_str()).unwrap_or("").to_owned()); + errors.push( + caps.name("error") + .map(|m| m.as_str()) + .unwrap_or("") + .to_owned(), + ); } }; } - let e = if errors.is_empty() { None } else { Some(errors) }; + let e = if errors.is_empty() { + None + } else { + Some(errors) + }; - let te = TelemetryEvent::RustcRun { duration_ms: ms, - exit_code: exit_code, - errors: e }; + let te = TelemetryEvent::RustcRun { + duration_ms: ms, + exit_code: exit_code, + errors: e, + }; let _ = t.log_telemetry(te).map_err(|xe| { (cfg.notify_handler)(Notification::TelemetryCleanupError(&xe)); }); process::exit(exit_code); - }, + } Err(e) => { let exit_code = e.raw_os_error().unwrap_or(1); - let te = TelemetryEvent::RustcRun { duration_ms: ms, - exit_code: exit_code, - errors: None }; + let te = TelemetryEvent::RustcRun { + duration_ms: ms, + exit_code: exit_code, + errors: None, + }; let _ = t.log_telemetry(te).map_err(|xe| { (cfg.notify_handler)(Notification::TelemetryCleanupError(&xe)); @@ -128,13 +144,15 @@ fn telemetry_rustc>(mut cmd: Command, Err(e).chain_err(|| rustup_utils::ErrorKind::RunningCommand { name: OsStr::new(arg0).to_owned(), }) - }, + } } } fn exec_command_for_dir_without_telemetry>( - mut cmd: Command, arg0: &str, args: &[S]) -> Result<()> -{ + mut cmd: Command, + arg0: &str, + args: &[S], +) -> Result<()> { cmd.args(args); // FIXME rust-lang/rust#32254. It's not clear to me @@ -172,8 +190,7 @@ fn stderr_isatty() -> bool { const STD_ERROR_HANDLE: DWORD = -12i32 as DWORD; extern "system" { fn GetStdHandle(which: DWORD) -> HANDLE; - fn GetConsoleMode(hConsoleHandle: HANDLE, - lpMode: *mut DWORD) -> BOOL; + fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *mut DWORD) -> BOOL; } unsafe { let handle = GetStdHandle(STD_ERROR_HANDLE); diff --git a/src/rustup/config.rs b/src/rustup/config.rs index e915dacbc9..0e354f4998 100644 --- a/src/rustup/config.rs +++ b/src/rustup/config.rs @@ -8,11 +8,11 @@ use std::sync::Arc; use errors::*; use notifications::*; -use rustup_dist::{temp, dist}; +use rustup_dist::{dist, temp}; use rustup_utils::utils; use toolchain::{Toolchain, UpdateStatus}; use telemetry_analysis::*; -use settings::{TelemetryMode, SettingsFile, Settings, DEFAULT_METADATA_VERSION}; +use settings::{Settings, SettingsFile, TelemetryMode, DEFAULT_METADATA_VERSION}; #[derive(Debug)] pub enum OverrideReason { @@ -52,36 +52,33 @@ pub struct Cfg { impl Cfg { pub fn from_env(notify_handler: Arc) -> Result { // Set up the rustup home directory - let rustup_dir = try!(utils::rustup_home()); + let rustup_dir = utils::rustup_home()?; - try!(utils::ensure_dir_exists("home", &rustup_dir, - &|n| notify_handler(n.into()))); + utils::ensure_dir_exists("home", &rustup_dir, &|n| notify_handler(n.into()))?; let settings_file = SettingsFile::new(rustup_dir.join("settings.toml")); // Convert from old settings format if necessary - try!(settings_file.maybe_upgrade_from_legacy(&rustup_dir)); + settings_file.maybe_upgrade_from_legacy(&rustup_dir)?; let toolchains_dir = rustup_dir.join("toolchains"); let update_hash_dir = rustup_dir.join("update-hashes"); let download_dir = rustup_dir.join("downloads"); // GPG key - let gpg_key = if let Some(path) = env::var_os("RUSTUP_GPG_KEY") - .and_then(utils::if_not_empty) { - Cow::Owned(try!(utils::read_file("public key", Path::new(&path)))) - } else { - Cow::Borrowed(include_str!("rust-key.gpg.ascii")) - }; + let gpg_key = + if let Some(path) = env::var_os("RUSTUP_GPG_KEY").and_then(utils::if_not_empty) { + Cow::Owned(utils::read_file("public key", Path::new(&path))?) + } else { + Cow::Borrowed(include_str!("rust-key.gpg.ascii")) + }; // Environment override let env_override = env::var("RUSTUP_TOOLCHAIN") - .ok() - .and_then(utils::if_not_empty); + .ok() + .and_then(utils::if_not_empty); let dist_root_server = match env::var("RUSTUP_DIST_SERVER") { - Ok(ref s) if !s.is_empty() => { - s.clone() - } + Ok(ref s) if !s.is_empty() => s.clone(), _ => { // For backward compatibility env::var("RUSTUP_DIST_ROOT") @@ -95,11 +92,11 @@ impl Cfg { }; let notify_clone = notify_handler.clone(); - let temp_cfg = temp::Cfg::new(rustup_dir.join("tmp"), - dist_root_server.as_str(), - Box::new(move |n| { - (notify_clone)(n.into()) - })); + let temp_cfg = temp::Cfg::new( + rustup_dir.join("tmp"), + dist_root_server.as_str(), + Box::new(move |n| (notify_clone)(n.into())), + ); let dist_root = dist_root_server.clone() + "/dist"; Ok(Cfg { @@ -118,43 +115,42 @@ impl Cfg { } pub fn set_default(&self, toolchain: &str) -> Result<()> { - try!(self.settings_file.with_mut(|s| { + self.settings_file.with_mut(|s| { s.default_toolchain = Some(toolchain.to_owned()); Ok(()) - })); + })?; (self.notify_handler)(Notification::SetDefaultToolchain(toolchain)); Ok(()) } pub fn get_toolchain(&self, name: &str, create_parent: bool) -> Result { if create_parent { - try!(utils::ensure_dir_exists("toolchains", - &self.toolchains_dir, - &|n| (self.notify_handler)(n.into()))); + utils::ensure_dir_exists("toolchains", &self.toolchains_dir, &|n| { + (self.notify_handler)(n.into()) + })?; } Toolchain::from(self, name) } pub fn verify_toolchain(&self, name: &str) -> Result { - let toolchain = try!(self.get_toolchain(name, false)); - try!(toolchain.verify()); + let toolchain = self.get_toolchain(name, false)?; + toolchain.verify()?; Ok(toolchain) } pub fn get_hash_file(&self, toolchain: &str, create_parent: bool) -> Result { if create_parent { - try!(utils::ensure_dir_exists("update-hash", - &self.update_hash_dir, - &|n| (self.notify_handler)(n.into()))); + utils::ensure_dir_exists("update-hash", &self.update_hash_dir, &|n| { + (self.notify_handler)(n.into()) + })?; } Ok(self.update_hash_dir.join(toolchain)) } pub fn which_binary(&self, path: &Path, binary: &str) -> Result> { - - if let Some((toolchain, _)) = try!(self.find_override_toolchain_or_default(path)) { + if let Some((toolchain, _)) = self.find_override_toolchain_or_default(path)? { Ok(Some(toolchain.binary_file(binary))) } else { Ok(None) @@ -162,35 +158,36 @@ impl Cfg { } pub fn upgrade_data(&self) -> Result<()> { - - let current_version = try!(self.settings_file.with(|s| Ok(s.version.clone()))); + let current_version = self.settings_file.with(|s| Ok(s.version.clone()))?; if current_version == DEFAULT_METADATA_VERSION { - (self.notify_handler) - (Notification::MetadataUpgradeNotNeeded(¤t_version)); + (self.notify_handler)(Notification::MetadataUpgradeNotNeeded(¤t_version)); return Ok(()); } - (self.notify_handler) - (Notification::UpgradingMetadata(¤t_version, DEFAULT_METADATA_VERSION)); + (self.notify_handler)(Notification::UpgradingMetadata( + ¤t_version, + DEFAULT_METADATA_VERSION, + )); match &*current_version { "2" => { // The toolchain installation format changed. Just delete them all. (self.notify_handler)(Notification::UpgradeRemovesToolchains); - let dirs = try!(utils::read_dir("toolchains", &self.toolchains_dir)); + let dirs = utils::read_dir("toolchains", &self.toolchains_dir)?; for dir in dirs { - let dir = try!(dir.chain_err(|| ErrorKind::UpgradeIoError)); - try!(utils::remove_dir("toolchain", &dir.path(), - &|n| (self.notify_handler)(n.into()))); + let dir = dir.chain_err(|| ErrorKind::UpgradeIoError)?; + utils::remove_dir("toolchain", &dir.path(), &|n| { + (self.notify_handler)(n.into()) + })?; } // Also delete the update hashes - let files = try!(utils::read_dir("update hashes", &self.update_hash_dir)); + let files = utils::read_dir("update hashes", &self.update_hash_dir)?; for file in files { - let file = try!(file.chain_err(|| ErrorKind::UpgradeIoError)); - try!(utils::remove_file("update hash", &file.path())); + let file = file.chain_err(|| ErrorKind::UpgradeIoError)?; + utils::remove_file("update hash", &file.path())?; } self.settings_file.with_mut(|s| { @@ -204,19 +201,21 @@ impl Cfg { pub fn delete_data(&self) -> Result<()> { if utils::path_exists(&self.rustup_dir) { - Ok(try!(utils::remove_dir("home", &self.rustup_dir, - &|n| (self.notify_handler)(n.into())))) + Ok(utils::remove_dir("home", &self.rustup_dir, &|n| { + (self.notify_handler)(n.into()) + })?) } else { Ok(()) } } pub fn find_default(&self) -> Result> { - let opt_name = try!(self.settings_file.with(|s| Ok(s.default_toolchain.clone()))); + let opt_name = self.settings_file + .with(|s| Ok(s.default_toolchain.clone()))?; if let Some(name) = opt_name { - let toolchain = try!(self.verify_toolchain(&name) - .chain_err(|| ErrorKind::ToolchainNotInstalled(name.to_string()))); + let toolchain = self.verify_toolchain(&name) + .chain_err(|| ErrorKind::ToolchainNotInstalled(name.to_string()))?; Ok(Some(toolchain)) } else { @@ -248,15 +247,17 @@ impl Cfg { // on a line after the proximate error. let reason_err = match reason { - OverrideReason::Environment => { - format!("the RUSTUP_TOOLCHAIN environment variable specifies an uninstalled toolchain") - } - OverrideReason::OverrideDB(ref path) => { - format!("the directory override for '{}' specifies an uninstalled toolchain", path.display()) - } - OverrideReason::ToolchainFile(ref path) => { - format!("the toolchain file at '{}' specifies an uninstalled toolchain", path.display()) - } + OverrideReason::Environment => format!( + "the RUSTUP_TOOLCHAIN environment variable specifies an uninstalled toolchain" + ), + OverrideReason::OverrideDB(ref path) => format!( + "the directory override for '{}' specifies an uninstalled toolchain", + path.display() + ), + OverrideReason::ToolchainFile(ref path) => format!( + "the toolchain file at '{}' specifies an uninstalled toolchain", + path.display() + ), }; match self.get_toolchain(&name, false) { @@ -264,29 +265,30 @@ impl Cfg { if toolchain.exists() { Ok(Some((toolchain, reason))) } else if toolchain.is_custom() { - // Strip the confusing NotADirectory error and only mention that the override - // toolchain is not installed. - Err(Error::from(reason_err)) - .chain_err(|| ErrorKind::OverrideToolchainNotInstalled(name.to_string())) + // Strip the confusing NotADirectory error and only mention that the + // override toolchain is not installed. + Err(Error::from(reason_err)).chain_err(|| { + ErrorKind::OverrideToolchainNotInstalled(name.to_string()) + }) } else { - try!(toolchain.install_from_dist()); + toolchain.install_from_dist()?; Ok(Some((toolchain, reason))) } } - Err(e) => { - Err(e) - .chain_err(|| Error::from(reason_err)) - .chain_err(|| ErrorKind::OverrideToolchainNotInstalled(name.to_string())) - } + Err(e) => Err(e) + .chain_err(|| Error::from(reason_err)) + .chain_err(|| ErrorKind::OverrideToolchainNotInstalled(name.to_string())), } } else { Ok(None) } } - fn find_override_from_dir_walk(&self, dir: &Path, settings: &Settings) - -> Result> - { + fn find_override_from_dir_walk( + &self, + dir: &Path, + settings: &Settings, + ) -> Result> { let notify = self.notify_handler.as_ref(); let dir = utils::canonicalize_path(dir, &|n| notify(n.into())); let mut dir = Some(&*dir); @@ -303,10 +305,13 @@ impl Cfg { if let Ok(s) = utils::read_file("toolchain file", &toolchain_file) { if let Some(s) = s.lines().next() { let toolchain_name = s.trim(); - dist::validate_channel_name(&toolchain_name) - .chain_err(|| format!("invalid channel name '{}' in '{}'", - toolchain_name, - toolchain_file.display()))?; + dist::validate_channel_name(&toolchain_name).chain_err(|| { + format!( + "invalid channel name '{}' in '{}'", + toolchain_name, + toolchain_file.display() + ) + })?; let reason = OverrideReason::ToolchainFile(toolchain_file); return Ok(Some((toolchain_name.to_string(), reason))); @@ -319,32 +324,31 @@ impl Cfg { Ok(None) } - pub fn find_override_toolchain_or_default - (&self, - path: &Path) - -> Result)>> { - Ok(if let Some((toolchain, reason)) = try!(self.find_override(path)) { - Some((toolchain, Some(reason))) - } else { - try!(self.find_default()).map(|toolchain| (toolchain, None)) - }) + pub fn find_override_toolchain_or_default( + &self, + path: &Path, + ) -> Result)>> { + Ok( + if let Some((toolchain, reason)) = self.find_override(path)? { + Some((toolchain, Some(reason))) + } else { + self.find_default()?.map(|toolchain| (toolchain, None)) + }, + ) } pub fn get_default(&self) -> Result { - self.settings_file.with(|s| { - Ok(s.default_toolchain.clone().unwrap()) - }) + self.settings_file + .with(|s| Ok(s.default_toolchain.clone().unwrap())) } - - pub fn list_toolchains(&self) -> Result> { if utils::is_directory(&self.toolchains_dir) { - let mut toolchains: Vec<_> = try!(utils::read_dir("toolchains", &self.toolchains_dir)) - .filter_map(io::Result::ok) - .filter(|e| e.file_type().map(|f| !f.is_file()).unwrap_or(false)) - .filter_map(|e| e.file_name().into_string().ok()) - .collect(); + let mut toolchains: Vec<_> = utils::read_dir("toolchains", &self.toolchains_dir)? + .filter_map(io::Result::ok) + .filter(|e| e.file_type().map(|f| !f.is_file()).unwrap_or(false)) + .filter_map(|e| e.file_name().into_string().ok()) + .collect(); utils::toolchain_sort(&mut toolchains); @@ -355,16 +359,15 @@ impl Cfg { } pub fn update_all_channels(&self) -> Result)>> { - let toolchains = try!(self.list_toolchains()); + let toolchains = self.list_toolchains()?; // Convert the toolchain strings to Toolchain values let toolchains = toolchains.into_iter(); let toolchains = toolchains.map(|n| (n.clone(), self.get_toolchain(&n, true))); // Filter out toolchains that don't track a release channel - let toolchains = toolchains.filter(|&(_, ref t)| { - t.as_ref().map(|t| t.is_tracking()).unwrap_or(false) - }); + let toolchains = + toolchains.filter(|&(_, ref t)| t.as_ref().map(|t| t.is_tracking()).unwrap_or(false)); // Update toolchains and collect the results let toolchains = toolchains.map(|(n, t)| { @@ -383,7 +386,7 @@ impl Cfg { } pub fn check_metadata_version(&self) -> Result<()> { - try!(utils::assert_is_directory(&self.rustup_dir)); + utils::assert_is_directory(&self.rustup_dir)?; self.settings_file.with(|s| { (self.notify_handler)(Notification::ReadMetadataVersion(&s.version)); @@ -401,23 +404,27 @@ impl Cfg { } pub fn create_command_for_dir(&self, path: &Path, binary: &str) -> Result { - let (ref toolchain, _) = try!(self.toolchain_for_dir(path)); + let (ref toolchain, _) = self.toolchain_for_dir(path)?; - if let Some(cmd) = try!(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) } } - pub fn create_command_for_toolchain(&self, toolchain: &str, install_if_missing: bool, - binary: &str) -> Result { - let ref toolchain = try!(self.get_toolchain(toolchain, false)); + pub fn create_command_for_toolchain( + &self, + toolchain: &str, + install_if_missing: bool, + binary: &str, + ) -> Result { + let ref toolchain = self.get_toolchain(toolchain, false)?; if install_if_missing && !toolchain.exists() { - try!(toolchain.install_from_dist()); + toolchain.install_from_dist()?; } - if let Some(cmd) = try!(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) @@ -426,7 +433,11 @@ impl Cfg { // Custom toolchains don't have cargo, so here we detect that situation and // try to find a different cargo. - fn maybe_do_cargo_fallback(&self, toolchain: &Toolchain, binary: &str) -> Result> { + fn maybe_do_cargo_fallback( + &self, + toolchain: &Toolchain, + binary: &str, + ) -> Result> { if !toolchain.is_custom() { return Ok(None); } @@ -443,9 +454,9 @@ impl Cfg { } for fallback in &["nightly", "beta", "stable"] { - let fallback = try!(self.get_toolchain(fallback, false)); + let fallback = self.get_toolchain(fallback, false)?; if fallback.exists() { - let cmd = try!(fallback.create_fallback_command("cargo", toolchain)); + let cmd = fallback.create_fallback_command("cargo", toolchain)?; return Ok(Some(cmd)); } } @@ -454,18 +465,18 @@ impl Cfg { } pub fn doc_path_for_dir(&self, path: &Path, relative: &str) -> Result { - let (toolchain, _) = try!(self.toolchain_for_dir(path)); + let (toolchain, _) = self.toolchain_for_dir(path)?; toolchain.doc_path(relative) } pub fn open_docs_for_dir(&self, path: &Path, relative: &str) -> Result<()> { - let (toolchain, _) = try!(self.toolchain_for_dir(path)); + let (toolchain, _) = self.toolchain_for_dir(path)?; toolchain.open_docs(relative) } pub fn set_default_host_triple(&self, host_triple: &str) -> Result<()> { if dist::PartialTargetTriple::from_str(host_triple).is_none() { - return Err("Invalid host triple".into()) + return Err("Invalid host triple".into()); } self.settings_file.with_mut(|s| { s.default_host_triple = Some(host_triple.to_owned()); @@ -474,14 +485,18 @@ impl Cfg { } pub fn get_default_host_triple(&self) -> Result { - Ok(try!(self.settings_file.with(|s| { - Ok(s.default_host_triple.as_ref().map(|s| dist::TargetTriple::from_str(&s))) - })).unwrap_or_else(dist::TargetTriple::from_build)) + Ok(self.settings_file + .with(|s| { + Ok(s.default_host_triple + .as_ref() + .map(|s| dist::TargetTriple::from_str(&s))) + })? + .unwrap_or_else(dist::TargetTriple::from_build)) } pub fn resolve_toolchain(&self, name: &str) -> Result { if let Ok(desc) = dist::PartialToolchainDesc::from_str(name) { - let host = try!(self.get_default_host_triple()); + let host = self.get_default_host_triple()?; Ok(desc.resolve(&host).to_string()) } else { Ok(name.to_owned()) @@ -489,17 +504,20 @@ impl Cfg { } pub fn set_telemetry(&self, telemetry_enabled: bool) -> Result<()> { - if telemetry_enabled { self.enable_telemetry() } else { self.disable_telemetry() } + if telemetry_enabled { + self.enable_telemetry() + } else { + self.disable_telemetry() + } } fn enable_telemetry(&self) -> Result<()> { - try!(self.settings_file.with_mut(|s| { + self.settings_file.with_mut(|s| { s.telemetry = TelemetryMode::On; Ok(()) - })); + })?; - let _ = utils::ensure_dir_exists("telemetry", &self.rustup_dir.join("telemetry"), - &|_| ()); + let _ = utils::ensure_dir_exists("telemetry", &self.rustup_dir.join("telemetry"), &|_| ()); (self.notify_handler)(Notification::SetTelemetry("on")); @@ -507,10 +525,10 @@ impl Cfg { } fn disable_telemetry(&self) -> Result<()> { - try!(self.settings_file.with_mut(|s| { + self.settings_file.with_mut(|s| { s.telemetry = TelemetryMode::Off; Ok(()) - })); + })?; (self.notify_handler)(Notification::SetTelemetry("off")); @@ -518,7 +536,7 @@ impl Cfg { } pub fn telemetry_enabled(&self) -> Result { - Ok(match try!(self.settings_file.with(|s| Ok(s.telemetry))) { + Ok(match self.settings_file.with(|s| Ok(s.telemetry))? { TelemetryMode::On => true, TelemetryMode::Off => false, }) @@ -527,8 +545,8 @@ impl Cfg { pub fn analyze_telemetry(&self) -> Result { let mut t = TelemetryAnalysis::new(self.rustup_dir.join("telemetry")); - let events = try!(t.import_telemery()); - try!(t.analyze_telemetry_events(&events)); + let events = t.import_telemery()?; + t.analyze_telemetry_events(&events)?; Ok(t) } diff --git a/src/rustup/env_var.rs b/src/rustup/env_var.rs index ff00ef7dea..9c3bc03940 100644 --- a/src/rustup/env_var.rs +++ b/src/rustup/env_var.rs @@ -36,9 +36,9 @@ pub fn prepend_path(name: &str, value: Vec, cmd: &mut Command) { pub fn inc(name: &str, cmd: &mut Command) { let old_value = env::var(name) - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0); + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(0); cmd.env(name, (old_value + 1).to_string()); } diff --git a/src/rustup/install.rs b/src/rustup/install.rs index 49c5814c41..7373c733cd 100644 --- a/src/rustup/install.rs +++ b/src/rustup/install.rs @@ -1,13 +1,13 @@ //! Installation and upgrade of both distribution-managed and local //! toolchains -use rustup_dist::{Notification}; +use rustup_dist::Notification; use rustup_dist::prefix::InstallPrefix; use rustup_utils::utils; use rustup_dist::temp; use rustup_dist::dist; use rustup_dist::download::DownloadCfg; -use rustup_dist::component::{Components, TarGzPackage, Transaction, Package}; +use rustup_dist::component::{Components, Package, TarGzPackage, Transaction}; use errors::Result; use std::path::Path; @@ -24,40 +24,34 @@ impl<'a> InstallMethod<'a> { if path.exists() { // Don't uninstall first for Dist method match self { - InstallMethod::Dist(_, _, _) | - InstallMethod::Installer(_, _) => {} + InstallMethod::Dist(_, _, _) | InstallMethod::Installer(_, _) => {} _ => { - try!(uninstall(path, notify_handler)); + uninstall(path, notify_handler)?; } } } match self { InstallMethod::Copy(src) => { - try!(utils::copy_dir(src, path, &|n| notify_handler(n.into()))); + utils::copy_dir(src, path, &|n| notify_handler(n.into()))?; Ok(true) } InstallMethod::Link(src) => { - try!(utils::symlink_dir(src, &path, &|n| notify_handler(n.into()))); + utils::symlink_dir(src, &path, &|n| notify_handler(n.into()))?; Ok(true) } InstallMethod::Installer(src, temp_cfg) => { - try!(InstallMethod::tar_gz(src, path, &temp_cfg, notify_handler)); + InstallMethod::tar_gz(src, path, &temp_cfg, notify_handler)?; Ok(true) } InstallMethod::Dist(toolchain, update_hash, dl_cfg) => { let prefix = &InstallPrefix::from(path.to_owned()); let maybe_new_hash = - try!(dist::update_from_dist( - dl_cfg, - update_hash, - toolchain, - prefix, - &[], &[])); + dist::update_from_dist(dl_cfg, update_hash, toolchain, prefix, &[], &[])?; if let Some(hash) = maybe_new_hash { if let Some(hash_file) = update_hash { - try!(utils::write_file("update hash", hash_file, &hash)); + utils::write_file("update hash", hash_file, &hash)?; } Ok(true) @@ -68,18 +62,22 @@ impl<'a> InstallMethod<'a> { } } - fn tar_gz(src: &Path, path: &Path, temp_cfg: &temp::Cfg, - notify_handler: &Fn(Notification)) -> Result<()> { + fn tar_gz( + src: &Path, + path: &Path, + temp_cfg: &temp::Cfg, + notify_handler: &Fn(Notification), + ) -> Result<()> { notify_handler(Notification::Extracting(src, path)); let prefix = InstallPrefix::from(path.to_owned()); - let installation = try!(Components::open(prefix.clone())); - let package = try!(TarGzPackage::new_file(src, temp_cfg)); + let installation = Components::open(prefix.clone())?; + let package = TarGzPackage::new_file(src, temp_cfg)?; let mut tx = Transaction::new(prefix.clone(), temp_cfg, notify_handler); for component in package.components() { - tx = try!(package.install(&installation, &component, None, tx)); + tx = package.install(&installation, &component, None, tx)?; } tx.commit(); @@ -89,6 +87,7 @@ impl<'a> InstallMethod<'a> { } pub fn uninstall(path: &Path, notify_handler: &Fn(Notification)) -> Result<()> { - Ok(try!(utils::remove_dir("install", path, - &|n| notify_handler(n.into())))) + Ok(utils::remove_dir("install", path, &|n| { + notify_handler(n.into()) + })?) } diff --git a/src/rustup/lib.rs b/src/rustup/lib.rs index a6d5c6d94d..0e70055394 100644 --- a/src/rustup/lib.rs +++ b/src/rustup/lib.rs @@ -1,26 +1,26 @@ #![recursion_limit = "1024"] -extern crate rustup_dist; -extern crate rustup_utils; #[macro_use] extern crate error_chain; -extern crate url; -extern crate regex; extern crate itertools; +#[cfg(unix)] +extern crate libc; +extern crate regex; +extern crate rustup_dist; +extern crate rustup_utils; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate tempfile; extern crate time; extern crate toml; -#[cfg(unix)] -extern crate libc; +extern crate url; pub use errors::*; pub use notifications::*; pub use config::*; pub use toolchain::*; -pub use rustup_utils::{utils, notify, toml_utils}; +pub use rustup_utils::{notify, toml_utils, utils}; mod errors; mod notifications; diff --git a/src/rustup/notifications.rs b/src/rustup/notifications.rs index 2b06ccfc1f..5a9f152f23 100644 --- a/src/rustup/notifications.rs +++ b/src/rustup/notifications.rs @@ -60,27 +60,26 @@ impl<'a> Notification<'a> { Install(ref n) => n.level(), Utils(ref n) => n.level(), Temp(ref n) => n.level(), - ToolchainDirectory(_, _) | - LookingForToolchain(_) | - WritingMetadataVersion(_) | - InstallingToolchain(_) | - UpdatingToolchain(_) | - ReadMetadataVersion(_) | - InstalledToolchain(_) | - UpdateHashMatches | - TelemetryCleanupError(_) => NotificationLevel::Verbose, - SetDefaultToolchain(_) | - SetOverrideToolchain(_, _) | - UsingExistingToolchain(_) | - UninstallingToolchain(_) | - UninstalledToolchain(_) | - ToolchainNotInstalled(_) | - UpgradingMetadata(_, _) | - MetadataUpgradeNotNeeded(_) | - SetTelemetry(_) => NotificationLevel::Info, + ToolchainDirectory(_, _) + | LookingForToolchain(_) + | WritingMetadataVersion(_) + | InstallingToolchain(_) + | UpdatingToolchain(_) + | ReadMetadataVersion(_) + | InstalledToolchain(_) + | UpdateHashMatches + | TelemetryCleanupError(_) => NotificationLevel::Verbose, + SetDefaultToolchain(_) + | SetOverrideToolchain(_, _) + | UsingExistingToolchain(_) + | UninstallingToolchain(_) + | UninstalledToolchain(_) + | ToolchainNotInstalled(_) + | UpgradingMetadata(_, _) + | MetadataUpgradeNotNeeded(_) + | SetTelemetry(_) => NotificationLevel::Info, NonFatalError(_) => NotificationLevel::Error, - UpgradeRemovesToolchains | - MissingFileDuringSelfUninstall(_) => NotificationLevel::Warn, + UpgradeRemovesToolchains | MissingFileDuringSelfUninstall(_) => NotificationLevel::Warn, } } } @@ -93,12 +92,12 @@ impl<'a> Display for Notification<'a> { Utils(ref n) => n.fmt(f), Temp(ref n) => n.fmt(f), SetDefaultToolchain(name) => write!(f, "default toolchain set to '{}'", name), - SetOverrideToolchain(path, name) => { - write!(f, - "override toolchain for '{}' set to '{}'", - path.display(), - name) - } + SetOverrideToolchain(path, name) => write!( + f, + "override toolchain for '{}' set to '{}'", + path.display(), + name + ), LookingForToolchain(name) => write!(f, "looking for installed toolchain '{}'", name), ToolchainDirectory(path, _) => write!(f, "toolchain directory: '{}'", path.display()), UpdatingToolchain(name) => write!(f, "updating existing install for '{}'", name), @@ -108,27 +107,29 @@ impl<'a> Display for Notification<'a> { UninstallingToolchain(name) => write!(f, "uninstalling toolchain '{}'", name), UninstalledToolchain(name) => write!(f, "toolchain '{}' uninstalled", name), ToolchainNotInstalled(name) => write!(f, "no toolchain installed for '{}'", name), - UpdateHashMatches => { - write!(f, "toolchain is already up to date") - } - UpgradingMetadata(from_ver, to_ver) => { - write!(f, - "upgrading metadata version from '{}' to '{}'", - from_ver, - to_ver) - } - MetadataUpgradeNotNeeded(ver) => { - write!(f, - "nothing to upgrade: metadata version is already '{}'", - ver) - } + UpdateHashMatches => write!(f, "toolchain is already up to date"), + UpgradingMetadata(from_ver, to_ver) => write!( + f, + "upgrading metadata version from '{}' to '{}'", + from_ver, to_ver + ), + MetadataUpgradeNotNeeded(ver) => write!( + f, + "nothing to upgrade: metadata version is already '{}'", + ver + ), WritingMetadataVersion(ver) => write!(f, "writing metadata version: '{}'", ver), ReadMetadataVersion(ver) => write!(f, "read metadata version: '{}'", ver), NonFatalError(e) => write!(f, "{}", e), - UpgradeRemovesToolchains => write!(f, "this upgrade will remove all existing toolchains. you will need to reinstall them"), - MissingFileDuringSelfUninstall(ref p) => { - write!(f, "expected file does not exist to uninstall: {}", p.display()) - } + UpgradeRemovesToolchains => write!( + f, + "this upgrade will remove all existing toolchains. you will need to reinstall them" + ), + MissingFileDuringSelfUninstall(ref p) => write!( + f, + "expected file does not exist to uninstall: {}", + p.display() + ), SetTelemetry(telemetry_status) => write!(f, "telemetry set to '{}'", telemetry_status), TelemetryCleanupError(e) => write!(f, "unable to remove old telemetry files: '{}'", e), } diff --git a/src/rustup/settings.rs b/src/rustup/settings.rs index 5a6b4b5d43..383bbd726f 100644 --- a/src/rustup/settings.rs +++ b/src/rustup/settings.rs @@ -11,23 +11,22 @@ use std::str::FromStr; pub const SUPPORTED_METADATA_VERSIONS: [&'static str; 2] = ["2", "12"]; pub const DEFAULT_METADATA_VERSION: &'static str = "12"; - #[derive(Clone, Debug, PartialEq)] pub struct SettingsFile { path: PathBuf, - cache: RefCell> + cache: RefCell>, } impl SettingsFile { pub fn new(path: PathBuf) -> Self { SettingsFile { path: path, - cache: RefCell::new(None) + cache: RefCell::new(None), } } fn write_settings(&self) -> Result<()> { let s = self.cache.borrow().as_ref().unwrap().clone(); - try!(utils::write_file("settings", &self.path, &s.stringify())); + utils::write_file("settings", &self.path, &s.stringify())?; Ok(()) } fn read_settings(&self) -> Result<()> { @@ -36,8 +35,8 @@ impl SettingsFile { let mut b = self.cache.borrow_mut(); if b.is_none() { *b = Some(if utils::is_file(&self.path) { - let content = try!(utils::read_file("settings", &self.path)); - try!(Settings::parse(&content)) + let content = utils::read_file("settings", &self.path)?; + Settings::parse(&content)? } else { needs_save = true; Default::default() @@ -45,24 +44,22 @@ impl SettingsFile { } } if needs_save { - try!(self.write_settings()); + self.write_settings()?; } Ok(()) } pub fn with Result>(&self, f: F) -> Result { - try!(self.read_settings()); + self.read_settings()?; // Settings can no longer be None so it's OK to unwrap f(self.cache.borrow().as_ref().unwrap()) } pub fn with_mut Result>(&self, f: F) -> Result { - try!(self.read_settings()); + self.read_settings()?; // Settings can no longer be None so it's OK to unwrap - let result = { - try!(f(self.cache.borrow_mut().as_mut().unwrap())) - }; - try!(self.write_settings()); + let result = { f(self.cache.borrow_mut().as_mut().unwrap())? }; + self.write_settings()?; Ok(result) } pub fn maybe_upgrade_from_legacy(&self, multirust_dir: &Path) -> Result<()> { @@ -73,7 +70,7 @@ impl SettingsFile { s.find(separator).and_then(|index| { match (T::from_str(&s[..index]), T::from_str(&s[index + 1..])) { (Ok(l), Ok(r)) => Some((l, r)), - _ => None + _ => None, } }) } @@ -82,16 +79,20 @@ impl SettingsFile { let default_file = multirust_dir.join("default"); let telemetry_file = multirust_dir.join("telemetry-on"); // Legacy upgrade - try!(self.with_mut(|s| { - s.version = try!(utils::read_file("version", &legacy_version_file)) - .trim().to_owned(); + self.with_mut(|s| { + s.version = utils::read_file("version", &legacy_version_file)? + .trim() + .to_owned(); if utils::is_file(&default_file) { - s.default_toolchain = Some(try!(utils::read_file("default", &default_file)) - .trim().to_owned()); + s.default_toolchain = Some( + utils::read_file("default", &default_file)? + .trim() + .to_owned(), + ); } if utils::is_file(&override_db) { - let overrides = try!(utils::read_file("overrides", &override_db)); + let overrides = utils::read_file("overrides", &override_db)?; for o in overrides.lines() { if let Some((k, v)) = split_override(o, ';') { s.overrides.insert(k, v); @@ -102,7 +103,7 @@ impl SettingsFile { s.telemetry = TelemetryMode::On; } Ok(()) - })); + })?; // Failure to delete these is not a fatal error let _ = utils::remove_file("version", &legacy_version_file); @@ -114,7 +115,6 @@ impl SettingsFile { } } - #[derive(Copy, Clone, Debug, PartialEq)] pub enum TelemetryMode { On, @@ -127,7 +127,7 @@ pub struct Settings { pub default_host_triple: Option, pub default_toolchain: Option, pub overrides: BTreeMap, - pub telemetry: TelemetryMode + pub telemetry: TelemetryMode, } impl Default for Settings { @@ -137,7 +137,7 @@ impl Default for Settings { default_host_triple: None, default_toolchain: None, overrides: BTreeMap::new(), - telemetry: TelemetryMode::Off + telemetry: TelemetryMode::Off, } } } @@ -145,7 +145,9 @@ impl Default for Settings { impl Settings { fn path_to_key(path: &Path, notify_handler: &Fn(Notification)) -> String { if path.exists() { - utils::canonicalize_path(path, &|n| notify_handler(n.into())).display().to_string() + utils::canonicalize_path(path, &|n| notify_handler(n.into())) + .display() + .to_string() } else { path.display().to_string() } @@ -156,7 +158,12 @@ impl Settings { self.overrides.remove(&key).is_some() } - pub fn add_override(&mut self, path: &Path, toolchain: String, notify_handler: &Fn(Notification)) { + pub fn add_override( + &mut self, + path: &Path, + toolchain: String, + notify_handler: &Fn(Notification), + ) { let key = Self::path_to_key(path, notify_handler); notify_handler(Notification::SetOverrideToolchain(path, &toolchain)); self.overrides.insert(key, toolchain); @@ -176,27 +183,26 @@ impl Settings { } pub fn from_toml(mut table: toml::value::Table, path: &str) -> Result { - let version = try!(get_string(&mut table, "version", path)); + let version = get_string(&mut table, "version", path)?; if !SUPPORTED_METADATA_VERSIONS.contains(&&*version) { return Err(ErrorKind::UnknownMetadataVersion(version).into()); } Ok(Settings { version: version, - default_host_triple: try!(get_opt_string(&mut table, "default_host_triple", path)), - default_toolchain: try!(get_opt_string(&mut table, "default_toolchain", path)), - overrides: try!(Self::table_to_overrides(&mut table, path)), - telemetry: if try!(get_opt_bool(&mut table, "telemetry", path)).unwrap_or(false) { + 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)?, + telemetry: if get_opt_bool(&mut table, "telemetry", path)?.unwrap_or(false) { TelemetryMode::On } else { TelemetryMode::Off - } + }, }) } pub fn to_toml(self) -> toml::value::Table { let mut result = toml::value::Table::new(); - result.insert("version".to_owned(), - toml::Value::String(self.version)); + result.insert("version".to_owned(), toml::Value::String(self.version)); if let Some(v) = self.default_host_triple { result.insert("default_host_triple".to_owned(), toml::Value::String(v)); @@ -215,9 +221,12 @@ impl Settings { result } - fn table_to_overrides(table: &mut toml::value::Table, path: &str) -> Result> { + fn table_to_overrides( + table: &mut toml::value::Table, + path: &str, + ) -> Result> { let mut result = BTreeMap::new(); - let pkg_table = try!(get_table(table, "overrides", path)); + let pkg_table = get_table(table, "overrides", path)?; for (k, v) in pkg_table { if let toml::Value::String(t) = v { diff --git a/src/rustup/telemetry.rs b/src/rustup/telemetry.rs index 9a5c040a8e..7f8e69826c 100644 --- a/src/rustup/telemetry.rs +++ b/src/rustup/telemetry.rs @@ -8,9 +8,20 @@ use std::path::PathBuf; #[derive(Deserialize, Serialize, Debug, Clone)] pub enum TelemetryEvent { - RustcRun { duration_ms: u64, exit_code: i32, errors: Option> }, - ToolchainUpdate { toolchain: String, success: bool } , - TargetAdd { toolchain: String, target: String, success: bool }, + RustcRun { + duration_ms: u64, + exit_code: i32, + errors: Option>, + }, + ToolchainUpdate { + toolchain: String, + success: bool, + }, + TargetAdd { + toolchain: String, + target: String, + success: bool, + }, } #[derive(Deserialize, Serialize, Debug)] @@ -28,7 +39,7 @@ impl LogMessage { #[derive(Debug)] pub struct Telemetry { - telemetry_dir: PathBuf + telemetry_dir: PathBuf, } const LOG_FILE_VERSION: i32 = 1; @@ -36,28 +47,35 @@ const MAX_TELEMETRY_FILES: usize = 100; impl Telemetry { pub fn new(telemetry_dir: PathBuf) -> Telemetry { - Telemetry { telemetry_dir: telemetry_dir } + Telemetry { + telemetry_dir: telemetry_dir, + } } pub fn log_telemetry(&self, event: TelemetryEvent) -> Result<()> { let current_time = time::now_utc(); - let ln = LogMessage { log_time_s: current_time.to_timespec().sec, - event: event, - version: LOG_FILE_VERSION }; + let ln = LogMessage { + log_time_s: current_time.to_timespec().sec, + event: event, + version: LOG_FILE_VERSION, + }; let json = serde_json::to_string(&ln).unwrap(); - let filename = format!("log-{}-{:02}-{:02}.json", current_time.tm_year + 1900, current_time.tm_mon + 1, current_time.tm_mday); + let filename = format!( + "log-{}-{:02}-{:02}.json", + current_time.tm_year + 1900, + current_time.tm_mon + 1, + current_time.tm_mday + ); // Check for the telemetry file. If it doesn't exist, it's a new day. // If it is a new day, then attempt to clean the telemetry directory. if !raw::is_file(&self.telemetry_dir.join(&filename)) { - try!(self.clean_telemetry_dir()); + self.clean_telemetry_dir()?; } - let _ = utils::append_file("telemetry", - &self.telemetry_dir.join(&filename), - &json); + let _ = utils::append_file("telemetry", &self.telemetry_dir.join(&filename), &json); Ok(()) } @@ -65,7 +83,7 @@ impl Telemetry { pub fn clean_telemetry_dir(&self) -> Result<()> { let telemetry_dir_contents = self.telemetry_dir.read_dir(); - let contents = try!(telemetry_dir_contents.chain_err(|| ErrorKind::TelemetryCleanupError)); + let contents = telemetry_dir_contents.chain_err(|| ErrorKind::TelemetryCleanupError)?; let mut telemetry_files: Vec = Vec::new(); @@ -89,7 +107,7 @@ impl Telemetry { for i in 0..dl { let i = i as usize; - try!(fs::remove_file(&telemetry_files[i]).chain_err(|| ErrorKind::TelemetryCleanupError)); + fs::remove_file(&telemetry_files[i]).chain_err(|| ErrorKind::TelemetryCleanupError)?; } Ok(()) diff --git a/src/rustup/telemetry_analysis.rs b/src/rustup/telemetry_analysis.rs index 343053835f..4b15ac4266 100644 --- a/src/rustup/telemetry_analysis.rs +++ b/src/rustup/telemetry_analysis.rs @@ -59,7 +59,9 @@ impl fmt::Display for RustcStatistics { } } - write!(f, r" + write!( + f, + r" Total compiles: {} Compile Time (ms) Total : {} @@ -89,7 +91,9 @@ impl fmt::Display for RustcStatistics { impl fmt::Display for TelemetryAnalysis { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, r" + write!( + f, + r" Overall rustc statistics: {} @@ -98,9 +102,7 @@ rustc successful execution statistics rustc error statistics {}", - self.rustc_statistics, - self.rustc_success_statistics, - self.rustc_error_statistics + self.rustc_statistics, self.rustc_success_statistics, self.rustc_error_statistics ) } } @@ -117,7 +119,9 @@ impl TelemetryAnalysis { pub fn import_telemery(&mut self) -> Result> { let mut events: Vec = Vec::new(); - let contents = try!(self.telemetry_dir.read_dir().chain_err(|| ErrorKind::TelemetryAnalysisError)); + let contents = self.telemetry_dir + .read_dir() + .chain_err(|| ErrorKind::TelemetryAnalysisError)?; let mut telemetry_files: Vec = Vec::new(); @@ -140,7 +144,7 @@ impl TelemetryAnalysis { fn read_telemetry_file(&self, path: PathBuf) -> Result> { let mut events: Vec = Vec::new(); - let f = try!(File::open(&path).chain_err(|| ErrorKind::TelemetryAnalysisError)); + let f = File::open(&path).chain_err(|| ErrorKind::TelemetryAnalysisError)?; let file = BufReader::new(&f); @@ -177,11 +181,18 @@ impl TelemetryAnalysis { for event in events { match *event { - TelemetryEvent::RustcRun{ duration_ms, ref exit_code, ref errors } => { + TelemetryEvent::RustcRun { + duration_ms, + ref exit_code, + ref errors, + } => { self.rustc_statistics.rustc_execution_count += 1; rustc_durations.push(duration_ms); - let exit_count = self.rustc_statistics.exit_codes_with_count.entry(*exit_code).or_insert(0); + let exit_count = self.rustc_statistics + .exit_codes_with_count + .entry(*exit_code) + .or_insert(0); *exit_count += 1; rustc_exit_codes.push(exit_code); @@ -190,7 +201,8 @@ impl TelemetryAnalysis { let errors = errors.clone().unwrap(); for e in &errors { - let error_count = error_codes_with_counts.entry(e.to_owned()).or_insert(0); + let error_count = + error_codes_with_counts.entry(e.to_owned()).or_insert(0); *error_count += 1; } @@ -199,22 +211,29 @@ impl TelemetryAnalysis { } else { rustc_successful_durations.push(duration_ms); } - }, - TelemetryEvent::TargetAdd{ ref toolchain, ref target, success } => { + } + TelemetryEvent::TargetAdd { + ref toolchain, + ref target, + success, + } => { toolchains.push(toolchain.to_owned()); targets.push(target.to_owned()); if !success { toolchains_with_errors.push(toolchain.to_owned()); } - }, - TelemetryEvent::ToolchainUpdate{ ref toolchain, success } => { + } + TelemetryEvent::ToolchainUpdate { + ref toolchain, + success, + } => { updated_toolchains.push(toolchain.to_owned()); if !success { updated_toolchains_with_errors.push(toolchain.to_owned()); } - }, + } } - }; + } self.rustc_statistics = compute_rustc_percentiles(&rustc_durations); self.rustc_error_statistics = compute_rustc_percentiles(&rustc_error_durations); @@ -224,7 +243,10 @@ impl TelemetryAnalysis { let error_list = error_list.into_iter().flatten(); for e in error_list { - let error_count = self.rustc_statistics.error_codes_with_counts.entry(e).or_insert(0); + let error_count = self.rustc_statistics + .error_codes_with_counts + .entry(e) + .or_insert(0); *error_count += 1; } @@ -243,7 +265,7 @@ pub fn compute_rustc_percentiles(values: &[u64]) -> RustcStatistics { compile_time_ms_ntile_99: ntile(99, values), compile_time_ms_stdev: stdev(values), exit_codes_with_count: HashMap::new(), - error_codes_with_counts: HashMap::new() + error_codes_with_counts: HashMap::new(), } } diff --git a/src/rustup/toolchain.rs b/src/rustup/toolchain.rs index 38edd8d4f2..04f6ab1074 100644 --- a/src/rustup/toolchain.rs +++ b/src/rustup/toolchain.rs @@ -4,8 +4,8 @@ use rustup_dist; use rustup_dist::download::DownloadCfg; use rustup_utils::utils; use rustup_dist::prefix::InstallPrefix; -use rustup_dist::dist::{ToolchainDesc}; -use rustup_dist::manifestation::{Manifestation, Changes}; +use rustup_dist::dist::ToolchainDesc; +use rustup_dist::manifestation::{Changes, Manifestation}; use rustup_dist::manifest::Component; use config::Cfg; use env_var; @@ -47,30 +47,30 @@ pub enum UpdateStatus { impl<'a> Toolchain<'a> { pub fn from(cfg: &'a Cfg, name: &str) -> Result { - let resolved_name = try!(cfg.resolve_toolchain(name)); + let resolved_name = cfg.resolve_toolchain(name)?; let path = cfg.toolchains_dir.join(&resolved_name); Ok(Toolchain { cfg: cfg, name: resolved_name, path: path.clone(), telemetry: Telemetry::new(cfg.rustup_dir.join("telemetry")), - dist_handler: Box::new(move |n| { - (cfg.notify_handler)(n.into()) - }) + dist_handler: Box::new(move |n| (cfg.notify_handler)(n.into())), }) } pub fn name(&self) -> &str { &self.name } pub fn desc(&self) -> Result { - Ok(try!(ToolchainDesc::from_str(&self.name))) + Ok(ToolchainDesc::from_str(&self.name)?) } pub fn path(&self) -> &Path { &self.path } fn is_symlink(&self) -> bool { use std::fs; - fs::symlink_metadata(&self.path).map(|m| m.file_type().is_symlink()).unwrap_or(false) + fs::symlink_metadata(&self.path) + .map(|m| m.file_type().is_symlink()) + .unwrap_or(false) } pub fn exists(&self) -> bool { // HACK: linked toolchains are symlinks, and, contrary to what std docs @@ -84,7 +84,7 @@ impl<'a> Toolchain<'a> { utils::is_directory(&self.path) || is_symlink } pub fn verify(&self) -> Result<()> { - Ok(try!(utils::assert_is_directory(&self.path))) + Ok(utils::assert_is_directory(&self.path)?) } pub fn remove(&self) -> Result<()> { if self.exists() || self.is_symlink() { @@ -93,15 +93,14 @@ impl<'a> Toolchain<'a> { (self.cfg.notify_handler)(Notification::ToolchainNotInstalled(&self.name)); return Ok(()); } - if let Some(update_hash) = try!(self.update_hash()) { - try!(utils::remove_file("update hash", &update_hash)); + if let Some(update_hash) = self.update_hash()? { + utils::remove_file("update hash", &update_hash)?; } - let result = install::uninstall(&self.path, - &|n| (self.cfg.notify_handler)(n.into())); + let result = install::uninstall(&self.path, &|n| (self.cfg.notify_handler)(n.into())); if !self.exists() { (self.cfg.notify_handler)(Notification::UninstalledToolchain(&self.name)); } - Ok(try!(result)) + Ok(result?) } fn install(&self, install_method: InstallMethod) -> Result { assert!(self.is_valid_install_method(install_method)); @@ -111,10 +110,8 @@ impl<'a> Toolchain<'a> { } else { (self.cfg.notify_handler)(Notification::InstallingToolchain(&self.name)); } - (self.cfg.notify_handler) - (Notification::ToolchainDirectory(&self.path, &self.name)); - let updated = try!(install_method.run(&self.path, - &|n| (self.cfg.notify_handler)(n.into()))); + (self.cfg.notify_handler)(Notification::ToolchainDirectory(&self.path, &self.name)); + let updated = install_method.run(&self.path, &|n| (self.cfg.notify_handler)(n.into()))?; if !updated { (self.cfg.notify_handler)(Notification::UpdateHashMatches); @@ -135,7 +132,7 @@ impl<'a> Toolchain<'a> { assert!(self.is_valid_install_method(install_method)); (self.cfg.notify_handler)(Notification::LookingForToolchain(&self.name)); if !self.exists() { - Ok(try!(self.install(install_method))) + Ok(self.install(install_method)?) } else { (self.cfg.notify_handler)(Notification::UsingExistingToolchain(&self.name)); Ok(UpdateStatus::Unchanged) @@ -143,9 +140,9 @@ impl<'a> Toolchain<'a> { } fn is_valid_install_method(&self, install_method: InstallMethod) -> bool { match install_method { - InstallMethod::Copy(_) | - InstallMethod::Link(_) | - InstallMethod::Installer(_, _) => self.is_custom(), + InstallMethod::Copy(_) | InstallMethod::Link(_) | InstallMethod::Installer(_, _) => { + self.is_custom() + } InstallMethod::Dist(_, _, _) => !self.is_custom(), } } @@ -153,7 +150,7 @@ impl<'a> Toolchain<'a> { if self.is_custom() { Ok(None) } else { - Ok(Some(try!(self.cfg.get_hash_file(&self.name, true)))) + Ok(Some(self.cfg.get_hash_file(&self.name, true)?)) } } @@ -167,17 +164,19 @@ impl<'a> Toolchain<'a> { } pub fn install_from_dist(&self) -> Result { - if try!(self.cfg.telemetry_enabled()) { + if self.cfg.telemetry_enabled()? { return self.install_from_dist_with_telemetry(); } self.install_from_dist_inner() } pub fn install_from_dist_inner(&self) -> Result { - let update_hash = try!(self.update_hash()); - self.install(InstallMethod::Dist(&try!(self.desc()), - update_hash.as_ref().map(|p| &**p), - self.download_cfg())) + let update_hash = self.update_hash()?; + self.install(InstallMethod::Dist( + &self.desc()?, + update_hash.as_ref().map(|p| &**p), + self.download_cfg(), + )) } pub fn install_from_dist_with_telemetry(&self) -> Result { @@ -185,8 +184,10 @@ impl<'a> Toolchain<'a> { match result { Ok(us) => { - let te = TelemetryEvent::ToolchainUpdate { toolchain: self.name().to_string() , - success: true }; + let te = TelemetryEvent::ToolchainUpdate { + toolchain: self.name().to_string(), + success: true, + }; match self.telemetry.log_telemetry(te) { Ok(_) => Ok(us), Err(e) => { @@ -196,8 +197,10 @@ impl<'a> Toolchain<'a> { } } Err(e) => { - let te = TelemetryEvent::ToolchainUpdate { toolchain: self.name().to_string() , - success: true }; + let te = TelemetryEvent::ToolchainUpdate { + toolchain: self.name().to_string(), + success: true, + }; let _ = self.telemetry.log_telemetry(te).map_err(|xe| { (self.cfg.notify_handler)(Notification::TelemetryCleanupError(&xe)); }); @@ -207,30 +210,38 @@ impl<'a> Toolchain<'a> { } pub fn install_from_dist_if_not_installed(&self) -> Result { - let update_hash = try!(self.update_hash()); - self.install_if_not_installed(InstallMethod::Dist(&try!(self.desc()), - update_hash.as_ref().map(|p| &**p), - self.download_cfg())) + let update_hash = self.update_hash()?; + self.install_if_not_installed(InstallMethod::Dist( + &self.desc()?, + update_hash.as_ref().map(|p| &**p), + self.download_cfg(), + )) } pub fn is_custom(&self) -> bool { ToolchainDesc::from_str(&self.name).is_err() } pub fn is_tracking(&self) -> bool { - ToolchainDesc::from_str(&self.name).ok().map(|d| d.is_tracking()) == Some(true) + ToolchainDesc::from_str(&self.name) + .ok() + .map(|d| d.is_tracking()) == Some(true) } fn ensure_custom(&self) -> Result<()> { if !self.is_custom() { - Err(ErrorKind::Dist(::rustup_dist::ErrorKind::InvalidCustomToolchainName(self.name.to_string())).into()) + Err( + ErrorKind::Dist(::rustup_dist::ErrorKind::InvalidCustomToolchainName( + self.name.to_string(), + )).into(), + ) } else { Ok(()) } } pub fn install_from_installers(&self, installers: &[&OsStr]) -> Result<()> { - try!(self.ensure_custom()); + self.ensure_custom()?; - try!(self.remove()); + self.remove()?; // FIXME: This should do all downloads first, then do // installs, and do it all in a single transaction. @@ -238,12 +249,12 @@ impl<'a> Toolchain<'a> { let installer_str = installer.to_str().unwrap_or("bogus"); match installer_str.rfind('.') { Some(i) => { - let extension = &installer_str[i+1..]; + let extension = &installer_str[i + 1..]; if extension != "gz" { return Err(ErrorKind::BadInstallerType(extension.to_string()).into()); } } - None => return Err(ErrorKind::BadInstallerType(String::from("(none)")).into()) + None => return Err(ErrorKind::BadInstallerType(String::from("(none)")).into()), } // FIXME: Pretty hacky @@ -253,14 +264,15 @@ impl<'a> Toolchain<'a> { let url = Url::parse(installer_str).ok(); let url = if is_url { url } else { None }; if let Some(url) = url { - // Download to a local file - let local_installer = try!(self.cfg.temp_cfg.new_file_with_ext("", ".tar.gz")); - try!(utils::download_file(&url, - &local_installer, - None, - &|n| (self.cfg.notify_handler)(n.into()))); - try!(self.install(InstallMethod::Installer(&local_installer, &self.cfg.temp_cfg))); + let local_installer = self.cfg.temp_cfg.new_file_with_ext("", ".tar.gz")?; + utils::download_file(&url, &local_installer, None, &|n| { + (self.cfg.notify_handler)(n.into()) + })?; + self.install(InstallMethod::Installer( + &local_installer, + &self.cfg.temp_cfg, + ))?; } else { // If installer is a filename @@ -268,7 +280,10 @@ impl<'a> Toolchain<'a> { let local_installer = Path::new(installer); // Install from file - try!(self.install(InstallMethod::Installer(&local_installer, &self.cfg.temp_cfg))); + self.install(InstallMethod::Installer( + &local_installer, + &self.cfg.temp_cfg, + ))?; } } @@ -276,22 +291,22 @@ impl<'a> Toolchain<'a> { } pub fn install_from_dir(&self, src: &Path, link: bool) -> Result<()> { - try!(self.ensure_custom()); + self.ensure_custom()?; let mut pathbuf = PathBuf::from(src); pathbuf.push("lib"); - try!(utils::assert_is_directory(&pathbuf)); + utils::assert_is_directory(&pathbuf)?; pathbuf.pop(); pathbuf.push("bin"); - try!(utils::assert_is_directory(&pathbuf)); + utils::assert_is_directory(&pathbuf)?; pathbuf.push(format!("rustc{}", EXE_SUFFIX)); - try!(utils::assert_is_file(&pathbuf)); + utils::assert_is_file(&pathbuf)?; if link { - try!(self.install(InstallMethod::Link(&try!(utils::to_absolute(src))))); + self.install(InstallMethod::Link(&utils::to_absolute(src)?))?; } else { - try!(self.install(InstallMethod::Copy(src))); + self.install(InstallMethod::Copy(src))?; } Ok(()) @@ -318,13 +333,15 @@ impl<'a> Toolchain<'a> { let path = if utils::is_file(&bin_path) { &bin_path } else { - let recursion_count = env::var("RUST_RECURSION_COUNT").ok() - .and_then(|s| s.parse().ok()).unwrap_or(0); + let recursion_count = env::var("RUST_RECURSION_COUNT") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); if recursion_count > env_var::RUST_RECURSION_COUNT_MAX - 1 { - return Err(ErrorKind::BinaryNotFound(self.name.clone(), - binary.to_string_lossy() - .into()) - .into()) + return Err(ErrorKind::BinaryNotFound( + self.name.clone(), + binary.to_string_lossy().into(), + ).into()); } Path::new(&binary) }; @@ -335,8 +352,11 @@ impl<'a> Toolchain<'a> { // Create a command as a fallback for another toolchain. This is used // to give custom toolchains access to cargo - pub fn create_fallback_command>(&self, binary: T, - primary_toolchain: &Toolchain) -> Result { + pub fn create_fallback_command>( + &self, + binary: T, + primary_toolchain: &Toolchain, + ) -> Result { // With the hacks below this only works for cargo atm assert!(binary.as_ref() == "cargo" || binary.as_ref() == "cargo.exe"); @@ -363,15 +383,14 @@ impl<'a> Toolchain<'a> { let exe_path = if cfg!(windows) { use std::fs; let fallback_dir = self.cfg.rustup_dir.join("fallback"); - try!(fs::create_dir_all(&fallback_dir) - .chain_err(|| "unable to create dir to hold fallback exe")); + fs::create_dir_all(&fallback_dir) + .chain_err(|| "unable to create dir to hold fallback exe")?; let fallback_file = fallback_dir.join("cargo.exe"); if fallback_file.exists() { - try!(fs::remove_file(&fallback_file) - .chain_err(|| "unable to unlink old fallback exe")); + fs::remove_file(&fallback_file).chain_err(|| "unable to unlink old fallback exe")?; } - try!(fs::hard_link(&src_file, &fallback_file) - .chain_err(|| "unable to hard link fallback exe")); + fs::hard_link(&src_file, &fallback_file) + .chain_err(|| "unable to hard link fallback exe")?; fallback_file } else { src_file @@ -429,7 +448,7 @@ impl<'a> Toolchain<'a> { } pub fn doc_path(&self, relative: &str) -> Result { - try!(self.verify()); + self.verify()?; let parts = vec!["share", "doc", "rust", "html"]; let mut doc_dir = self.path.clone(); @@ -441,19 +460,19 @@ impl<'a> Toolchain<'a> { Ok(doc_dir) } pub fn open_docs(&self, relative: &str) -> Result<()> { - try!(self.verify()); + self.verify()?; - Ok(try!(utils::open_browser(&try!(self.doc_path(relative))))) + Ok(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(try!(self.cfg.settings_file.with_mut(|s| { + Ok(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> { @@ -462,32 +481,41 @@ impl<'a> Toolchain<'a> { } let toolchain = &self.name; - let ref toolchain = try!(ToolchainDesc::from_str(toolchain) - .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))); + let ref toolchain = ToolchainDesc::from_str(toolchain) + .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))?; let prefix = InstallPrefix::from(self.path.to_owned()); - let manifestation = try!(Manifestation::open(prefix, toolchain.target.clone())); + let manifestation = Manifestation::open(prefix, toolchain.target.clone())?; - if let Some(manifest) = try!(manifestation.load_manifest()) { - let config = try!(manifestation.read_config()); + if let Some(manifest) = manifestation.load_manifest()? { + let config = manifestation.read_config()?; // Return all optional components of the "rust" package for the // toolchain's target triple. let mut res = Vec::new(); - let rust_pkg = manifest.packages.get("rust") + let rust_pkg = manifest + .packages + .get("rust") .expect("manifest should cantain a rust package"); - let targ_pkg = rust_pkg.targets.get(&toolchain.target) + let targ_pkg = rust_pkg + .targets + .get(&toolchain.target) .expect("installed manifest should have a known target"); for component in &targ_pkg.components { - let installed = config.as_ref() + let installed = config + .as_ref() .map(|c| c.components.contains(component)) .unwrap_or(false); // Get the component so we can check if it is available - let component_pkg = manifest.get_package(&component.pkg) - .expect(&format!("manifest should contain component {}", &component.pkg)); - let component_target_pkg = component_pkg.targets.get(&toolchain.target) + let component_pkg = manifest.get_package(&component.pkg).expect(&format!( + "manifest should contain component {}", + &component.pkg + )); + let component_target_pkg = component_pkg + .targets + .get(&toolchain.target) .expect("component should have target toolchain"); res.push(ComponentStatus { @@ -499,14 +527,19 @@ impl<'a> Toolchain<'a> { } for extension in &targ_pkg.extensions { - let installed = config.as_ref() + let installed = config + .as_ref() .map(|c| c.components.contains(extension)) .unwrap_or(false); // Get the component so we can check if it is available - let extension_pkg = manifest.get_package(&extension.pkg) - .expect(&format!("manifest should contain extension {}", &extension.pkg)); - let extension_target_pkg = extension_pkg.targets.get(&toolchain.target) + let extension_pkg = manifest.get_package(&extension.pkg).expect(&format!( + "manifest should contain extension {}", + &extension.pkg + )); + let extension_target_pkg = extension_pkg + .targets + .get(&toolchain.target) .expect("extension should have target toolchain"); res.push(ComponentStatus { @@ -526,7 +559,7 @@ impl<'a> Toolchain<'a> { } pub fn add_component(&self, component: Component) -> Result<()> { - if try!(self.cfg.telemetry_enabled()) { + if self.cfg.telemetry_enabled()? { return self.telemetry_add_component(component); } self.add_component_without_telemetry(component) @@ -537,8 +570,10 @@ impl<'a> Toolchain<'a> { match output { Ok(_) => { - let te = TelemetryEvent::ToolchainUpdate { toolchain: self.name.to_owned(), - success: true }; + let te = TelemetryEvent::ToolchainUpdate { + toolchain: self.name.to_owned(), + success: true, + }; match self.telemetry.log_telemetry(te) { Ok(_) => Ok(()), @@ -547,10 +582,12 @@ impl<'a> Toolchain<'a> { Ok(()) } } - }, + } Err(e) => { - let te = TelemetryEvent::ToolchainUpdate { toolchain: self.name.to_owned(), - success: false }; + let te = TelemetryEvent::ToolchainUpdate { + toolchain: self.name.to_owned(), + success: false, + }; let _ = self.telemetry.log_telemetry(te).map_err(|xe| { (self.cfg.notify_handler)(Notification::TelemetryCleanupError(&xe)); @@ -570,41 +607,53 @@ impl<'a> Toolchain<'a> { } let toolchain = &self.name; - let ref toolchain = try!(ToolchainDesc::from_str(toolchain) - .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))); + let ref toolchain = ToolchainDesc::from_str(toolchain) + .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))?; let prefix = InstallPrefix::from(self.path.to_owned()); - let manifestation = try!(Manifestation::open(prefix, toolchain.target.clone())); - - if let Some(manifest) = try!(manifestation.load_manifest()) { + let manifestation = Manifestation::open(prefix, toolchain.target.clone())?; + if let Some(manifest) = manifestation.load_manifest()? { // Validate the component name - let rust_pkg = manifest.packages.get("rust") + let rust_pkg = manifest + .packages + .get("rust") .expect("manifest should cantain a rust package"); - let targ_pkg = rust_pkg.targets.get(&toolchain.target) + let targ_pkg = rust_pkg + .targets + .get(&toolchain.target) .expect("installed manifest should have a known target"); if targ_pkg.components.contains(&component) { - return Err(ErrorKind::AddingRequiredComponent(self.name.to_string(), component).into()); + return Err( + ErrorKind::AddingRequiredComponent(self.name.to_string(), component).into(), + ); } if !targ_pkg.extensions.contains(&component) { - let wildcard_component = Component { target: None, ..component.clone() }; + let wildcard_component = Component { + target: None, + ..component.clone() + }; if targ_pkg.extensions.contains(&wildcard_component) { component = wildcard_component; } else { - return Err(ErrorKind::UnknownComponent(self.name.to_string(), component).into()); + return Err( + ErrorKind::UnknownComponent(self.name.to_string(), component).into(), + ); } } let changes = Changes { add_extensions: vec![component], - remove_extensions: vec![] + remove_extensions: vec![], }; - try!(manifestation.update(&manifest, - changes, - &self.download_cfg(), - self.download_cfg().notify_handler.clone())); + manifestation.update( + &manifest, + changes, + &self.download_cfg(), + self.download_cfg().notify_handler.clone(), + )?; Ok(()) } else { @@ -618,42 +667,54 @@ impl<'a> Toolchain<'a> { } let toolchain = &self.name; - let ref toolchain = try!(ToolchainDesc::from_str(toolchain) - .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))); + let ref toolchain = ToolchainDesc::from_str(toolchain) + .chain_err(|| ErrorKind::ComponentsUnsupported(self.name.to_string()))?; let prefix = InstallPrefix::from(self.path.to_owned()); - let manifestation = try!(Manifestation::open(prefix, toolchain.target.clone())); - - if let Some(manifest) = try!(manifestation.load_manifest()) { + let manifestation = Manifestation::open(prefix, toolchain.target.clone())?; + if let Some(manifest) = manifestation.load_manifest()? { // Validate the component name - let rust_pkg = manifest.packages.get("rust") + let rust_pkg = manifest + .packages + .get("rust") .expect("manifest should cantain a rust package"); - let targ_pkg = rust_pkg.targets.get(&toolchain.target) + let targ_pkg = rust_pkg + .targets + .get(&toolchain.target) .expect("installed manifest should have a known target"); if targ_pkg.components.contains(&component) { - return Err(ErrorKind::RemovingRequiredComponent(self.name.to_string(), component).into()); + return Err( + ErrorKind::RemovingRequiredComponent(self.name.to_string(), component).into(), + ); } - let dist_config = try!(manifestation.read_config()).unwrap(); + let dist_config = manifestation.read_config()?.unwrap(); if !dist_config.components.contains(&component) { - let wildcard_component = Component { target: None, ..component.clone() }; + let wildcard_component = Component { + target: None, + ..component.clone() + }; if dist_config.components.contains(&wildcard_component) { component = wildcard_component; } else { - return Err(ErrorKind::UnknownComponent(self.name.to_string(), component).into()); + return Err( + ErrorKind::UnknownComponent(self.name.to_string(), component).into(), + ); } } let changes = Changes { add_extensions: vec![], - remove_extensions: vec![component] + remove_extensions: vec![component], }; - try!(manifestation.update(&manifest, - changes, - &self.download_cfg(), - self.download_cfg().notify_handler.clone())); + manifestation.update( + &manifest, + changes, + &self.download_cfg(), + self.download_cfg().notify_handler.clone(), + )?; Ok(()) } else { diff --git a/tests/cli-exact.rs b/tests/cli-exact.rs index 3cb5441a2b..a833d12577 100644 --- a/tests/cli-exact.rs +++ b/tests/cli-exact.rs @@ -3,13 +3,11 @@ extern crate rustup_dist; extern crate rustup_mock; -extern crate tempdir; extern crate rustup_utils; +extern crate tempdir; -use rustup_mock::clitools::{self, Config, Scenario, - expect_ok, expect_ok_ex, - expect_err_ex, - this_host_triple}; +use rustup_mock::clitools::{self, expect_err_ex, expect_ok, expect_ok_ex, this_host_triple, + Config, Scenario}; macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) } @@ -20,12 +18,17 @@ fn setup(f: &Fn(&mut Config)) { #[test] fn update() { setup(&|config| { - expect_ok_ex(config, &["rustup", "update", "nightly"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "update", "nightly"], + for_host!( + r" nightly-{0} installed - 1.3.0 (hash-n-2) -"), -for_host!(r"info: syncing channel updates for 'nightly-{0}' +" + ), + for_host!( + r"info: syncing channel updates for 'nightly-{0}' info: latest update on 2015-01-02, rust version 1.3.0 info: downloading component 'rust-std' info: downloading component 'rustc' @@ -35,7 +38,9 @@ info: installing component 'rust-std' info: installing component 'rustc' info: installing component 'cargo' info: installing component 'rust-docs' -")); +" + ), + ); }); } @@ -43,25 +48,37 @@ info: installing component 'rust-docs' fn update_again() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_ok_ex(config, &["rustup", "update", "nightly"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "update", "nightly"], + for_host!( + r" nightly-{0} unchanged - 1.3.0 (hash-n-2) -"), -for_host!(r"info: syncing channel updates for 'nightly-{0}' -")); +" + ), + for_host!( + r"info: syncing channel updates for 'nightly-{0}' +" + ), + ); }); } #[test] fn default() { setup(&|config| { - expect_ok_ex(config, &["rustup", "default", "nightly"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "default", "nightly"], + for_host!( + r" nightly-{0} installed - 1.3.0 (hash-n-2) -"), -for_host!(r"info: syncing channel updates for 'nightly-{0}' +" + ), + for_host!( + r"info: syncing channel updates for 'nightly-{0}' info: latest update on 2015-01-02, rust version 1.3.0 info: downloading component 'rust-std' info: downloading component 'rustc' @@ -72,7 +89,9 @@ info: installing component 'rustc' info: installing component 'cargo' info: installing component 'rust-docs' info: default toolchain set to 'nightly-{0}' -")); +" + ), + ); }); } @@ -81,15 +100,23 @@ fn override_again() { setup(&|config| { let cwd = config.current_dir(); expect_ok(config, &["rustup", "override", "add", "nightly"]); - expect_ok_ex(config, &["rustup", "override", "add", "nightly"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "override", "add", "nightly"], + for_host!( + r" nightly-{} unchanged - 1.3.0 (hash-n-2) -"), -&format!( -r"info: using existing install for 'nightly-{1}' +" + ), + &format!( + r"info: using existing install for 'nightly-{1}' info: override toolchain for '{}' set to 'nightly-{1}' -", cwd.display(), &this_host_triple())); +", + cwd.display(), + &this_host_triple() + ), + ); }); } @@ -99,11 +126,13 @@ fn remove_override() { setup(&|config| { let cwd = config.current_dir(); expect_ok(config, &["rustup", "override", "add", "nightly"]); - expect_ok_ex(config, &["rustup", "override", keyword], - r"", - &format!("info: override toolchain for '{}' removed\n", cwd.display())); + expect_ok_ex( + config, + &["rustup", "override", keyword], + r"", + &format!("info: override toolchain for '{}' removed\n", cwd.display()), + ); }); - } } @@ -112,11 +141,16 @@ fn remove_override_none() { for keyword in &["remove", "unset"] { setup(&|config| { let cwd = config.current_dir(); - expect_ok_ex(config, &["rustup", "override", keyword], - r"", - &format!("info: no override toolchain for '{}' + expect_ok_ex( + config, + &["rustup", "override", keyword], + r"", + &format!( + "info: no override toolchain for '{}' info: you may use `--path ` option to remove override toolchain for a specific path\n", - cwd.display())); + cwd.display() + ), + ); }); } } @@ -129,11 +163,22 @@ fn remove_override_with_path() { config.change_dir(dir.path(), || { expect_ok(config, &["rustup", "override", "add", "nightly"]); }); - expect_ok_ex(config, &["rustup", "override", keyword, "--path", dir.path().to_str().unwrap()], - r"", - &format!("info: override toolchain for '{}' removed\n", dir.path().display())); + expect_ok_ex( + config, + &[ + "rustup", + "override", + keyword, + "--path", + dir.path().to_str().unwrap(), + ], + r"", + &format!( + "info: override toolchain for '{}' removed\n", + dir.path().display() + ), + ); }); - } } @@ -147,11 +192,23 @@ fn remove_override_with_path_deleted() { config.change_dir(&path, || { expect_ok(config, &["rustup", "override", "add", "nightly"]); }); - path + path }; - expect_ok_ex(config, &["rustup", "override", keyword, "--path", path.to_str().unwrap()], - r"", - &format!("info: override toolchain for '{}' removed\n", path.display())); + expect_ok_ex( + config, + &[ + "rustup", + "override", + keyword, + "--path", + path.to_str().unwrap(), + ], + r"", + &format!( + "info: override toolchain for '{}' removed\n", + path.display() + ), + ); }); } } @@ -172,14 +229,19 @@ fn remove_override_nonexistent() { // FIXME TempDir seems to succumb to difficulties removing dirs on windows let _ = rustup_utils::raw::remove_dir(&path); assert!(!path.exists()); - expect_ok_ex(config, &["rustup", "override", keyword, "--nonexistent"], - r"", - &format!("info: override toolchain for '{}' removed\n", path.display())); + expect_ok_ex( + config, + &["rustup", "override", keyword, "--nonexistent"], + r"", + &format!( + "info: override toolchain for '{}' removed\n", + path.display() + ), + ); }); } } - #[test] fn list_overrides() { setup(&|config| { @@ -192,16 +254,22 @@ fn list_overrides() { let trip = this_host_triple(); expect_ok(config, &["rustup", "override", "add", "nightly"]); - expect_ok_ex(config, &["rustup", "override", "list"], - &format!("{:<40}\t{:<20}\n", cwd_formatted, &format!("nightly-{}", trip)), r""); + expect_ok_ex( + config, + &["rustup", "override", "list"], + &format!( + "{:<40}\t{:<20}\n", + cwd_formatted, + &format!("nightly-{}", trip) + ), + r"", + ); }); } - #[test] fn list_overrides_with_nonexistent() { setup(&|config| { - let trip = this_host_triple(); let nonexistent_path = { @@ -220,70 +288,83 @@ fn list_overrides_with_nonexistent() { path_formatted = path_formatted[4..].to_owned(); } - expect_ok_ex(config, &["rustup", "override", "list"], - &format!("{:<40}\t{:<20}\n\n", - path_formatted + " (not a directory)", - &format!("nightly-{}", trip)), - "info: you may remove overrides for non-existent directories with -`rustup override unset --nonexistent`\n"); + expect_ok_ex( + config, + &["rustup", "override", "list"], + &format!( + "{:<40}\t{:<20}\n\n", + path_formatted + " (not a directory)", + &format!("nightly-{}", trip) + ), + "info: you may remove overrides for non-existent directories with +`rustup override unset --nonexistent`\n", + ); }); } - - #[test] fn update_no_manifest() { setup(&|config| { - expect_err_ex(config, &["rustup", "update", "nightly-2016-01-01"], -r"", -for_host!(r"info: syncing channel updates for 'nightly-2016-01-01-{0}' + expect_err_ex( + config, + &["rustup", "update", "nightly-2016-01-01"], + r"", + for_host!( + r"info: syncing channel updates for 'nightly-2016-01-01-{0}' error: no release found for 'nightly-2016-01-01' -")); +" + ), + ); }); } // Issue #111 #[test] fn update_invalid_toolchain() { - setup(&|config| { - expect_err_ex(config, &["rustup", "update", "nightly-2016-03-1"], -r"", -r"info: syncing channel updates for 'nightly-2016-03-1' + setup(&|config| { + expect_err_ex( + config, + &["rustup", "update", "nightly-2016-03-1"], + r"", + r"info: syncing channel updates for 'nightly-2016-03-1' info: latest update on 2015-01-02, rust version 1.3.0 error: target not found: '2016-03-1' -"); - }); - } +", + ); + }); +} #[test] fn default_invalid_toolchain() { - setup(&|config| { - expect_err_ex(config, &["rustup", "default", "nightly-2016-03-1"], -r"", -r"info: syncing channel updates for 'nightly-2016-03-1' + setup(&|config| { + expect_err_ex( + config, + &["rustup", "default", "nightly-2016-03-1"], + r"", + r"info: syncing channel updates for 'nightly-2016-03-1' info: latest update on 2015-01-02, rust version 1.3.0 error: target not found: '2016-03-1' -"); - }); +", + ); + }); } #[test] fn list_targets() { setup(&|config| { let trip = this_host_triple(); - let mut sorted = vec![format!("{} (default)", &*trip), - format!("{} (installed)", clitools::CROSS_ARCH1), - clitools::CROSS_ARCH2.to_string()]; + let mut sorted = vec![ + format!("{} (default)", &*trip), + format!("{} (installed)", clitools::CROSS_ARCH1), + clitools::CROSS_ARCH2.to_string(), + ]; sorted.sort(); let expected = format!("{}\n{}\n{}\n", sorted[0], sorted[1], sorted[2]); expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok(config, &["rustup", "target", "add", - clitools::CROSS_ARCH1]); - expect_ok_ex(config, &["rustup", "target", "list"], -&expected, -r""); + expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1]); + expect_ok_ex(config, &["rustup", "target", "list"], &expected, r""); }); } @@ -291,32 +372,41 @@ r""); fn cross_install_indicates_target() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok_ex(config, &["rustup", "target", "add", clitools::CROSS_ARCH1], -r"", -&format!(r"info: downloading component 'rust-std' for '{0}' + expect_ok_ex( + config, + &["rustup", "target", "add", clitools::CROSS_ARCH1], + r"", + &format!( + r"info: downloading component 'rust-std' for '{0}' info: installing component 'rust-std' for '{0}' -", clitools::CROSS_ARCH1)); +", + clitools::CROSS_ARCH1 + ), + ); }); } - #[test] fn enable_telemetry() { setup(&|config| { - expect_ok_ex(config, - &["rustup", "telemetry", "enable"], - r"", - "info: telemetry set to 'on'\n"); + expect_ok_ex( + config, + &["rustup", "telemetry", "enable"], + r"", + "info: telemetry set to 'on'\n", + ); }); } #[test] fn disable_telemetry() { setup(&|config| { - expect_ok_ex(config, - &["rustup", "telemetry", "disable"], - r"", - "info: telemetry set to 'off'\n"); + expect_ok_ex( + config, + &["rustup", "telemetry", "disable"], + r"", + "info: telemetry set to 'off'\n", + ); }); } @@ -324,9 +414,11 @@ fn disable_telemetry() { #[test] fn undefined_linked_toolchain() { setup(&|config| { - expect_err_ex(config, - &["cargo", "+bogus", "test"], - r"", - &format!("error: toolchain 'bogus' is not installed\n")); + expect_err_ex( + config, + &["cargo", "+bogus", "test"], + r"", + &format!("error: toolchain 'bogus' is not installed\n"), + ); }); } diff --git a/tests/cli-inst-interactive.rs b/tests/cli-inst-interactive.rs index de1a132fc3..7dd0fb62e6 100644 --- a/tests/cli-inst-interactive.rs +++ b/tests/cli-inst-interactive.rs @@ -1,17 +1,15 @@ //! Tests of the interactive console installer -extern crate rustup_mock; -extern crate rustup_utils; #[macro_use] extern crate lazy_static; +extern crate rustup_mock; +extern crate rustup_utils; extern crate scopeguard; use std::sync::Mutex; use std::process::Stdio; use std::io::Write; -use rustup_mock::clitools::{self, Config, Scenario, - SanitizedOutput, - expect_stdout_ok}; +use rustup_mock::clitools::{self, expect_stdout_ok, Config, SanitizedOutput, Scenario}; use rustup_mock::{get_path, restore_path}; pub fn setup(f: &Fn(&Config)) { @@ -40,7 +38,12 @@ fn run_input(config: &Config, args: &[&str], input: &str) -> SanitizedOutput { cmd.stderr(Stdio::piped()); let mut child = cmd.spawn().unwrap(); - child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap(); + child + .stdin + .as_mut() + .unwrap() + .write_all(input.as_bytes()) + .unwrap(); let out = child.wait_with_output().unwrap(); SanitizedOutput { @@ -79,7 +82,8 @@ fn blank_lines_around_stderr_log_output_install() { // line that comes from the user pressing enter, then log // output on stderr, then an explicit blank line on stdout // before printing $toolchain installed - assert!(out.stdout.contains(r" + assert!(out.stdout.contains( + r" 3) Cancel installation @@ -87,7 +91,8 @@ fn blank_lines_around_stderr_log_output_install() { Rust is installed now. Great! -")); +" + )); }); } @@ -97,13 +102,15 @@ fn blank_lines_around_stderr_log_output_update() { run_input(config, &["rustup-init"], "\n\n"); let out = run_input(config, &["rustup-init"], "\n\n"); - assert!(out.stdout.contains(r" + assert!(out.stdout.contains( + r" 3) Cancel installation Rust is installed now. Great! -")); +" + )); }); } @@ -121,7 +128,10 @@ fn with_no_modify_path() { setup(&|config| { let out = run_input(config, &["rustup-init", "--no-modify-path"], "\n\n"); assert!(out.ok); - assert!(out.stdout.contains("This path needs to be in your PATH environment variable")); + assert!( + out.stdout + .contains("This path needs to be in your PATH environment variable") + ); if cfg!(unix) { assert!(!config.homedir.join(".profile").exists()); @@ -142,7 +152,11 @@ fn with_no_toolchain() { #[test] fn with_non_default_toolchain() { setup(&|config| { - let out = run_input(config, &["rustup-init", "--default-toolchain=nightly"], "\n\n"); + let out = run_input( + config, + &["rustup-init", "--default-toolchain=nightly"], + "\n\n", + ); assert!(out.ok); expect_stdout_ok(config, &["rustup", "show"], "nightly"); @@ -152,8 +166,11 @@ fn with_non_default_toolchain() { #[test] fn with_non_release_channel_non_default_toolchain() { setup(&|config| { - let out = run_input(config, &["rustup-init", "--default-toolchain=nightly-2015-01-02"], - "\n\n"); + let out = run_input( + config, + &["rustup-init", "--default-toolchain=nightly-2015-01-02"], + "\n\n", + ); assert!(out.ok); expect_stdout_ok(config, &["rustup", "show"], "nightly"); @@ -164,8 +181,7 @@ fn with_non_release_channel_non_default_toolchain() { #[test] fn set_nightly_toolchain() { setup(&|config| { - let out = run_input(config, &["rustup-init"], - "2\n\nnightly\n\n\n\n"); + let out = run_input(config, &["rustup-init"], "2\n\nnightly\n\n\n\n"); assert!(out.ok); expect_stdout_ok(config, &["rustup", "show"], "nightly"); @@ -175,8 +191,7 @@ fn set_nightly_toolchain() { #[test] fn set_no_modify_path() { setup(&|config| { - let out = run_input(config, &["rustup-init"], - "2\n\n\nno\n\n\n"); + let out = run_input(config, &["rustup-init"], "2\n\n\nno\n\n\n"); assert!(out.ok); if cfg!(unix) { @@ -188,8 +203,11 @@ fn set_no_modify_path() { #[test] fn set_nightly_toolchain_and_unset() { setup(&|config| { - let out = run_input(config, &["rustup-init"], - "2\n\nnightly\n\n2\n\nbeta\n\n\n\n"); + let out = run_input( + config, + &["rustup-init"], + "2\n\nnightly\n\n2\n\nbeta\n\n\n\n", + ); assert!(out.ok); expect_stdout_ok(config, &["rustup", "show"], "beta"); @@ -199,8 +217,7 @@ fn set_nightly_toolchain_and_unset() { #[test] fn user_says_nope_after_advanced_install() { setup(&|config| { - let out = run_input(config, &["rustup-init"], - "2\n\n\n\nn\n\n"); + let out = run_input(config, &["rustup-init"], "2\n\n\n\nn\n\n"); assert!(out.ok); assert!(!config.cargodir.join("bin").exists()); }); diff --git a/tests/cli-misc.rs b/tests/cli-misc.rs index 9abd621756..06c76f6270 100644 --- a/tests/cli-misc.rs +++ b/tests/cli-misc.rs @@ -2,15 +2,14 @@ //! dist server, mostly derived from multirust/test-v2.sh extern crate rustup_dist; -extern crate rustup_utils; extern crate rustup_mock; -extern crate time; +extern crate rustup_utils; extern crate tempdir; +extern crate time; -use rustup_mock::clitools::{self, Config, Scenario, - expect_stdout_ok, expect_stderr_ok, expect_ok_ex, - expect_ok, expect_err, expect_timeout_ok, - run, this_host_triple, set_current_dist_date}; +use rustup_mock::clitools::{self, expect_err, expect_ok, expect_ok_ex, expect_stderr_ok, + expect_stdout_ok, expect_timeout_ok, run, set_current_dist_date, + this_host_triple, Config, Scenario}; use rustup_utils::{raw, utils}; use std::ops::Add; @@ -54,30 +53,42 @@ fn rustc_with_bad_rustup_toolchain_env_var() { #[test] fn custom_invalid_names() { setup(&|config| { - expect_err(config, &["rustup", "toolchain", "link", "nightly", - "foo"], - for_host!("invalid custom toolchain name: 'nightly-{0}'")); - expect_err(config, &["rustup", "toolchain", "link", "beta", - "foo"], - for_host!("invalid custom toolchain name: 'beta-{0}'")); - expect_err(config, &["rustup", "toolchain", "link", "stable", - "foo"], - for_host!("invalid custom toolchain name: 'stable-{0}'")); + expect_err( + config, + &["rustup", "toolchain", "link", "nightly", "foo"], + for_host!("invalid custom toolchain name: 'nightly-{0}'"), + ); + expect_err( + config, + &["rustup", "toolchain", "link", "beta", "foo"], + for_host!("invalid custom toolchain name: 'beta-{0}'"), + ); + expect_err( + config, + &["rustup", "toolchain", "link", "stable", "foo"], + for_host!("invalid custom toolchain name: 'stable-{0}'"), + ); }); } #[test] fn custom_invalid_names_with_archive_dates() { setup(&|config| { - expect_err(config, &["rustup", "toolchain", "link", "nightly-2015-01-01", - "foo"], - for_host!("invalid custom toolchain name: 'nightly-2015-01-01-{0}'")); - expect_err(config, &["rustup", "toolchain", "link", "beta-2015-01-01", - "foo"], - for_host!("invalid custom toolchain name: 'beta-2015-01-01-{0}'")); - expect_err(config, &["rustup", "toolchain", "link", "stable-2015-01-01", - "foo"], - for_host!("invalid custom toolchain name: 'stable-2015-01-01-{0}'")); + expect_err( + config, + &["rustup", "toolchain", "link", "nightly-2015-01-01", "foo"], + for_host!("invalid custom toolchain name: 'nightly-2015-01-01-{0}'"), + ); + expect_err( + config, + &["rustup", "toolchain", "link", "beta-2015-01-01", "foo"], + for_host!("invalid custom toolchain name: 'beta-2015-01-01-{0}'"), + ); + expect_err( + config, + &["rustup", "toolchain", "link", "stable-2015-01-01", "foo"], + for_host!("invalid custom toolchain name: 'stable-2015-01-01-{0}'"), + ); }); } @@ -86,12 +97,17 @@ fn running_with_v2_metadata() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); // Replace the metadata version - rustup_utils::raw::write_file(&config.rustupdir.join("version"), - "2").unwrap(); - expect_err(config, &["rustup", "default", "nightly"], - "rustup's metadata is out of date. run `rustup self upgrade-data`"); - expect_err(config, &["rustc", "--version"], - "rustup's metadata is out of date. run `rustup self upgrade-data`"); + rustup_utils::raw::write_file(&config.rustupdir.join("version"), "2").unwrap(); + expect_err( + config, + &["rustup", "default", "nightly"], + "rustup's metadata is out of date. run `rustup self upgrade-data`", + ); + expect_err( + config, + &["rustc", "--version"], + "rustup's metadata is out of date. run `rustup self upgrade-data`", + ); }); } @@ -103,15 +119,16 @@ fn upgrade_v2_metadata_to_v12() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); // Replace the metadata version - rustup_utils::raw::write_file(&config.rustupdir.join("version"), - "2").unwrap(); + rustup_utils::raw::write_file(&config.rustupdir.join("version"), "2").unwrap(); expect_stderr_ok(config, &["rustup", "self", "upgrade-data"], "warning: this upgrade will remove all existing toolchains. you will need to reinstall them"); - expect_err(config, &["rustc", "--version"], - for_host!("toolchain 'nightly-{0}' is not installed")); + expect_err( + config, + &["rustc", "--version"], + for_host!("toolchain 'nightly-{0}' is not installed"), + ); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } @@ -121,19 +138,33 @@ fn upgrade_toml_settings() { setup(&|config| { rustup_utils::raw::write_file(&config.rustupdir.join("version"), "2").unwrap(); rustup_utils::raw::write_file(&config.rustupdir.join("default"), "beta").unwrap(); - rustup_utils::raw::write_file(&config.rustupdir.join("overrides"), - "a;nightly\nb;stable").unwrap(); + rustup_utils::raw::write_file(&config.rustupdir.join("overrides"), "a;nightly\nb;stable") + .unwrap(); rustup_utils::raw::write_file(&config.rustupdir.join("telemetry-on"), "").unwrap(); - expect_err(config, &["rustup", "default", "nightly"], - "rustup's metadata is out of date. run `rustup self upgrade-data`"); + expect_err( + config, + &["rustup", "default", "nightly"], + "rustup's metadata is out of date. run `rustup self upgrade-data`", + ); // Replace the metadata version - assert!(!rustup_utils::raw::is_file(&config.rustupdir.join("version"))); - assert!(!rustup_utils::raw::is_file(&config.rustupdir.join("default"))); - assert!(!rustup_utils::raw::is_file(&config.rustupdir.join("overrides"))); - assert!(!rustup_utils::raw::is_file(&config.rustupdir.join("telemetry-on"))); - assert!(rustup_utils::raw::is_file(&config.rustupdir.join("settings.toml"))); - - let content = rustup_utils::raw::read_file(&config.rustupdir.join("settings.toml")).unwrap(); + assert!(!rustup_utils::raw::is_file(&config + .rustupdir + .join("version"))); + assert!(!rustup_utils::raw::is_file(&config + .rustupdir + .join("default"))); + assert!(!rustup_utils::raw::is_file(&config + .rustupdir + .join("overrides"))); + assert!(!rustup_utils::raw::is_file(&config + .rustupdir + .join("telemetry-on"))); + assert!(rustup_utils::raw::is_file(&config + .rustupdir + .join("settings.toml"))); + + let content = + rustup_utils::raw::read_file(&config.rustupdir.join("settings.toml")).unwrap(); assert!(content.contains("version = \"2\"")); assert!(content.contains("[overrides]")); assert!(content.contains("a = \"nightly")); @@ -146,11 +177,16 @@ fn upgrade_toml_settings() { #[test] fn update_all_no_update_whitespace() { setup(&|config| { - expect_stdout_ok(config, &["rustup", "update", "nightly"], -for_host!(r" + expect_stdout_ok( + config, + &["rustup", "update", "nightly"], + for_host!( + r" nightly-{} installed - 1.3.0 (hash-n-2) -")); +" + ), + ); }); } @@ -232,8 +268,7 @@ fn multi_host_smoke_test() { clitools::setup(Scenario::MultiHost, &|config| { let ref toolchain = format!("nightly-{}", clitools::MULTI_ARCH1); expect_ok(config, &["rustup", "default", toolchain]); - expect_stdout_ok(config, &["rustc", "--version"], - "xxxx-n-2"); // cross-host mocks have their own versions + expect_stdout_ok(config, &["rustc", "--version"], "xxxx-n-2"); // cross-host mocks have their own versions }); } @@ -242,21 +277,26 @@ fn custom_toolchain_cargo_fallback_proxy() { setup(&|config| { let path = config.customdir.join("custom-1"); - expect_ok(config, &["rustup", "toolchain", "link", "mytoolchain", - &path.to_string_lossy()]); + expect_ok( + config, + &[ + "rustup", + "toolchain", + "link", + "mytoolchain", + &path.to_string_lossy(), + ], + ); expect_ok(config, &["rustup", "default", "mytoolchain"]); expect_ok(config, &["rustup", "update", "stable"]); - expect_stdout_ok(config, &["cargo", "--version"], - "hash-s-2"); + expect_stdout_ok(config, &["cargo", "--version"], "hash-s-2"); expect_ok(config, &["rustup", "update", "beta"]); - expect_stdout_ok(config, &["cargo", "--version"], - "hash-b-2"); + expect_stdout_ok(config, &["cargo", "--version"], "hash-b-2"); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["cargo", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["cargo", "--version"], "hash-n-2"); }); } @@ -265,25 +305,38 @@ fn custom_toolchain_cargo_fallback_run() { setup(&|config| { let path = config.customdir.join("custom-1"); - expect_ok(config, &["rustup", "toolchain", "link", "mytoolchain", - &path.to_string_lossy()]); + expect_ok( + config, + &[ + "rustup", + "toolchain", + "link", + "mytoolchain", + &path.to_string_lossy(), + ], + ); expect_ok(config, &["rustup", "default", "mytoolchain"]); expect_ok(config, &["rustup", "update", "stable"]); - expect_stdout_ok(config, &["rustup", "run", "mytoolchain", - "cargo", "--version"], - "hash-s-2"); + expect_stdout_ok( + config, + &["rustup", "run", "mytoolchain", "cargo", "--version"], + "hash-s-2", + ); expect_ok(config, &["rustup", "update", "beta"]); - expect_stdout_ok(config, &["rustup", "run", "mytoolchain", - "cargo", "--version"], - "hash-b-2"); + expect_stdout_ok( + config, + &["rustup", "run", "mytoolchain", "cargo", "--version"], + "hash-b-2", + ); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustup", "run", "mytoolchain", - "cargo", "--version"], - "hash-n-2"); - + expect_stdout_ok( + config, + &["rustup", "run", "mytoolchain", "cargo", "--version"], + "hash-n-2", + ); }); } @@ -309,12 +362,25 @@ fn rustup_failed_path_search() { let ref tool_path = config.exedir.join(&format!("fake_proxy{}", EXE_SUFFIX)); utils::hardlink_file(rustup_path, tool_path).expect("Failed to create fake proxy for test"); - expect_ok(config, &["rustup", "toolchain", "link", "custom", - &config.customdir.join("custom-1").to_string_lossy()]); + expect_ok( + config, + &[ + "rustup", + "toolchain", + "link", + "custom", + &config.customdir.join("custom-1").to_string_lossy(), + ], + ); let broken = &["rustup", "run", "custom", "fake_proxy"]; - expect_err(config, broken, &format!( - "toolchain 'custom' does not have the binary `fake_proxy{}`", EXE_SUFFIX - )); + expect_err( + config, + broken, + &format!( + "toolchain 'custom' does not have the binary `fake_proxy{}`", + EXE_SUFFIX + ), + ); // Hardlink will be automatically cleaned up by test setup code }); @@ -324,8 +390,11 @@ fn rustup_failed_path_search() { fn rustup_run_not_installed() { setup(&|config| { expect_ok(config, &["rustup", "install", "stable"]); - expect_err(config, &["rustup", "run", "nightly", "rustc", "--version"], - for_host!("toolchain 'nightly-{0}' is not installed")); + expect_err( + config, + &["rustup", "run", "nightly", "rustc", "--version"], + for_host!("toolchain 'nightly-{0}' is not installed"), + ); }); } @@ -333,8 +402,18 @@ fn rustup_run_not_installed() { fn rustup_run_install() { setup(&|config| { expect_ok(config, &["rustup", "install", "stable"]); - expect_stderr_ok(config, &["rustup", "run", "--install", "nightly", "cargo", "--version"], - "info: installing component 'rustc'"); + expect_stderr_ok( + config, + &[ + "rustup", + "run", + "--install", + "nightly", + "cargo", + "--version", + ], + "info: installing component 'rustc'", + ); }); } @@ -348,7 +427,9 @@ fn multirust_env_compat() { let out = cmd.output().unwrap(); assert!(out.status.success()); let stderr = String::from_utf8(out.stderr).unwrap(); - assert!(stderr.contains("environment variable MULTIRUST_HOME is deprecated. Use RUSTUP_HOME")); + assert!( + stderr.contains("environment variable MULTIRUST_HOME is deprecated. Use RUSTUP_HOME") + ); }); } @@ -358,8 +439,11 @@ fn toolchains_are_resolved_early() { expect_ok(config, &["rustup", "default", "nightly"]); let full_toolchain = format!("nightly-{}", this_host_triple()); - expect_stderr_ok(config, &["rustup", "default", &full_toolchain], - &format!("info: using existing install for '{}'", full_toolchain)); + expect_stderr_ok( + config, + &["rustup", "default", &full_toolchain], + &format!("info: using existing install for '{}'", full_toolchain), + ); }); } @@ -368,7 +452,10 @@ fn toolchains_are_resolved_early() { fn proxies_pass_empty_args() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok(config, &["rustup", "run", "nightly", "rustc", "--empty-arg-test", ""]); + expect_ok( + config, + &["rustup", "run", "nightly", "rustc", "--empty-arg-test", ""], + ); }); } @@ -395,8 +482,16 @@ fn telemetry_supports_huge_output() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); expect_ok(config, &["rustup", "telemetry", "enable"]); - expect_timeout_ok(config, StdDuration::from_secs(5), &["rustc", "--huge-output"]); - expect_stdout_ok(config, &["rustup", "telemetry", "analyze"], "'E0428': 10000") + expect_timeout_ok( + config, + StdDuration::from_secs(5), + &["rustc", "--huge-output"], + ); + expect_stdout_ok( + config, + &["rustup", "telemetry", "analyze"], + "'E0428': 10000", + ) }) } @@ -412,7 +507,12 @@ fn telemetry_cleanup_removes_old_files() { let one_day = time::Duration::days(1); for _ in 0..110 { - let file_name = format!("log-{}-{:02}-{:02}.json", d.tm_year + 1900, d.tm_mon + 1, d.tm_mday); + let file_name = format!( + "log-{}-{:02}-{:02}.json", + d.tm_year + 1900, + d.tm_mon + 1, + d.tm_mday + ); let _ = raw::write_file(&telemetry_dir.join(&file_name), ""); d = d.add(one_day); } @@ -446,9 +546,15 @@ fn rls_does_not_exist_in_toolchain() { // FIXME: If rls exists in the toolchain, this should suggest a command // to run to install it expect_ok(config, &["rustup", "default", "stable"]); - expect_err(config, &["rls", "--version"], - &format!("toolchain 'stable-{}' does not have the binary `rls{}`", - this_host_triple(), EXE_SUFFIX)); + expect_err( + config, + &["rls", "--version"], + &format!( + "toolchain 'stable-{}' does not have the binary `rls{}`", + this_host_triple(), + EXE_SUFFIX + ), + ); }); } @@ -491,11 +597,24 @@ fn install_stops_if_rustc_exists() { let temp_dir_path = temp_dir.path().to_str().unwrap(); setup(&|config| { - let out = run(config, "rustup-init", &[], - &[("RUSTUP_INIT_SKIP_PATH_CHECK", "no"), ("PATH", &temp_dir_path)]); + let out = run( + config, + "rustup-init", + &[], + &[ + ("RUSTUP_INIT_SKIP_PATH_CHECK", "no"), + ("PATH", &temp_dir_path), + ], + ); assert!(!out.ok); - assert!(out.stderr.contains("it looks like you have an existing installation of Rust at:")); - assert!(out.stderr.contains("if this is what you want, restart the installation with `-y'")); + assert!( + out.stderr + .contains("it looks like you have an existing installation of Rust at:") + ); + assert!( + out.stderr + .contains("if this is what you want, restart the installation with `-y'") + ); }); } @@ -508,11 +627,24 @@ fn install_stops_if_cargo_exists() { let temp_dir_path = temp_dir.path().to_str().unwrap(); setup(&|config| { - let out = run(config, "rustup-init", &[], - &[("RUSTUP_INIT_SKIP_PATH_CHECK", "no"), ("PATH", &temp_dir_path)]); + let out = run( + config, + "rustup-init", + &[], + &[ + ("RUSTUP_INIT_SKIP_PATH_CHECK", "no"), + ("PATH", &temp_dir_path), + ], + ); assert!(!out.ok); - assert!(out.stderr.contains("it looks like you have an existing installation of Rust at:")); - assert!(out.stderr.contains("if this is what you want, restart the installation with `-y'")); + assert!( + out.stderr + .contains("it looks like you have an existing installation of Rust at:") + ); + assert!( + out.stderr + .contains("if this is what you want, restart the installation with `-y'") + ); }); } @@ -525,8 +657,15 @@ fn with_no_prompt_install_succeeds_if_rustc_exists() { let temp_dir_path = temp_dir.path().to_str().unwrap(); setup(&|config| { - let out = run(config, "rustup-init", &["-y"], - &[("RUSTUP_INIT_SKIP_PATH_CHECK", "no"), ("PATH", &temp_dir_path)]); + let out = run( + config, + "rustup-init", + &["-y"], + &[ + ("RUSTUP_INIT_SKIP_PATH_CHECK", "no"), + ("PATH", &temp_dir_path), + ], + ); assert!(out.ok); }); } @@ -554,17 +693,28 @@ fn toolchain_broken_symlink() { // We artifically create a broken symlink toolchain -- but this can also happen "legitimately" // by having a proper toolchain there, using "toolchain link", and later removing the directory. fs::create_dir(config.rustupdir.join("toolchains")).unwrap(); - create_symlink_dir(config.rustupdir.join("this-directory-does-not-exist"), config.rustupdir.join("toolchains").join("test")); + create_symlink_dir( + config.rustupdir.join("this-directory-does-not-exist"), + config.rustupdir.join("toolchains").join("test"), + ); // Make sure this "fake install" actually worked expect_ok_ex(config, &["rustup", "toolchain", "list"], "test\n", ""); // Now try to uninstall it. That should work only once. - expect_ok_ex(config, &["rustup", "toolchain", "uninstall", "test"], "", -r"info: uninstalling toolchain 'test' + expect_ok_ex( + config, + &["rustup", "toolchain", "uninstall", "test"], + "", + r"info: uninstalling toolchain 'test' info: toolchain 'test' uninstalled -"); - expect_ok_ex(config, &["rustup", "toolchain", "uninstall", "test"], "", -r"info: no toolchain installed for 'test' -"); +", + ); + expect_ok_ex( + config, + &["rustup", "toolchain", "uninstall", "test"], + "", + r"info: no toolchain installed for 'test' +", + ); }); } @@ -578,8 +728,11 @@ fn update_unavailable_rustc() { expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); - expect_err(config, &["rustup", "update", "nightly"], - "some components unavailable for download: 'rustc', 'cargo'"); + expect_err( + config, + &["rustup", "update", "nightly"], + "some components unavailable for download: 'rustc', 'cargo'", + ); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); }); diff --git a/tests/cli-rustup.rs b/tests/cli-rustup.rs index ad88e4bb38..e4ecfef4c0 100644 --- a/tests/cli-rustup.rs +++ b/tests/cli-rustup.rs @@ -1,20 +1,17 @@ //! Test cases for new rustup UI extern crate rustup_dist; -extern crate rustup_utils; extern crate rustup_mock; +extern crate rustup_utils; extern crate tempdir; use std::fs; use std::env::consts::EXE_SUFFIX; use std::process; use rustup_utils::raw; -use rustup_mock::clitools::{self, Config, Scenario, - expect_ok, expect_ok_ex, - expect_stderr_ok, expect_stdout_ok, - expect_err, - set_current_dist_date, - this_host_triple}; +use rustup_mock::clitools::{self, expect_err, expect_ok, expect_ok_ex, expect_stderr_ok, + expect_stdout_ok, set_current_dist_date, this_host_triple, Config, + Scenario}; macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) } @@ -30,12 +27,17 @@ fn rustup_stable() { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "update", "stable"]); set_current_dist_date(config, "2015-01-02"); - expect_ok_ex(config, &["rustup", "update", "--no-self-update"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "update", "--no-self-update"], + for_host!( + r" stable-{0} updated - 1.1.0 (hash-s-2) -"), -for_host!(r"info: syncing channel updates for 'stable-{0}' +" + ), + for_host!( + r"info: syncing channel updates for 'stable-{0}' info: latest update on 2015-01-02, rust version 1.1.0 info: downloading component 'rust-std' info: downloading component 'rustc' @@ -49,7 +51,9 @@ info: installing component 'rust-std' info: installing component 'rustc' info: installing component 'cargo' info: installing component 'rust-docs' -")); +" + ), + ); }); } @@ -58,13 +62,20 @@ fn rustup_stable_no_change() { setup(&|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "update", "stable"]); - expect_ok_ex(config, &["rustup", "update", "--no-self-update"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "update", "--no-self-update"], + for_host!( + r" stable-{0} unchanged - 1.0.0 (hash-s-1) -"), -for_host!(r"info: syncing channel updates for 'stable-{0}' -")); +" + ), + for_host!( + r"info: syncing channel updates for 'stable-{0}' +" + ), + ); }); } @@ -76,14 +87,19 @@ fn rustup_all_channels() { expect_ok(config, &["rustup", "update", "beta"]); expect_ok(config, &["rustup", "update", "nightly"]); set_current_dist_date(config, "2015-01-02"); - expect_ok_ex(config, &["rustup", "update", "--no-self-update"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "update", "--no-self-update"], + for_host!( + r" stable-{0} updated - 1.1.0 (hash-s-2) beta-{0} updated - 1.2.0 (hash-b-2) nightly-{0} updated - 1.3.0 (hash-n-2) -"), -for_host!(r"info: syncing channel updates for 'stable-{0}' +" + ), + for_host!( + r"info: syncing channel updates for 'stable-{0}' info: latest update on 2015-01-02, rust version 1.1.0 info: downloading component 'rust-std' info: downloading component 'rustc' @@ -125,7 +141,9 @@ info: installing component 'rust-std' info: installing component 'rustc' info: installing component 'cargo' info: installing component 'rust-docs' -")); +" + ), + ); }) } @@ -138,14 +156,19 @@ fn rustup_some_channels_up_to_date() { expect_ok(config, &["rustup", "update", "nightly"]); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "beta"]); - expect_ok_ex(config, &["rustup", "update", "--no-self-update"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "update", "--no-self-update"], + for_host!( + r" stable-{0} updated - 1.1.0 (hash-s-2) beta-{0} unchanged - 1.2.0 (hash-b-2) nightly-{0} updated - 1.3.0 (hash-n-2) -"), -for_host!(r"info: syncing channel updates for 'stable-{0}' +" + ), + for_host!( + r"info: syncing channel updates for 'stable-{0}' info: latest update on 2015-01-02, rust version 1.1.0 info: downloading component 'rust-std' info: downloading component 'rustc' @@ -174,7 +197,9 @@ info: installing component 'rust-std' info: installing component 'rustc' info: installing component 'cargo' info: installing component 'rust-docs' -")); +" + ), + ); }) } @@ -183,22 +208,30 @@ fn rustup_no_channels() { setup(&|config| { expect_ok(config, &["rustup", "update", "stable"]); expect_ok(config, &["rustup", "toolchain", "remove", "stable"]); - expect_ok_ex(config, &["rustup", "update", "--no-self-update"], -r"", -r"info: no updatable toolchains installed -"); + expect_ok_ex( + config, + &["rustup", "update", "--no-self-update"], + r"", + r"info: no updatable toolchains installed +", + ); }) } #[test] fn default() { setup(&|config| { - expect_ok_ex(config, &["rustup", "default", "nightly"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "default", "nightly"], + for_host!( + r" nightly-{0} installed - 1.3.0 (hash-n-2) -"), -for_host!(r"info: syncing channel updates for 'nightly-{0}' +" + ), + for_host!( + r"info: syncing channel updates for 'nightly-{0}' info: latest update on 2015-01-02, rust version 1.3.0 info: downloading component 'rust-std' info: downloading component 'rustc' @@ -209,7 +242,9 @@ info: installing component 'rustc' info: installing component 'cargo' info: installing component 'rust-docs' info: default toolchain set to 'nightly-{0}' -")); +" + ), + ); }); } @@ -217,19 +252,24 @@ info: default toolchain set to 'nightly-{0}' fn rustup_xz() { setup(&|config| { set_current_dist_date(config, "2015-01-01"); - expect_stderr_ok(config, &["rustup", "--verbose", "update", "nightly"], -for_host!(r"dist/2015-01-01/rust-std-nightly-{0}.tar.xz")); + expect_stderr_ok( + config, + &["rustup", "--verbose", "update", "nightly"], + for_host!(r"dist/2015-01-01/rust-std-nightly-{0}.tar.xz"), + ); }); } #[test] fn add_target() { setup(&|config| { - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH1); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH1 + ); expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok(config, &["rustup", "target", "add", - clitools::CROSS_ARCH1]); + expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1]); assert!(config.rustupdir.join(path).exists()); }); } @@ -237,14 +277,18 @@ fn add_target() { #[test] fn remove_target() { setup(&|config| { - let ref path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH1); + let ref path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH1 + ); expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok(config, &["rustup", "target", "add", - clitools::CROSS_ARCH1]); + expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1]); assert!(config.rustupdir.join(path).exists()); - expect_ok(config, &["rustup", "target", "remove", - clitools::CROSS_ARCH1]); + expect_ok( + config, + &["rustup", "target", "remove", clitools::CROSS_ARCH1], + ); assert!(!config.rustupdir.join(path).exists()); }); } @@ -253,24 +297,50 @@ fn remove_target() { fn add_remove_multiple_targets() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok(config, &["rustup", "target", "add", - clitools::CROSS_ARCH1, - clitools::CROSS_ARCH2]); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH1); + expect_ok( + config, + &[ + "rustup", + "target", + "add", + clitools::CROSS_ARCH1, + clitools::CROSS_ARCH2, + ], + ); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH1 + ); assert!(config.rustupdir.join(path).exists()); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH2); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH2 + ); assert!(config.rustupdir.join(path).exists()); - expect_ok(config, &["rustup", "target", "remove", - clitools::CROSS_ARCH1, - clitools::CROSS_ARCH2]); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH1); + expect_ok( + config, + &[ + "rustup", + "target", + "remove", + clitools::CROSS_ARCH1, + clitools::CROSS_ARCH2, + ], + ); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH1 + ); assert!(!config.rustupdir.join(path).exists()); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH2); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH2 + ); assert!(!config.rustupdir.join(path).exists()); }); } @@ -279,19 +349,30 @@ fn add_remove_multiple_targets() { fn list_targets() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustup", "target", "list"], - clitools::CROSS_ARCH1); + expect_stdout_ok(config, &["rustup", "target", "list"], clitools::CROSS_ARCH1); }); } #[test] fn add_target_explicit() { setup(&|config| { - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH1); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH1 + ); expect_ok(config, &["rustup", "update", "nightly"]); - expect_ok(config, &["rustup", "target", "add", "--toolchain", "nightly", - clitools::CROSS_ARCH1]); + expect_ok( + config, + &[ + "rustup", + "target", + "add", + "--toolchain", + "nightly", + clitools::CROSS_ARCH1, + ], + ); assert!(config.rustupdir.join(path).exists()); }); } @@ -299,14 +380,35 @@ fn add_target_explicit() { #[test] fn remove_target_explicit() { setup(&|config| { - let ref path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - &this_host_triple(), clitools::CROSS_ARCH1); + let ref path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + &this_host_triple(), + clitools::CROSS_ARCH1 + ); expect_ok(config, &["rustup", "update", "nightly"]); - expect_ok(config, &["rustup", "target", "add", "--toolchain", "nightly", - clitools::CROSS_ARCH1]); + expect_ok( + config, + &[ + "rustup", + "target", + "add", + "--toolchain", + "nightly", + clitools::CROSS_ARCH1, + ], + ); assert!(config.rustupdir.join(path).exists()); - expect_ok(config, &["rustup", "target", "remove", "--toolchain", "nightly", - clitools::CROSS_ARCH1]); + expect_ok( + config, + &[ + "rustup", + "target", + "remove", + "--toolchain", + "nightly", + clitools::CROSS_ARCH1, + ], + ); assert!(!config.rustupdir.join(path).exists()); }); } @@ -315,8 +417,11 @@ fn remove_target_explicit() { fn list_targets_explicit() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustup", "target", "list", "--toolchain", "nightly"], - clitools::CROSS_ARCH1); + expect_stdout_ok( + config, + &["rustup", "target", "list", "--toolchain", "nightly"], + clitools::CROSS_ARCH1, + ); }); } @@ -325,17 +430,13 @@ fn link() { setup(&|config| { let path = config.customdir.join("custom-1"); let path = path.to_string_lossy(); - expect_ok(config, &["rustup", "toolchain", "link", "custom", - &path]); + expect_ok(config, &["rustup", "toolchain", "link", "custom", &path]); expect_ok(config, &["rustup", "default", "custom"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-c-1"); - expect_stdout_ok(config, &["rustup", "show"], - "custom (default)"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-c-1"); + expect_stdout_ok(config, &["rustup", "show"], "custom (default)"); expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustup", "show"], - "custom"); + expect_stdout_ok(config, &["rustup", "show"], "custom"); }); } @@ -356,14 +457,11 @@ fn fallback_cargo_calls_correct_rustc() { // Install a custom toolchain and a nightly toolchain for the cargo fallback let path = config.customdir.join("custom-1"); let path = path.to_string_lossy(); - expect_ok(config, &["rustup", "toolchain", "link", "custom", - &path]); + expect_ok(config, &["rustup", "toolchain", "link", "custom", &path]); expect_ok(config, &["rustup", "default", "custom"]); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-c-1"); - expect_stdout_ok(config, &["cargo", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-c-1"); + expect_stdout_ok(config, &["cargo", "--version"], "hash-n-2"); assert!(rustc_path.exists()); @@ -371,20 +469,24 @@ fn fallback_cargo_calls_correct_rustc() { // We should be ultimately calling the custom rustc, according to the // RUSTUP_TOOLCHAIN variable set by the original "cargo" proxy, and // interpreted by the nested "rustc" proxy. - expect_stdout_ok(config, &["cargo", "--call-rustc"], - "hash-c-1"); + expect_stdout_ok(config, &["cargo", "--call-rustc"], "hash-c-1"); }); } #[test] fn show_toolchain_none() { setup(&|config| { - expect_ok_ex(config, &["rustup", "show"], -for_host!(r"Default host: {0} + expect_ok_ex( + config, + &["rustup", "show"], + for_host!( + r"Default host: {0} no active toolchain -"), -r""); +" + ), + r"", + ); }); } @@ -392,13 +494,18 @@ r""); fn show_toolchain_default() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok_ex(config, &["rustup", "show"], -for_host!(r"Default host: {0} + expect_ok_ex( + config, + &["rustup", "show"], + for_host!( + r"Default host: {0} nightly-{0} (default) 1.3.0 (hash-n-2) -"), -r""); +" + ), + r"", + ); }); } @@ -407,8 +514,11 @@ fn show_multiple_toolchains() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "update", "stable"]); - expect_ok_ex(config, &["rustup", "show"], -for_host!(r"Default host: {0} + expect_ok_ex( + config, + &["rustup", "show"], + for_host!( + r"Default host: {0} installed toolchains -------------------- @@ -422,22 +532,35 @@ active toolchain nightly-{0} (default) 1.3.0 (hash-n-2) -"), -r""); +" + ), + r"", + ); }); } #[test] fn show_multiple_targets() { // Using the MULTI_ARCH1 target doesn't work on i686 linux - if cfg!(target_os = "linux") && cfg!(target_arch = "x86") { return } + if cfg!(target_os = "linux") && cfg!(target_arch = "x86") { + return; + } clitools::setup(Scenario::MultiHost, &|config| { - expect_ok(config, &["rustup", "default", - &format!("nightly-{}", clitools::MULTI_ARCH1)]); + expect_ok( + config, + &[ + "rustup", + "default", + &format!("nightly-{}", clitools::MULTI_ARCH1), + ], + ); expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH2]); - expect_ok_ex(config, &["rustup", "show"], -&format!(r"Default host: {2} + expect_ok_ex( + config, + &["rustup", "show"], + &format!( + r"Default host: {2} installed targets for active toolchain -------------------------------------- @@ -451,23 +574,45 @@ active toolchain nightly-{0} (default) 1.3.0 (xxxx-n-2) -", clitools::MULTI_ARCH1, clitools::CROSS_ARCH2, this_host_triple()), -r""); +", + clitools::MULTI_ARCH1, + clitools::CROSS_ARCH2, + this_host_triple() + ), + r"", + ); }); } #[test] fn show_multiple_toolchains_and_targets() { - if cfg!(target_os = "linux") && cfg!(target_arch = "x86") { return } + if cfg!(target_os = "linux") && cfg!(target_arch = "x86") { + return; + } clitools::setup(Scenario::MultiHost, &|config| { - expect_ok(config, &["rustup", "default", - &format!("nightly-{}", clitools::MULTI_ARCH1)]); + expect_ok( + config, + &[ + "rustup", + "default", + &format!("nightly-{}", clitools::MULTI_ARCH1), + ], + ); expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH2]); - expect_ok(config, &["rustup", "update", - &format!("stable-{}", clitools::MULTI_ARCH1)]); - expect_ok_ex(config, &["rustup", "show"], -&format!(r"Default host: {2} + expect_ok( + config, + &[ + "rustup", + "update", + &format!("stable-{}", clitools::MULTI_ARCH1), + ], + ); + expect_ok_ex( + config, + &["rustup", "show"], + &format!( + r"Default host: {2} installed toolchains -------------------- @@ -487,8 +632,13 @@ active toolchain nightly-{0} (default) 1.3.0 (xxxx-n-2) -", clitools::MULTI_ARCH1, clitools::CROSS_ARCH2, this_host_triple()), -r""); +", + clitools::MULTI_ARCH1, + clitools::CROSS_ARCH2, + this_host_triple() + ), + r"", + ); }); } @@ -496,10 +646,15 @@ r""); fn list_default_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok_ex(config, &["rustup", "toolchain", "list"], -for_host!(r"nightly-{0} (default) -"), -r""); + expect_ok_ex( + config, + &["rustup", "toolchain", "list"], + for_host!( + r"nightly-{0} (default) +" + ), + r"", + ); }); } @@ -509,13 +664,20 @@ fn show_toolchain_override() { setup(&|config| { let cwd = config.current_dir(); expect_ok(config, &["rustup", "override", "add", "nightly"]); - expect_ok_ex(config, &["rustup", "show"], -&format!(r"Default host: {0} + expect_ok_ex( + config, + &["rustup", "show"], + &format!( + r"Default host: {0} nightly-{0} (directory override for '{1}') 1.3.0 (hash-n-2) -", this_host_triple(), cwd.display()), -r""); +", + this_host_triple(), + cwd.display() + ), + r"", + ); }); } @@ -531,8 +693,11 @@ fn show_toolchain_toolchain_file_override() { raw::write_file(&toolchain_file, "nightly").unwrap(); - expect_ok_ex(config, &["rustup", "show"], -&format!(r"Default host: {0} + expect_ok_ex( + config, + &["rustup", "show"], + &format!( + r"Default host: {0} installed toolchains -------------------- @@ -546,8 +711,12 @@ active toolchain nightly-{0} (overridden by '{1}') 1.3.0 (hash-n-2) -", this_host_triple(), toolchain_file.display()), -r""); +", + this_host_triple(), + toolchain_file.display() + ), + r"", + ); }); } @@ -567,8 +736,11 @@ fn show_toolchain_version_nested_file_override() { fs::create_dir_all(&subdir).unwrap(); config.change_dir(&subdir, &|| { - expect_ok_ex(config, &["rustup", "show"], - &format!(r"Default host: {0} + expect_ok_ex( + config, + &["rustup", "show"], + &format!( + r"Default host: {0} installed toolchains -------------------- @@ -582,8 +754,12 @@ active toolchain nightly-{0} (overridden by '{1}') 1.3.0 (hash-n-2) -", this_host_triple(), toolchain_file.display()), - r""); +", + this_host_triple(), + toolchain_file.display() + ), + r"", + ); }); }); } @@ -606,11 +782,11 @@ fn show_toolchain_toolchain_file_override_not_installed() { let out = cmd.output().unwrap(); assert!(!out.status.success()); let stderr = String::from_utf8(out.stderr).unwrap(); - assert!(stderr.starts_with( - "error: override toolchain 'nightly' is not installed")); - assert!(stderr.contains( - &format!("the toolchain file at '{}' specifies an uninstalled toolchain", - toolchain_file.display()))); + assert!(stderr.starts_with("error: override toolchain 'nightly' is not installed")); + assert!(stderr.contains(&format!( + "the toolchain file at '{}' specifies an uninstalled toolchain", + toolchain_file.display() + ))); }); } @@ -641,11 +817,16 @@ fn show_toolchain_env() { let out = cmd.output().unwrap(); assert!(out.status.success()); let stdout = String::from_utf8(out.stdout).unwrap(); - assert_eq!(&stdout, for_host!(r"Default host: {0} + assert_eq!( + &stdout, + for_host!( + r"Default host: {0} nightly-{0} (environment override by RUSTUP_TOOLCHAIN) 1.3.0 (hash-n-2) -")); +" + ) + ); }); } @@ -668,9 +849,11 @@ fn show_toolchain_env_not_installed() { #[test] fn set_default_host() { setup(&|config| { - expect_ok(config, &["rustup", "set", "default-host", &this_host_triple()]); - expect_stdout_ok(config, &["rustup", "show"], - for_host!("Default host: {0}")); + expect_ok( + config, + &["rustup", "set", "default-host", &this_host_triple()], + ); + expect_stdout_ok(config, &["rustup", "show"], for_host!("Default host: {0}")); }); } @@ -678,8 +861,11 @@ fn set_default_host() { #[test] fn set_default_host_invalid_triple() { setup(&|config| { - expect_err(config, &["rustup", "set", "default-host", "foo"], - "Invalid host triple"); + expect_err( + config, + &["rustup", "set", "default-host", "foo"], + "Invalid host triple", + ); }); } @@ -693,38 +879,47 @@ fn update_doesnt_update_non_tracking_channels() { clitools::env(config, &mut cmd); let out = cmd.output().unwrap(); let stderr = String::from_utf8(out.stderr).unwrap(); - assert!(!stderr.contains( - for_host!("syncing channel updates for 'nightly-2015-01-01-{}'"))); + assert!(!stderr.contains(for_host!( + "syncing channel updates for 'nightly-2015-01-01-{}'" + ))); }); } #[test] fn toolchain_install_is_like_update() { setup(&|config| { - expect_ok(config, &["rustup", "toolchain", "install" , "nightly"]); - expect_stdout_ok(config, &["rustup", "run", "nightly", "rustc", "--version"], - "hash-n-2"); + expect_ok(config, &["rustup", "toolchain", "install", "nightly"]); + expect_stdout_ok( + config, + &["rustup", "run", "nightly", "rustc", "--version"], + "hash-n-2", + ); }); } #[test] fn toolchain_install_is_like_update_except_that_bare_install_is_an_error() { setup(&|config| { - expect_err(config, &["rustup", "toolchain", "install"], - "arguments were not provided"); + expect_err( + config, + &["rustup", "toolchain", "install"], + "arguments were not provided", + ); }); } #[test] fn toolchain_update_is_like_update() { setup(&|config| { - expect_ok(config, &["rustup", "toolchain", "update" , "nightly"]); - expect_stdout_ok(config, &["rustup", "run", "nightly", "rustc", "--version"], - "hash-n-2"); + expect_ok(config, &["rustup", "toolchain", "update", "nightly"]); + expect_stdout_ok( + config, + &["rustup", "run", "nightly", "rustc", "--version"], + "hash-n-2", + ); }); } - #[test] fn toolchain_uninstall_is_like_uninstall() { setup(&|config| { @@ -734,17 +929,18 @@ fn toolchain_uninstall_is_like_uninstall() { let out = cmd.output().unwrap(); assert!(out.status.success()); let stdout = String::from_utf8(out.stdout).unwrap(); - assert!(!stdout.contains( - for_host!("'nightly-2015-01-01-{}'"))); - + assert!(!stdout.contains(for_host!("'nightly-2015-01-01-{}'"))); }); } #[test] fn toolchain_update_is_like_update_except_that_bare_install_is_an_error() { setup(&|config| { - expect_err(config, &["rustup", "toolchain", "update"], - "arguments were not provided"); + expect_err( + config, + &["rustup", "toolchain", "update"], + "arguments were not provided", + ); }); } @@ -752,7 +948,7 @@ fn toolchain_update_is_like_update_except_that_bare_install_is_an_error() { fn proxy_toolchain_shorthand() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); - expect_ok(config, &["rustup", "toolchain", "update" , "nightly"]); + expect_ok(config, &["rustup", "toolchain", "update", "nightly"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); expect_stdout_ok(config, &["rustc", "+stable", "--version"], "hash-s-2"); expect_stdout_ok(config, &["rustc", "+nightly", "--version"], "hash-n-2"); @@ -764,8 +960,10 @@ fn add_component() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); expect_ok(config, &["rustup", "component", "add", "rust-src"]); - let path = format!("toolchains/stable-{}/lib/rustlib/src/rust-src/foo.rs", - this_host_triple()); + let path = format!( + "toolchains/stable-{}/lib/rustlib/src/rust-src/foo.rs", + this_host_triple() + ); let path = config.rustupdir.join(path); assert!(path.exists()); }); @@ -776,8 +974,10 @@ fn remove_component() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); expect_ok(config, &["rustup", "component", "add", "rust-src"]); - let path = format!("toolchains/stable-{}/lib/rustlib/src/rust-src/foo.rs", - this_host_triple()); + let path = format!( + "toolchains/stable-{}/lib/rustlib/src/rust-src/foo.rs", + this_host_triple() + ); let path = config.rustupdir.join(path); assert!(path.exists()); expect_ok(config, &["rustup", "component", "remove", "rust-src"]); @@ -787,22 +987,28 @@ fn remove_component() { #[test] fn add_remove_multiple_components() { - let files = ["lib/rustlib/src/rust-src/foo.rs".to_owned(), - format!("lib/rustlib/{}/analysis/libfoo.json", this_host_triple())]; + let files = [ + "lib/rustlib/src/rust-src/foo.rs".to_owned(), + format!("lib/rustlib/{}/analysis/libfoo.json", this_host_triple()), + ]; setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_ok(config, &["rustup", "component", "add", "rust-src", "rust-analysis"]); + expect_ok( + config, + &["rustup", "component", "add", "rust-src", "rust-analysis"], + ); for file in &files { - let path = format!("toolchains/nightly-{}/{}", - this_host_triple(), file); + let path = format!("toolchains/nightly-{}/{}", this_host_triple(), file); let path = config.rustupdir.join(path); assert!(path.exists()); } - expect_ok(config, &["rustup", "component", "remove", "rust-src", "rust-analysis"]); + expect_ok( + config, + &["rustup", "component", "remove", "rust-src", "rust-analysis"], + ); for file in &files { - let path = format!("toolchains/nightly-{}/{}", - this_host_triple(), file); + let path = format!("toolchains/nightly-{}/{}", this_host_triple(), file); let path = config.rustupdir.join(path); assert!(!path.parent().unwrap().exists()); } @@ -835,10 +1041,16 @@ fn multirust_dir_upgrade_rename_multirust_dir_to_rustup() { let multirust_dir_str = &format!("{}", multirust_dir.display()); // First write data into ~/.multirust - run_no_home(config, &["rustup", "default", "stable"], - &[("RUSTUP_HOME", multirust_dir_str)]); - let out = run_no_home(config, &["rustup", "toolchain", "list"], - &[("RUSTUP_HOME", multirust_dir_str)]); + run_no_home( + config, + &["rustup", "default", "stable"], + &[("RUSTUP_HOME", multirust_dir_str)], + ); + let out = run_no_home( + config, + &["rustup", "toolchain", "list"], + &[("RUSTUP_HOME", multirust_dir_str)], + ); assert!(String::from_utf8(out.stdout).unwrap().contains("stable")); assert!(multirust_dir.exists()); @@ -851,7 +1063,12 @@ fn multirust_dir_upgrade_rename_multirust_dir_to_rustup() { assert!(String::from_utf8(out.stdout).unwrap().contains("stable")); assert!(multirust_dir.exists()); - assert!(fs::symlink_metadata(&multirust_dir).unwrap().file_type().is_symlink()); + assert!( + fs::symlink_metadata(&multirust_dir) + .unwrap() + .file_type() + .is_symlink() + ); assert!(rustup_dir.exists()); }); } @@ -869,10 +1086,16 @@ fn multirust_dir_upgrade_old_rustup_exists() { let new_rustup_sh_version_file = rustup_sh_dir.join("rustup-version"); // First write data into ~/.multirust - run_no_home(config, &["rustup", "default", "stable"], - &[("RUSTUP_HOME", multirust_dir_str)]); - let out = run_no_home(config, &["rustup", "toolchain", "list"], - &[("RUSTUP_HOME", multirust_dir_str)]); + run_no_home( + config, + &["rustup", "default", "stable"], + &[("RUSTUP_HOME", multirust_dir_str)], + ); + let out = run_no_home( + config, + &["rustup", "toolchain", "list"], + &[("RUSTUP_HOME", multirust_dir_str)], + ); assert!(String::from_utf8(out.stdout).unwrap().contains("stable")); assert!(multirust_dir.exists()); @@ -888,7 +1111,12 @@ fn multirust_dir_upgrade_old_rustup_exists() { assert!(String::from_utf8(out.stdout).unwrap().contains("stable")); assert!(multirust_dir.exists()); - assert!(fs::symlink_metadata(&multirust_dir).unwrap().file_type().is_symlink()); + assert!( + fs::symlink_metadata(&multirust_dir) + .unwrap() + .file_type() + .is_symlink() + ); assert!(rustup_dir.exists()); assert!(!old_rustup_sh_version_file.exists()); assert!(new_rustup_sh_version_file.exists()); @@ -909,10 +1137,16 @@ fn multirust_dir_upgrade_old_rustup_existsand_new_rustup_sh_exists() { let new_rustup_sh_version_file = rustup_sh_dir.join("rustup-version"); // First write data into ~/.multirust - run_no_home(config, &["rustup", "default", "stable"], - &[("RUSTUP_HOME", multirust_dir_str)]); - let out = run_no_home(config, &["rustup", "toolchain", "list"], - &[("RUSTUP_HOME", multirust_dir_str)]); + run_no_home( + config, + &["rustup", "default", "stable"], + &[("RUSTUP_HOME", multirust_dir_str)], + ); + let out = run_no_home( + config, + &["rustup", "toolchain", "list"], + &[("RUSTUP_HOME", multirust_dir_str)], + ); assert!(String::from_utf8(out.stdout).unwrap().contains("stable")); assert!(multirust_dir.exists()); @@ -938,7 +1172,12 @@ fn multirust_dir_upgrade_old_rustup_existsand_new_rustup_sh_exists() { // .multirust is now a symlink to .rustup assert!(multirust_dir.exists()); - assert!(fs::symlink_metadata(&multirust_dir).unwrap().file_type().is_symlink()); + assert!( + fs::symlink_metadata(&multirust_dir) + .unwrap() + .file_type() + .is_symlink() + ); assert!(rustup_dir.exists()); assert!(!old_rustup_sh_version_file.exists()); @@ -953,13 +1192,21 @@ fn multirust_upgrade_works_with_proxy() { let rustup_dir = config.homedir.join(".rustup"); // Put data in ~/.multirust - run_no_home(config, &["rustup", "default", "stable"], - &[("RUSTUP_HOME", &format!("{}", multirust_dir.display()))]); + run_no_home( + config, + &["rustup", "default", "stable"], + &[("RUSTUP_HOME", &format!("{}", multirust_dir.display()))], + ); run_no_home(config, &["rustc", "--version"], &[]); assert!(multirust_dir.exists()); - assert!(fs::symlink_metadata(&multirust_dir).unwrap().file_type().is_symlink()); + assert!( + fs::symlink_metadata(&multirust_dir) + .unwrap() + .file_type() + .is_symlink() + ); assert!(rustup_dir.exists()); }); } @@ -1000,12 +1247,14 @@ fn file_override_subdir() { }); } - #[test] fn file_override_with_archive() { setup(&|config| { expect_ok(config, &["rustup", "default", "stable"]); - expect_ok(config, &["rustup", "toolchain", "install", "nightly-2015-01-01"]); + expect_ok( + config, + &["rustup", "toolchain", "install", "nightly-2015-01-01"], + ); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); @@ -1059,7 +1308,6 @@ fn close_file_override_beats_far_directory_override() { }); } - #[test] fn directory_override_doesnt_need_to_exist_unless_it_is_selected() { setup(&|config| { @@ -1120,8 +1368,11 @@ fn bad_file_override() { let toolchain_file = cwd.join("rust-toolchain"); raw::write_file(&toolchain_file, "gumbo").unwrap(); - expect_err(config, &["rustc", "--version"], - "invalid channel name 'gumbo' in"); + expect_err( + config, + &["rustc", "--version"], + "invalid channel name 'gumbo' in", + ); }); } @@ -1132,7 +1383,10 @@ fn file_override_with_target_info() { let toolchain_file = cwd.join("rust-toolchain"); raw::write_file(&toolchain_file, "nightly-x86_64-unknown-linux-gnu").unwrap(); - expect_err(config, &["rustc", "--version"], - "target triple in channel name 'nightly-x86_64-unknown-linux-gnu'"); + expect_err( + config, + &["rustc", "--version"], + "target triple in channel name 'nightly-x86_64-unknown-linux-gnu'", + ); }); } diff --git a/tests/cli-self-upd.rs b/tests/cli-self-upd.rs index c8bc9c4b45..61ce79c5fc 100644 --- a/tests/cli-self-upd.rs +++ b/tests/cli-self-upd.rs @@ -4,13 +4,13 @@ // The `self update` and `self uninstall` commands just call `msiexec`. #![cfg(not(feature = "msi-installed"))] -extern crate rustup_mock; -extern crate rustup_utils; #[macro_use] extern crate lazy_static; -extern crate tempdir; extern crate remove_dir_all; +extern crate rustup_mock; +extern crate rustup_utils; extern crate scopeguard; +extern crate tempdir; #[cfg(windows)] extern crate winapi; @@ -25,14 +25,11 @@ use std::path::Path; use std::fs; use std::process::Command; use remove_dir_all::remove_dir_all; -use rustup_mock::clitools::{self, Config, Scenario, - expect_ok, expect_ok_ex, - expect_stdout_ok, expect_stderr_ok, - expect_err, expect_err_ex, - this_host_triple}; -use rustup_mock::dist::{calc_hash}; +use rustup_mock::clitools::{self, expect_err, expect_err_ex, expect_ok, expect_ok_ex, + expect_stderr_ok, expect_stdout_ok, this_host_triple, Config, Scenario}; +use rustup_mock::dist::calc_hash; use rustup_mock::{get_path, restore_path}; -use rustup_utils::{utils, raw}; +use rustup_utils::{raw, utils}; macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) } @@ -57,7 +54,6 @@ pub fn setup(f: &Fn(&Config)) { pub fn update_setup(f: &Fn(&Config, &Path)) { setup(&|config| { - // Create a mock self-update server let ref self_dist_tmp = TempDir::new("self_dist").unwrap(); let ref self_dist = self_dist_tmp.path(); @@ -81,10 +77,13 @@ pub fn update_setup(f: &Fn(&Config, &Path)) { } fn output_release_file(dist_dir: &Path, schema: &str, version: &str) { - let contents = format!(r#" + let contents = format!( + r#" schema-version = "{}" version = "{}" -"#, schema, version); +"#, + schema, version + ); let file = dist_dir.join("release-stable.toml"); utils::write_file("release", &file, &contents).unwrap(); } @@ -97,7 +96,9 @@ fn install_bins_to_cargo_home() { let rustc = config.cargodir.join(&format!("bin/rustc{}", EXE_SUFFIX)); let rustdoc = config.cargodir.join(&format!("bin/rustdoc{}", EXE_SUFFIX)); let cargo = config.cargodir.join(&format!("bin/cargo{}", EXE_SUFFIX)); - let rust_lldb = config.cargodir.join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); + let rust_lldb = config + .cargodir + .join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); let rust_gdb = config.cargodir.join(&format!("bin/rust-gdb{}", EXE_SUFFIX)); assert!(rustup.exists()); assert!(rustc.exists()); @@ -127,7 +128,9 @@ fn bins_are_executable() { let ref rustc = config.cargodir.join(&format!("bin/rustc{}", EXE_SUFFIX)); let ref rustdoc = config.cargodir.join(&format!("bin/rustdoc{}", EXE_SUFFIX)); let ref cargo = config.cargodir.join(&format!("bin/cargo{}", EXE_SUFFIX)); - let ref rust_lldb = config.cargodir.join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); + let ref rust_lldb = config + .cargodir + .join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); let ref rust_gdb = config.cargodir.join(&format!("bin/rust-gdb{}", EXE_SUFFIX)); assert!(is_exe(rustup)); assert!(is_exe(rustc)); @@ -164,7 +167,9 @@ fn uninstall_deletes_bins() { let rustc = config.cargodir.join(&format!("bin/rustc{}", EXE_SUFFIX)); let rustdoc = config.cargodir.join(&format!("bin/rustdoc{}", EXE_SUFFIX)); let cargo = config.cargodir.join(&format!("bin/cargo{}", EXE_SUFFIX)); - let rust_lldb = config.cargodir.join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); + let rust_lldb = config + .cargodir + .join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); let rust_gdb = config.cargodir.join(&format!("bin/rust-gdb{}", EXE_SUFFIX)); assert!(!rustup.exists()); assert!(!rustc.exists()); @@ -183,7 +188,9 @@ fn uninstall_works_if_some_bins_dont_exist() { let rustc = config.cargodir.join(&format!("bin/rustc{}", EXE_SUFFIX)); let rustdoc = config.cargodir.join(&format!("bin/rustdoc{}", EXE_SUFFIX)); let cargo = config.cargodir.join(&format!("bin/cargo{}", EXE_SUFFIX)); - let rust_lldb = config.cargodir.join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); + let rust_lldb = config + .cargodir + .join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); let rust_gdb = config.cargodir.join(&format!("bin/rust-gdb{}", EXE_SUFFIX)); fs::remove_file(&rustc).unwrap(); @@ -234,8 +241,11 @@ fn uninstall_fails_if_not_installed() { expect_ok(config, &["rustup-init", "-y"]); let rustup = config.cargodir.join(&format!("bin/rustup{}", EXE_SUFFIX)); fs::remove_file(&rustup).unwrap(); - expect_err(config, &["rustup", "self", "uninstall", "-y"], - "rustup is not installed"); + expect_err( + config, + &["rustup", "self", "uninstall", "-y"], + "rustup is not installed", + ); }); } @@ -261,7 +271,9 @@ fn uninstall_self_delete_works() { let rustc = config.cargodir.join(&format!("bin/rustc{}", EXE_SUFFIX)); let rustdoc = config.cargodir.join(&format!("bin/rustdoc{}", EXE_SUFFIX)); let cargo = config.cargodir.join(&format!("bin/cargo{}", EXE_SUFFIX)); - let rust_lldb = config.cargodir.join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); + let rust_lldb = config + .cargodir + .join(&format!("bin/rust-lldb{}", EXE_SUFFIX)); let rust_gdb = config.cargodir.join(&format!("bin/rust-gdb{}", EXE_SUFFIX)); assert!(!rustc.exists()); assert!(!rustdoc.exists()); @@ -297,8 +309,7 @@ fn uninstall_doesnt_leave_gc_file() { #[test] #[ignore] -fn uninstall_stress_test() { -} +fn uninstall_stress_test() {} #[cfg(unix)] fn install_adds_path_to_rc(rcfile: &str) { @@ -309,8 +320,7 @@ fn install_adds_path_to_rc(rcfile: &str) { expect_ok(config, &["rustup-init", "-y"]); let new_rc = raw::read_file(rc).unwrap(); - let addition = format!(r#"export PATH="{}/bin:$PATH""#, - config.cargodir.display()); + let addition = format!(r#"export PATH="{}/bin:$PATH""#, config.cargodir.display()); let expected = format!("{}\n{}\n", my_rc, addition); assert_eq!(new_rc, expected); }); @@ -352,8 +362,7 @@ fn install_with_zsh_adds_path_to_zprofile() { assert!(cmd.output().unwrap().status.success()); let new_rc = raw::read_file(rc).unwrap(); - let addition = format!(r#"export PATH="{}/bin:$PATH""#, - config.cargodir.display()); + let addition = format!(r#"export PATH="{}/bin:$PATH""#, config.cargodir.display()); let expected = format!("{}\n{}\n", my_rc, addition); assert_eq!(new_rc, expected); }); @@ -374,8 +383,7 @@ fn install_with_zsh_adds_path_to_zdotdir_zprofile() { assert!(cmd.output().unwrap().status.success()); let new_rc = raw::read_file(rc).unwrap(); - let addition = format!(r#"export PATH="{}/bin:$PATH""#, - config.cargodir.display()); + let addition = format!(r#"export PATH="{}/bin:$PATH""#, config.cargodir.display()); let expected = format!("{}\n{}\n", my_rc, addition); assert_eq!(new_rc, expected); }); @@ -392,8 +400,7 @@ fn install_adds_path_to_rcfile_just_once() { expect_ok(config, &["rustup-init", "-y"]); let new_profile = raw::read_file(profile).unwrap(); - let addition = format!(r#"export PATH="{}/bin:$PATH""#, - config.cargodir.display()); + let addition = format!(r#"export PATH="{}/bin:$PATH""#, config.cargodir.display()); let expected = format!("{}\n{}\n", my_profile, addition); assert_eq!(new_profile, expected); }); @@ -508,7 +515,6 @@ fn uninstall_removes_path() { }); } - #[test] #[cfg(unix)] fn install_doesnt_modify_path_if_passed_no_modify_path() { @@ -527,13 +533,15 @@ fn install_doesnt_modify_path_if_passed_no_modify_path() { setup(&|config| { let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let old_path = environment.get_raw_value("PATH").unwrap(); expect_ok(config, &["rustup-init", "-y", "--no-modify-path"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let new_path = environment.get_raw_value("PATH").unwrap(); assert!(old_path == new_path); @@ -543,27 +551,32 @@ fn install_doesnt_modify_path_if_passed_no_modify_path() { #[test] fn update_exact() { let version = env!("CARGO_PKG_VERSION"); - let expected_output = &( -r"info: checking for self-updates + let expected_output = &(r"info: checking for self-updates info: downloading self-update -info: rustup updated successfully to ".to_owned() + version + " +info: rustup updated successfully to " + .to_owned() + version + + " "); update_setup(&|config, _| { expect_ok(config, &["rustup-init", "-y"]); - expect_ok_ex(config, &["rustup", "self", "update"], - r"", expected_output) + expect_ok_ex(config, &["rustup", "self", "update"], r"", expected_output) }); } #[test] fn update_but_not_installed() { update_setup(&|config, _| { - expect_err_ex(config, &["rustup", "self", "update"], -r"", -&format!( -r"error: rustup is not installed at '{}' -", config.cargodir.display())); + expect_err_ex( + config, + &["rustup", "self", "update"], + r"", + &format!( + r"error: rustup is not installed at '{}' +", + config.cargodir.display() + ), + ); }); } @@ -571,7 +584,9 @@ r"error: rustup is not installed at '{}' fn update_but_delete_existing_updater_first() { update_setup(&|config, _| { // The updater is stored in a known location - let ref setup = config.cargodir.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); + let ref setup = config + .cargodir + .join(&format!("bin/rustup-init{}", EXE_SUFFIX)); expect_ok(config, &["rustup-init", "-y"]); @@ -596,8 +611,11 @@ fn update_download_404() { fs::remove_file(dist_exe).unwrap(); - expect_err(config, &["rustup", "self", "update"], - "could not download file"); + expect_err( + config, + &["rustup", "self", "update"], + "could not download file", + ); }); } @@ -605,8 +623,11 @@ fn update_download_404() { fn update_bogus_version() { update_setup(&|config, _| { expect_ok(config, &["rustup-init", "-y"]); - expect_err(config, &["rustup", "update", "1.0.0-alpha"], - "could not download nonexistent rust version `1.0.0-alpha`"); + expect_err( + config, + &["rustup", "update", "1.0.0-alpha"], + "could not download nonexistent rust version `1.0.0-alpha`", + ); }); } @@ -644,8 +665,11 @@ fn update_bad_schema() { update_setup(&|config, self_dist| { expect_ok(config, &["rustup-init", "-y"]); output_release_file(self_dist, "17", "1.1.1"); - expect_err(config, &["rustup", "self", "update"], - "unknown schema version"); + expect_err( + config, + &["rustup", "self", "update"], + "unknown schema version", + ); }); } @@ -655,10 +679,13 @@ fn update_no_change() { update_setup(&|config, self_dist| { expect_ok(config, &["rustup-init", "-y"]); output_release_file(self_dist, "1", version); - expect_ok_ex(config, &["rustup", "self", "update"], -r"", -r"info: checking for self-updates -"); + expect_ok_ex( + config, + &["rustup", "self", "update"], + r"", + r"info: checking for self-updates +", + ); }); } @@ -683,15 +710,22 @@ fn rustup_self_update_exact() { update_setup(&|config, _| { expect_ok(config, &["rustup-init", "-y"]); - expect_ok_ex(config, &["rustup", "update"], -for_host!(r" + expect_ok_ex( + config, + &["rustup", "update"], + for_host!( + r" stable-{0} unchanged - 1.1.0 (hash-s-2) -"), -for_host!(r"info: syncing channel updates for 'stable-{0}' +" + ), + for_host!( + r"info: syncing channel updates for 'stable-{0}' info: checking for self-updates info: downloading self-update -")); +" + ), + ); }) } @@ -705,7 +739,9 @@ fn updater_leaves_itself_for_later_deletion() { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "self", "update"]); - let setup = config.cargodir.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); + let setup = config + .cargodir + .join(&format!("bin/rustup-init{}", EXE_SUFFIX)); assert!(setup.exists()); }); } @@ -719,7 +755,9 @@ fn updater_is_deleted_after_running_rustup() { expect_ok(config, &["rustup", "update", "nightly"]); - let setup = config.cargodir.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); + let setup = config + .cargodir + .join(&format!("bin/rustup-init{}", EXE_SUFFIX)); assert!(!setup.exists()); }); } @@ -733,7 +771,9 @@ fn updater_is_deleted_after_running_rustc() { expect_ok(config, &["rustc", "--version"]); - let setup = config.cargodir.join(&format!("bin/rustup-init{}", EXE_SUFFIX)); + let setup = config + .cargodir + .join(&format!("bin/rustup-init{}", EXE_SUFFIX)); assert!(!setup.exists()); }); } @@ -755,8 +795,7 @@ fn rustup_still_works_after_update() { // invocations of rustup and rustc (on windows). #[test] #[ignore] -fn update_stress_test() { -} +fn update_stress_test() {} // The installer used to be called rustup-setup. For compatibility it // still needs to work in that mode. @@ -774,12 +813,15 @@ fn as_rustup_setup() { #[test] fn first_install_exact() { setup(&|config| { - expect_ok_ex(config, &["rustup-init", "-y"], -r" + expect_ok_ex( + config, + &["rustup-init", "-y"], + r" stable installed - 1.1.0 (hash-s-2) ", -for_host!(r"info: syncing channel updates for 'stable-{0}' + for_host!( + r"info: syncing channel updates for 'stable-{0}' info: latest update on 2015-01-02, rust version 1.1.0 info: downloading component 'rust-std' info: downloading component 'rustc' @@ -790,8 +832,9 @@ info: installing component 'rustc' info: installing component 'cargo' info: installing component 'rust-docs' info: default toolchain set to 'stable' -") - ); +" + ), + ); }); } @@ -799,12 +842,14 @@ info: default toolchain set to 'stable' fn reinstall_exact() { setup(&|config| { expect_ok(config, &["rustup-init", "-y"]); - expect_ok_ex(config, &["rustup-init", "-y"], -r" + expect_ok_ex( + config, + &["rustup-init", "-y"], + r" ", -r"info: updating existing rustup installation -" - ); + r"info: updating existing rustup installation +", + ); }); } @@ -827,24 +872,24 @@ fn produces_env_file_on_unix() { #[test] #[cfg(windows)] -fn doesnt_produce_env_file_on_windows() { -} +fn doesnt_produce_env_file_on_windows() {} #[test] fn install_sets_up_stable() { setup(&|config| { expect_ok(config, &["rustup-init", "-y"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-s-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } #[test] fn install_sets_up_stable_unless_a_different_default_is_requested() { setup(&|config| { - expect_ok(config, &["rustup-init", "-y", "--default-toolchain", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_ok( + config, + &["rustup-init", "-y", "--default-toolchain", "nightly"], + ); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } @@ -855,10 +900,12 @@ fn install_sets_up_stable_unless_there_is_already_a_default() { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "stable"]); expect_ok(config, &["rustup-init", "-y"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); - expect_err(config, &["rustup", "run", "stable", "rustc", "--version"], - for_host!("toolchain 'stable-{0}' is not installed")); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); + expect_err( + config, + &["rustup", "run", "stable", "rustc", "--version"], + for_host!("toolchain 'stable-{0}' is not installed"), + ); }); } @@ -913,7 +960,9 @@ fn legacy_upgrade_installs_to_correct_location() { cmd.env("CARGO_HOME", format!("{}", fake_cargo.display())); assert!(cmd.output().unwrap().status.success()); - let rustup = config.homedir.join(&format!(".cargo/bin/rustup{}", EXE_SUFFIX)); + let rustup = config + .homedir + .join(&format!(".cargo/bin/rustup{}", EXE_SUFFIX)); assert!(rustup.exists()); }); } @@ -921,8 +970,11 @@ fn legacy_upgrade_installs_to_correct_location() { #[test] fn readline_no_stdin() { setup(&|config| { - expect_err(config, &["rustup-init"], - "unable to read from stdin for confirmation"); + expect_err( + config, + &["rustup-init"], + "unable to read from stdin for confirmation", + ); }); } @@ -931,10 +983,8 @@ fn rustup_init_works_with_weird_names() { // Browsers often rename bins to e.g. rustup-init(2).exe. setup(&|config| { - let ref old = config.exedir.join( - &format!("rustup-init{}", EXE_SUFFIX)); - let ref new = config.exedir.join( - &format!("rustup-init(2){}", EXE_SUFFIX)); + let ref old = config.exedir.join(&format!("rustup-init{}", EXE_SUFFIX)); + let ref new = config.exedir.join(&format!("rustup-init(2){}", EXE_SUFFIX)); fs::rename(old, new).unwrap(); expect_ok(config, &["rustup-init(2)", "-y"]); let rustup = config.cargodir.join(&format!("bin/rustup{}", EXE_SUFFIX)); @@ -954,20 +1004,21 @@ fn doesnt_write_wrong_path_type_to_reg() { expect_ok(config, &["rustup-init", "-y"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path = environment.get_raw_value("PATH").unwrap(); assert!(path.vtype == RegType::REG_EXPAND_SZ); expect_ok(config, &["rustup", "self", "uninstall", "-y"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path = environment.get_raw_value("PATH").unwrap(); assert!(path.vtype == RegType::REG_EXPAND_SZ); }); } - // HKCU\Environment\PATH may not exist during install, and it may need to be // deleted during uninstall if we remove the last path from it #[test] @@ -979,20 +1030,23 @@ fn windows_handle_empty_path_registry_key() { setup(&|config| { let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let _ = environment.delete_value("PATH"); expect_ok(config, &["rustup-init", "-y"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path = environment.get_raw_value("PATH").unwrap(); assert!(path.vtype == RegType::REG_EXPAND_SZ); expect_ok(config, &["rustup", "self", "uninstall", "-y"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path = environment.get_raw_value("PATH"); assert!(path.is_err()); @@ -1008,7 +1062,8 @@ fn windows_uninstall_removes_semicolon_from_path() { setup(&|config| { let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); // This time set the value of PATH and make sure it's restored exactly after uninstall, // not leaving behind any semi-colons @@ -1017,14 +1072,16 @@ fn windows_uninstall_removes_semicolon_from_path() { expect_ok(config, &["rustup-init", "-y"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path = environment.get_raw_value("PATH").unwrap(); assert!(path.vtype == RegType::REG_EXPAND_SZ); expect_ok(config, &["rustup", "self", "uninstall", "-y"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path: String = environment.get_value("PATH").unwrap(); assert!(path == "foo"); }); @@ -1039,13 +1096,14 @@ fn install_doesnt_mess_with_a_non_unicode_path() { setup(&|config| { let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let reg_value = RegValue { bytes: vec![0x00, 0xD8, // leading surrogate 0x01, 0x01, // bogus trailing surrogate 0x00, 0x00], // null - vtype: RegType::REG_EXPAND_SZ + vtype: RegType::REG_EXPAND_SZ, }; environment.set_raw_value("PATH", ®_value).unwrap(); @@ -1054,7 +1112,8 @@ fn install_doesnt_mess_with_a_non_unicode_path() { Not modifying the PATH variable"); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path = environment.get_raw_value("PATH").unwrap(); assert!(path.bytes == reg_value.bytes); }); @@ -1071,13 +1130,14 @@ fn uninstall_doesnt_mess_with_a_non_unicode_path() { expect_ok(config, &["rustup-init", "-y"]); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let reg_value = RegValue { bytes: vec![0x00, 0xD8, // leading surrogate 0x01, 0x01, // bogus trailing surrogate 0x00, 0x00], // null - vtype: RegType::REG_EXPAND_SZ + vtype: RegType::REG_EXPAND_SZ, }; environment.set_raw_value("PATH", ®_value).unwrap(); @@ -1086,7 +1146,8 @@ fn uninstall_doesnt_mess_with_a_non_unicode_path() { Not modifying the PATH variable"); let root = RegKey::predef(HKEY_CURRENT_USER); - let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE).unwrap(); + let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE) + .unwrap(); let path = environment.get_raw_value("PATH").unwrap(); assert!(path.bytes == reg_value.bytes); }); @@ -1094,13 +1155,11 @@ fn uninstall_doesnt_mess_with_a_non_unicode_path() { #[test] #[ignore] // untestable -fn install_but_rustup_is_installed() { -} +fn install_but_rustup_is_installed() {} #[test] #[ignore] // untestable -fn install_but_rustc_is_installed() { -} +fn install_but_rustc_is_installed() {} #[test] fn install_but_rustup_sh_is_installed() { @@ -1109,8 +1168,11 @@ fn install_but_rustup_sh_is_installed() { fs::create_dir_all(&rustup_dir).unwrap(); let version_file = rustup_dir.join("rustup-version"); raw::write_file(&version_file, "").unwrap(); - expect_err(config, &["rustup-init", "-y"], - "cannot install while rustup.sh is installed"); + expect_err( + config, + &["rustup-init", "-y"], + "cannot install while rustup.sh is installed", + ); }); } @@ -1121,8 +1183,11 @@ fn install_but_rustup_metadata() { fs::create_dir_all(&multirust_dir).unwrap(); let version_file = multirust_dir.join("version"); raw::write_file(&version_file, "2").unwrap(); - expect_err(config, &["rustup-init", "-y"], - "cannot install while multirust is installed"); + expect_err( + config, + &["rustup-init", "-y"], + "cannot install while multirust is installed", + ); }); } @@ -1162,7 +1227,12 @@ fn install_creates_legacy_home_symlink() { assert!(rustup_dir.exists()); let multirust_dir = config.homedir.join(".multirust"); assert!(multirust_dir.exists()); - assert!(fs::symlink_metadata(&multirust_dir).unwrap().file_type().is_symlink()); + assert!( + fs::symlink_metadata(&multirust_dir) + .unwrap() + .file_type() + .is_symlink() + ); }); } @@ -1174,7 +1244,11 @@ fn install_over_unupgraded_multirust_dir() { let multirust_dir = config.homedir.join(".multirust"); // Install rustup - let mut cmd = clitools::cmd(config, "rustup-init", &["-y", "--default-toolchain=nightly"]); + let mut cmd = clitools::cmd( + config, + "rustup-init", + &["-y", "--default-toolchain=nightly"], + ); cmd.env_remove("RUSTUP_HOME"); assert!(cmd.output().unwrap().status.success()); @@ -1198,7 +1272,12 @@ fn install_over_unupgraded_multirust_dir() { // Directories should be set up correctly assert!(rustup_dir.exists()); assert!(multirust_dir.exists()); - assert!(fs::symlink_metadata(&multirust_dir).unwrap().file_type().is_symlink()); + assert!( + fs::symlink_metadata(&multirust_dir) + .unwrap() + .file_type() + .is_symlink() + ); // We should still be on nightly let mut cmd = clitools::cmd(config, "rustc", &["--version"]); @@ -1228,9 +1307,15 @@ fn uninstall_removes_legacy_home_symlink() { fn rls_proxy_set_up_after_install() { setup(&|config| { expect_ok(config, &["rustup-init", "-y"]); - expect_err(config, &["rls", "--version"], - &format!("toolchain 'stable-{}' does not have the binary `rls{}`", - this_host_triple(), EXE_SUFFIX)); + expect_err( + config, + &["rls", "--version"], + &format!( + "toolchain 'stable-{}' does not have the binary `rls{}`", + this_host_triple(), + EXE_SUFFIX + ), + ); expect_ok(config, &["rustup", "component", "add", "rls-preview"]); expect_ok(config, &["rls", "--version"]); }); @@ -1247,7 +1332,6 @@ fn rls_proxy_set_up_after_update() { }); } - #[test] fn update_does_not_overwrite_rustfmt() { update_setup(&|config, _| { @@ -1256,21 +1340,26 @@ fn update_does_not_overwrite_rustfmt() { raw::write_file(rustfmt_path, "").unwrap(); assert_eq!(utils::file_size(rustfmt_path).unwrap(), 0); - expect_stderr_ok(config, &["rustup", "self", "update"], - "`rustfmt` is already installed"); + expect_stderr_ok( + config, + &["rustup", "self", "update"], + "`rustfmt` is already installed", + ); expect_ok(config, &["rustup", "self", "update"]); assert!(rustfmt_path.exists()); assert_eq!(utils::file_size(rustfmt_path).unwrap(), 0); - // We run the test twice because the first time around none of the shims // exist, and we want to check that out check for rustfmt works if there // are shims or not. let ref rustdoc_path = config.cargodir.join(format!("bin/rustdoc{}", EXE_SUFFIX)); assert!(rustdoc_path.exists()); - expect_stderr_ok(config, &["rustup", "self", "update"], - "`rustfmt` is already installed"); + expect_stderr_ok( + config, + &["rustup", "self", "update"], + "`rustfmt` is already installed", + ); assert!(rustfmt_path.exists()); assert_eq!(utils::file_size(rustfmt_path).unwrap(), 0); }); diff --git a/tests/cli-v1.rs b/tests/cli-v1.rs index 98a0699ef0..490f57e42e 100644 --- a/tests/cli-v1.rs +++ b/tests/cli-v1.rs @@ -2,16 +2,14 @@ //! derived from multirust/test-v2.sh extern crate rustup_dist; -extern crate rustup_utils; extern crate rustup_mock; +extern crate rustup_utils; extern crate tempdir; use std::fs; use tempdir::TempDir; -use rustup_mock::clitools::{self, Config, Scenario, - expect_ok, expect_stdout_ok, expect_err, - expect_stderr_ok, set_current_dist_date, - this_host_triple}; +use rustup_mock::clitools::{self, expect_err, expect_ok, expect_stderr_ok, expect_stdout_ok, + set_current_dist_date, this_host_triple, Config, Scenario}; macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) } @@ -22,8 +20,7 @@ pub fn setup(f: &Fn(&mut Config)) { #[test] fn rustc_no_default_toolchain() { setup(&|config| { - expect_err(config, &["rustc"], - "no default toolchain configured"); + expect_err(config, &["rustc"], "no default toolchain configured"); }); } @@ -50,11 +47,11 @@ fn install_toolchain_from_channel() { #[test] fn install_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV1, &|config| { - expect_ok(config, &["rustup", "default" , "nightly-2015-01-01"]); + expect_ok(config, &["rustup", "default", "nightly-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); - expect_ok(config, &["rustup", "default" , "beta-2015-01-01"]); + expect_ok(config, &["rustup", "default", "beta-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); - expect_ok(config, &["rustup", "default" , "stable-2015-01-01"]); + expect_ok(config, &["rustup", "default", "stable-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } @@ -62,7 +59,7 @@ fn install_toolchain_from_archive() { #[test] fn install_toolchain_from_version() { setup(&|config| { - expect_ok(config, &["rustup", "default" , "1.1.0"]); + expect_ok(config, &["rustup", "default", "1.1.0"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } @@ -71,8 +68,11 @@ fn install_toolchain_from_version() { fn default_existing_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_stderr_ok(config, &["rustup", "default", "nightly"], - for_host!("using existing install for 'nightly-{0}'")); + expect_stderr_ok( + config, + &["rustup", "default", "nightly"], + for_host!("using existing install for 'nightly-{0}'"), + ); }); } @@ -81,12 +81,10 @@ fn update_channel() { clitools::setup(Scenario::ArchivesV1, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } @@ -95,18 +93,19 @@ fn list_toolchains() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "update", "beta-2015-01-01"]); - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "nightly"); - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "beta-2015-01-01"); + expect_stdout_ok(config, &["rustup", "toolchain", "list"], "nightly"); + expect_stdout_ok(config, &["rustup", "toolchain", "list"], "beta-2015-01-01"); }); } #[test] fn list_toolchains_with_none() { setup(&|config| { - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "no installed toolchains"); + expect_stdout_ok( + config, + &["rustup", "toolchain", "list"], + "no installed toolchains", + ); }); } @@ -116,8 +115,11 @@ fn remove_toolchain() { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); expect_ok(config, &["rustup", "toolchain", "list"]); - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "no installed toolchains"); + expect_stdout_ok( + config, + &["rustup", "toolchain", "list"], + "no installed toolchains", + ); }); } @@ -126,8 +128,11 @@ fn remove_default_toolchain_err_handling() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); - expect_err(config, &["rustc"], - for_host!("toolchain 'nightly-{0}' is not installed")); + expect_err( + config, + &["rustc"], + for_host!("toolchain 'nightly-{0}' is not installed"), + ); }); } @@ -139,7 +144,11 @@ fn remove_override_toolchain_err_handling() { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_ok(config, &["rustup", "toolchain", "remove", "beta"]); - expect_stderr_ok(config, &["rustc", "--version"], "info: installing component"); + expect_stderr_ok( + config, + &["rustc", "--version"], + "info: installing component", + ); }); }); } @@ -153,8 +162,7 @@ fn bad_sha_on_manifest() { sha_bytes[..10].clone_from_slice(b"aaaaaaaaaa"); let sha_str = String::from_utf8(sha_bytes).unwrap(); rustup_utils::raw::write_file(&sha_file, &sha_str).unwrap(); - expect_err(config, &["rustup", "default", "nightly"], - "checksum failed"); + expect_err(config, &["rustup", "default", "nightly"], "checksum failed"); }); } @@ -170,8 +178,7 @@ fn bad_sha_on_installer() { rustup_utils::raw::write_file(&path, "xxx").unwrap(); } } - expect_err(config, &["rustup", "default", "nightly"], - "checksum failed"); + expect_err(config, &["rustup", "default", "nightly"], "checksum failed"); }); } @@ -179,14 +186,11 @@ fn bad_sha_on_installer() { fn install_override_toolchain_from_channel() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); expect_ok(config, &["rustup", "override", "add", "beta"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-b-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); expect_ok(config, &["rustup", "override", "add", "stable"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-s-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } @@ -194,14 +198,11 @@ fn install_override_toolchain_from_channel() { fn install_override_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV1, &|config| { expect_ok(config, &["rustup", "override", "add", "nightly-2015-01-01"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); expect_ok(config, &["rustup", "override", "add", "beta-2015-01-01"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-b-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); expect_ok(config, &["rustup", "override", "add", "stable-2015-01-01"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-s-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } @@ -209,8 +210,7 @@ fn install_override_toolchain_from_archive() { fn install_override_toolchain_from_version() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "1.1.0"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-s-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } @@ -218,9 +218,9 @@ fn install_override_toolchain_from_version() { fn override_overrides_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); - expect_ok(config, &["rustup", "default" , "nightly"]); + expect_ok(config, &["rustup", "default", "nightly"]); config.change_dir(tempdir.path(), &|| { - expect_ok(config, &["rustup", "override" , "add", "beta"]); + expect_ok(config, &["rustup", "override", "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); }); @@ -270,8 +270,7 @@ fn remove_override_no_default() { config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_ok(config, &["rustup", "override", "remove"]); - expect_err(config, &["rustc"], - "no default toolchain configured"); + expect_err(config, &["rustc"], "no default toolchain configured"); }); }); } @@ -316,8 +315,7 @@ fn remove_override_with_multiple_overrides() { fn no_update_on_channel_when_date_has_not_changed() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustup", "update", "nightly"], - "unchanged"); + expect_stdout_ok(config, &["rustup", "update", "nightly"], "unchanged"); }); } @@ -326,12 +324,10 @@ fn update_on_channel_when_date_has_changed() { clitools::setup(Scenario::ArchivesV1, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } @@ -340,8 +336,11 @@ fn run_command() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "default", "beta"]); - expect_stdout_ok(config, &["rustup", "run", "nightly", "rustc" , "--version"], - "hash-n-2"); + expect_stdout_ok( + config, + &["rustup", "run", "nightly", "rustc", "--version"], + "hash-n-2", + ); }); } diff --git a/tests/cli-v2.rs b/tests/cli-v2.rs index faebc2781a..9184d8b3d1 100644 --- a/tests/cli-v2.rs +++ b/tests/cli-v2.rs @@ -2,17 +2,15 @@ //! derived from multirust/test-v2.sh extern crate rustup_dist; -extern crate rustup_utils; extern crate rustup_mock; +extern crate rustup_utils; extern crate tempdir; use std::fs; use tempdir::TempDir; -use rustup_mock::clitools::{self, Config, Scenario, - expect_ok, expect_stdout_ok, expect_err, - expect_stderr_ok, expect_not_stdout_ok, - set_current_dist_date, - this_host_triple}; +use rustup_mock::clitools::{self, expect_err, expect_not_stdout_ok, expect_ok, expect_stderr_ok, + expect_stdout_ok, set_current_dist_date, this_host_triple, Config, + Scenario}; use rustup_dist::dist::TargetTriple; @@ -25,8 +23,7 @@ pub fn setup(f: &Fn(&mut Config)) { #[test] fn rustc_no_default_toolchain() { setup(&|config| { - expect_err(config, &["rustc"], - "no default toolchain configured"); + expect_err(config, &["rustc"], "no default toolchain configured"); }); } @@ -53,11 +50,11 @@ fn install_toolchain_from_channel() { #[test] fn install_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV2, &|config| { - expect_ok(config, &["rustup", "default" , "nightly-2015-01-01"]); + expect_ok(config, &["rustup", "default", "nightly-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); - expect_ok(config, &["rustup", "default" , "beta-2015-01-01"]); + expect_ok(config, &["rustup", "default", "beta-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); - expect_ok(config, &["rustup", "default" , "stable-2015-01-01"]); + expect_ok(config, &["rustup", "default", "stable-2015-01-01"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } @@ -65,7 +62,7 @@ fn install_toolchain_from_archive() { #[test] fn install_toolchain_from_version() { setup(&|config| { - expect_ok(config, &["rustup", "default" , "1.1.0"]); + expect_ok(config, &["rustup", "default", "1.1.0"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } @@ -74,8 +71,11 @@ fn install_toolchain_from_version() { fn default_existing_toolchain() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_stderr_ok(config, &["rustup", "default", "nightly"], - for_host!("using existing install for 'nightly-{0}'")); + expect_stderr_ok( + config, + &["rustup", "default", "nightly"], + for_host!("using existing install for 'nightly-{0}'"), + ); }); } @@ -84,12 +84,10 @@ fn update_channel() { clitools::setup(Scenario::ArchivesV2, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } @@ -98,10 +96,8 @@ fn list_toolchains() { clitools::setup(Scenario::ArchivesV2, &|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "update", "beta-2015-01-01"]); - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "nightly"); - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "beta-2015-01-01"); + expect_stdout_ok(config, &["rustup", "toolchain", "list"], "nightly"); + expect_stdout_ok(config, &["rustup", "toolchain", "list"], "beta-2015-01-01"); }); } @@ -122,8 +118,11 @@ fn list_toolchains_with_bogus_file() { #[test] fn list_toolchains_with_none() { setup(&|config| { - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "no installed toolchains"); + expect_stdout_ok( + config, + &["rustup", "toolchain", "list"], + "no installed toolchains", + ); }); } @@ -133,8 +132,11 @@ fn remove_toolchain() { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); expect_ok(config, &["rustup", "toolchain", "list"]); - expect_stdout_ok(config, &["rustup", "toolchain", "list"], - "no installed toolchains"); + expect_stdout_ok( + config, + &["rustup", "toolchain", "list"], + "no installed toolchains", + ); }); } @@ -169,8 +171,11 @@ fn remove_default_toolchain_err_handling() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]); - expect_err(config, &["rustc"], - for_host!("toolchain 'nightly-{0}' is not installed")); + expect_err( + config, + &["rustc"], + for_host!("toolchain 'nightly-{0}' is not installed"), + ); }); } @@ -182,7 +187,11 @@ fn remove_override_toolchain_err_handling() { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "override", "add", "beta"]); expect_ok(config, &["rustup", "toolchain", "remove", "beta"]); - expect_stderr_ok(config, &["rustc", "--version"], "info: installing component"); + expect_stderr_ok( + config, + &["rustc", "--version"], + "info: installing component", + ); }); }); } @@ -193,15 +202,22 @@ fn file_override_toolchain_err_handling() { let cwd = config.current_dir(); let toolchain_file = cwd.join("rust-toolchain"); rustup_utils::raw::write_file(&toolchain_file, "beta").unwrap(); - expect_stderr_ok(config, &["rustc", "--version"], "info: installing component"); + expect_stderr_ok( + config, + &["rustc", "--version"], + "info: installing component", + ); }); } #[test] fn plus_override_toolchain_err_handling() { setup(&|config| { - expect_err(config, &["rustc", "+beta"], - for_host!("toolchain 'beta-{0}' is not installed")); + expect_err( + config, + &["rustc", "+beta"], + for_host!("toolchain 'beta-{0}' is not installed"), + ); }); } @@ -232,8 +248,7 @@ fn bad_sha_on_installer() { rustup_utils::raw::write_file(&path, "xxx").unwrap(); } } - expect_err(config, &["rustup", "default", "nightly"], - "checksum failed"); + expect_err(config, &["rustup", "default", "nightly"], "checksum failed"); }); } @@ -241,14 +256,11 @@ fn bad_sha_on_installer() { fn install_override_toolchain_from_channel() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); expect_ok(config, &["rustup", "override", "add", "beta"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-b-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); expect_ok(config, &["rustup", "override", "add", "stable"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-s-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } @@ -256,14 +268,11 @@ fn install_override_toolchain_from_channel() { fn install_override_toolchain_from_archive() { clitools::setup(Scenario::ArchivesV2, &|config| { expect_ok(config, &["rustup", "override", "add", "nightly-2015-01-01"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); expect_ok(config, &["rustup", "override", "add", "beta-2015-01-01"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-b-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-b-1"); expect_ok(config, &["rustup", "override", "add", "stable-2015-01-01"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-s-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-s-1"); }); } @@ -271,8 +280,7 @@ fn install_override_toolchain_from_archive() { fn install_override_toolchain_from_version() { setup(&|config| { expect_ok(config, &["rustup", "override", "add", "1.1.0"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-s-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-s-2"); }); } @@ -280,9 +288,9 @@ fn install_override_toolchain_from_version() { fn override_overrides_default() { setup(&|config| { let tempdir = TempDir::new("rustup").unwrap(); - expect_ok(config, &["rustup", "default" , "nightly"]); + expect_ok(config, &["rustup", "default", "nightly"]); config.change_dir(tempdir.path(), &|| { - expect_ok(config, &["rustup", "override" , "add", "beta"]); + expect_ok(config, &["rustup", "override", "add", "beta"]); expect_stdout_ok(config, &["rustc", "--version"], "hash-b-2"); }); }); @@ -318,13 +326,13 @@ fn multiple_overrides() { #[cfg(windows)] fn override_windows_root() { setup(&|config| { - use std::path::{PathBuf, Component}; + use std::path::{Component, PathBuf}; let cwd = config.current_dir(); let prefix = cwd.components().next().unwrap(); let prefix = match prefix { Component::Prefix(p) => p, - _ => panic!() + _ => panic!(), }; // This value is probably "C:" @@ -360,8 +368,7 @@ fn remove_override_no_default() { config.change_dir(tempdir.path(), &|| { expect_ok(config, &["rustup", "override", "add", "nightly"]); expect_ok(config, &["rustup", "override", "remove"]); - expect_err(config, &["rustc"], - "no default toolchain configured"); + expect_err(config, &["rustc"], "no default toolchain configured"); }); }); } @@ -406,8 +413,7 @@ fn remove_override_with_multiple_overrides() { fn no_update_on_channel_when_date_has_not_changed() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustup", "update", "nightly"], - "unchanged"); + expect_stdout_ok(config, &["rustup", "update", "nightly"], "unchanged"); }); } @@ -416,12 +422,10 @@ fn update_on_channel_when_date_has_changed() { clitools::setup(Scenario::ArchivesV2, &|config| { set_current_dist_date(config, "2015-01-01"); expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-1"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-1"); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } @@ -430,8 +434,11 @@ fn run_command() { setup(&|config| { expect_ok(config, &["rustup", "update", "nightly"]); expect_ok(config, &["rustup", "default", "beta"]); - expect_stdout_ok(config, &["rustup", "run", "nightly", "rustc" , "--version"], - "hash-n-2"); + expect_stdout_ok( + config, + &["rustup", "run", "nightly", "rustc", "--version"], + "hash-n-2", + ); }); } @@ -455,8 +462,7 @@ fn upgrade_v1_to_v2() { expect_ok(config, &["rustup", "default", "nightly"]); set_current_dist_date(config, "2015-01-02"); expect_ok(config, &["rustup", "update", "nightly"]); - expect_stdout_ok(config, &["rustc", "--version"], - "hash-n-2"); + expect_stdout_ok(config, &["rustc", "--version"], "hash-n-2"); }); } @@ -467,16 +473,22 @@ fn upgrade_v2_to_v1() { expect_ok(config, &["rustup", "default", "nightly"]); set_current_dist_date(config, "2015-01-02"); fs::remove_file(config.distdir.join("dist/channel-rust-nightly.toml.sha256")).unwrap(); - expect_err(config, &["rustup", "update", "nightly"], - "the server unexpectedly provided an obsolete version of the distribution manifest"); + expect_err( + config, + &["rustup", "update", "nightly"], + "the server unexpectedly provided an obsolete version of the distribution manifest", + ); }); } #[test] fn list_targets_no_toolchain() { setup(&|config| { - expect_err(config, &["rustup", "target", "list", "--toolchain=nightly"], - for_host!("toolchain 'nightly-{0}' is not installed")); + expect_err( + config, + &["rustup", "target", "list", "--toolchain=nightly"], + for_host!("toolchain 'nightly-{0}' is not installed"), + ); }); } @@ -484,8 +496,11 @@ fn list_targets_no_toolchain() { fn list_targets_v1_toolchain() { clitools::setup(Scenario::SimpleV1, &|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_err(config, &["rustup", "target", "list", "--toolchain=nightly"], - for_host!("toolchain 'nightly-{0}' does not support components")); + expect_err( + config, + &["rustup", "target", "list", "--toolchain=nightly"], + for_host!("toolchain 'nightly-{0}' does not support components"), + ); }); } @@ -494,11 +509,16 @@ fn list_targets_custom_toolchain() { setup(&|config| { let path = config.customdir.join("custom-1"); let path = path.to_string_lossy(); - expect_ok(config, &["rustup", "toolchain", "link", "default-from-path", - &path]); + expect_ok( + config, + &["rustup", "toolchain", "link", "default-from-path", &path], + ); expect_ok(config, &["rustup", "default", "default-from-path"]); - expect_err(config, &["rustup", "target", "list"], - "toolchain 'default-from-path' does not support components"); + expect_err( + config, + &["rustup", "target", "list"], + "toolchain 'default-from-path' does not support components", + ); }); } @@ -506,10 +526,8 @@ fn list_targets_custom_toolchain() { fn list_targets() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_stdout_ok(config, &["rustup", "target", "list"], - clitools::CROSS_ARCH1); - expect_stdout_ok(config, &["rustup", "target", "list"], - clitools::CROSS_ARCH2); + expect_stdout_ok(config, &["rustup", "target", "list"], clitools::CROSS_ARCH1); + expect_stdout_ok(config, &["rustup", "target", "list"], clitools::CROSS_ARCH2); }); } @@ -518,8 +536,11 @@ fn add_target() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1]); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - this_host_triple(), clitools::CROSS_ARCH1); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + this_host_triple(), + clitools::CROSS_ARCH1 + ); assert!(config.rustupdir.join(path).exists()); }); } @@ -527,16 +548,28 @@ fn add_target() { #[test] fn add_target_no_toolchain() { setup(&|config| { - expect_err(config, &["rustup", "target", "add", clitools::CROSS_ARCH1, "--toolchain=nightly"], - for_host!("toolchain 'nightly-{0}' is not installed")); + expect_err( + config, + &[ + "rustup", + "target", + "add", + clitools::CROSS_ARCH1, + "--toolchain=nightly", + ], + for_host!("toolchain 'nightly-{0}' is not installed"), + ); }); } #[test] fn add_target_bogus() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_err(config, &["rustup", "target", "add", "bogus"], - "does not contain component 'rust-std' for target 'bogus'"); + expect_err( + config, + &["rustup", "target", "add", "bogus"], + "does not contain component 'rust-std' for target 'bogus'", + ); }); } @@ -544,8 +577,17 @@ fn add_target_bogus() { fn add_target_v1_toolchain() { clitools::setup(Scenario::SimpleV1, &|config| { expect_ok(config, &["rustup", "update", "nightly"]); - expect_err(config, &["rustup", "target", "add", clitools::CROSS_ARCH1, "--toolchain=nightly"], - for_host!("toolchain 'nightly-{0}' does not support components")); + expect_err( + config, + &[ + "rustup", + "target", + "add", + clitools::CROSS_ARCH1, + "--toolchain=nightly", + ], + for_host!("toolchain 'nightly-{0}' does not support components"), + ); }); } @@ -554,11 +596,16 @@ fn add_target_custom_toolchain() { setup(&|config| { let path = config.customdir.join("custom-1"); let path = path.to_string_lossy(); - expect_ok(config, &["rustup", "toolchain", "link", "default-from-path", - &path]); + expect_ok( + config, + &["rustup", "toolchain", "link", "default-from-path", &path], + ); expect_ok(config, &["rustup", "default", "default-from-path"]); - expect_err(config, &["rustup", "target", "add", clitools::CROSS_ARCH1], - "toolchain 'default-from-path' does not support components"); + expect_err( + config, + &["rustup", "target", "add", clitools::CROSS_ARCH1], + "toolchain 'default-from-path' does not support components", + ); }); } @@ -567,11 +614,19 @@ fn add_target_again() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1]); - expect_stderr_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1], - &format!("component 'rust-std' for target '{}' is up to date", - clitools::CROSS_ARCH1)); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - this_host_triple(), clitools::CROSS_ARCH1); + expect_stderr_ok( + config, + &["rustup", "target", "add", clitools::CROSS_ARCH1], + &format!( + "component 'rust-std' for target '{}' is up to date", + clitools::CROSS_ARCH1 + ), + ); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + this_host_triple(), + clitools::CROSS_ARCH1 + ); assert!(config.rustupdir.join(path).exists()); }); } @@ -591,15 +646,27 @@ fn remove_target() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1]); - expect_ok(config, &["rustup", "target", "remove", clitools::CROSS_ARCH1]); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", - this_host_triple(), clitools::CROSS_ARCH1); + expect_ok( + config, + &["rustup", "target", "remove", clitools::CROSS_ARCH1], + ); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib", + this_host_triple(), + clitools::CROSS_ARCH1 + ); assert!(!config.rustupdir.join(path).exists()); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib", - this_host_triple(), clitools::CROSS_ARCH1); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}/lib", + this_host_triple(), + clitools::CROSS_ARCH1 + ); assert!(!config.rustupdir.join(path).exists()); - let path = format!("toolchains/nightly-{}/lib/rustlib/{}", - this_host_triple(), clitools::CROSS_ARCH1); + let path = format!( + "toolchains/nightly-{}/lib/rustlib/{}", + this_host_triple(), + clitools::CROSS_ARCH1 + ); assert!(!config.rustupdir.join(path).exists()); }); } @@ -608,17 +675,32 @@ fn remove_target() { fn remove_target_not_installed() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_err(config, &["rustup", "target", "remove", clitools::CROSS_ARCH1], - &format!("toolchain 'nightly-{}' does not contain component 'rust-std' for target '{}'", - this_host_triple(), clitools::CROSS_ARCH1)); + expect_err( + config, + &["rustup", "target", "remove", clitools::CROSS_ARCH1], + &format!( + "toolchain 'nightly-{}' does not contain component 'rust-std' for target '{}'", + this_host_triple(), + clitools::CROSS_ARCH1 + ), + ); }); } #[test] fn remove_target_no_toolchain() { setup(&|config| { - expect_err(config, &["rustup", "target", "remove", clitools::CROSS_ARCH1, "--toolchain=nightly"], - for_host!("toolchain 'nightly-{0}' is not installed")); + expect_err( + config, + &[ + "rustup", + "target", + "remove", + clitools::CROSS_ARCH1, + "--toolchain=nightly", + ], + for_host!("toolchain 'nightly-{0}' is not installed"), + ); }); } @@ -626,8 +708,11 @@ fn remove_target_no_toolchain() { fn remove_target_bogus() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_err(config, &["rustup", "target", "remove", "bogus"], - "does not contain component 'rust-std' for target 'bogus'"); + expect_err( + config, + &["rustup", "target", "remove", "bogus"], + "does not contain component 'rust-std' for target 'bogus'", + ); }); } @@ -635,8 +720,17 @@ fn remove_target_bogus() { fn remove_target_v1_toolchain() { clitools::setup(Scenario::SimpleV1, &|config| { expect_ok(config, &["rustup", "default", "nightly"]); - expect_err(config, &["rustup", "target", "remove", clitools::CROSS_ARCH1, "--toolchain=nightly"], - for_host!("toolchain 'nightly-{0}' does not support components")); + expect_err( + config, + &[ + "rustup", + "target", + "remove", + clitools::CROSS_ARCH1, + "--toolchain=nightly", + ], + for_host!("toolchain 'nightly-{0}' does not support components"), + ); }); } @@ -645,11 +739,16 @@ fn remove_target_custom_toolchain() { setup(&|config| { let path = config.customdir.join("custom-1"); let path = path.to_string_lossy(); - expect_ok(config, &["rustup", "toolchain", "link", "default-from-path", - &path]); + expect_ok( + config, + &["rustup", "toolchain", "link", "default-from-path", &path], + ); expect_ok(config, &["rustup", "default", "default-from-path"]); - expect_err(config, &["rustup", "target", "remove", clitools::CROSS_ARCH1], - "toolchain 'default-from-path' does not support components"); + expect_err( + config, + &["rustup", "target", "remove", clitools::CROSS_ARCH1], + "toolchain 'default-from-path' does not support components", + ); }); } @@ -658,10 +757,19 @@ fn remove_target_again() { setup(&|config| { expect_ok(config, &["rustup", "default", "nightly"]); expect_ok(config, &["rustup", "target", "add", clitools::CROSS_ARCH1]); - expect_ok(config, &["rustup", "target", "remove", clitools::CROSS_ARCH1]); - expect_err(config, &["rustup", "target", "remove", clitools::CROSS_ARCH1], - &format!("toolchain 'nightly-{}' does not contain component 'rust-std' for target '{}'", - this_host_triple(), clitools::CROSS_ARCH1)); + expect_ok( + config, + &["rustup", "target", "remove", clitools::CROSS_ARCH1], + ); + expect_err( + config, + &["rustup", "target", "remove", clitools::CROSS_ARCH1], + &format!( + "toolchain 'nightly-{}' does not contain component 'rust-std' for target '{}'", + this_host_triple(), + clitools::CROSS_ARCH1 + ), + ); }); } @@ -701,7 +809,13 @@ fn update_unavailable_std() { setup(&|config| { let ref trip = TargetTriple::from_build(); make_component_unavailable(config, "rust-std", trip); - expect_err(config, &["rustup", "update", "nightly"], - &format!("component 'rust-std' for '{}' is unavailable for download", trip)); + expect_err( + config, + &["rustup", "update", "nightly"], + &format!( + "component 'rust-std' for '{}' is unavailable for download", + trip + ), + ); }); }