CLean up source (as per Clippy)

This commit is contained in:
James 2018-08-04 18:35:00 +10:00
parent 2673e5b475
commit 390440c8b0
20 changed files with 114 additions and 137 deletions

11
Cargo.lock generated
View File

@ -112,6 +112,15 @@ dependencies = [
"build_const 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "build_const 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]]
name = "dirs"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"libc 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "dtoa" name = "dtoa"
version = "0.4.2" version = "0.4.2"
@ -311,6 +320,7 @@ name = "liftinstall"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"chrono 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "chrono 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
"dirs 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
"fern 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", "fern 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
"futures 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", "futures 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)",
"hyper 0.11.27 (registry+https://github.com/rust-lang/crates.io-index)", "hyper 0.11.27 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1110,6 +1120,7 @@ dependencies = [
"checksum core-foundation 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "25bfd746d203017f7d5cbd31ee5d8e17f94b6521c7af77ece6c9e4b2d4b16c67" "checksum core-foundation 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "25bfd746d203017f7d5cbd31ee5d8e17f94b6521c7af77ece6c9e4b2d4b16c67"
"checksum core-foundation-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "065a5d7ffdcbc8fa145d6f0746f3555025b9097a9e9cda59f7467abae670c78d" "checksum core-foundation-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "065a5d7ffdcbc8fa145d6f0746f3555025b9097a9e9cda59f7467abae670c78d"
"checksum crc 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bd5d02c0aac6bd68393ed69e00bbc2457f3e89075c6349db7189618dc4ddc1d7" "checksum crc 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bd5d02c0aac6bd68393ed69e00bbc2457f3e89075c6349db7189618dc4ddc1d7"
"checksum dirs 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "37a76dd8b997af7107d0bb69d43903cf37153a18266f8b3fdb9911f28efb5444"
"checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab" "checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab"
"checksum encoding_rs 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "98fd0f24d1fb71a4a6b9330c8ca04cbd4e7cc5d846b54ca74ff376bc7c9f798d" "checksum encoding_rs 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "98fd0f24d1fb71a4a6b9330c8ca04cbd4e7cc5d846b54ca74ff376bc7c9f798d"
"checksum fern 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "57915fe00a83af935983eb2d00b0ecc62419c4741b28c207ecbf98fd4a1b94c8" "checksum fern 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)" = "57915fe00a83af935983eb2d00b0ecc62419c4741b28c207ecbf98fd4a1b94c8"

View File

@ -31,6 +31,7 @@ toml = "0.4"
semver = {version = "0.9.0", features = ["serde"]} semver = {version = "0.9.0", features = ["serde"]}
regex = "0.2" regex = "0.2"
dirs = "1.0"
zip = "0.2.8" zip = "0.2.8"
log = "0.4" log = "0.4"

View File

@ -19,7 +19,7 @@ macro_rules! include_files_as_assets {
/// ///
/// file_path: String path, beginning with a / /// file_path: String path, beginning with a /
pub fn file_from_string(file_path: &str) -> Option<(String, &'static [u8])> { pub fn file_from_string(file_path: &str) -> Option<(String, &'static [u8])> {
let guessed_mime = match file_path.rfind(".") { let guessed_mime = match file_path.rfind('.') {
Some(ext_ptr) => { Some(ext_ptr) => {
let ext = &file_path[ext_ptr + 1..]; let ext = &file_path[ext_ptr + 1..];

View File

@ -9,11 +9,11 @@ use reqwest;
use std::io::Read; use std::io::Read;
/// Streams a file from a HTTP server. /// Streams a file from a HTTP server.
pub fn stream_file<F>(url: String, mut callback: F) -> Result<(), String> pub fn stream_file<F>(url: &str, mut callback: F) -> Result<(), String>
where where
F: FnMut(Vec<u8>, u64) -> (), F: FnMut(Vec<u8>, u64) -> (),
{ {
let mut client = match reqwest::get(&url) { let mut client = match reqwest::get(url) {
Ok(v) => v, Ok(v) => v,
Err(v) => return Err(format!("Failed to GET resource: {:?}", v)), Err(v) => return Err(format!("Failed to GET resource: {:?}", v)),
}; };

View File

@ -6,7 +6,6 @@ use serde_json;
use std::fs::File; use std::fs::File;
use std::env::home_dir;
use std::env::var; use std::env::var;
use std::path::Path; use std::path::Path;
@ -24,6 +23,8 @@ use tasks::DependencyTree;
use logging::LoggingErrors; use logging::LoggingErrors;
use dirs::home_dir;
/// A message thrown during the installation of packages. /// A message thrown during the installation of packages.
#[derive(Serialize)] #[derive(Serialize)]
pub enum InstallMessage { pub enum InstallMessage {
@ -121,11 +122,10 @@ impl InstallerFramework {
info!("Dependency tree:\n{}", tree); info!("Dependency tree:\n{}", tree);
tree.execute(self, &|msg: &str, progress: f32| match messages tree.execute(self, &|msg: &str, progress: f64| {
.send(InstallMessage::Status(msg.to_string(), progress as _)) if let Err(v) = messages.send(InstallMessage::Status(msg.to_string(), progress as _)) {
{ error!("Failed to submit queue message: {:?}", v);
Err(v) => error!("Failed to submit queue message: {:?}", v), }
_ => {}
}).map(|_x| ()) }).map(|_x| ())
} }
@ -141,11 +141,10 @@ impl InstallerFramework {
info!("Dependency tree:\n{}", tree); info!("Dependency tree:\n{}", tree);
tree.execute(self, &|msg: &str, progress: f32| match messages tree.execute(self, &|msg: &str, progress: f64| {
.send(InstallMessage::Status(msg.to_string(), progress as _)) if let Err(v) = messages.send(InstallMessage::Status(msg.to_string(), progress as _)) {
{ error!("Failed to submit queue message: {:?}", v);
Err(v) => error!("Failed to submit queue message: {:?}", v), }
_ => {}
}).map(|_x| ()) }).map(|_x| ())
} }
@ -154,7 +153,7 @@ impl InstallerFramework {
// We have to have a install path for us to be able to do anything // We have to have a install path for us to be able to do anything
let path = match self.install_path.clone() { let path = match self.install_path.clone() {
Some(v) => v, Some(v) => v,
None => return Err(format!("No install directory for installer")), None => return Err("No install directory for installer".to_string()),
}; };
let metadata_path = path.join("metadata.json"); let metadata_path = path.join("metadata.json");

View File

@ -17,8 +17,7 @@ pub fn setup_logger() -> Result<(), fern::InitError> {
record.level(), record.level(),
message message
)) ))
}) }).level(log::LevelFilter::Info)
.level(log::LevelFilter::Info)
.chain(io::stdout()) .chain(io::stdout())
.chain(fern::log_file("installer.log")?) .chain(fern::log_file("installer.log")?)
.apply()?; .apply()?;
@ -32,13 +31,11 @@ where
Self: Sized, Self: Sized,
{ {
/// Unwraps this object. See `unwrap()`. /// Unwraps this object. See `unwrap()`.
#[inline]
fn log_unwrap(self) -> T { fn log_unwrap(self) -> T {
self.log_expect("Failed to unwrap") self.log_expect("Failed to unwrap")
} }
/// Unwraps this object, with a specified error message on failure. See `expect()`. /// Unwraps this object, with a specified error message on failure. See `expect()`.
#[inline]
fn log_expect(self, msg: &str) -> T; fn log_expect(self, msg: &str) -> T;
} }

View File

@ -5,6 +5,7 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![deny(unsafe_code)] #![deny(unsafe_code)]
#![deny(missing_docs)]
#[cfg(windows)] #[cfg(windows)]
extern crate nfd; extern crate nfd;
@ -27,6 +28,7 @@ extern crate toml;
extern crate regex; extern crate regex;
extern crate semver; extern crate semver;
extern crate dirs;
extern crate zip; extern crate zip;
extern crate fern; extern crate fern;
@ -117,7 +119,7 @@ fn main() {
for mut address in addresses { for mut address in addresses {
address.set_port(target_port); address.set_port(target_port);
let server = WebServer::with_addr(framework.clone(), address.clone()) let server = WebServer::with_addr(framework.clone(), address)
.log_expect("Failed to bind to address"); .log_expect("Failed to bind to address");
debug!("Server: {:?}", address); debug!("Server: {:?}", address);
@ -163,7 +165,7 @@ fn main() {
let result = let result =
wv.dialog(Dialog::ChooseDirectory, "Select a install directory...", ""); wv.dialog(Dialog::ChooseDirectory, "Select a install directory...", "");
if result.len() > 0 { if !result.is_empty() {
let result = serde_json::to_string(&result) let result = serde_json::to_string(&result)
.log_expect("Unable to serialize response"); .log_expect("Unable to serialize response");
let command = format!("{}({});", callback_name, result); let command = format!("{}({});", callback_name, result);

View File

@ -54,8 +54,7 @@ impl WebServer {
Ok(WebService { Ok(WebService {
framework: framework.clone(), framework: framework.clone(),
}) })
}) }).log_expect("Failed to bind to port");
.log_expect("Failed to bind to port");
server.run().log_expect("Failed to run HTTP server"); server.run().log_expect("Failed to run HTTP server");
}); });
@ -172,25 +171,16 @@ impl Service for WebService {
.write() .write()
.log_expect("InstallerFramework has been dirtied"); .log_expect("InstallerFramework has been dirtied");
match framework.uninstall(&sender) { if let Err(v) = framework.uninstall(&sender) {
Err(v) => {
error!("Uninstall error occurred: {:?}", v); error!("Uninstall error occurred: {:?}", v);
match sender.send(InstallMessage::Error(v)) { if let Err(v) = sender.send(InstallMessage::Error(v)) {
Err(v) => {
error!("Failed to send uninstall error: {:?}", v); error!("Failed to send uninstall error: {:?}", v);
}
_ => {}
}; };
} }
_ => {}
}
match sender.send(InstallMessage::EOF) { if let Err(v) = sender.send(InstallMessage::EOF) {
Err(v) => {
error!("Failed to send EOF to client: {:?}", v); error!("Failed to send EOF to client: {:?}", v);
} }
_ => {}
};
}); });
// Spawn a thread for transforming messages to chunk messages // Spawn a thread for transforming messages to chunk messages
@ -201,9 +191,8 @@ impl Service for WebService {
.recv() .recv()
.log_expect("Failed to recieve message from runner thread"); .log_expect("Failed to recieve message from runner thread");
match &response { if let InstallMessage::EOF = response {
&InstallMessage::EOF => break, break;
_ => {}
} }
let mut response = serde_json::to_string(&response) let mut response = serde_json::to_string(&response)
@ -236,7 +225,7 @@ impl Service for WebService {
let mut path: Option<String> = None; let mut path: Option<String> = None;
// Transform results into just an array of stuff to install // Transform results into just an array of stuff to install
for (key, value) in results.iter() { for (key, value) in &results {
if key == "path" { if key == "path" {
path = Some(value.to_owned()); path = Some(value.to_owned());
continue; continue;
@ -266,25 +255,16 @@ impl Service for WebService {
framework.set_install_dir(&path); framework.set_install_dir(&path);
} }
match framework.install(to_install, &sender, new_install) { if let Err(v) = framework.install(to_install, &sender, new_install) {
Err(v) => {
error!("Uninstall error occurred: {:?}", v); error!("Uninstall error occurred: {:?}", v);
match sender.send(InstallMessage::Error(v)) { if let Err(v) = sender.send(InstallMessage::Error(v)) {
Err(v) => {
error!("Failed to send uninstall error: {:?}", v); error!("Failed to send uninstall error: {:?}", v);
} }
_ => {}
};
}
_ => {}
} }
match sender.send(InstallMessage::EOF) { if let Err(v) = sender.send(InstallMessage::EOF) {
Err(v) => {
error!("Failed to send EOF to client: {:?}", v); error!("Failed to send EOF to client: {:?}", v);
} }
_ => {}
};
}); });
// Spawn a thread for transforming messages to chunk messages // Spawn a thread for transforming messages to chunk messages
@ -295,9 +275,8 @@ impl Service for WebService {
.recv() .recv()
.log_expect("Failed to recieve message from runner thread"); .log_expect("Failed to recieve message from runner thread");
match &response { if let InstallMessage::EOF = response {
&InstallMessage::EOF => break, break;
_ => {}
} }
let mut response = serde_json::to_string(&response) let mut response = serde_json::to_string(&response)
@ -322,7 +301,7 @@ impl Service for WebService {
// At this point, we have a web browser client. Search for a index page // At this point, we have a web browser client. Search for a index page
// if needed // if needed
let mut path: String = req.path().to_owned(); let mut path: String = req.path().to_owned();
if path.ends_with("/") { if path.ends_with('/') {
path += "index.html"; path += "index.html";
} }

View File

@ -40,8 +40,7 @@ impl ReleaseSource for GithubReleases {
.get(&format!( .get(&format!(
"https://api.github.com/repos/{}/releases", "https://api.github.com/repos/{}/releases",
config.repo config.repo
)) )).header(UserAgent::new("liftinstall (j-selby)"))
.header(UserAgent::new("liftinstall (j-selby)"))
.send() .send()
.map_err(|x| format!("Error while sending HTTP request: {:?}", x))?; .map_err(|x| format!("Error while sending HTTP request: {:?}", x))?;
@ -53,43 +52,39 @@ impl ReleaseSource for GithubReleases {
.text() .text()
.map_err(|x| format!("Failed to decode HTTP response body: {:?}", x))?; .map_err(|x| format!("Failed to decode HTTP response body: {:?}", x))?;
let result: serde_json::Value = let result: serde_json::Value = serde_json::from_str(&body)
serde_json::from_str(&body).map_err(|x| format!("Failed to parse response: {:?}", x))?; .map_err(|x| format!("Failed to parse response: {:?}", x))?;
let result: &Vec<serde_json::Value> = result let result: &Vec<serde_json::Value> = result
.as_array() .as_array()
.ok_or(format!("Response was not an array!"))?; .ok_or_else(|| "Response was not an array!".to_string())?;
// Parse JSON from server // Parse JSON from server
for entry in result.into_iter() { for entry in result.iter() {
let mut files = Vec::new(); let mut files = Vec::new();
let id: u64 = match entry["id"].as_u64() { let id: u64 = match entry["id"].as_u64() {
Some(v) => v, Some(v) => v,
None => return Err(format!("JSON payload missing information about ID")), None => return Err("JSON payload missing information about ID".to_string()),
}; };
let assets = match entry["assets"].as_array() { let assets = match entry["assets"].as_array() {
Some(v) => v, Some(v) => v,
None => return Err(format!("JSON payload not an array")), None => return Err("JSON payload not an array".to_string()),
}; };
for asset in assets.into_iter() { for asset in assets.iter() {
let string = match asset["name"].as_str() { let string = match asset["name"].as_str() {
Some(v) => v, Some(v) => v,
None => { None => {
return Err(format!( return Err("JSON payload missing information about release name".to_string())
"JSON payload missing information about release name"
))
} }
}; };
let url = match asset["browser_download_url"].as_str() { let url = match asset["browser_download_url"].as_str() {
Some(v) => v, Some(v) => v,
None => { None => {
return Err(format!( return Err("JSON payload missing information about release URL".to_string())
"JSON payload missing information about release URL"
))
} }
}; };

View File

@ -21,9 +21,9 @@ impl Version {
/// Coarses versions into semver versions. This will use a integer version as the major /// Coarses versions into semver versions. This will use a integer version as the major
/// field if required. /// field if required.
fn coarse_into_semver(&self) -> SemverVersion { fn coarse_into_semver(&self) -> SemverVersion {
match self { match *self {
&Version::Semver(ref version) => version.to_owned(), Version::Semver(ref version) => version.to_owned(),
&Version::Integer(ref version) => { Version::Integer(ref version) => {
SemverVersion::from((version.to_owned(), 0 as u64, 0 as u64)) SemverVersion::from((version.to_owned(), 0 as u64, 0 as u64))
} }
} }
@ -42,13 +42,13 @@ impl Version {
impl PartialOrd for Version { impl PartialOrd for Version {
fn partial_cmp(&self, other: &Version) -> Option<Ordering> { fn partial_cmp(&self, other: &Version) -> Option<Ordering> {
match self { match *self {
&Version::Semver(ref version) => match other { Version::Semver(ref version) => match *other {
&Version::Semver(ref other_version) => Some(version.cmp(other_version)), Version::Semver(ref other_version) => Some(version.cmp(other_version)),
_ => None, _ => None,
}, },
&Version::Integer(ref num) => match other { Version::Integer(ref num) => match *other {
&Version::Integer(ref other_num) => Some(num.cmp(other_num)), Version::Integer(ref other_num) => Some(num.cmp(other_num)),
_ => None, _ => None,
}, },
} }

View File

@ -22,14 +22,14 @@ impl Task for DownloadPackageTask {
&mut self, &mut self,
mut input: Vec<TaskParamType>, mut input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
assert_eq!(input.len(), 1); assert_eq!(input.len(), 1);
let file = input.pop().log_expect("Should have input from resolver!"); let file = input.pop().log_expect("Should have input from resolver!");
let (version, file) = match file { let (version, file) = match file {
TaskParamType::File(v, f) => (v, f), TaskParamType::File(v, f) => (v, f),
_ => return Err(format!("Unexpected param type to download package")), _ => return Err("Unexpected param type to download package".to_string()),
}; };
// Check to see if this is the newest file available already // Check to see if this is the newest file available already
@ -48,7 +48,7 @@ impl Task for DownloadPackageTask {
let mut downloaded = 0; let mut downloaded = 0;
let mut data_storage: Vec<u8> = Vec::new(); let mut data_storage: Vec<u8> = Vec::new();
stream_file(file.url, |data, size| { stream_file(&file.url, |data, size| {
{ {
data_storage.extend_from_slice(&data); data_storage.extend_from_slice(&data);
} }
@ -58,7 +58,7 @@ impl Task for DownloadPackageTask {
let percentage = if size == 0 { let percentage = if size == 0 {
0.0 0.0
} else { } else {
(downloaded as f32) / (size as f32) (downloaded as f64) / (size as f64)
}; };
// Pretty print data volumes // Pretty print data volumes

View File

@ -22,7 +22,7 @@ impl Task for InstallTask {
&mut self, &mut self,
_: Vec<TaskParamType>, _: Vec<TaskParamType>,
_: &mut InstallerFramework, _: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
messenger("Wrapping up...", 0.0); messenger("Wrapping up...", 0.0);
Ok(TaskParamType::None) Ok(TaskParamType::None)
@ -56,6 +56,6 @@ impl Task for InstallTask {
} }
fn name(&self) -> String { fn name(&self) -> String {
format!("InstallTask") "InstallTask".to_string()
} }
} }

View File

@ -19,7 +19,7 @@ impl Task for VerifyInstallDirTask {
&mut self, &mut self,
input: Vec<TaskParamType>, input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
assert_eq!(input.len(), 0); assert_eq!(input.len(), 0);
messenger("Polling installation directory...", 0.0); messenger("Polling installation directory...", 0.0);
@ -39,7 +39,7 @@ impl Task for VerifyInstallDirTask {
.map_err(|x| format!("Failed to read install destination: {:?}", x))?; .map_err(|x| format!("Failed to read install destination: {:?}", x))?;
if paths.count() != 0 { if paths.count() != 0 {
return Err(format!("Install destination is not empty.")); return Err("Install destination is not empty.".to_string());
} }
} }

View File

@ -29,7 +29,7 @@ impl Task for InstallPackageTask {
&mut self, &mut self,
mut input: Vec<TaskParamType>, mut input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
messenger(&format!("Installing package {:?}...", self.name), 0.0); messenger(&format!("Installing package {:?}...", self.name), 0.0);
@ -42,7 +42,7 @@ impl Task for InstallPackageTask {
let mut metadata: Option<PackageDescription> = None; let mut metadata: Option<PackageDescription> = None;
for description in &context.config.packages { for description in &context.config.packages {
if &self.name == &description.name { if self.name == description.name {
metadata = Some(description.clone()); metadata = Some(description.clone());
break; break;
} }
@ -54,19 +54,18 @@ impl Task for InstallPackageTask {
}; };
// Check to see if no archive was available. // Check to see if no archive was available.
match input if let TaskParamType::Break = input
.pop() .pop()
.log_expect("Should have input from uninstaller!") .log_expect("Should have input from uninstaller!")
{ {
// No file to install, but all is good. // No file to install, but all is good.
TaskParamType::Break => return Ok(TaskParamType::None), return Ok(TaskParamType::None);
_ => {}
} }
let data = input.pop().log_expect("Should have input from resolver!"); let data = input.pop().log_expect("Should have input from resolver!");
let (file, data) = match data { let (file, data) = match data {
TaskParamType::FileContents(file, data) => (file, data), TaskParamType::FileContents(file, data) => (file, data),
_ => return Err(format!("Unexpected param type to install package")), _ => return Err("Unexpected param type to install package".to_string()),
}; };
// TODO: Handle files other then zips // TODO: Handle files other then zips
@ -83,14 +82,14 @@ impl Task for InstallPackageTask {
messenger( messenger(
&format!("Extracting {} ({} of {})", file.name(), i + 1, zip_size), &format!("Extracting {} ({} of {})", file.name(), i + 1, zip_size),
(i as f32) / (zip_size as f32), (i as f64) / (zip_size as f64),
); );
let filename = file.name().replace("\\", "/"); let filename = file.name().replace("\\", "/");
// Ensure that parent directories exist // Ensure that parent directories exist
let mut parent_dir = &filename[..]; let mut parent_dir = &filename[..];
while let Some(v) = parent_dir.rfind("/") { while let Some(v) = parent_dir.rfind('/') {
parent_dir = &parent_dir[0..v + 1]; parent_dir = &parent_dir[0..v + 1];
if !installed_files.contains(&parent_dir.to_string()) { if !installed_files.contains(&parent_dir.to_string()) {
@ -109,7 +108,7 @@ impl Task for InstallPackageTask {
let target_path = path.join(&filename); let target_path = path.join(&filename);
// Check to make sure this isn't a directory // Check to make sure this isn't a directory
if filename.ends_with("/") || filename.ends_with("\\") { if filename.ends_with('/') || filename.ends_with('\\') {
// Directory was already created // Directory was already created
continue; continue;
} }

View File

@ -39,7 +39,7 @@ pub trait Task {
&mut self, &mut self,
input: Vec<TaskParamType>, input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String>; ) -> Result<TaskParamType, String>;
/// Returns a vector containing all dependencies that need to be executed /// Returns a vector containing all dependencies that need to be executed
@ -84,25 +84,25 @@ impl DependencyTree {
pub fn execute( pub fn execute(
&mut self, &mut self,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
let total_tasks = (self.dependencies.len() + 1) as f32; let total_tasks = (self.dependencies.len() + 1) as f64;
let mut inputs = Vec::<TaskParamType>::with_capacity(self.dependencies.len()); let mut inputs = Vec::<TaskParamType>::with_capacity(self.dependencies.len());
let mut count = 0; let mut count = 0;
for i in &mut self.dependencies { for i in &mut self.dependencies {
let result = i.execute(context, &|msg: &str, progress: f32| { let result = i.execute(context, &|msg: &str, progress: f64| {
messenger( messenger(
msg, msg,
progress / total_tasks + (1.0 / total_tasks) * count as f32, progress / total_tasks + (1.0 / total_tasks) * f64::from(count),
) )
})?; })?;
// Check to see if we skip matching other dependencies // Check to see if we skip matching other dependencies
let do_break = match &result { let do_break = match &result {
&TaskParamType::Break => true, TaskParamType::Break => true,
_ => false, _ => false,
}; };
@ -115,10 +115,10 @@ impl DependencyTree {
} }
self.task self.task
.execute(inputs, context, &|msg: &str, progress: f32| { .execute(inputs, context, &|msg: &str, progress: f64| {
messenger( messenger(
msg, msg,
progress / total_tasks + (1.0 / total_tasks) * count as f32, progress / total_tasks + (1.0 / total_tasks) * f64::from(count),
) )
}) })
} }

View File

@ -22,12 +22,12 @@ impl Task for ResolvePackageTask {
&mut self, &mut self,
input: Vec<TaskParamType>, input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
assert_eq!(input.len(), 0); assert_eq!(input.len(), 0);
let mut metadata: Option<PackageDescription> = None; let mut metadata: Option<PackageDescription> = None;
for description in &context.config.packages { for description in &context.config.packages {
if &self.name == &description.name { if self.name == description.name {
metadata = Some(description.clone()); metadata = Some(description.clone());
break; break;
} }
@ -67,7 +67,7 @@ impl Task for ResolvePackageTask {
let latest_result = match latest_result { let latest_result = match latest_result {
Some(v) => v, Some(v) => v,
None => return Err(format!("No release with correct file found")), None => return Err("No release with correct file found".to_string()),
}; };
let latest_version = latest_result.version.clone(); let latest_version = latest_result.version.clone();
@ -76,8 +76,7 @@ impl Task for ResolvePackageTask {
let latest_file = latest_result let latest_file = latest_result
.files .files
.into_iter() .into_iter()
.filter(|x| regex.is_match(&x.name)) .find(|x| regex.is_match(&x.name))
.next()
.log_expect("Searched file should have existed, but didn't"); .log_expect("Searched file should have existed, but didn't");
info!("Selected file: {:?}", latest_file); info!("Selected file: {:?}", latest_file);

View File

@ -12,7 +12,7 @@ impl Task for SaveDatabaseTask {
&mut self, &mut self,
input: Vec<TaskParamType>, input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
assert_eq!(input.len(), 0); assert_eq!(input.len(), 0);
messenger("Saving application database...", 0.0); messenger("Saving application database...", 0.0);
@ -27,6 +27,6 @@ impl Task for SaveDatabaseTask {
} }
fn name(&self) -> String { fn name(&self) -> String {
format!("SaveDatabaseTask") "SaveDatabaseTask".to_string()
} }
} }

View File

@ -21,7 +21,7 @@ impl Task for SaveExecutableTask {
&mut self, &mut self,
input: Vec<TaskParamType>, input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
assert_eq!(input.len(), 0); assert_eq!(input.len(), 0);
messenger("Copying installer binary...", 0.0); messenger("Copying installer binary...", 0.0);
@ -64,10 +64,9 @@ impl Task for SaveExecutableTask {
Err(v) => return Err(format!("Unable to open installer binary: {:?}", v)), Err(v) => return Err(format!("Unable to open installer binary: {:?}", v)),
}; };
match copy(&mut current_app_file, &mut new_app_file) { if let Err(v) = copy(&mut current_app_file, &mut new_app_file) {
Err(v) => return Err(format!("Unable to copy installer binary: {:?}", v)), return Err(format!("Unable to copy installer binary: {:?}", v));
_ => {} }
};
Ok(TaskParamType::None) Ok(TaskParamType::None)
} }
@ -77,6 +76,6 @@ impl Task for SaveExecutableTask {
} }
fn name(&self) -> String { fn name(&self) -> String {
format!("SaveExecutableTask") "SaveExecutableTask".to_string()
} }
} }

View File

@ -17,7 +17,7 @@ impl Task for UninstallTask {
&mut self, &mut self,
_: Vec<TaskParamType>, _: Vec<TaskParamType>,
_: &mut InstallerFramework, _: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
messenger("Wrapping up...", 0.0); messenger("Wrapping up...", 0.0);
Ok(TaskParamType::None) Ok(TaskParamType::None)
@ -39,6 +39,6 @@ impl Task for UninstallTask {
} }
fn name(&self) -> String { fn name(&self) -> String {
format!("UninstallTask") "UninstallTask".to_string()
} }
} }

View File

@ -22,7 +22,7 @@ impl Task for UninstallPackageTask {
&mut self, &mut self,
input: Vec<TaskParamType>, input: Vec<TaskParamType>,
context: &mut InstallerFramework, context: &mut InstallerFramework,
messenger: &Fn(&str, f32), messenger: &Fn(&str, f64),
) -> Result<TaskParamType, String> { ) -> Result<TaskParamType, String> {
assert_eq!(input.len(), 0); assert_eq!(input.len(), 0);
@ -33,7 +33,7 @@ impl Task for UninstallPackageTask {
let mut metadata: Option<LocalInstallation> = None; let mut metadata: Option<LocalInstallation> = None;
for i in 0..context.database.len() { for i in 0..context.database.len() {
if &self.name == &context.database[i].name { if self.name == context.database[i].name {
metadata = Some(context.database.remove(i)); metadata = Some(context.database.remove(i));
break; break;
} }
@ -59,15 +59,14 @@ impl Task for UninstallPackageTask {
package.files.reverse(); package.files.reverse();
let max = package.files.len(); let max = package.files.len();
let mut i = 0; for (i, file) in package.files.iter().enumerate() {
for file in package.files {
let name = file.clone(); let name = file.clone();
let file = path.join(file); let file = path.join(file);
info!("Deleting {:?}", file); info!("Deleting {:?}", file);
messenger( messenger(
&format!("Deleting {} ({} of {})", name, i + 1, max), &format!("Deleting {} ({} of {})", name, i + 1, max),
(i as f32) / (max as f32), (i as f64) / (max as f64),
); );
let result = if file.is_dir() { let result = if file.is_dir() {
@ -76,12 +75,9 @@ impl Task for UninstallPackageTask {
remove_file(file) remove_file(file)
}; };
match result { if let Err(v) = result {
Err(v) => error!("Failed to delete file: {:?}", v), error!("Failed to delete file: {:?}", v);
_ => {}
} }
i += 1;
} }
Ok(TaskParamType::None) Ok(TaskParamType::None)