diff options
author | Alex Crichton <alex@alexcrichton.com> | 2019-06-26 07:58:22 -0700 |
---|---|---|
committer | Alex Crichton <alex@alexcrichton.com> | 2019-06-26 07:58:22 -0700 |
commit | c38b3418a0d2e5ca5a4c6eee11e99c5739b79d00 (patch) | |
tree | ccb2b59fd780236a1c0e4553292933b97e4e38b9 | |
parent | 5afc0089f282570f2c39b4345d2706bf97e3d84b (diff) | |
download | rust-installer-c38b3418a0d2e5ca5a4c6eee11e99c5739b79d00.tar.gz |
Run `cargo fmt`
-rw-r--r-- | src/combiner.rs | 41 | ||||
-rw-r--r-- | src/generator.rs | 40 | ||||
-rw-r--r-- | src/lib.rs | 4 | ||||
-rw-r--r-- | src/main.rs | 6 | ||||
-rw-r--r-- | src/remove_dir_all.rs | 326 | ||||
-rw-r--r-- | src/scripter.rs | 13 | ||||
-rw-r--r-- | src/tarballer.rs | 29 | ||||
-rw-r--r-- | src/util.rs | 29 |
8 files changed, 310 insertions, 178 deletions
diff --git a/src/combiner.rs b/src/combiner.rs index 2d22992..e48d6ac 100644 --- a/src/combiner.rs +++ b/src/combiner.rs @@ -4,12 +4,12 @@ use std::path::Path; use flate2::read::GzDecoder; use tar::Archive; -use crate::errors::*; -use crate::util::*; use super::Scripter; use super::Tarballer; +use crate::errors::*; +use crate::util::*; -actor!{ +actor! { #[derive(Debug)] pub struct Combiner { /// The name of the product, for display. @@ -54,12 +54,20 @@ impl Combiner { // Merge each installer into the work directory of the new installer. let components = create_new_file(package_dir.join("components"))?; - for input_tarball in self.input_tarballs.split(',').map(str::trim).filter(|s| !s.is_empty()) { + for input_tarball in self + .input_tarballs + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + { // Extract the input tarballs let tar = GzDecoder::new(open_file(&input_tarball)?); - Archive::new(tar).unpack(&self.work_dir) - .chain_err(|| format!("unable to extract '{}' into '{}'", - &input_tarball, self.work_dir))?; + Archive::new(tar).unpack(&self.work_dir).chain_err(|| { + format!( + "unable to extract '{}' into '{}'", + &input_tarball, self.work_dir + ) + })?; let pkg_name = input_tarball.trim_end_matches(".tar.gz"); let pkg_name = Path::new(pkg_name).file_name().unwrap(); @@ -77,7 +85,10 @@ impl Combiner { // Copy components to the new combined installer. let mut pkg_components = String::new(); open_file(pkg_dir.join("components")) - .and_then(|mut file| file.read_to_string(&mut pkg_components).map_err(Error::from)) + .and_then(|mut file| { + file.read_to_string(&mut pkg_components) + .map_err(Error::from) + }) .chain_err(|| format!("failed to read components in '{}'", input_tarball))?; for component in pkg_components.split_whitespace() { // All we need to do is copy the component directory. We could @@ -96,8 +107,12 @@ impl Combiner { // Write the installer version. let version = package_dir.join("rust-installer-version"); - writeln!(create_new_file(version)?, "{}", crate::RUST_INSTALLER_VERSION) - .chain_err(|| "failed to write new installer version")?; + writeln!( + create_new_file(version)?, + "{}", + crate::RUST_INSTALLER_VERSION + ) + .chain_err(|| "failed to write new installer version")?; // Copy the overlay. if !self.non_installed_overlay.is_empty() { @@ -107,7 +122,8 @@ impl Combiner { // Generate the install script. let output_script = package_dir.join("install.sh"); let mut scripter = Scripter::default(); - scripter.product_name(self.product_name) + scripter + .product_name(self.product_name) .rel_manifest_dir(self.rel_manifest_dir) .success_message(self.success_message) .legacy_manifest_dirs(self.legacy_manifest_dirs) @@ -118,7 +134,8 @@ impl Combiner { create_dir_all(&self.output_dir)?; let output = Path::new(&self.output_dir).join(&self.package_name); let mut tarballer = Tarballer::default(); - tarballer.work_dir(self.work_dir) + tarballer + .work_dir(self.work_dir) .input(self.package_name) .output(path_to_str(&output)?); tarballer.run()?; diff --git a/src/generator.rs b/src/generator.rs index 60e54f2..62fe8b6 100644 --- a/src/generator.rs +++ b/src/generator.rs @@ -1,12 +1,12 @@ use std::io::Write; use std::path::Path; -use crate::errors::*; use super::Scripter; use super::Tarballer; +use crate::errors::*; use crate::util::*; -actor!{ +actor! { #[derive(Debug)] pub struct Generator { /// The name of the product, for display @@ -66,8 +66,12 @@ impl Generator { // Write the installer version (only used by combine-installers.sh) let version = package_dir.join("rust-installer-version"); - writeln!(create_new_file(version)?, "{}", crate::RUST_INSTALLER_VERSION) - .chain_err(|| "failed to write new installer version")?; + writeln!( + create_new_file(version)?, + "{}", + crate::RUST_INSTALLER_VERSION + ) + .chain_err(|| "failed to write new installer version")?; // Copy the overlay if !self.non_installed_overlay.is_empty() { @@ -77,7 +81,8 @@ impl Generator { // Generate the install script let output_script = package_dir.join("install.sh"); let mut scripter = Scripter::default(); - scripter.product_name(self.product_name) + scripter + .product_name(self.product_name) .rel_manifest_dir(self.rel_manifest_dir) .success_message(self.success_message) .legacy_manifest_dirs(self.legacy_manifest_dirs) @@ -88,7 +93,8 @@ impl Generator { create_dir_all(&self.output_dir)?; let output = Path::new(&self.output_dir).join(&self.package_name); let mut tarballer = Tarballer::default(); - tarballer.work_dir(self.work_dir) + tarballer + .work_dir(self.work_dir) .input(self.package_name) .output(path_to_str(&output)?); tarballer.run()?; @@ -100,20 +106,32 @@ impl Generator { /// Copies the `src` directory recursively to `dst`, writing `manifest.in` too. fn copy_and_manifest(src: &Path, dst: &Path, bulk_dirs: &str) -> Result<()> { let manifest = create_new_file(dst.join("manifest.in"))?; - let bulk_dirs: Vec<_> = bulk_dirs.split(',') + let bulk_dirs: Vec<_> = bulk_dirs + .split(',') .filter(|s| !s.is_empty()) - .map(Path::new).collect(); + .map(Path::new) + .collect(); copy_with_callback(src, dst, |path, file_type| { // We need paths to be compatible with both Unix and Windows. - if path.components().filter_map(|c| c.as_os_str().to_str()).any(|s| s.contains('\\')) { - bail!("rust-installer doesn't support '\\' in path components: {:?}", path); + if path + .components() + .filter_map(|c| c.as_os_str().to_str()) + .any(|s| s.contains('\\')) + { + bail!( + "rust-installer doesn't support '\\' in path components: {:?}", + path + ); } // Normalize to Unix-style path separators. let normalized_string; let mut string = path.to_str().ok_or_else(|| { - format!("rust-installer doesn't support non-Unicode paths: {:?}", path) + format!( + "rust-installer doesn't support non-Unicode paths: {:?}", + path + ) })?; if string.contains('\\') { normalized_string = string.replace('\\', "/"); @@ -8,7 +8,7 @@ extern crate winapi; extern crate lazy_static; mod errors { - error_chain!{ + error_chain! { foreign_links { Io(::std::io::Error); StripPrefix(::std::path::StripPrefixError); @@ -28,8 +28,8 @@ mod generator; mod scripter; mod tarballer; -pub use crate::errors::{Result, Error, ErrorKind}; pub use crate::combiner::Combiner; +pub use crate::errors::{Error, ErrorKind, Result}; pub use crate::generator::Generator; pub use crate::scripter::Scripter; pub use crate::tarballer::Tarballer; diff --git a/src/main.rs b/src/main.rs index bc6025c..49ea6ba 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,7 @@ use crate::errors::*; use clap::{App, ArgMatches}; mod errors { - error_chain!{ + error_chain! { links { Installer(::installer::Error, ::installer::ErrorKind); } @@ -84,7 +84,9 @@ fn script(matches: &ArgMatches<'_>) -> Result<()> { "output-script" => output_script, }); - scripter.run().chain_err(|| "failed to generate installation script") + scripter + .run() + .chain_err(|| "failed to generate installation script") } fn tarball(matches: &ArgMatches<'_>) -> Result<()> { diff --git a/src/remove_dir_all.rs b/src/remove_dir_all.rs index 70c16a2..1109765 100644 --- a/src/remove_dir_all.rs +++ b/src/remove_dir_all.rs @@ -1,7 +1,7 @@ #![allow(non_snake_case)] -use std::path::Path; use std::io; +use std::path::Path; #[cfg(not(windows))] pub fn remove_dir_all(path: &Path) -> io::Result<()> { @@ -15,35 +15,43 @@ pub fn remove_dir_all(path: &Path) -> io::Result<()> { #[cfg(windows)] mod win { - use winapi::ctypes::{c_ushort, c_uint}; + use winapi::ctypes::{c_uint, c_ushort}; use winapi::shared::minwindef::{BOOL, DWORD, FALSE, FILETIME, LPVOID}; - use winapi::shared::winerror::{ERROR_CALL_NOT_IMPLEMENTED, ERROR_INSUFFICIENT_BUFFER, ERROR_NO_MORE_FILES}; + use winapi::shared::winerror::{ + ERROR_CALL_NOT_IMPLEMENTED, ERROR_INSUFFICIENT_BUFFER, ERROR_NO_MORE_FILES, + }; use winapi::um::errhandlingapi::{GetLastError, SetLastError}; + use winapi::um::fileapi::{ + CreateFileW, FindFirstFileW, FindNextFileW, GetFileInformationByHandle, + }; use winapi::um::fileapi::{BY_HANDLE_FILE_INFORMATION, CREATE_ALWAYS, CREATE_NEW}; use winapi::um::fileapi::{FILE_BASIC_INFO, FILE_RENAME_INFO, TRUNCATE_EXISTING}; use winapi::um::fileapi::{OPEN_ALWAYS, OPEN_EXISTING}; - use winapi::um::fileapi::{CreateFileW, GetFileInformationByHandle, FindFirstFileW, FindNextFileW}; use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE}; use winapi::um::ioapiset::DeviceIoControl; - use winapi::um::libloaderapi::{GetProcAddress, GetModuleHandleW}; - use winapi::um::minwinbase::{FileBasicInfo, FileRenameInfo, FILE_INFO_BY_HANDLE_CLASS, WIN32_FIND_DATAW}; - use winapi::um::winbase::{FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_DELETE_ON_CLOSE, FILE_FLAG_OPEN_REPARSE_POINT}; + use winapi::um::libloaderapi::{GetModuleHandleW, GetProcAddress}; + use winapi::um::minwinbase::{ + FileBasicInfo, FileRenameInfo, FILE_INFO_BY_HANDLE_CLASS, WIN32_FIND_DATAW, + }; use winapi::um::winbase::SECURITY_SQOS_PRESENT; + use winapi::um::winbase::{ + FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_DELETE_ON_CLOSE, FILE_FLAG_OPEN_REPARSE_POINT, + }; use winapi::um::winioctl::FSCTL_GET_REPARSE_POINT; - use winapi::um::winnt::{FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_READONLY}; + use winapi::um::winnt::{DELETE, FILE_ATTRIBUTE_DIRECTORY, HANDLE, LPCWSTR}; + use winapi::um::winnt::{FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_REPARSE_POINT}; + use winapi::um::winnt::{FILE_GENERIC_WRITE, FILE_WRITE_DATA, GENERIC_READ, GENERIC_WRITE}; + use winapi::um::winnt::{FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES}; use winapi::um::winnt::{FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE}; - use winapi::um::winnt::{FILE_WRITE_ATTRIBUTES, FILE_READ_ATTRIBUTES}; - use winapi::um::winnt::{FILE_WRITE_DATA, FILE_GENERIC_WRITE, GENERIC_READ, GENERIC_WRITE}; - use winapi::um::winnt::{LARGE_INTEGER, IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK}; - use winapi::um::winnt::{LPCWSTR, DELETE, FILE_ATTRIBUTE_DIRECTORY, HANDLE}; + use winapi::um::winnt::{IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK, LARGE_INTEGER}; - use std::ptr; - use std::sync::Arc; - use std::path::{PathBuf, Path}; - use std::mem; - use std::io; use std::ffi::{OsStr, OsString}; + use std::io; + use std::mem; use std::os::windows::ffi::{OsStrExt, OsStringExt}; + use std::path::{Path, PathBuf}; + use std::ptr; + use std::sync::Arc; pub fn remove_dir_all(path: &Path) -> io::Result<()> { // On Windows it is not enough to just recursively remove the contents of a @@ -91,8 +99,7 @@ mod win { let (path, metadata) = { let mut opts = OpenOptions::new(); opts.access_mode(FILE_READ_ATTRIBUTES); - opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | - FILE_FLAG_OPEN_REPARSE_POINT); + opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT); let file = File::open(path, &opts)?; (get_path(&file)?, file.file_attr()?) }; @@ -100,8 +107,12 @@ mod win { let mut ctx = RmdirContext { base_dir: match path.parent() { Some(dir) => dir, - None => return Err(io::Error::new(io::ErrorKind::PermissionDenied, - "can't delete root directory")) + None => { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "can't delete root directory", + )) + } }, readonly: metadata.perm().readonly(), counter: 0, @@ -113,11 +124,13 @@ mod win { } else if filetype.is_symlink_dir() { remove_item(path.as_ref(), &mut ctx) } else { - Err(io::Error::new(io::ErrorKind::PermissionDenied, "Not a directory")) + Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Not a directory", + )) } } - fn readdir(p: &Path) -> io::Result<ReadDir> { let root = p.to_path_buf(); let star = p.join("*"); @@ -144,8 +157,7 @@ mod win { counter: u64, } - fn remove_dir_all_recursive(path: &Path, ctx: &mut RmdirContext) - -> io::Result<()> { + fn remove_dir_all_recursive(path: &Path, ctx: &mut RmdirContext) -> io::Result<()> { let dir_readonly = ctx.readonly; for child in readdir(path)? { let child = child?; @@ -165,9 +177,11 @@ mod win { if !ctx.readonly { let mut opts = OpenOptions::new(); opts.access_mode(DELETE); - opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | // delete directory + opts.custom_flags( + FILE_FLAG_BACKUP_SEMANTICS | // delete directory FILE_FLAG_OPEN_REPARSE_POINT | // delete symlink - FILE_FLAG_DELETE_ON_CLOSE); + FILE_FLAG_DELETE_ON_CLOSE, + ); let file = File::open(path, &opts)?; move_item(&file, ctx) } else { @@ -177,9 +191,11 @@ mod win { // only the access mode is different. let mut opts = OpenOptions::new(); opts.access_mode(DELETE | FILE_WRITE_ATTRIBUTES); - opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | - FILE_FLAG_OPEN_REPARSE_POINT | - FILE_FLAG_DELETE_ON_CLOSE); + opts.custom_flags( + FILE_FLAG_BACKUP_SEMANTICS + | FILE_FLAG_OPEN_REPARSE_POINT + | FILE_FLAG_DELETE_ON_CLOSE, + ); let file = File::open(path, &opts)?; move_item(&file, ctx)?; // restore read-only flag just in case there are other hard links @@ -271,8 +287,10 @@ mod win { fn inner(s: &OsStr) -> io::Result<Vec<u16>> { let mut maybe_result: Vec<u16> = 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) @@ -284,13 +302,14 @@ mod win { match v.iter().position(|c| *c == 0) { // don't include the 0 Some(i) => &v[..i], - None => v + None => v, } } fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> io::Result<T> - where F1: FnMut(*mut u16, DWORD) -> DWORD, - F2: FnOnce(&[u16]) -> T + where + F1: FnMut(*mut u16, DWORD) -> DWORD, + F2: FnOnce(&[u16]) -> T, { // Start off with a stack buf but then spill over to the heap if we end up // needing more space. @@ -328,19 +347,27 @@ mod win { } else if k >= n { n = k; } else { - return Ok(f2(&buf[..k])) + return Ok(f2(&buf[..k])); } } } } #[derive(Clone, PartialEq, Eq, Debug, Default)] - struct FilePermissions { readonly: bool } + struct FilePermissions { + readonly: bool, + } impl FilePermissions { - fn new() -> FilePermissions { Default::default() } - fn readonly(&self) -> bool { self.readonly } - fn set_readonly(&mut self, readonly: bool) { self.readonly = readonly } + fn new() -> FilePermissions { + Default::default() + } + fn readonly(&self) -> bool { + self.readonly + } + fn set_readonly(&mut self, readonly: bool) { + self.readonly = readonly + } } #[derive(Clone)] @@ -380,21 +407,26 @@ mod win { security_attributes: 0, } } - fn custom_flags(&mut self, flags: u32) { self.custom_flags = flags; } - fn access_mode(&mut self, access_mode: u32) { self.access_mode = Some(access_mode); } + fn custom_flags(&mut self, flags: u32) { + self.custom_flags = flags; + } + fn access_mode(&mut self, access_mode: u32) { + self.access_mode = Some(access_mode); + } fn get_access_mode(&self) -> io::Result<DWORD> { const ERROR_INVALID_PARAMETER: i32 = 87; match (self.read, self.write, self.append, self.access_mode) { (_, _, _, Some(mode)) => Ok(mode), - (true, false, false, None) => Ok(GENERIC_READ), - (false, true, false, None) => Ok(GENERIC_WRITE), - (true, true, false, None) => Ok(GENERIC_READ | GENERIC_WRITE), - (false, _, true, None) => Ok(FILE_GENERIC_WRITE & !FILE_WRITE_DATA), - (true, _, true, None) => Ok(GENERIC_READ | - (FILE_GENERIC_WRITE & !FILE_WRITE_DATA)), - (false, false, false, None) => Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER)), + (true, false, false, None) => Ok(GENERIC_READ), + (false, true, false, None) => Ok(GENERIC_WRITE), + (true, true, false, None) => Ok(GENERIC_READ | GENERIC_WRITE), + (false, _, true, None) => Ok(FILE_GENERIC_WRITE & !FILE_WRITE_DATA), + (true, _, true, None) => Ok(GENERIC_READ | (FILE_GENERIC_WRITE & !FILE_WRITE_DATA)), + (false, false, false, None) => { + Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER)) + } } } @@ -403,60 +435,75 @@ mod win { match (self.write, self.append) { (true, false) => {} - (false, false) => + (false, false) => { if self.truncate || self.create || self.create_new { return Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER)); - }, - (_, true) => + } + } + (_, true) => { if self.truncate && !self.create_new { return Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER)); - }, + } + } } Ok(match (self.create, self.truncate, self.create_new) { (false, false, false) => OPEN_EXISTING, - (true, false, false) => OPEN_ALWAYS, - (false, true, false) => TRUNCATE_EXISTING, - (true, true, false) => CREATE_ALWAYS, - (_, _, true) => CREATE_NEW, + (true, false, false) => OPEN_ALWAYS, + (false, true, false) => TRUNCATE_EXISTING, + (true, true, false) => CREATE_ALWAYS, + (_, _, true) => CREATE_NEW, }) } fn get_flags_and_attributes(&self) -> DWORD { - self.custom_flags | - self.attributes | - self.security_qos_flags | - if self.security_qos_flags != 0 { SECURITY_SQOS_PRESENT } else { 0 } | - if self.create_new { FILE_FLAG_OPEN_REPARSE_POINT } else { 0 } + self.custom_flags + | self.attributes + | self.security_qos_flags + | if self.security_qos_flags != 0 { + SECURITY_SQOS_PRESENT + } else { + 0 + } + | if self.create_new { + FILE_FLAG_OPEN_REPARSE_POINT + } else { + 0 + } } } - struct File { handle: Handle } + struct File { + handle: Handle, + } impl File { fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> { let path = to_u16s(path)?; let handle = unsafe { - CreateFileW(path.as_ptr(), - opts.get_access_mode()?, - opts.share_mode, - opts.security_attributes as *mut _, - opts.get_creation_mode()?, - opts.get_flags_and_attributes(), - ptr::null_mut()) + CreateFileW( + path.as_ptr(), + opts.get_access_mode()?, + opts.share_mode, + opts.security_attributes as *mut _, + opts.get_creation_mode()?, + opts.get_flags_and_attributes(), + ptr::null_mut(), + ) }; if handle == INVALID_HANDLE_VALUE { Err(io::Error::last_os_error()) } else { - Ok(File { handle: Handle::new(handle) }) + Ok(File { + handle: Handle::new(handle), + }) } } fn file_attr(&self) -> io::Result<FileAttr> { unsafe { let mut info: BY_HANDLE_FILE_INFORMATION = mem::zeroed(); - cvt(GetFileInformationByHandle(self.handle.raw(), - &mut info))?; + cvt(GetFileInformationByHandle(self.handle.raw(), &mut info))?; let mut attr = FileAttr { attributes: info.dwFileAttributes, creation_time: info.ftCreationTime, @@ -476,23 +523,23 @@ mod win { } fn set_attributes(&self, attr: DWORD) -> io::Result<()> { - let zero: LARGE_INTEGER = unsafe { - mem::zeroed() - }; + let zero: LARGE_INTEGER = unsafe { mem::zeroed() }; let mut info = FILE_BASIC_INFO { - CreationTime: zero, // do not change + CreationTime: zero, // do not change LastAccessTime: zero, // do not change - LastWriteTime: zero, // do not change - ChangeTime: zero, // do not change + LastWriteTime: zero, // do not change + ChangeTime: zero, // do not change FileAttributes: attr, }; let size = mem::size_of_val(&info); cvt(unsafe { - SetFileInformationByHandle(self.handle.raw(), - FileBasicInfo, - &mut info as *mut _ as *mut _, - size as DWORD) + SetFileInformationByHandle( + self.handle.raw(), + FileBasicInfo, + &mut info as *mut _ as *mut _, + size as DWORD, + ) })?; Ok(()) } @@ -506,7 +553,8 @@ mod win { const STRUCT_SIZE: usize = 20; // FIXME: check for internal NULs in 'new' - let mut data: Vec<u16> = iter::repeat(0u16).take(STRUCT_SIZE/2) + let mut data: Vec<u16> = iter::repeat(0u16) + .take(STRUCT_SIZE / 2) .chain(new.as_os_str().encode_wide()) .collect(); data.push(0); @@ -521,10 +569,12 @@ mod win { (*info).ReplaceIfExists = if replace { -1 } else { FALSE }; (*info).RootDirectory = ptr::null_mut(); (*info).FileNameLength = (size - STRUCT_SIZE) as DWORD; - cvt(SetFileInformationByHandle(self.handle().raw(), - FileRenameInfo, - data.as_mut_ptr() as *mut _ as *mut _, - size as DWORD))?; + cvt(SetFileInformationByHandle( + self.handle().raw(), + FileRenameInfo, + data.as_mut_ptr() as *mut _ as *mut _, + size as DWORD, + ))?; Ok(()) } } @@ -539,39 +589,50 @@ mod win { } } - fn handle(&self) -> &Handle { &self.handle } + fn handle(&self) -> &Handle { + &self.handle + } - fn reparse_point<'a>(&self, - space: &'a mut [u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE]) - -> io::Result<(DWORD, &'a REPARSE_DATA_BUFFER)> { + fn reparse_point<'a>( + &self, + space: &'a mut [u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE], + ) -> io::Result<(DWORD, &'a REPARSE_DATA_BUFFER)> { unsafe { let mut bytes = 0; cvt({ - DeviceIoControl(self.handle.raw(), - FSCTL_GET_REPARSE_POINT, - ptr::null_mut(), - 0, - space.as_mut_ptr() as *mut _, - space.len() as DWORD, - &mut bytes, - ptr::null_mut()) + DeviceIoControl( + self.handle.raw(), + FSCTL_GET_REPARSE_POINT, + ptr::null_mut(), + 0, + space.as_mut_ptr() as *mut _, + space.len() as DWORD, + &mut bytes, + ptr::null_mut(), + ) })?; Ok((bytes, &*(space.as_ptr() as *const REPARSE_DATA_BUFFER))) } } } - #[derive(Copy, Clone, PartialEq, Eq, Hash)] enum FileType { - Dir, File, SymlinkFile, SymlinkDir, ReparsePoint, MountPoint, + Dir, + File, + SymlinkFile, + SymlinkDir, + ReparsePoint, + MountPoint, } impl FileType { fn new(attrs: DWORD, reparse_tag: DWORD) -> FileType { - match (attrs & FILE_ATTRIBUTE_DIRECTORY != 0, - attrs & FILE_ATTRIBUTE_REPARSE_POINT != 0, - reparse_tag) { + match ( + attrs & FILE_ATTRIBUTE_DIRECTORY != 0, + attrs & FILE_ATTRIBUTE_REPARSE_POINT != 0, + reparse_tag, + ) { (false, false, _) => FileType::File, (true, false, _) => FileType::Dir, (false, true, IO_REPARSE_TAG_SYMLINK) => FileType::SymlinkFile, @@ -584,7 +645,9 @@ mod win { } } - fn is_dir(&self) -> bool { *self == FileType::Dir } + fn is_dir(&self) -> bool { + *self == FileType::Dir + } fn is_symlink_dir(&self) -> bool { *self == FileType::SymlinkDir || *self == FileType::MountPoint } @@ -613,8 +676,10 @@ mod win { } fn file_type(&self) -> io::Result<FileType> { - Ok(FileType::new(self.data.dwFileAttributes, - /* reparse_tag = */ self.data.dwReserved0)) + Ok(FileType::new( + self.data.dwFileAttributes, + /* reparse_tag = */ self.data.dwReserved0, + )) } fn metadata(&self) -> io::Result<FileAttr> { @@ -623,7 +688,8 @@ mod win { creation_time: self.data.ftCreationTime, last_access_time: self.data.ftLastAccessTime, last_write_time: self.data.ftLastWriteTime, - file_size: ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64), + file_size: ((self.data.nFileSizeHigh as u64) << 32) + | (self.data.nFileSizeLow as u64), reparse_tag: if self.data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 { // reserved unless this is a reparse point self.data.dwReserved0 @@ -634,8 +700,6 @@ mod win { } } - - struct DirEntry { root: Arc<PathBuf>, data: WIN32_FIND_DATAW, @@ -660,20 +724,19 @@ mod win { loop { if FindNextFileW(self.handle.0, &mut wfd) == 0 { if GetLastError() == ERROR_NO_MORE_FILES { - return None + return None; } else { - return Some(Err(io::Error::last_os_error())) + return Some(Err(io::Error::last_os_error())); } } if let Some(e) = DirEntry::new(&self.root, &wfd) { - return Some(Ok(e)) + return Some(Ok(e)); } } } } } - #[derive(Clone)] struct FileAttr { attributes: DWORD, @@ -687,7 +750,7 @@ mod win { impl FileAttr { fn perm(&self) -> FilePermissions { FilePermissions { - readonly: self.attributes & FILE_ATTRIBUTE_READONLY != 0 + readonly: self.attributes & FILE_ATTRIBUTE_READONLY != 0, } } @@ -710,7 +773,6 @@ mod win { const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024; - /// An owned container for `HANDLE` object, closing them on Drop. /// /// All methods are inherited through a `Deref` impl to `RawHandle` @@ -737,12 +799,16 @@ mod win { impl Deref for Handle { type Target = RawHandle; - fn deref(&self) -> &RawHandle { &self.0 } + fn deref(&self) -> &RawHandle { + &self.0 + } } impl Drop for Handle { fn drop(&mut self) { - unsafe { let _ = CloseHandle(self.raw()); } + unsafe { + let _ = CloseHandle(self.raw()); + } } } @@ -751,27 +817,31 @@ mod win { RawHandle(handle) } - fn raw(&self) -> HANDLE { self.0 } + fn raw(&self) -> HANDLE { + self.0 + } } struct FindNextFileHandle(HANDLE); fn get_path(f: &File) -> io::Result<PathBuf> { - fill_utf16_buf(|buf, sz| unsafe { - GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, - VOLUME_NAME_DOS) - }, |buf| { - PathBuf::from(OsString::from_wide(buf)) - }) + fill_utf16_buf( + |buf, sz| unsafe { + GetFinalPathNameByHandleW(f.handle.raw(), buf, sz, VOLUME_NAME_DOS) + }, + |buf| PathBuf::from(OsString::from_wide(buf)), + ) } fn move_item(file: &File, ctx: &mut RmdirContext) -> io::Result<()> { - let mut tmpname = ctx.base_dir.join(format!{"rm-{}", ctx.counter}); + let mut tmpname = ctx.base_dir.join(format! {"rm-{}", ctx.counter}); ctx.counter += 1; // Try to rename the file. If it already exists, just retry with an other // filename. while let Err(err) = file.rename(tmpname.as_ref(), false) { - if err.kind() != io::ErrorKind::AlreadyExists { return Err(err) }; + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(err); + }; tmpname = ctx.base_dir.join(format!("rm-{}", ctx.counter)); ctx.counter += 1; } diff --git a/src/scripter.rs b/src/scripter.rs index fae464c..1f83985 100644 --- a/src/scripter.rs +++ b/src/scripter.rs @@ -5,8 +5,7 @@ use crate::util::*; const TEMPLATE: &'static str = include_str!("../install-template.sh"); - -actor!{ +actor! { #[derive(Debug)] pub struct Scripter { /// The name of the product, for display @@ -41,8 +40,14 @@ impl Scripter { .replace("%%TEMPLATE_PRODUCT_NAME%%", &sh_quote(&product_name)) .replace("%%TEMPLATE_REL_MANIFEST_DIR%%", &self.rel_manifest_dir) .replace("%%TEMPLATE_SUCCESS_MESSAGE%%", &sh_quote(&success_message)) - .replace("%%TEMPLATE_LEGACY_MANIFEST_DIRS%%", &sh_quote(&self.legacy_manifest_dirs)) - .replace("%%TEMPLATE_RUST_INSTALLER_VERSION%%", &sh_quote(&crate::RUST_INSTALLER_VERSION)); + .replace( + "%%TEMPLATE_LEGACY_MANIFEST_DIRS%%", + &sh_quote(&self.legacy_manifest_dirs), + ) + .replace( + "%%TEMPLATE_RUST_INSTALLER_VERSION%%", + &sh_quote(&crate::RUST_INSTALLER_VERSION), + ); create_new_executable(&self.output_script)? .write_all(script.as_ref()) diff --git a/src/tarballer.rs b/src/tarballer.rs index 9dfaa1c..f8b6520 100644 --- a/src/tarballer.rs +++ b/src/tarballer.rs @@ -1,5 +1,5 @@ use std::fs::{read_link, symlink_metadata}; -use std::io::{self, empty, Write, BufWriter}; +use std::io::{self, empty, BufWriter, Write}; use std::path::Path; use flate2; @@ -12,7 +12,7 @@ use xz2::write::XzEncoder; use crate::errors::*; use crate::util::*; -actor!{ +actor! { #[derive(Debug)] pub struct Tarballer { /// The input folder to be compressed. @@ -58,11 +58,15 @@ impl Tarballer { let buf = BufWriter::with_capacity(1024 * 1024, tee); let mut builder = Builder::new(buf); - let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap(); + let pool = rayon::ThreadPoolBuilder::new() + .num_threads(2) + .build() + .unwrap(); pool.install(move || { for path in dirs { let src = Path::new(&self.work_dir).join(&path); - builder.append_dir(&path, &src) + builder + .append_dir(&path, &src) .chain_err(|| format!("failed to tar dir '{}'", src.display()))?; } for path in files { @@ -70,9 +74,12 @@ impl Tarballer { append_path(&mut builder, &src, &path) .chain_err(|| format!("failed to tar file '{}'", src.display()))?; } - let RayonTee(xz, gz) = builder.into_inner() + let RayonTee(xz, gz) = builder + .into_inner() .chain_err(|| "failed to finish writing .tar stream")? - .into_inner().ok().unwrap(); + .into_inner() + .ok() + .unwrap(); // Finish both encoded files. let (rxz, rgz) = rayon::join( @@ -112,13 +119,19 @@ fn append_path<W: Write>(builder: &mut Builder<W>, src: &Path, path: &String) -> /// Returns all `(directories, files)` under the source path. fn get_recursive_paths<P, Q>(root: P, name: Q) -> Result<(Vec<String>, Vec<String>)> - where P: AsRef<Path>, Q: AsRef<Path> +where + P: AsRef<Path>, + Q: AsRef<Path>, { let root = root.as_ref(); let name = name.as_ref(); if !name.is_relative() && !name.starts_with(root) { - bail!("input '{}' is not in work dir '{}'", name.display(), root.display()); + bail!( + "input '{}' is not in work dir '{}'", + name.display(), + root.display() + ); } let mut dirs = vec![]; diff --git a/src/util.rs b/src/util.rs index f499b89..ec9d43a 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,4 +1,3 @@ - use std::fs; use std::path::Path; use walkdir::WalkDir; @@ -29,9 +28,13 @@ pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<u64> { symlink_file(link, &to)?; Ok(0) } else { - fs::copy(&from, &to) - .chain_err(|| format!("failed to copy '{}' to '{}'", - from.as_ref().display(), to.as_ref().display())) + fs::copy(&from, &to).chain_err(|| { + format!( + "failed to copy '{}' to '{}'", + from.as_ref().display(), + to.as_ref().display() + ) + }) } } @@ -51,21 +54,25 @@ pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> { pub fn create_new_executable<P: AsRef<Path>>(path: P) -> Result<fs::File> { let mut options = fs::OpenOptions::new(); options.write(true).create_new(true); - #[cfg(unix)] options.mode(0o755); - options.open(&path) + #[cfg(unix)] + options.mode(0o755); + options + .open(&path) .chain_err(|| format!("failed to create file '{}'", path.as_ref().display())) } /// Wraps `fs::OpenOptions::create_new().open()`, with a nicer error message. pub fn create_new_file<P: AsRef<Path>>(path: P) -> Result<fs::File> { - fs::OpenOptions::new().write(true).create_new(true).open(&path) + fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) .chain_err(|| format!("failed to create file '{}'", path.as_ref().display())) } /// Wraps `fs::File::open()` with a nicer error message. pub fn open_file<P: AsRef<Path>>(path: P) -> Result<fs::File> { - fs::File::open(&path) - .chain_err(|| format!("failed to open file '{}'", path.as_ref().display())) + fs::File::open(&path).chain_err(|| format!("failed to open file '{}'", path.as_ref().display())) } /// Wraps `remove_dir_all` with a nicer error message. @@ -89,7 +96,8 @@ pub fn copy_recursive(src: &Path, dst: &Path) -> Result<()> { /// Copies the `src` directory recursively to `dst`. Both are assumed to exist /// when this function is called. Invokes a callback for each path visited. pub fn copy_with_callback<F>(src: &Path, dst: &Path, mut callback: F) -> Result<()> - where F: FnMut(&Path, fs::FileType) -> Result<()> +where + F: FnMut(&Path, fs::FileType) -> Result<()>, { for entry in WalkDir::new(src).min_depth(1) { let entry = entry?; @@ -107,7 +115,6 @@ pub fn copy_with_callback<F>(src: &Path, dst: &Path, mut callback: F) -> Result< Ok(()) } - /// Creates an "actor" with default values and setters for all fields. macro_rules! actor { ($( #[ $attr:meta ] )+ pub struct $name:ident { |