From 7222004b8a50425af778a441cd02af9a8c4f7669 Mon Sep 17 00:00:00 2001 From: Andrew Cantino Date: Fri, 6 Dec 2019 17:13:51 -0500 Subject: [PATCH 1/3] Use the Default trait --- src/node.rs | 18 +----------------- src/trainer.rs | 2 +- 2 files changed, 2 insertions(+), 18 deletions(-) diff --git a/src/node.rs b/src/node.rs index bb372385..797f27f7 100644 --- a/src/node.rs +++ b/src/node.rs @@ -2,7 +2,7 @@ use crate::history::Features; use rand::Rng; use std::f64; -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, Default)] pub struct Node { pub offset: f64, pub age: f64, @@ -36,22 +36,6 @@ impl Node { } } - pub fn empty() -> Node { - Node { - offset: 0.0, - age: 0.0, - length: 0.0, - exit: 0.0, - recent_failure: 0.0, - selected_dir: 0.0, - dir: 0.0, - overlap: 0.0, - immediate_overlap: 0.0, - selected_occurrences: 0.0, - occurrences: 0.0, - } - } - pub fn dot(&self, features: &Features) -> f64 { self.offset + features.age_factor * self.age diff --git a/src/trainer.rs b/src/trainer.rs index 58232b0e..48fa1cf9 100644 --- a/src/trainer.rs +++ b/src/trainer.rs @@ -33,7 +33,7 @@ impl<'a> Trainer<'a> { let mut best_restart_error = 10000.0; let mut cycles_since_best_restart_error = 0; let mut network = Network::random(); - let mut node_increments = [Node::empty(), Node::empty(), Node::empty()]; + let mut node_increments = [Node::default(), Node::default(), Node::default()]; let mut output_increments = [0.0, 0.0, 0.0, 0.0]; loop { From c6426bf630d060fc4e91ab65b3cb043a51e97120 Mon Sep 17 00:00:00 2001 From: Andrew Cantino Date: Fri, 6 Dec 2019 18:26:46 -0500 Subject: [PATCH 2/3] Lazy evaluate error paths --- src/bash_history.rs | 6 +-- src/history/db_extensions.rs | 2 +- src/history/history.rs | 88 ++++++++++++++++++------------------ src/history/schema.rs | 20 ++++---- src/history_cleaner.rs | 4 +- src/main.rs | 2 +- src/path_update_helpers.rs | 6 +-- src/settings.rs | 20 ++++---- src/training_cache.rs | 14 +++--- 9 files changed, 82 insertions(+), 80 deletions(-) diff --git a/src/bash_history.rs b/src/bash_history.rs index 7aaeed5f..b066bde3 100644 --- a/src/bash_history.rs +++ b/src/bash_history.rs @@ -32,8 +32,8 @@ fn has_leading_timestamp(line: &str) -> bool { pub fn bash_history_file_path() -> PathBuf { let path = - PathBuf::from(env::var("HISTFILE").expect("McFly error: Please ensure HISTFILE is set for your shell.")); - fs::canonicalize(&path).expect("McFly error: The contents of $HISTFILE appear invalid") + PathBuf::from(env::var("HISTFILE").unwrap_or_else(|err| panic!(format!("McFly error: Please ensure HISTFILE is set for your shell ({})", err)))); + fs::canonicalize(&path).unwrap_or_else(|err| panic!(format!("McFly error: The contents of $HISTFILE appear invalid ({})", err))) } pub fn full_history(path: &PathBuf) -> Vec { @@ -95,7 +95,7 @@ pub fn append_history_entry(command: &str, path: &PathBuf) { .write(true) .append(true) .open(path) - .expect("McFly error: please make sure HISTFILE exists."); + .unwrap_or_else(|err| panic!(format!("McFly error: please make sure HISTFILE exists ({})", err))); if let Err(e) = writeln!(file, "{}", command) { eprintln!("Couldn't append to file {:?}: {}", &path, e); diff --git a/src/history/db_extensions.rs b/src/history/db_extensions.rs index d8689595..fc377240 100644 --- a/src/history/db_extensions.rs +++ b/src/history/db_extensions.rs @@ -31,5 +31,5 @@ pub fn add_db_functions(db: &Connection) { }; Ok(network.output(&features)) - }).expect("McFly error: Successful create_scalar_function"); + }).unwrap_or_else(|err| panic!(format!("McFly error: Successful create_scalar_function ({})", err))); } diff --git a/src/history/history.rs b/src/history/history.rs index 82b66d63..02241d39 100644 --- a/src/history/history.rs +++ b/src/history/history.rs @@ -125,7 +125,7 @@ impl History { (":selected", &selected), (":dir", &dir.to_owned()), (":old_dir", &old_dir.to_owned()), - ]).expect("McFly error: Insert into commands to work"); + ]).unwrap_or_else(|err| panic!(format!("McFly error: Insert into commands to work ({})", err))); } fn determine_if_selected_from_ui( @@ -146,7 +146,7 @@ impl History { (":dir", &dir.to_owned()), ], ) - .expect("McFly error: DELETE from selected_commands to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: DELETE from selected_commands to work ({})", err))); // Delete any other pending selected commands for this session -- they must have been aborted or edited. self.connection @@ -154,7 +154,7 @@ impl History { "DELETE FROM selected_commands WHERE session_id = :session_id", &[(":session_id", &session_id.to_owned())], ) - .expect("McFly error: DELETE from selected_commands to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: DELETE from selected_commands to work ({})", err))); rows_affected > 0 } @@ -165,7 +165,7 @@ impl History { (":cmd", &command.to_owned()), (":session_id", &session_id.to_owned()), (":dir", &dir.to_owned()) - ]).expect("McFly error: Insert into selected_commands to work"); + ]).unwrap_or_else(|err| panic!(format!("McFly error: Insert into selected_commands to work ({})", err))); } // Update historical paths in our database if a directory has been renamed or moved. @@ -224,44 +224,44 @@ impl History { FROM contextual_commands WHERE cmd LIKE (:like) ORDER BY rank DESC LIMIT :limit"; - let mut statement = self.connection.prepare(query).expect("McFly error: Prepare to work"); + let mut statement = self.connection.prepare(query).unwrap_or_else(|err| panic!(format!("McFly error: Prepare to work ({})", err))); let command_iter = statement .query_map_named( &[(":like", &like_query), (":limit", &num)], |row| Command { - id: row.get_checked(0).expect("McFly error: id to be readable"), - cmd: row.get_checked(1).expect("McFly error: cmd to be readable"), - cmd_tpl: row.get_checked(2).expect("McFly error: cmd_tpl to be readable"), - session_id: row.get_checked(3).expect("McFly error: session_id to be readable"), - when_run: row.get_checked(4).expect("McFly error: when_run to be readable"), - exit_code: row.get_checked(5).expect("McFly error: exit_code to be readable"), - selected: row.get_checked(6).expect("McFly error: selected to be readable"), - dir: row.get_checked(7).expect("McFly error: dir to be readable"), - rank: row.get_checked(8).expect("McFly error: rank to be readable"), + id: row.get_checked(0).unwrap_or_else(|err| panic!(format!("McFly error: id to be readable ({})", err))), + cmd: row.get_checked(1).unwrap_or_else(|err| panic!(format!("McFly error: cmd to be readable ({})", err))), + cmd_tpl: row.get_checked(2).unwrap_or_else(|err| panic!(format!("McFly error: cmd_tpl to be readable ({})", err))), + session_id: row.get_checked(3).unwrap_or_else(|err| panic!(format!("McFly error: session_id to be readable ({})", err))), + when_run: row.get_checked(4).unwrap_or_else(|err| panic!(format!("McFly error: when_run to be readable ({})", err))), + exit_code: row.get_checked(5).unwrap_or_else(|err| panic!(format!("McFly error: exit_code to be readable ({})", err))), + selected: row.get_checked(6).unwrap_or_else(|err| panic!(format!("McFly error: selected to be readable ({})", err))), + dir: row.get_checked(7).unwrap_or_else(|err| panic!(format!("McFly error: dir to be readable ({})", err))), + rank: row.get_checked(8).unwrap_or_else(|err| panic!(format!("McFly error: rank to be readable ({})", err))), features: Features { - age_factor: row.get_checked(9).expect("McFly error: age_factor to be readable"), - length_factor: row.get_checked(10).expect("McFly error: length_factor to be readable"), - exit_factor: row.get_checked(11).expect("McFly error: exit_factor to be readable"), + age_factor: row.get_checked(9).unwrap_or_else(|err| panic!(format!("McFly error: age_factor to be readable ({})", err))), + length_factor: row.get_checked(10).unwrap_or_else(|err| panic!(format!("McFly error: length_factor to be readable ({})", err))), + exit_factor: row.get_checked(11).unwrap_or_else(|err| panic!(format!("McFly error: exit_factor to be readable ({})", err))), recent_failure_factor: row.get_checked(12) - .expect("McFly error: recent_failure_factor to be readable"), + .unwrap_or_else(|err| panic!(format!("McFly error: recent_failure_factor to be readable ({})", err))), selected_dir_factor: row.get_checked(13) - .expect("McFly error: selected_dir_factor to be readable"), - dir_factor: row.get_checked(14).expect("McFly error: dir_factor to be readable"), - overlap_factor: row.get_checked(15).expect("McFly error: overlap_factor to be readable"), + .unwrap_or_else(|err| panic!(format!("McFly error: selected_dir_factor to be readable ({})", err))), + dir_factor: row.get_checked(14).unwrap_or_else(|err| panic!(format!("McFly error: dir_factor to be readable ({})", err))), + overlap_factor: row.get_checked(15).unwrap_or_else(|err| panic!(format!("McFly error: overlap_factor to be readable ({})", err))), immediate_overlap_factor: row.get_checked(16) - .expect("McFly error: immediate_overlap_factor to be readable"), + .unwrap_or_else(|err| panic!(format!("McFly error: immediate_overlap_factor to be readable ({})", err))), selected_occurrences_factor: row.get_checked(17) - .expect("McFly error: selected_occurrences_factor to be readable"), + .unwrap_or_else(|err| panic!(format!("McFly error: selected_occurrences_factor to be readable ({})", err))), occurrences_factor: row.get_checked(18) - .expect("McFly error: occurrences_factor to be readable"), + .unwrap_or_else(|err| panic!(format!("McFly error: occurrences_factor to be readable ({})", err))), }, }, ) - .expect("McFly error: Query Map to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Query Map to work ({})", err))); let mut names = Vec::new(); for command in command_iter { - names.push(command.expect("McFly error: Unable to load command from DB")); + names.push(command.unwrap_or_else(|err| panic!(format!("McFly error: Unable to load command from DB ({})", err)))); } names @@ -287,7 +287,7 @@ impl History { self.connection .execute("DROP TABLE IF EXISTS temp.contextual_commands;", NO_PARAMS) - .expect("McFly error: Removal of temp table to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Removal of temp table to work ({})", err))); let (mut when_run_min, when_run_max): (f64, f64) = self.connection .query_row( @@ -295,7 +295,7 @@ impl History { NO_PARAMS, |row| (row.get(0), row.get(1)), ) - .expect("McFly error: Query to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Query to work ({})", err))); if (when_run_min - when_run_max).abs() < std::f64::EPSILON { when_run_min -= 60.0 * 60.0; @@ -375,9 +375,9 @@ impl History { (":last_commands1", &last_commands[1].to_owned()), (":last_commands2", &last_commands[2].to_owned()), (":start_time", &start_time.unwrap_or(0).to_owned()), - (":end_time", &end_time.unwrap_or(SystemTime::now().duration_since(UNIX_EPOCH).expect("McFly error: Time went backwards").as_secs() as i64).to_owned()), - (":now", &now.unwrap_or(SystemTime::now().duration_since(UNIX_EPOCH).expect("McFly error: Time went backwards").as_secs() as i64).to_owned()) - ]).expect("McFly error: Creation of temp table to work"); + (":end_time", &end_time.unwrap_or(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_else(|err| panic!(format!("McFly error: Time went backwards ({})", err))).as_secs() as i64).to_owned()), + (":now", &now.unwrap_or(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_else(|err| panic!(format!("McFly error: Time went backwards ({})", err))).as_secs() as i64).to_owned()) + ]).unwrap_or_else(|err| panic!(format!("McFly error: Creation of temp table to work ({})", err))); self.connection .execute( @@ -388,14 +388,14 @@ impl History { selected_occurrences_factor, occurrences_factor);", NO_PARAMS, ) - .expect("McFly error: Ranking of temp table to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Ranking of temp table to work ({})", err))); self.connection .execute( "CREATE INDEX temp.MyIndex ON contextual_commands(id);", NO_PARAMS, ) - .expect("McFly error: Creation of index on temp table to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Creation of index on temp table to work ({})", err))); // println!("Seconds: {}", (beginning_of_execution.elapsed().as_secs() as f64) + (beginning_of_execution.elapsed().subsec_nanos() as f64 / 1000_000_000.0)); } @@ -439,7 +439,7 @@ impl History { let command_iter: MappedRows<_> = statement. query_map_named(params, closure). - expect("McFly error: Query Map to work"); + unwrap_or_else(|err| panic!(format!("McFly error: Query Map to work ({})", err))); let mut vec = Vec::new(); for result in command_iter { @@ -475,14 +475,14 @@ impl History { "DELETE FROM selected_commands WHERE cmd = :command", &[(":command", &command)], ) - .expect("McFly error: DELETE from selected_commands to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: DELETE from selected_commands to work ({})", err))); self.connection .execute_named( "DELETE FROM commands WHERE cmd = :command", &[(":command", &command)], ) - .expect("McFly error: DELETE from commands to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: DELETE from commands to work ({})", err))); } pub fn update_paths(&self, old_path: &str, new_path: &str, print_output: bool) { @@ -505,14 +505,14 @@ impl History { (":exact", &normalized_old_path), (":new_dir", &normalized_new_path), (":length", &(normalized_old_path.chars().count() as u32 + 1)), - ]).expect("McFly error: dir UPDATE to work"); + ]).unwrap_or_else(|err| panic!(format!("McFly error: dir UPDATE to work ({})", err))); old_dir_update_statement.execute_named(&[ (":like", &like_query), (":exact", &normalized_old_path), (":new_dir", &normalized_new_path), (":length", &(normalized_old_path.chars().count() as u32 + 1)), - ]).expect("McFly error: old_dir UPDATE to work"); + ]).unwrap_or_else(|err| panic!(format!("McFly error: old_dir UPDATE to work ({})", err))); if print_output { println!("McFly: Command database paths renamed from {} to {} (affected {} commands)", normalized_old_path, normalized_new_path, affected); @@ -526,7 +526,7 @@ impl History { print!( "McFly: Importing Bash history for the first time. This may take a minute or two..." ); - io::stdout().flush().expect("McFly error: STDOUT flush should work"); + io::stdout().flush().unwrap_or_else(|err| panic!(format!("McFly error: STDOUT flush should work ({})", err))); // Load this first to make sure it works before we create the DB. let bash_history = bash_history::full_history(&bash_history::bash_history_file_path()); @@ -567,15 +567,15 @@ impl History { dir TEXT NOT NULL \ ); \ CREATE INDEX selected_command_session_cmds ON selected_commands (session_id, cmd);" - ).expect("McFly error: Unable to initialize history db"); + ).unwrap_or_else(|err| panic!(format!("McFly error: Unable to initialize history db ({})", err))); { let mut statement = connection .prepare("INSERT INTO commands (cmd, cmd_tpl, session_id, when_run, exit_code, selected) VALUES (:cmd, :cmd_tpl, :session_id, :when_run, :exit_code, :selected)") - .expect("McFly error: Unable to prepare insert"); + .unwrap_or_else(|err| panic!(format!("McFly error: Unable to prepare insert ({})", err))); let epoch = SystemTime::now() .duration_since(UNIX_EPOCH) - .expect("McFly error: Time went backwards") + .unwrap_or_else(|err| panic!(format!("McFly error: Time went backwards ({})", err))) .as_secs() as i64; for command in &bash_history { if !IGNORED_COMMANDS.contains(&command.as_str()) { @@ -590,7 +590,7 @@ impl History { (":exit_code", &0), (":selected", &0), ]) - .expect("McFly error: Insert to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Insert to work ({})", err))); } } } @@ -607,7 +607,7 @@ impl History { } fn from_db_path(path: PathBuf) -> History { - let connection = Connection::open(path).expect("McFly error: Unable to open history database"); + let connection = Connection::open(path).unwrap_or_else(|err| panic!(format!("McFly error: Unable to open history database ({})", err))); db_extensions::add_db_functions(&connection); History { connection, diff --git a/src/history/schema.rs b/src/history/schema.rs index 324d0c6c..3d2d6b20 100644 --- a/src/history/schema.rs +++ b/src/history/schema.rs @@ -19,7 +19,7 @@ pub fn migrate(connection: &Connection) { NO_PARAMS, |row| row.get(0), ) - .expect("McFly error: Query to work") + .unwrap_or_else(|err| panic!(format!("McFly error: Query to work ({})", err))) .unwrap_or(0); if current_version < CURRENT_SCHEMA_VERSION { @@ -27,7 +27,7 @@ pub fn migrate(connection: &Connection) { "McFly: Upgrading McFly DB to version {}, please wait...", CURRENT_SCHEMA_VERSION ); - io::stdout().flush().expect("McFly error: STDOUT flush should work"); + io::stdout().flush().unwrap_or_else(|err| panic!(format!("McFly error: STDOUT flush should work ({})", err))); } if current_version < 1 { @@ -35,17 +35,17 @@ pub fn migrate(connection: &Connection) { .execute_batch( "ALTER TABLE commands ADD COLUMN cmd_tpl TEXT; UPDATE commands SET cmd_tpl = '';", ) - .expect("McFly error: Unable to add cmd_tpl to commands"); + .unwrap_or_else(|err| panic!(format!("McFly error: Unable to add cmd_tpl to commands ({})", err))); let mut statement = connection .prepare("UPDATE commands SET cmd_tpl = :cmd_tpl WHERE id = :id") - .expect("McFly error: Unable to prepare update"); + .unwrap_or_else(|err| panic!(format!("McFly error: Unable to prepare update ({})", err))); for (id, cmd) in cmd_strings(connection) { let simplified_command = SimplifiedCommand::new(cmd.as_str(), true); statement .execute_named(&[(":cmd_tpl", &simplified_command.result), (":id", &id)]) - .expect("McFly error: Insert to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Insert to work ({})", err))); } } @@ -56,7 +56,7 @@ pub fn migrate(connection: &Connection) { UPDATE commands SET session_id = 'UNKNOWN'; \ CREATE INDEX command_session_id ON commands (session_id);", ) - .expect("McFly error: Unable to add session_id to commands"); + .unwrap_or_else(|err| panic!(format!("McFly error: Unable to add session_id to commands ({})", err))); } if current_version < 3 { @@ -71,7 +71,7 @@ pub fn migrate(connection: &Connection) { \ ALTER TABLE commands ADD COLUMN selected INTEGER; \ UPDATE commands SET selected = 0;") - .expect("McFly error: Unable to add selected_commands"); + .unwrap_or_else(|err| panic!(format!("McFly error: Unable to add selected_commands ({})", err))); } if current_version < CURRENT_SCHEMA_VERSION { @@ -90,7 +90,7 @@ fn make_schema_versions_table(connection: &Connection) { CREATE UNIQUE INDEX IF NOT EXISTS schema_versions_index ON schema_versions (version);", ) - .expect("McFly error: Unable to create schema_versions db table"); + .unwrap_or_else(|err| panic!(format!("McFly error: Unable to create schema_versions db table ({})", err))); } fn write_current_schema_version(connection: &Connection) { @@ -100,7 +100,7 @@ fn write_current_schema_version(connection: &Connection) { ); connection .execute_batch(&insert) - .expect("McFly error: Unable to update schema_versions"); + .unwrap_or_else(|err| panic!(format!("McFly error: Unable to update schema_versions ({})", err))); } fn cmd_strings(connection: &Connection) -> Vec<(i64, String)> { @@ -108,7 +108,7 @@ fn cmd_strings(connection: &Connection) -> Vec<(i64, String)> { let mut statement = connection.prepare(query).unwrap(); let command_iter = statement .query_map(NO_PARAMS, |row| (row.get(0), row.get(1))) - .expect("McFly error: Query Map to work"); + .unwrap_or_else(|err| panic!(format!("McFly error: Query Map to work ({})", err))); let mut vec = Vec::new(); for result in command_iter { diff --git a/src/history_cleaner.rs b/src/history_cleaner.rs index 9a4b5933..ffa72e0b 100644 --- a/src/history_cleaner.rs +++ b/src/history_cleaner.rs @@ -15,7 +15,7 @@ pub fn clean(settings: &Settings, history: &History, command: &str) { // Clean up HISTFILE. let histfile = - PathBuf::from(env::var("HISTFILE").expect("McFly error: Please ensure that HISTFILE is set.")); + PathBuf::from(env::var("HISTFILE").unwrap_or_else(|err| panic!(format!("McFly error: Please ensure that HISTFILE is set ({})", err)))); bash_history::delete_lines(&histfile, command); } @@ -23,7 +23,7 @@ fn clean_temporary_files(mcfly_history: &PathBuf, command: &str) { let path = mcfly_history.as_path(); if let Some(directory) = path.parent() { let expanded_path = - fs::canonicalize(directory).expect("McFly error: The contents of $MCFLY_HISTORY appear invalid"); + fs::canonicalize(directory).unwrap_or_else(|err| panic!(format!("McFly error: The contents of $MCFLY_HISTORY appear invalid ({})", err))); let paths = fs::read_dir(&expanded_path).unwrap(); for path in paths { diff --git a/src/main.rs b/src/main.rs index 73cac99c..0b3d770f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,7 +21,7 @@ fn handle_addition(settings: &Settings, history: &mut History) { if settings.append_to_histfile { let histfile = PathBuf::from(env::var("HISTFILE") - .expect("McFly error: Please ensure that HISTFILE is set.")); + .unwrap_or_else(|err| panic!(format!("McFly error: Please ensure that HISTFILE is set ({})", err)))); bash_history::append_history_entry(&settings.command, &histfile) } } diff --git a/src/path_update_helpers.rs b/src/path_update_helpers.rs index 996c5b1c..dcc3f870 100644 --- a/src/path_update_helpers.rs +++ b/src/path_update_helpers.rs @@ -5,9 +5,9 @@ use std::path::Path; use unicode_segmentation::UnicodeSegmentation; pub fn normalize_path(incoming_path: &str) -> String { - let expanded_path = shellexpand::full(incoming_path).expect("McFly error: Unable to expand command path"); + let expanded_path = shellexpand::full(incoming_path).unwrap_or_else(|err| panic!(format!("McFly error: Unable to expand command path ({})", err))); - let current_dir = env::var("PWD").expect("McFly error: Unable to determine current directory"); + let current_dir = env::var("PWD").unwrap_or_else(|err| panic!(format!("McFly error: Unable to determine current directory ({})", err))); let current_dir_path = Path::new(¤t_dir); let path_buf = if expanded_path.starts_with('/') { @@ -17,7 +17,7 @@ pub fn normalize_path(incoming_path: &str) -> String { RelativePath::new(to_current_dir.to_str().unwrap()).normalize().to_path("/") }; - path_buf.to_str().expect("McFly error: Path must be a valid UTF8 string").to_string() + path_buf.to_str().unwrap_or_else(|| panic!("McFly error: Path must be a valid UTF8 string")).to_string() } pub fn parse_mv_command(command: &str) -> Vec { diff --git a/src/settings.rs b/src/settings.rs index c9d526cb..5145133f 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -162,14 +162,16 @@ impl Settings { .map(|s| s.to_string()) .unwrap_or_else( || env::var("MCFLY_SESSION_ID") - .expect("McFly error: Please ensure that MCFLY_SESSION_ID contains a random session ID."), + .unwrap_or_else(|err| panic!(format!("McFly error: Please ensure that MCFLY_SESSION_ID contains a random session ID ({})", err))), ); settings.mcfly_history = PathBuf::from( matches .value_of("mcfly_history") .map(|s| s.to_string()) - .unwrap_or_else( || - env::var("MCFLY_HISTORY").expect("McFly error: Please ensure that MCFLY_HISTORY is set."), + .unwrap_or_else(|| + env::var("MCFLY_HISTORY").unwrap_or_else(|err| + panic!(format!("McFly error: Please ensure that MCFLY_HISTORY is set ({})", err)) + ), ), ); @@ -180,7 +182,7 @@ impl Settings { settings.when_run = Some( value_t!(add_matches, "when", i64).unwrap_or(SystemTime::now() .duration_since(UNIX_EPOCH) - .expect("McFly error: Time went backwards") + .unwrap_or_else(|err| panic!(format!("McFly error: Time went backwards ({})", err))) .as_secs() as i64), ); @@ -195,7 +197,7 @@ impl Settings { if let Some(dir) = add_matches.value_of("directory") { settings.dir = dir.to_string(); } else { - settings.dir = env::var("PWD").expect("McFly error: Unable to determine current directory"); + settings.dir = env::var("PWD").unwrap_or_else(|err| panic!(format!("McFly error: Unable to determine current directory ({})", err))); } if let Some(old_dir) = add_matches.value_of("old_directory") { @@ -225,7 +227,7 @@ impl Settings { if let Some(dir) = search_matches.value_of("directory") { settings.dir = dir.to_string(); } else { - settings.dir = env::var("PWD").expect("McFly error: Unable to determine current directory"); + settings.dir = env::var("PWD").unwrap_or_else(|err| panic!(format!("McFly error: Unable to determine current directory ({})", err))); } if let Some(values) = search_matches.values_of("command") { settings.command = values.collect::>().join(" "); @@ -246,8 +248,8 @@ impl Settings { ("move", Some(move_matches)) => { settings.mode = Mode::Move; - settings.old_dir = Some(String::from(move_matches.value_of("old_dir_path").expect("McFly error: Value for old_dir_path"))); - settings.dir = String::from(move_matches.value_of("new_dir_path").expect("McFly error: Value for new_dir_path")); + settings.old_dir = Some(String::from(move_matches.value_of("old_dir_path").unwrap_or_else(|| panic!("McFly error: Value for old_dir_path")))); + settings.dir = String::from(move_matches.value_of("new_dir_path").unwrap_or_else(|| panic!("McFly error: Value for new_dir_path"))); } ("", None) => println!("No subcommand was used"), // If no subcommand was used it'll match the tuple ("", None) @@ -272,7 +274,7 @@ impl Settings { pub fn storage_dir_path() -> PathBuf { home_dir() - .expect("McFly error: Unable to access home directory") + .unwrap_or_else(|| panic!("McFly error: Unable to access home directory")) .join(PathBuf::from(".mcfly")) } diff --git a/src/training_cache.rs b/src/training_cache.rs index c321f0e2..4ef4bb8b 100644 --- a/src/training_cache.rs +++ b/src/training_cache.rs @@ -5,7 +5,7 @@ use csv::Reader; use std::path::PathBuf; pub fn write(data_set: &[(Features, bool)], cache_path: &PathBuf) { - let mut writer = Writer::from_path(cache_path).expect("McFly error: Expected to be able to write a CSV"); + let mut writer = Writer::from_path(cache_path).unwrap_or_else(|err| panic!(format!("McFly error: Expected to be able to write a CSV ({})", err))); output_header(&mut writer); for (features, correct) in data_set { @@ -16,10 +16,10 @@ pub fn write(data_set: &[(Features, bool)], cache_path: &PathBuf) { pub fn read(cache_path: &PathBuf) -> Vec<(Features, bool)> { let mut data_set: Vec<(Features, bool)> = Vec::new(); - let mut reader = Reader::from_path(cache_path).expect("McFly error: Expected to be able to read from CSV"); + let mut reader = Reader::from_path(cache_path).unwrap_or_else(|err| panic!(format!("McFly error: Expected to be able to read from CSV ({})", err))); for result in reader.records() { - let record = result.expect("McFly error: Expected to be able to unwrap cached result"); + let record = result.unwrap_or_else(|err| panic!(format!("McFly error: Expected to be able to unwrap cached result ({})", err))); let features = Features { age_factor: record[0].parse().unwrap(), @@ -55,8 +55,8 @@ fn output_header(writer: &mut Writer) { "occurrences_factor", "correct", ]) - .expect("McFly error: Expected to write to CSV"); - writer.flush().expect("McFly error: Expected to flush CSV"); + .unwrap_or_else(|err| panic!(format!("McFly error: Expected to write to CSV ({})", err))); + writer.flush().unwrap_or_else(|err| panic!(format!("McFly error: Expected to flush CSV ({})", err))); } fn output_row(writer: &mut Writer, features: &Features, correct: bool) { @@ -78,6 +78,6 @@ fn output_row(writer: &mut Writer, features: &Features, correct: bool) { String::from("f") }, ]) - .expect("McFly error: Expected to write to CSV"); - writer.flush().expect("McFly error: Expected to flush CSV"); + .unwrap_or_else(|err| panic!(format!("McFly error: Expected to write to CSV ({})", err))); + writer.flush().unwrap_or_else(|err| panic!(format!("McFly error: Expected to flush CSV ({})", err))); } From 95545be957ca962a0f00ed6a7ed4129ebcc89c9d Mon Sep 17 00:00:00 2001 From: Andrew Cantino Date: Sun, 15 Dec 2019 13:53:45 -0800 Subject: [PATCH 3/3] Minor text change --- src/settings.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/settings.rs b/src/settings.rs index 5145133f..2abb2edb 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -248,8 +248,8 @@ impl Settings { ("move", Some(move_matches)) => { settings.mode = Mode::Move; - settings.old_dir = Some(String::from(move_matches.value_of("old_dir_path").unwrap_or_else(|| panic!("McFly error: Value for old_dir_path")))); - settings.dir = String::from(move_matches.value_of("new_dir_path").unwrap_or_else(|| panic!("McFly error: Value for new_dir_path"))); + settings.old_dir = Some(String::from(move_matches.value_of("old_dir_path").unwrap_or_else(|| panic!("McFly error: Expected value for old_dir_path")))); + settings.dir = String::from(move_matches.value_of("new_dir_path").unwrap_or_else(|| panic!("McFly error: Expected value for new_dir_path"))); } ("", None) => println!("No subcommand was used"), // If no subcommand was used it'll match the tuple ("", None)