diff --git a/.travis.yml b/.travis.yml index b467461c3ad..fc8e05f34aa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,13 @@ language: rust matrix: include: + # Separate build to detect if the code is formatted correctly + - os: linux + env: TARGET=x86_64-unknown-linux-gnu + DOCKER=alexcrichton/rust-slave-dist:2015-10-20b + RUSTFMT_ONLY=1 + NO_ADD=1 + ALLOW_PR=1 # Linux builds use the `rust-slave-dist` image so we link them against a # "super old glibc" to ensure that it runs on as many platforms as possible. - os: linux @@ -124,6 +131,7 @@ branches: install: - if [ -z "$NO_ADD" ]; then rustup target add $TARGET; fi + - rustup component add rustfmt-preview script: - mkdir -p target/$TARGET; @@ -134,7 +142,7 @@ script: echo 'skipping master build'; else if [ ! -z "$DOCKER" ]; then - sh ci/build-run-docker.sh "$DOCKER" "$TARGET" "$SKIP_TESTS"; + sh ci/build-run-docker.sh "$DOCKER" "$TARGET" "$SKIP_TESTS" "$RUSTFMT_ONLY"; else PATH=$HOME/rust/bin:$PATH sh ci/run.sh; fi diff --git a/build.rs b/build.rs index 3c642ea44ba..a36192a6c02 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,21 @@ 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(try!(String::from_utf8( + try!( + 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(try!(String::from_utf8( + try!( + Command::new("git") + .args(&["log", "-1", "--date=short", "--pretty=format:%cd"]) + .output() + ).stdout + ))) } diff --git a/ci/build-run-docker.sh b/ci/build-run-docker.sh index bf456f592a3..05c3feaec56 100644 --- a/ci/build-run-docker.sh +++ b/ci/build-run-docker.sh @@ -7,6 +7,7 @@ mkdir -p target DOCKER="$1" TARGET="$2" SKIP_TESTS="$3" +RUSTFMT_ONLY="$4" if [ -f "ci/docker/$DOCKER/Dockerfile" ]; then docker build -t "$DOCKER" "ci/docker/$DOCKER/" @@ -21,6 +22,7 @@ docker run \ --workdir /src \ --env TARGET=$TARGET \ --env SKIP_TESTS=$SKIP_TESTS \ + --env RUSTFMT_ONLY=$RUSTFMT_ONLY \ $DOCKER \ ci/run-docker.sh diff --git a/ci/run.sh b/ci/run.sh index c95df5fd20d..6e2ddac800f 100644 --- a/ci/run.sh +++ b/ci/run.sh @@ -7,6 +7,11 @@ echo "toolchain versions\n------------------" rustc -vV cargo -vV +if [ ! -z "$RUSTFMT_ONLY" ]; then + cargo fmt --all -- --write-mode=diff + exit 0 +fi + cargo build --locked -v --release --target $TARGET if [ -z "$SKIP_TESTS" ]; then diff --git a/src/download/src/errors.rs b/src/download/src/errors.rs index 54d92253213..f1a228a1c3a 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 2d92f47865d..96ba559492b 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,18 +48,15 @@ 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 { @@ -81,43 +82,55 @@ pub fn download_to_path_with_backend( 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 = try!( + OpenOptions::new() + .write(true) + .create(true) + .open(&path) + .chain_err(|| "error opening file for download") + ); try!(possible_partial.seek(SeekFrom::End(0))); (possible_partial, downloaded_so_far) } else { - (try!(OpenOptions::new() - .write(true) - .create(true) - .open(&path) - .chain_err(|| "error creating file for download")), 0) + ( + try!( + OpenOptions::new() + .write(true) + .create(true) + .open(&path) + .chain_err(|| "error creating file for download") + ), + 0, + ) }; let file = RefCell::new(file); try!(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")); + try!( + 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")); + try!( + 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 +151,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 +161,23 @@ 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")); + try!( + handle + .url(&url.to_string()) + .chain_err(|| "failed to set url") + ); + try!( + 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")); + try!( + 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 +185,11 @@ pub mod curl { } // Take at most 30s to connect - try!(handle.connect_timeout(Duration::new(30, 0)).chain_err(|| "failed to set connect timeout")); + try!( + handle + .connect_timeout(Duration::new(30, 0)) + .chain_err(|| "failed to set connect timeout") + ); { let cberr = RefCell::new(None); @@ -173,36 +198,43 @@ 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)) { - Ok(()) => Ok(data.len()), - Err(e) => { - *cberr.borrow_mut() = Some(e); - Ok(0) - } - } - }).chain_err(|| "failed to set write")); + try!( + 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") + ); // 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; + 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; + } + } } } } - } - } - 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. @@ -224,10 +256,16 @@ 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 = try!( + 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 +284,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 +305,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]))?; @@ -311,26 +344,28 @@ 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 = try!( + 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 @@ -339,16 +374,20 @@ 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 = + try!(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 = + 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] + ))); } Ok(true) @@ -365,10 +404,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()) } } @@ -380,10 +420,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 a3aaf501125..778eafe64e9 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 bbe03e245fb..6049bb9afb4 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 7882fadb81b..380211cf860 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 2b129064527..f1b740fe94e 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}; @@ -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 { @@ -47,7 +49,7 @@ pub fn confirm_advanced() -> Result { let input = try!(read_line()); let r = match &*input { - "1"|"" => Confirm::Yes, + "1" | "" => Confirm::Yes, "2" => Confirm::Advanced, _ => Confirm::No, }; @@ -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 { @@ -106,7 +109,7 @@ 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) { + if download_tracker.borrow_mut().handle_notification(&n) { return; } @@ -127,15 +130,20 @@ pub fn set_globals(verbose: bool) -> Result { } } })))) - } -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,7 +199,6 @@ fn show_channel_updates(cfg: &Cfg, toolchains: Vec<(String, rustup::Result Result<()> { - let toolchains = try!(cfg.update_all_channels(force_update)); if toolchains.is_empty() { @@ -241,7 +249,9 @@ pub fn rustc_version(toolchain: &Toolchain) -> String { let timeout = Duration::new(10, 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(_) => {} } @@ -274,7 +284,11 @@ pub fn list_targets(toolchain: &Toolchain) -> Result<()> { let mut t = term2::stdout(); for component in try!(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); @@ -327,7 +341,6 @@ pub fn list_toolchains(cfg: &Cfg) -> Result<()> { }; println!("{}{}", &toolchain, if_default); } - } else { for toolchain in toolchains { println!("{}", &toolchain); @@ -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 e6e61b7cf64..6673d9c26fb 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 da1d9a15f7a..696ad9c408e 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 d4850d01092..5dd590daf4d 100644 --- a/src/rustup-cli/job.rs +++ b/src/rustup-cli/job.rs @@ -67,7 +67,7 @@ mod imp { let job = jobapi2::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: winnt::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; info = mem::zeroed(); - info.BasicLimitInformation.LimitFlags = - winnt::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - let r = jobapi2::SetInformationJobObject(job.inner, - winnt::JobObjectExtendedLimitInformation, - &mut info as *mut _ as minwindef::LPVOID, - mem::size_of_val(&info) as minwindef::DWORD); + info.BasicLimitInformation.LimitFlags = winnt::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let r = jobapi2::SetInformationJobObject( + job.inner, + winnt::JobObjectExtendedLimitInformation, + &mut info as *mut _ as minwindef::LPVOID, + mem::size_of_val(&info) as minwindef::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 = processthreadsapi::GetCurrentProcess(); let r = jobapi2::AssignProcessToJobObject(job.inner, me); if r == 0 { - return None + return None; } Some(Setup { job: job }) @@ -121,13 +122,13 @@ mod imp { let mut info: winnt::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; info = mem::zeroed(); let r = jobapi2::SetInformationJobObject( - self.job.inner, - winnt::JobObjectExtendedLimitInformation, - &mut info as *mut _ as minwindef::LPVOID, - mem::size_of_val(&info) as minwindef::DWORD); + self.job.inner, + winnt::JobObjectExtendedLimitInformation, + &mut info as *mut _ as minwindef::LPVOID, + mem::size_of_val(&info) as minwindef::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,68 @@ mod imp { let mut jobs: Jobs = mem::zeroed(); let r = jobapi2::QueryInformationJobObject( - self.job.inner, - winnt::JobObjectBasicProcessIdList, - &mut jobs as *mut _ as minwindef::LPVOID, - mem::size_of_val(&jobs) as minwindef::DWORD, - 0 as *mut _); + self.job.inner, + winnt::JobObjectBasicProcessIdList, + &mut jobs as *mut _ as minwindef::LPVOID, + mem::size_of_val(&jobs) as minwindef::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 minwindef::DWORD != processthreadsapi::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 = winnt::PROCESS_QUERY_INFORMATION | - winnt::PROCESS_TERMINATE | - winnt::SYNCHRONIZE; - let p = processthreadsapi::OpenProcess(flags, - minwindef::FALSE, - id as minwindef::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 = jobapi::IsProcessInJob(p.inner, self.job.inner, &mut res); - if r == 0 { - info!("failed to test is process in job: {}", last_err()); - return false - } - res == minwindef::TRUE - }); - + let list = list.iter() + .filter(|&&id| { + // let's not kill ourselves + id as minwindef::DWORD != processthreadsapi::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 = winnt::PROCESS_QUERY_INFORMATION | winnt::PROCESS_TERMINATE + | winnt::SYNCHRONIZE; + let p = processthreadsapi::OpenProcess( + flags, + minwindef::FALSE, + id as minwindef::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 = jobapi::IsProcessInJob(p.inner, self.job.inner, &mut res); + if r == 0 { + info!("failed to test is process in job: {}", last_err()); + return false; + } + res == minwindef::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 minwindef::DWORD); + let r = psapi::GetProcessImageFileNameW( + p.inner, + buf.as_mut_ptr(), + buf.len() as minwindef::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 +224,7 @@ mod imp { if let Some(s) = s.to_str() { if s.contains("mspdbsrv") { info!("\toops, this is mspdbsrv"); - continue + continue; } } @@ -234,18 +241,20 @@ mod imp { let r = synchapi::WaitForSingleObject(p.inner, winbase::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 { handleapi::CloseHandle(self.inner); } + unsafe { + handleapi::CloseHandle(self.inner); + } } } } diff --git a/src/rustup-cli/main.rs b/src/rustup-cli/main.rs index 20890d17bca..115f9b5389c 100644 --- a/src/rustup-cli/main.rs +++ b/src/rustup-cli/main.rs @@ -14,33 +14,33 @@ #![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 same_file; 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; +extern crate libc; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate winreg; -extern crate libc; #[macro_use] mod log; @@ -83,12 +83,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 @@ -118,9 +117,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()) @@ -129,8 +126,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()); } @@ -158,7 +157,7 @@ fn make_environment_compatible() { env::set_var(rvar, mval); warn!("environment variable {} is deprecated. Use {}.", mvar, rvar); } - _ => () + _ => (), } } } @@ -179,7 +178,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; @@ -187,7 +188,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 f865d927f74..34787febae6 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; @@ -23,14 +23,13 @@ pub fn main() -> Result<()> { // 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() { diff --git a/src/rustup-cli/rustup_mode.rs b/src/rustup-cli/rustup_mode.rs index 05c932772c0..b33895a4820 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; @@ -23,7 +23,7 @@ pub fn main() -> Result<()> { let ref cfg = try!(common::set_globals(verbose)); if try!(maybe_upgrade_data(cfg, matches)) { - return Ok(()) + return Ok(()); } try!(cfg.check_metadata_version()); @@ -34,67 +34,57 @@ pub fn main() -> Result<()> { ("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!(), - } - } + ("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!(), - } - } + ("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!(), + }, ("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,265 +101,349 @@ 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)) - .arg(Arg::with_name("force") - .help("Force an update, even if some components are missing") - .long("force") - .takes_value(false))) - .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), + ) + .arg( + Arg::with_name("force") + .help("Force an update, even if some components are missing") + .long("force") + .takes_value(false), + ), + ) + .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(_)) => { + try!(cfg.upgrade_data()); + Ok(true) } - } - _ => Ok(false) + _ => Ok(false), + }, + _ => Ok(false), } } @@ -378,8 +452,7 @@ fn update_bare_triple_check(cfg: &Cfg, name: &str) -> Result<()> { 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 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 { @@ -390,10 +463,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); } @@ -419,16 +500,21 @@ 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_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)); 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()); } @@ -453,7 +539,11 @@ fn default_(cfg: &Cfg, m: &ArgMatches) -> Result<()> { if let Some(status) = status { println!(""); - try!(common::show_channel_update(cfg, toolchain.name(), Ok(status))); + try!(common::show_channel_update( + cfg, + toolchain.name(), + Ok(status) + )); } Ok(()) @@ -475,7 +565,11 @@ fn update(cfg: &Cfg, m: &ArgMatches) -> Result<()> { if let Some(status) = status { println!(""); - try!(common::show_channel_update(cfg, toolchain.name(), Ok(status))); + try!(common::show_channel_update( + cfg, + toolchain.name(), + Ok(status) + )); } } } else { @@ -495,14 +589,19 @@ fn run(cfg: &Cfg, m: &ArgMatches) -> Result<()> { 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))) + Ok(try!(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 = + try!(cfg.which_binary(&try!(utils::current_dir()), binary)).expect("binary not found"); try!(utils::assert_is_file(&binary_path)); @@ -535,7 +634,7 @@ fn show(cfg: &Cfg) -> Result<()> { .filter(|c| c.component.pkg == "rust-std") .filter(|c| c.installed) .collect(), - Err(_) => vec![] + Err(_) => vec![], } } else { vec![] @@ -552,11 +651,15 @@ 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") } + if show_headers { + print_header("installed toolchains") + } let default_name = try!(cfg.get_default()); for t in installed_toolchains { if default_name == t { @@ -565,7 +668,9 @@ fn show(cfg: &Cfg) -> Result<()> { println!("{}", t); } } - if show_headers { println!("") }; + if show_headers { + println!("") + }; } if show_active_targets { @@ -573,30 +678,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); @@ -606,7 +719,9 @@ fn show(cfg: &Cfg) -> Result<()> { } } - if show_headers { println!("") }; + if show_headers { + println!("") + }; } fn print_header(s: &str) { @@ -665,9 +780,15 @@ fn component_list(cfg: &Cfg, m: &ArgMatches) -> Result<()> { 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 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 { @@ -683,9 +804,15 @@ fn component_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { 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 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 { @@ -744,7 +871,11 @@ fn override_add(cfg: &Cfg, m: &ArgMatches) -> Result<()> { if let Some(status) = status { println!(""); - try!(common::show_channel_update(cfg, toolchain.name(), Ok(status))); + try!(common::show_channel_update( + cfg, + toolchain.name(), + Ok(status) + )); } Ok(()) @@ -752,13 +883,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<_> = 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()) + })); if list.is_empty() { info!("no nonexistent paths detected"); } @@ -772,15 +908,20 @@ fn override_remove(cfg: &Cfg, m: &ArgMatches) -> Result<()> { }; 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 try!( + 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" + ); } } } @@ -796,7 +937,10 @@ fn doc(cfg: &Cfg, m: &ArgMatches) -> Result<()> { "index.html" }; - Ok(try!(cfg.open_docs_for_dir(&try!(utils::current_dir()), doc_url))) + Ok(try!(cfg.open_docs_for_dir( + &try!(utils::current_dir()), + doc_url + ))) } fn man(cfg: &Cfg, m: &ArgMatches) -> Result<()> { diff --git a/src/rustup-cli/self_update.rs b/src/rustup-cli/self_update.rs index 8c736ebf351..7288d777432 100644 --- a/src/rustup-cli/self_update.rs +++ b/src/rustup-cli/self_update.rs @@ -37,7 +37,7 @@ use rustup_utils::utils; use same_file::Handle; 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; @@ -166,8 +166,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. @@ -190,16 +189,15 @@ 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 @@ -207,7 +205,9 @@ fn canonical_cargo_home() -> Result { let path = try!(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"); @@ -222,9 +222,7 @@ 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<()> { try!(do_pre_install_sanity_checks()); try!(check_existence_of_rustc_or_cargo_in_path(no_prompt)); try!(do_anti_sudo_check(no_prompt)); @@ -252,10 +250,10 @@ pub fn install(no_prompt: bool, verbose: bool, Confirm::No => { info!("aborting installation"); return Ok(()); - }, + } Confirm::Yes => { break; - }, + } Confirm::Advanced => { opts = try!(customize_install(opts)); } @@ -273,20 +271,21 @@ pub fn install(no_prompt: bool, verbose: bool, // 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)); + try!(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())); + let ref env_str = format!("{}\n", try!(shell_export_string())); try!(utils::write_file("env", env_file, env_str)); } Ok(()) })(); - if let Err(ref e) = install_res { common::report_error(e); @@ -308,19 +307,21 @@ pub fn install(no_prompt: bool, verbose: bool, let cargo_home = try!(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); @@ -341,8 +342,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") { @@ -381,27 +384,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()); @@ -418,35 +413,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"); @@ -472,13 +483,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; @@ -488,7 +511,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, } } @@ -503,7 +526,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"); } @@ -543,28 +566,39 @@ fn pre_install_msg(no_modify_path: bool) -> Result { 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() + )) } } @@ -584,24 +618,27 @@ 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 + )); opts.default_toolchain = try!(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 + )); Ok(opts) } @@ -629,9 +666,7 @@ fn cleanup_legacy() -> Result<()> { #[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("."))) @@ -689,7 +724,7 @@ pub fn install_proxies() -> Result<()> { if let Ok(handle) = Handle::from_path(&tool_path) { tool_handles.push(handle); if rustup == *tool_handles.last().unwrap() { - continue + continue; } } link_afterwards.push(tool_path); @@ -701,7 +736,7 @@ pub fn install_proxies() -> Result<()> { // Like above, don't clobber anything that's already hardlinked to // avoid extraneous errors from being returned. if rustup == handle { - continue + continue; } // If this file exists and is *not* equivalent to all other @@ -719,7 +754,7 @@ pub fn install_proxies() -> Result<()> { warn!("tool `{}` is already installed, remove it from `{}`, then run `rustup update` \ to have rustup manage this tool.", tool, bin_path.to_string_lossy()); - continue + continue; } } try!(utils::hard_or_symlink_file(rustup_path, tool_path)); @@ -770,24 +805,31 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { // 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") + try!( + Command::new("msiexec") .arg("/x") .arg(product_code) .spawn() - .chain_err(|| ErrorKind::WindowsUninstallMadness)); + .chain_err(|| ErrorKind::WindowsUninstallMadness) + ); process::exit(0); } let ref cargo_home = try!(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 = try!(canonical_cargo_home()) + ); term2::stdout().md(msg); if !try!(common::confirm("\nContinue? (y/N)", false)) { info!("aborting uninstallation"); @@ -829,7 +871,10 @@ pub fn uninstall(no_prompt: bool) -> Result<()> { // 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)); @@ -870,19 +915,11 @@ 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), } } @@ -937,7 +974,9 @@ fn delete_rustup_and_cargo_home() -> Result<()> { 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. @@ -969,23 +1008,30 @@ 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)); + try!( + 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 @@ -1017,12 +1063,14 @@ pub fn complete_windows_uninstall() -> Result<()> { // 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)); + try!( + Command::new(rm_gc_exe) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .chain_err(|| ErrorKind::WindowsUninstallMadness) + ); process::exit(0); } @@ -1031,10 +1079,11 @@ pub fn complete_windows_uninstall() -> Result<()> { fn wait_for_parent() -> Result<()> { use winapi::shared::minwindef::DWORD; use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE}; - use winapi::um::processthreadsapi::{OpenProcess, GetCurrentProcessId}; + use winapi::um::processthreadsapi::{GetCurrentProcessId, OpenProcess}; use winapi::um::synchapi::WaitForSingleObject; - use winapi::um::tlhelp32::{CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS}; - use winapi::um::winbase::{INFINITE, WAIT_OBJECT_0}; + use winapi::um::tlhelp32::{CreateToolhelp32Snapshot, PROCESSENTRY32, Process32First, + Process32Next, TH32CS_SNAPPROCESS}; + use winapi::um::winbase::{WAIT_OBJECT_0, INFINITE}; use winapi::um::winnt::SYNCHRONIZE; use std::io; use std::mem; @@ -1050,7 +1099,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; @@ -1083,7 +1134,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); @@ -1137,7 +1190,7 @@ 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() } @@ -1150,7 +1203,6 @@ 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() { @@ -1177,7 +1229,8 @@ fn do_add_to_path(methods: &[PathUpdateMethod]) -> Result<()> { use winreg::{RegKey, RegValue}; use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; use winapi::shared::minwindef::*; - use winapi::um::winuser::{SendMessageTimeoutA, HWND_BROADCAST, WM_SETTINGCHANGE, SMTO_ABORTIFHUNG}; + use winapi::um::winuser::{SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, + WM_SETTINGCHANGE}; use std::ptr; let old_path = if let Some(s) = try!(get_windows_path_var()) { @@ -1187,7 +1240,10 @@ fn do_add_to_path(methods: &[PathUpdateMethod]) -> Result<()> { return Ok(()); }; - let mut new_path = try!(utils::cargo_home()).join("bin").to_string_lossy().to_string(); + let mut new_path = try!(utils::cargo_home()) + .join("bin") + .to_string_lossy() + .to_string(); if old_path.contains(&new_path) { return Ok(()); } @@ -1198,24 +1254,31 @@ 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 = try!( + 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)); + try!( + 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(()) @@ -1231,8 +1294,10 @@ 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 = try!( + 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 { @@ -1245,12 +1310,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), } } @@ -1265,17 +1326,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 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 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()) } @@ -1285,7 +1343,8 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { assert!(methods.len() == 1 && methods[0] == PathUpdateMethod::Windows); use winapi::shared::minwindef::*; - use winapi::um::winuser::{SendMessageTimeoutA, SMTO_ABORTIFHUNG, HWND_BROADCAST, WM_SETTINGCHANGE}; + use winapi::um::winuser::{SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, + WM_SETTINGCHANGE}; use winreg::{RegKey, RegValue}; use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; use std::ptr; @@ -1297,7 +1356,10 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { return Ok(()); }; - let ref path_str = try!(utils::cargo_home()).join("bin").to_string_lossy().to_string(); + let ref path_str = try!(utils::cargo_home()) + .join("bin") + .to_string_lossy() + .to_string(); let idx = if let Some(i) = old_path.find(path_str) { i } else { @@ -1312,32 +1374,42 @@ 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 = try!( + 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)); + try!( + 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)); + try!( + 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(()) @@ -1353,7 +1425,8 @@ fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> { 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(); @@ -1417,8 +1490,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, + }, } } @@ -1427,7 +1500,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) } @@ -1462,11 +1535,9 @@ pub fn prepare_update() -> Result> { build_triple }; - let update_root = env::var("RUSTUP_UPDATE_ROOT") - .unwrap_or(String::from(UPDATE_ROOT)); + let update_root = env::var("RUSTUP_UPDATE_ROOT").unwrap_or(String::from(UPDATE_ROOT)); - let tempdir = try!(TempDir::new("rustup-update") - .chain_err(|| "error creating temp directory")); + let tempdir = try!(TempDir::new("rustup-update").chain_err(|| "error creating temp directory")); // Get current version let current_version = env!("CARGO_PKG_VERSION"); @@ -1476,21 +1547,43 @@ pub fn prepare_update() -> Result> { let release_file_url = format!("{}/release-stable.toml", update_root); let release_file_url = try!(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, &|_| ())); + 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"))); + 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")) + ); 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 @@ -1499,18 +1592,22 @@ 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)); // Download new version info!("downloading self-update"); - try!(utils::download_file(&download_url, - &setup_path, - None, - &|_| ())); + try!(utils::download_file( + &download_url, + &setup_path, + None, + &|_| () + )); // Mark as executable try!(utils::make_executable(setup_path)); @@ -1528,9 +1625,12 @@ pub fn prepare_update() -> Result> { /// considered successful. #[cfg(unix)] pub fn run_update(setup_path: &Path) -> Result<()> { - let status = try!(Command::new(setup_path) - .arg("--self-replace") - .status().chain_err(|| "unable to run updater")); + let status = try!( + Command::new(setup_path) + .arg("--self-replace") + .status() + .chain_err(|| "unable to run updater") + ); if !status.success() { return Err("self-updated failed to replace rustup executable".into()); @@ -1541,9 +1641,12 @@ pub fn run_update(setup_path: &Path) -> Result<()> { #[cfg(windows)] pub fn run_update(setup_path: &Path) -> Result<()> { - try!(Command::new(setup_path) - .arg("--self-replace") - .spawn().chain_err(|| "unable to run updater")); + try!( + Command::new(setup_path) + .arg("--self-replace") + .spawn() + .chain_err(|| "unable to run updater") + ); process::exit(0); } diff --git a/src/rustup-cli/setup_mode.rs b/src/rustup-cli/setup_mode.rs index f309d104ccf..1292078d5c0 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"); diff --git a/src/rustup-cli/term2.rs b/src/rustup-cli/term2.rs index 60daa15efe7..4034bb8824e 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 c3ea28b8ab5..2f3dbd8988a 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 9185f6e0c0e..c6ff9d6048f 100644 --- a/src/rustup-dist/src/component/components.rs +++ b/src/rustup-dist/src/component/components.rs @@ -41,16 +41,20 @@ 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( + try!(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)); + try!(utils::write_file( + VERSION_FILE, + &self.prefix.manifest_file(VERSION_FILE), + INSTALLER_VERSION + )); Ok(()) } @@ -60,14 +64,13 @@ impl Components { 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()) + 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 { @@ -90,20 +93,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) } @@ -115,7 +121,12 @@ impl<'a> ComponentBuilder<'a> { 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())); + try!(utils::write_line( + "component", + &mut file, + &abs_path, + &part.encode() + )); } // Add component to components file @@ -140,8 +151,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,7 +169,9 @@ 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 @@ -167,8 +179,10 @@ impl Component { 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())))); + result + .push(try!(ComponentPart::decode(line).ok_or_else(|| { + ErrorKind::CorruptComponent(self.name.clone()) + }))); } Ok(result) } @@ -251,10 +265,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; diff --git a/src/rustup-dist/src/component/mod.rs b/src/rustup-dist/src/component/mod.rs index 6d5442a1cfd..1c15c3aac33 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 b78cc818c84..7683edd1a35 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; } @@ -44,7 +45,10 @@ impl DirectoryPackage { pub fn new(path: PathBuf) -> Result { try!(validate_installer_version(&path)); - let content = try!(utils::read_file("package components", &path.join("components"))); + let content = try!(utils::read_file( + "package components", + &path.join("components") + )); let components = content.lines().map(|l| l.to_owned()).collect(); Ok(DirectoryPackage { path: path, @@ -54,7 +58,10 @@ impl DirectoryPackage { } fn validate_installer_version(path: &Path) -> Result<()> { - let file = try!(utils::read_file("installer version", &path.join(VERSION_FILE))); + let file = try!(utils::read_file( + "installer version", + &path.join(VERSION_FILE) + )); let v = file.trim(); if v == INSTALLER_VERSION { Ok(()) @@ -65,19 +72,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,12 +95,17 @@ 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 = try!(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 = try!( + ComponentPart::decode(l) + .ok_or_else(|| ErrorKind::CorruptComponent(name.to_owned())) + ); let path = part.1; let src_path = root.join(&path); @@ -104,7 +116,10 @@ impl Package for DirectoryPackage { _ => return Err(ErrorKind::CorruptComponent(name.to_owned()).into()), } - try!(set_file_perms(&target.prefix().path().join(path), &src_path)); + try!(set_file_perms( + &target.prefix().path().join(path), + &src_path + )); } let tx = try!(builder.finish()); @@ -146,16 +161,31 @@ fn set_file_perms(dest_path: &Path, src_path: &Path) -> Result<()> { // 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 meta = try!( + 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)); + try!( + fs::set_permissions(entry.path(), perm) + .chain_err(|| ErrorKind::ComponentFilePermissionsFailed) + ); } } else { - let meta = try!(fs::metadata(dest_path).chain_err(|| ErrorKind::ComponentFilePermissionsFailed)); + let meta = + try!(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 + }); + try!( + fs::set_permissions(dest_path, perm) + .chain_err(|| ErrorKind::ComponentFilePermissionsFailed) + ); } Ok(()) @@ -178,7 +208,10 @@ impl<'a> TarPackage<'a> { // unpacking. try!(unpack_without_first_dir(&mut archive, &*temp_dir)); - Ok(TarPackage(try!(DirectoryPackage::new(temp_dir.to_owned())), temp_dir)) + Ok(TarPackage( + try!(DirectoryPackage::new(temp_dir.to_owned())), + temp_dir, + )) } } @@ -198,12 +231,17 @@ 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() => { + try!(::std::fs::create_dir_all(&parent).chain_err(|| ErrorKind::ExtractingPackage)) + } _ => (), }; - try!(entry.unpack(&full_path).chain_err(|| ErrorKind::ExtractingPackage)); + try!( + entry + .unpack(&full_path) + .chain_err(|| ErrorKind::ExtractingPackage) + ); } Ok(()) @@ -213,12 +251,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 { @@ -245,12 +284,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 { @@ -277,12 +317,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 d1b3595cff5..b67abe8bb48 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(), @@ -76,7 +77,12 @@ 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 = try!(ChangedItem::copy_file( + &self.prefix, + component, + relpath, + src + )); self.change(item); Ok(()) } @@ -92,7 +98,12 @@ 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 = try!(ChangedItem::remove_file( + &self.prefix, + component, + relpath, + &self.temp_cfg + )); self.change(item); Ok(()) } @@ -101,7 +112,12 @@ 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 = try!(ChangedItem::remove_dir( + &self.prefix, + component, + relpath, + &self.temp_cfg + )); self.change(item); Ok(()) } @@ -110,9 +126,18 @@ 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) = try!(ChangedItem::add_file( + &self.prefix, + component, + relpath.clone() + )); self.change(item); - try!(utils::write_str("component", &mut file, &self.prefix.abs_path(&relpath), &content)); + try!(utils::write_str( + "component", + &mut file, + &self.prefix.abs_path(&relpath), + &content + )); Ok(()) } @@ -122,7 +147,11 @@ 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 = try!(ChangedItem::modify_file( + &self.prefix, + relpath, + &self.temp_cfg + )); self.change(item); Ok(()) } @@ -173,17 +202,19 @@ impl<'a> ChangedItem<'a> { 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), - &|_| ())) - } - RemovedFile(ref path, ref tmp) | ModifiedFile(ref path, Some(ref tmp)) => { - try!(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))) - } + AddedDir(ref path) => try!(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)) + ), + RemovedDir(ref path, ref tmp) => try!(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) { @@ -204,16 +235,19 @@ impl<'a> ChangedItem<'a> { if let Some(p) = abs_path.parent() { try!(utils::ensure_dir_exists("component", p, &|_| ())); } - let file = try!(File::create(&abs_path) - .chain_err(|| format!("error creating file '{}'", abs_path.display()))); + let file = try!( + 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 { @@ -228,7 +262,12 @@ impl<'a> ChangedItem<'a> { 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 { @@ -243,7 +282,12 @@ impl<'a> ChangedItem<'a> { 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()); if !utils::path_exists(&abs_path) { @@ -256,7 +300,12 @@ impl<'a> ChangedItem<'a> { 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()); if !utils::path_exists(&abs_path) { @@ -265,11 +314,19 @@ impl<'a> ChangedItem<'a> { path: relpath.clone(), }.into()) } else { - try!(utils::rename_dir("component", &abs_path, &backup.join("bk"))); + try!(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) { @@ -284,5 +341,3 @@ impl<'a> ChangedItem<'a> { } } } - - diff --git a/src/rustup-dist/src/config.rs b/src/rustup-dist/src/config.rs index 53908586e3a..fce56a4970c 100644 --- a/src/rustup-dist/src/config.rs +++ b/src/rustup-dist/src/config.rs @@ -21,8 +21,10 @@ impl Config { } let components = try!(get_array(&mut table, "components", path)); - let components = try!(Self::toml_to_components(components, - &format!("{}{}.", path, "components"))); + let components = try!(Self::toml_to_components( + components, + &format!("{}{}.", path, "components") + )); Ok(Config { config_version: version, @@ -31,8 +33,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)); diff --git a/src/rustup-dist/src/dist.rs b/src/rustup-dist/src/dist.rs index cfa0d13bd33..cec95890115 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,11 +417,12 @@ 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| { if line.starts_with(package) && line.ends_with(&suffix) { @@ -451,52 +474,57 @@ impl fmt::Display for ToolchainDesc { } } - // 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], - force_update: bool) - -> Result> { - +pub fn update_from_dist<'a>( + download: DownloadCfg<'a>, + update_hash: Option<&Path>, + toolchain: &ToolchainDesc, + prefix: &InstallPrefix, + add: &[Component], + remove: &[Component], + force_update: bool, +) -> Result> { let fresh_install = !prefix.path().exists(); - let res = update_from_dist_(download, - update_hash, - toolchain, - prefix, - add, - remove, - force_update); + let res = update_from_dist_( + download, + update_hash, + toolchain, + prefix, + add, + remove, + force_update, + ); // 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], - force_update: bool) - -> Result> { - +pub fn update_from_dist_<'a>( + download: DownloadCfg<'a>, + update_hash: Option<&Path>, + toolchain: &ToolchainDesc, + prefix: &InstallPrefix, + add: &[Component], + remove: &[Component], + force_update: bool, +) -> Result> { let toolchain_str = toolchain.to_string(); - let manifestation = try!(Manifestation::open(prefix.clone(), toolchain.target.clone())); + let manifestation = try!(Manifestation::open( + prefix.clone(), + toolchain.target.clone() + )); let changes = Changes { add_extensions: add.to_owned(), @@ -507,24 +535,27 @@ 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, - force_update, - &download, - download.notify_handler.clone())) { + (download.notify_handler)(Notification::DownloadedManifest( + &m.date, + m.get_rust_version().ok(), + )); + return match try!(manifestation.update( + &m, + changes, + force_update, + &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), } @@ -539,31 +570,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"); @@ -588,7 +626,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> { @@ -597,10 +634,10 @@ 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]); } @@ -608,7 +645,10 @@ fn dl_v1_manifest<'a>(download: DownloadCfg<'a>, toolchain: &ToolchainDesc) -> R let manifest_dl = try!(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 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 8e31568ddbd..0900b60928b 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,16 +31,17 @@ 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()))); + try!(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() { @@ -50,29 +49,30 @@ impl<'a> DownloadCfg<'a> { 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")); } } - - 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()))); + try!(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()); @@ -104,27 +104,28 @@ impl<'a> DownloadCfg<'a> { let hash_url = try!(utils::parse_url(&(url.to_owned() + ".sha256"))); let hash_file = try!(self.temp_cfg.new_file()); - try!(utils::download_file(&hash_url, - &hash_file, - None, - &|n| (self.notify_handler)(n.into()))); + try!(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(try!( + 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)>> { + /// 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)); 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 { @@ -143,20 +144,18 @@ impl<'a> DownloadCfg<'a> { let file = try!(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()))); + try!(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 +166,17 @@ 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 = + try!(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 b878b1ef8f4..f193c4288fa 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 c1f43f3972b..13fdda0fc86 100644 --- a/src/rustup-dist/src/lib.rs +++ b/src/rustup-dist/src/lib.rs @@ -1,26 +1,26 @@ #![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(not(windows))] +extern crate libc; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate winreg; -#[cfg(not(windows))] -extern crate libc; 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 5e149984cd9..29a8c587dd3 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)] @@ -89,8 +89,10 @@ impl Manifest { 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,7 +103,10 @@ 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)); @@ -121,7 +126,10 @@ 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)); @@ -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,14 @@ 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 = 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())) + ); } Ok(()) } @@ -166,12 +181,10 @@ impl Manifest { 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)); - } } + PackageTargets::Targeted(ref tpkgs) => for (_, tpkg) in tpkgs { + try!(self.validate_targeted_package(tpkg)); + }, } } @@ -209,12 +222,18 @@ impl Package { let mut target_table = try!(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(try!(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), + try!(TargetedPackage::from_toml(t, &path)), + ); } } Ok(PackageTargets::Targeted(result)) @@ -225,12 +244,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 +257,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,13 +272,13 @@ 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), } } } @@ -278,10 +296,14 @@ impl TargetedPackage { 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: try!(Self::toml_to_components( + components, + &format!("{}{}.", path, "components") + )), + extensions: try!(Self::toml_to_components( + extensions, + &format!("{}{}.", path, "extensions") + )), }) } else { Ok(TargetedPackage { @@ -344,20 +366,23 @@ 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| { - if s == "*" { - None - } else { - Some(TargetTriple::from_str(&s)) - } + target: try!(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 0765cf0af14..b1618d43d6d 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,23 +43,36 @@ impl Changes { fn check_invariants(&self, rust_target_package: &TargetedPackage, config: &Option) { for component_to_add in &self.add_extensions { - assert!(rust_target_package.extensions.contains(component_to_add), - "package must contain extension to add"); - assert!(!self.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!( + !self.remove_extensions.contains(component_to_add), + "can't both add and remove extensions" + ); } for component_to_remove in &self.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" + ); } } } #[derive(PartialEq, Debug)] -pub enum UpdateStatus { Changed, Unchanged } +pub enum UpdateStatus { + Changed, + Unchanged, +} impl Manifestation { /// Open the install prefix for updates from a distribution @@ -99,7 +112,6 @@ impl Manifestation { 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(); @@ -123,8 +135,8 @@ impl Manifestation { // Validate that the requested components are available match update.unavailable_components(new_manifest) { - Ok(_) => {}, - _ if force_update => {}, + Ok(_) => {} + _ if force_update => {} Err(e) => return Err(e), } @@ -134,10 +146,11 @@ 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 update.components_urls_and_hashes(new_manifest)? { - - 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 { @@ -146,9 +159,11 @@ impl Manifestation { let url_url = try!(utils::parse_url(&url)); - let dowloaded_file = try!(download_cfg.download(&url_url, &hash).chain_err(|| { - ErrorKind::ComponentDownloadFailed(component.clone()) - })); + let dowloaded_file = try!( + download_cfg + .download(&url_url, &hash) + .chain_err(|| ErrorKind::ComponentDownloadFailed(component.clone())) + ); things_downloaded.push(hash); things_to_install.push((component, format, dowloaded_file)); @@ -164,20 +179,22 @@ impl Manifestation { // Uninstall components for component in update.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())); } // 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; @@ -205,15 +222,17 @@ impl Manifestation { return Err(ErrorKind::CorruptComponent(component.pkg.clone()).into()); } - tx = try!(package.install(&self.installation, - name, Some(short_name), - tx)); + tx = try!(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)); + try!(utils::write_file( + "manifest", + installed_manifest_path, + new_manifest_str + )); // Write configuration. // @@ -244,7 +263,10 @@ 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 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)); @@ -256,8 +278,12 @@ impl Manifestation { 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 @@ -301,27 +327,39 @@ impl Manifestation { } /// 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()); + 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"); @@ -329,7 +367,7 @@ 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")); @@ -340,9 +378,11 @@ 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); @@ -356,9 +396,7 @@ impl Manifestation { let package = try!(TarGzPackage::new_file(&installer_file, temp_cfg)); for component in package.components() { - tx = try!(package.install(&self.installation, - &component, None, - tx)); + tx = try!(package.install(&self.installation, &component, None, tx)); } // End transaction @@ -371,13 +409,17 @@ 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> { + fn maybe_handle_v2_upgrade<'a>( + &self, + config: &Option, + mut tx: Transaction<'a>, + ) -> Result> { let installed_components = try!(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)); @@ -413,7 +455,10 @@ impl Update { changes.check_invariants(rust_target_package, &config); // 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()); let mut result = Update { components_to_uninstall: vec![], @@ -446,7 +491,9 @@ impl Update { if just_modifying_existing_install { for existing_component in &starting_list { if !result.final_component_list.contains(existing_component) { - result.components_to_uninstall.push(existing_component.clone()) + result + .components_to_uninstall + .push(existing_component.clone()) } } for component in &result.final_component_list { @@ -472,7 +519,7 @@ impl Update { starting_list: &[Component], rust_target_package: &TargetedPackage, new_manifest: &Manifest, - changes: &Changes + changes: &Changes, ) { // Add components required by the package, according to the // manifest @@ -494,16 +541,20 @@ impl Update { // old name and install a component with the new name if new_manifest.renames.contains_key(&existing_component.pkg) { let mut renamed_component = existing_component.clone(); - renamed_component.pkg = new_manifest.renames[&existing_component.pkg].to_owned(); - let is_already_included = self.final_component_list.contains(&renamed_component); + renamed_component.pkg = + new_manifest.renames[&existing_component.pkg].to_owned(); + let is_already_included = + self.final_component_list.contains(&renamed_component); if !is_already_included { self.final_component_list.push(renamed_component); } } else { - let is_already_included = self.final_component_list.contains(existing_component); + let is_already_included = + self.final_component_list.contains(existing_component); if !is_already_included { - let component_is_present = rust_target_package.extensions.contains(existing_component) - || rust_target_package.components.contains(existing_component); + let component_is_present = + rust_target_package.extensions.contains(existing_component) + || rust_target_package.components.contains(existing_component); if component_is_present { self.final_component_list.push(existing_component.clone()); @@ -523,30 +574,39 @@ impl Update { fn missing_essential_components(&self, target_triple: &TargetTriple) -> Result<()> { let missing_essential_components = ["rustc", "cargo"] .iter() - .filter_map(|pkg| if self.final_component_list.iter().any(|c| &c.pkg == pkg) { - None - } else { - Some(Component { - pkg: pkg.to_string(), - target: Some(target_triple.clone()), - }) + .filter_map(|pkg| { + if self.final_component_list.iter().any(|c| &c.pkg == pkg) { + None + } else { + Some(Component { + pkg: pkg.to_string(), + target: Some(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(), + ); } Ok(()) } fn unavailable_components(&self, new_manifest: &Manifest) -> Result<()> { - let mut unavailable_components: Vec = self.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 mut unavailable_components: Vec = self.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(); unavailable_components.extend_from_slice(&self.missing_components); @@ -558,20 +618,27 @@ impl Update { } /// Map components to urls and hashes - fn components_urls_and_hashes(&self, new_manifest: &Manifest) -> Result> { + fn components_urls_and_hashes( + &self, + new_manifest: &Manifest, + ) -> Result> { let mut components_urls_and_hashes = Vec::new(); for component in &self.components_to_install { let package = try!(new_manifest.get_package(&component.pkg)); let target_package = try!(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.clone(), Format::Xz, url, hash) - } else { - (component.clone(), 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.clone(), Format::Xz, url, hash) + } else { + ( + component.clone(), + Format::Gz, + bins.url.clone(), + bins.hash.clone(), + ) + }; components_urls_and_hashes.push(c_u_h); } diff --git a/src/rustup-dist/src/notifications.rs b/src/rustup-dist/src/notifications.rs index 4ad534dc29b..53470f1449b 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 8b8bd0dd6bf..b6a80d4f6ef 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 b69d5c7c21f..fbf2f4a6915 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,13 +140,10 @@ 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 { @@ -166,12 +158,12 @@ 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 { + try!( + 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, @@ -196,12 +188,12 @@ 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 { + try!( + 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 +206,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 +231,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 6933f94fe51..55a112f9ef5 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,40 +409,47 @@ 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 { update_from_dist_( dist_server, toolchain, @@ -405,19 +462,25 @@ fn update_from_dist(dist_server: &Url, ) } -fn update_from_dist_(dist_server: &Url, - toolchain: &ToolchainDesc, - prefix: &InstallPrefix, - add: &[Component], - remove: &[Component], - download_cfg: &DownloadCfg, - temp_cfg: &temp::Cfg, - force_update: bool) -> Result { - +fn update_from_dist_( + dist_server: &Url, + toolchain: &ToolchainDesc, + prefix: &InstallPrefix, + add: &[Component], + remove: &[Component], + download_cfg: &DownloadCfg, + temp_cfg: &temp::Cfg, + force_update: bool, +) -> 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, &|_| {})); + 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)); @@ -440,13 +503,20 @@ fn update_from_dist_(dist_server: &Url, } 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)); @@ -455,25 +525,33 @@ fn uninstall(toolchain: &ToolchainDesc, prefix: &InstallPrefix, temp_cfg: &temp: 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()); @@ -481,7 +559,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); @@ -489,7 +567,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"))); @@ -499,7 +581,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"))); @@ -509,7 +595,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(); @@ -520,7 +610,11 @@ 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"))); uninstall(toolchain, prefix, temp_cfg, &|_| ()).unwrap(); @@ -530,13 +624,23 @@ fn uninstall_removes_config_file() { #[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() + ); }); } @@ -545,7 +649,10 @@ fn force_update() { // On day 1 install the 'bonus' component, on day 2 its no longer 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(), @@ -553,48 +660,76 @@ fn force_update() { } }; - setup(Some(edit), false, &|url, toolchain, prefix, download_cfg, temp_cfg| { - change_channel_date(url, "nightly", "2016-02-01"); - // Update with bonus. - 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 without bonus, should fail. - let err = update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg).unwrap_err(); - match *err.kind() { - ErrorKind::RequestedComponentsUnavailable(..) => {}, - _ => panic!() - } - // Force update without bonus, should succeed, but bonus binary will be missing. - update_from_dist_(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg, true).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 with bonus. + 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 without bonus, should fail. + let err = update_from_dist(url, toolchain, prefix, &[], &[], download_cfg, temp_cfg) + .unwrap_err(); + match *err.kind() { + ErrorKind::RequestedComponentsUnavailable(..) => {} + _ => panic!(), + } + // Force update without bonus, should succeed, but bonus binary will be missing. + update_from_dist_( + url, + toolchain, + prefix, + &[], + &[], + download_cfg, + temp_cfg, + true, + ).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"))); }); } @@ -602,118 +737,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(); @@ -722,27 +908,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")), }, ]; @@ -753,10 +950,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")), }, ]; @@ -766,22 +968,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")), }, ]; @@ -795,10 +1000,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")), }, ]; @@ -808,43 +1018,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(); @@ -853,21 +1080,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(); @@ -876,7 +1112,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")), }, ]; @@ -892,44 +1129,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"); + 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"))); + 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")), }, ]; @@ -940,12 +1191,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")), }, ]; @@ -955,15 +1211,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")), }, ]; @@ -971,7 +1231,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")), }, ]; @@ -983,12 +1244,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")), }, ]; @@ -998,29 +1264,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")), }, ]; @@ -1028,79 +1313,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(); } @@ -1112,8 +1435,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)); @@ -1126,7 +1452,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(); @@ -1142,12 +1468,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()); @@ -1160,7 +1493,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 04571b511f7..306a863633f 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 0c2e4e469e3..1a91630398f 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 4fca7990e5a..a055755f26e 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 a7254b25350..2f6533eaa66 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()); @@ -334,7 +344,7 @@ pub fn run(config: &Config, name: &str, args: &[&str], env: &[(&str, &str)]) -> println!("status: {}", out.status); println!("----- stdout\n{}", output.stdout); println!("----- stderr\n{}", output.stderr); - return output + return output; } // Creates a mock dist server populated with some test data @@ -364,8 +374,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 { @@ -375,32 +386,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); @@ -415,11 +460,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); @@ -429,10 +481,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 { @@ -446,11 +500,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 { @@ -461,28 +522,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(); @@ -494,29 +557,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 { @@ -563,19 +626,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(), @@ -589,16 +655,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) @@ -610,28 +689,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(); @@ -643,72 +730,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(), } } @@ -781,8 +879,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 28788d67401..c119722efde 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 6cbab16417a..42d914203a2 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 winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; 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() } @@ -179,7 +192,8 @@ pub fn restore_path(p: &Option) { use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; 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 { @@ -200,8 +214,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 fd9d5b4fded..cd904664b2b 100644 --- a/src/rustup-utils/src/errors.rs +++ b/src/rustup-utils/src/errors.rs @@ -52,7 +52,8 @@ error_chain! { dest: PathBuf, } { description("could not copy file") - display("could not copy {} file from '{}' to '{}'", name, src.display(), dest.display()) + display("could not copy {} file from '{}' to '{}'", + name, src.display(), dest.display()) } RenamingFile { name: &'static str, @@ -60,7 +61,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, diff --git a/src/rustup-utils/src/lib.rs b/src/rustup-utils/src/lib.rs index 6a2c11393d5..feae1d009f6 100644 --- a/src/rustup-utils/src/lib.rs +++ b/src/rustup-utils/src/lib.rs @@ -1,14 +1,14 @@ #![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; @@ -26,5 +26,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 34589fa3fd5..b9f906355c1 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 ff6a7e6bf94..a21159639bd 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,11 +54,13 @@ 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 = try!( + fs::OpenOptions::new() + .write(true) + .truncate(true) + .create(true) + .open(path) + ); try!(io::Write::write_all(&mut file, contents.as_bytes())); @@ -65,9 +70,7 @@ pub fn write_file(path: &Path, contents: &str) -> io::Result<()> { } pub fn read_file(path: &Path) -> io::Result { - let mut file = try!(fs::OpenOptions::new() - .read(true) - .open(path)); + let mut file = try!(fs::OpenOptions::new().read(true).open(path)); let mut contents = String::new(); @@ -76,10 +79,11 @@ pub fn read_file(path: &Path) -> io::Result { Ok(contents) } -pub fn filter_file bool>(src: &Path, - dest: &Path, - mut filter: F) - -> io::Result { +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)); @@ -117,11 +121,13 @@ 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 = try!( + fs::OpenOptions::new() + .write(true) + .append(true) + .create(true) + .open(dest) + ); try!(writeln!(&mut dest_file, "{}", line)); @@ -131,9 +137,7 @@ pub fn append_file(dest: &Path, line: &str) -> io::Result<()> { } pub fn tee_file(path: &Path, w: &mut W) -> io::Result<()> { - let mut file = try!(fs::OpenOptions::new() - .read(true) - .open(path)); + let mut file = try!(fs::OpenOptions::new().read(true).open(path)); let buffer_size = 0x10000; let mut buffer = vec![0u8; buffer_size]; @@ -208,17 +212,18 @@ fn symlink_junction_inner(target: &Path, junction: &Path) -> io::Result<()> { let path = try!(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 db = data.as_mut_ptr() - as *mut REPARSE_MOUNTPOINT_DATA_BUFFER; + let db = data.as_mut_ptr() as *mut REPARSE_MOUNTPOINT_DATA_BUFFER; let buf = &mut (*db).ReparseTarget as *mut WCHAR; let mut i = 0; // FIXME: this conversion is very hacky @@ -233,17 +238,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()) @@ -344,11 +351,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> { @@ -360,7 +365,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) @@ -383,25 +394,28 @@ pub fn open_browser(path: &Path) -> io::Result { // FIXME: When winapi has this function, use their version extern "system" { - pub fn ShellExecuteW(hwnd: HWND, - lpOperation: LPCWSTR, - lpFile: LPCWSTR, - lpParameters: LPCWSTR, - lpDirectory: LPCWSTR, - nShowCmd: ctypes::c_int) - -> HINSTANCE; + pub fn ShellExecuteW( + hwnd: HWND, + lpOperation: LPCWSTR, + lpFile: LPCWSTR, + lpParameters: LPCWSTR, + lpDirectory: LPCWSTR, + nShowCmd: ctypes::c_int, + ) -> HINSTANCE; } const SW_SHOW: ctypes::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) } @@ -416,8 +430,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}; #[allow(non_upper_case_globals)] pub const FOLDERID_LocalAppData: GUID = GUID { @@ -459,8 +473,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 5da9e6fde2a..1ecc1741854 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 0b23d759b6d..c4af1d36bbf 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 96116faad0e..4a12ce756b1 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::shared::minwindef::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,13 @@ 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))); + try!(download_to_path_with_backend( + backend, + url, + path, + resume_from_partial, + Some(callback) + )); notify_handler(Notification::DownloadFinished); @@ -249,16 +240,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 +257,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 +267,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 +281,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 +299,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 +351,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 +378,11 @@ 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 { + let metadata = try!( + 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); @@ -446,21 +422,28 @@ pub fn home_dir() -> Option { use winapi::um::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)] @@ -471,8 +454,9 @@ 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 winapi::um::errhandlingapi::{GetLastError, SetLastError}; use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER; @@ -513,7 +497,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])); } } } @@ -534,22 +518,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 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()) } @@ -557,7 +539,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() } @@ -594,8 +575,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(()) @@ -604,8 +584,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(()) @@ -614,8 +593,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(()) @@ -623,7 +601,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 @@ -680,11 +660,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()?; @@ -702,9 +683,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(()) } @@ -713,8 +698,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) @@ -741,15 +726,15 @@ 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 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 { @@ -790,15 +775,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 { @@ -831,7 +818,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 eb1bafcf1a0..1af2175fe62 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 1177cc2cb88..5264c5b8013 100644 --- a/src/rustup-win-installer/src/lib.rs +++ b/src/rustup-win-installer/src/lib.rs @@ -1,14 +1,14 @@ #![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::shared::ntdef::{HRESULT, PCSTR, LPCWSTR, LPWSTR}; -use winapi::shared::minwindef::{UINT, LPVOID}; +use winapi::shared::ntdef::{HRESULT, LPCWSTR, LPWSTR, PCSTR}; +use winapi::shared::minwindef::{LPVOID, UINT}; pub type MSIHANDLE = u32; @@ -17,8 +17,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 @@ -88,7 +96,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() } @@ -97,7 +107,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" { @@ -109,4 +122,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 d8a1f460cbf..90fcac9c6a7 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,11 +12,12 @@ use notifications::*; use rustup_utils; use telemetry::{Telemetry, TelemetryEvent}; - -pub fn run_command_for_dir>(cmd: Command, - arg0: &str, - args: &[S], - cfg: &Cfg) -> Result<()> { +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()) { return telemetry_rustc(cmd, arg0, args, cfg); } @@ -24,9 +25,12 @@ pub fn run_command_for_dir>(cmd: Command, 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 1bd9f4265e7..bdaa8a1e343 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 { @@ -54,8 +54,9 @@ impl Cfg { // Set up the rustup home directory let rustup_dir = try!(utils::rustup_home()); - try!(utils::ensure_dir_exists("home", &rustup_dir, - &|n| notify_handler(n.into()))); + try!(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 @@ -66,22 +67,20 @@ impl Cfg { 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(try!(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 +94,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 { @@ -128,9 +127,11 @@ impl Cfg { 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()))); + try!(utils::ensure_dir_exists( + "toolchains", + &self.toolchains_dir, + &|n| (self.notify_handler)(n.into()) + )); } Toolchain::from(self, name) @@ -144,16 +145,17 @@ impl Cfg { 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()))); + try!(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)) { Ok(Some(toolchain.binary_file(binary))) } else { @@ -162,17 +164,17 @@ impl Cfg { } pub fn upgrade_data(&self) -> Result<()> { - let current_version = try!(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" => { @@ -182,8 +184,9 @@ impl Cfg { let dirs = try!(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()))); + try!(utils::remove_dir("toolchain", &dir.path(), &|n| { + (self.notify_handler)(n.into()) + })); } // Also delete the update hashes @@ -204,8 +207,9 @@ 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(try!(utils::remove_dir("home", &self.rustup_dir, &|n| { + (self.notify_handler)(n.into()) + }))) } else { Ok(()) } @@ -215,8 +219,10 @@ impl Cfg { let opt_name = try!(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 = try!( + self.verify_toolchain(&name) + .chain_err(|| ErrorKind::ToolchainNotInstalled(name.to_string())) + ); Ok(Some(toolchain)) } else { @@ -248,15 +254,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 +272,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(false)); 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 +312,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,30 +331,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)) = try!(self.find_override(path)) { + Some((toolchain, Some(reason))) + } else { + try!(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(); + .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); @@ -352,7 +365,10 @@ impl Cfg { } } - pub fn update_all_channels(&self, force_update: bool) -> Result)>> { + pub fn update_all_channels( + &self, + force_update: bool, + ) -> Result)>> { let toolchains = try!(self.list_toolchains()); // Convert the toolchain strings to Toolchain values @@ -360,9 +376,8 @@ impl Cfg { 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)| { @@ -408,8 +423,12 @@ impl Cfg { } } - pub fn create_command_for_toolchain(&self, toolchain: &str, install_if_missing: bool, - binary: &str) -> Result { + 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)); if install_if_missing && !toolchain.exists() { try!(toolchain.install_from_dist(false)); @@ -424,7 +443,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); } @@ -463,7 +486,7 @@ impl Cfg { 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()); @@ -473,7 +496,9 @@ 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))) + Ok(s.default_host_triple + .as_ref() + .map(|s| dist::TargetTriple::from_str(&s))) })).unwrap_or_else(dist::TargetTriple::from_build)) } @@ -487,7 +512,11 @@ 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<()> { @@ -496,8 +525,7 @@ impl Cfg { 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")); diff --git a/src/rustup/env_var.rs b/src/rustup/env_var.rs index ff00ef7deac..9c3bc039404 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 9d6270e505d..f3ba7c004e6 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; @@ -17,7 +17,12 @@ pub enum InstallMethod<'a> { Link(&'a Path), Installer(&'a Path, &'a temp::Cfg), // bool is whether to force an update - Dist(&'a dist::ToolchainDesc, Option<&'a Path>, DownloadCfg<'a>, bool), + Dist( + &'a dist::ToolchainDesc, + Option<&'a Path>, + DownloadCfg<'a>, + bool, + ), } impl<'a> InstallMethod<'a> { @@ -25,8 +30,7 @@ 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)); } @@ -39,7 +43,9 @@ impl<'a> InstallMethod<'a> { Ok(true) } InstallMethod::Link(src) => { - try!(utils::symlink_dir(src, &path, &|n| notify_handler(n.into()))); + try!(utils::symlink_dir(src, &path, &|n| notify_handler( + n.into() + ))); Ok(true) } InstallMethod::Installer(src, temp_cfg) => { @@ -48,16 +54,15 @@ impl<'a> InstallMethod<'a> { } InstallMethod::Dist(toolchain, update_hash, dl_cfg, force_update) => { let prefix = &InstallPrefix::from(path.to_owned()); - let maybe_new_hash = - try!(dist::update_from_dist( - dl_cfg, - update_hash, - toolchain, - prefix, - &[], - &[], - force_update, - )); + let maybe_new_hash = try!(dist::update_from_dist( + dl_cfg, + update_hash, + toolchain, + prefix, + &[], + &[], + force_update, + )); if let Some(hash) = maybe_new_hash { if let Some(hash_file) = update_hash { @@ -72,8 +77,12 @@ 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()); @@ -93,6 +102,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(try!(utils::remove_dir("install", path, &|n| { + notify_handler(n.into()) + }))) } diff --git a/src/rustup/lib.rs b/src/rustup/lib.rs index a6d5c6d94d4..0e70055394f 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 2b06ccfc1f4..5a9f152f23b 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 5a6b4b5d431..744a31315bd 100644 --- a/src/rustup/settings.rs +++ b/src/rustup/settings.rs @@ -11,18 +11,17 @@ 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<()> { @@ -59,9 +58,7 @@ impl SettingsFile { try!(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())) - }; + let result = { try!(f(self.cache.borrow_mut().as_mut().unwrap())) }; try!(self.write_settings()); Ok(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, } }) } @@ -84,11 +81,15 @@ impl SettingsFile { // Legacy upgrade try!(self.with_mut(|s| { s.version = try!(utils::read_file("version", &legacy_version_file)) - .trim().to_owned(); + .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( + try!(utils::read_file("default", &default_file)) + .trim() + .to_owned(), + ); } if utils::is_file(&override_db) { let overrides = try!(utils::read_file("overrides", &override_db)); @@ -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); @@ -189,14 +196,13 @@ impl Settings { 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,7 +221,10 @@ 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)); diff --git a/src/rustup/telemetry.rs b/src/rustup/telemetry.rs index 9a5c040a8e4..c3502a708dc 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,18 +47,27 @@ 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. @@ -55,9 +75,7 @@ impl Telemetry { try!(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(()) } @@ -89,7 +107,9 @@ impl Telemetry { for i in 0..dl { let i = i as usize; - try!(fs::remove_file(&telemetry_files[i]).chain_err(|| ErrorKind::TelemetryCleanupError)); + try!( + 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 343053835fc..0a46ce40d6f 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,11 @@ 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 = try!( + self.telemetry_dir + .read_dir() + .chain_err(|| ErrorKind::TelemetryAnalysisError) + ); let mut telemetry_files: Vec = Vec::new(); @@ -177,11 +183,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 +203,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 +213,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 +245,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 +267,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 898b645461e..0cd5f553bf4 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; @@ -54,9 +54,7 @@ impl<'a> Toolchain<'a> { 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 { @@ -70,7 +68,9 @@ impl<'a> Toolchain<'a> { } 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 @@ -96,8 +96,7 @@ impl<'a> Toolchain<'a> { if let Some(update_hash) = try!(self.update_hash()) { try!(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)); } @@ -111,10 +110,9 @@ 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 = + try!(install_method.run(&self.path, &|n| (self.cfg.notify_handler)(n.into()))); if !updated { (self.cfg.notify_handler)(Notification::UpdateHashMatches); @@ -143,9 +141,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(), } } @@ -175,10 +173,12 @@ impl<'a> Toolchain<'a> { pub fn install_from_dist_inner(&self, force_update: bool) -> 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(), - force_update)) + self.install(InstallMethod::Dist( + &try!(self.desc()), + update_hash.as_ref().map(|p| &**p), + self.download_cfg(), + force_update, + )) } pub fn install_from_dist_with_telemetry(&self, force_update: bool) -> Result { @@ -186,8 +186,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) => { @@ -197,8 +199,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)); }); @@ -209,21 +213,29 @@ 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(), - false)) + self.install_if_not_installed(InstallMethod::Dist( + &try!(self.desc()), + update_hash.as_ref().map(|p| &**p), + self.download_cfg(), + false, + )) } 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(()) } @@ -240,12 +252,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 @@ -255,14 +267,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))); + 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 + ))); } else { // If installer is a filename @@ -270,7 +283,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))); + try!(self.install(InstallMethod::Installer( + &local_installer, + &self.cfg.temp_cfg + ))); } } @@ -320,13 +336,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) }; @@ -337,8 +355,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"); @@ -365,15 +386,21 @@ 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")); + try!( + 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")); + try!( + 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")); + try!( + fs::hard_link(&src_file, &fallback_file) + .chain_err(|| "unable to hard link fallback exe") + ); fallback_file } else { src_file @@ -464,8 +491,10 @@ 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 = try!( + 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())); @@ -476,20 +505,29 @@ impl<'a> Toolchain<'a> { // 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 { @@ -501,14 +539,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 { @@ -539,8 +582,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(()), @@ -549,10 +594,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)); @@ -572,42 +619,56 @@ 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 = try!( + 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()) { - // 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, - false, - &self.download_cfg(), - self.download_cfg().notify_handler.clone())); + try!(manifestation.update( + &manifest, + changes, + false, + &self.download_cfg(), + self.download_cfg().notify_handler.clone() + )); Ok(()) } else { @@ -621,43 +682,57 @@ 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 = try!( + 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()) { - // 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(); 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, - false, - &self.download_cfg(), - self.download_cfg().notify_handler.clone())); + try!(manifestation.update( + &manifest, + changes, + false, + &self.download_cfg(), + self.download_cfg().notify_handler.clone() + )); Ok(()) } else { diff --git a/tests/cli-exact.rs b/tests/cli-exact.rs index 3cb5441a2ba..a833d12577a 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 a2379fe5b89..4f3498789c4 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! -")); +" + )); }); } @@ -99,13 +104,15 @@ fn blank_lines_around_stderr_log_output_update() { println!("-- stdout --\n {}", out.stdout); println!("-- stderr --\n {}", out.stderr); - assert!(out.stdout.contains(r" + assert!(out.stdout.contains( + r" 3) Cancel installation Rust is installed now. Great! -")); +" + )); }); } @@ -123,7 +130,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()); @@ -144,7 +154,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"); @@ -154,8 +168,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"); @@ -166,8 +183,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"); @@ -177,8 +193,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) { @@ -190,8 +205,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"); @@ -201,8 +219,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 9abd6217568..06c76f6270e 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 58d18fa7609..e4ecfef4c01 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", + ); }); } @@ -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 bfd1ab04ebe..2158597f362 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)); @@ -953,20 +1003,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] @@ -977,20 +1028,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()); @@ -1005,7 +1059,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 @@ -1014,14 +1069,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"); }); @@ -1035,13 +1092,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(); @@ -1050,7 +1108,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); }); @@ -1066,13 +1125,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(); @@ -1081,7 +1141,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); }); @@ -1089,13 +1150,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() { @@ -1104,8 +1163,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", + ); }); } @@ -1116,8 +1178,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", + ); }); } @@ -1157,7 +1222,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() + ); }); } @@ -1169,7 +1239,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()); @@ -1193,7 +1267,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"]); @@ -1223,9 +1302,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"]); }); @@ -1242,7 +1327,6 @@ fn rls_proxy_set_up_after_update() { }); } - #[test] fn update_does_not_overwrite_rustfmt() { update_setup(&|config, self_dist| { @@ -1261,8 +1345,11 @@ fn update_does_not_overwrite_rustfmt() { // Ok, now a self-update should complain about `rustfmt` not looking // like rustup and the user should take some action. - 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); @@ -1273,7 +1360,10 @@ fn update_does_not_overwrite_rustfmt() { // current process. fs::remove_file(rustfmt_path).unwrap(); let installed_rustup = config.cargodir.join("bin/rustup"); - expect_ok(config, &[installed_rustup.to_str().unwrap(), "self", "update"]); + expect_ok( + config, + &[installed_rustup.to_str().unwrap(), "self", "update"], + ); assert!(rustfmt_path.exists()); assert!(utils::file_size(rustfmt_path).unwrap() > 0); }); diff --git a/tests/cli-v1.rs b/tests/cli-v1.rs index 98a0699ef0a..490f57e42e1 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 faebc2781a1..9184d8b3d10 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 + ), + ); }); }