From 9fd4fad54bd5deea44bf1a30f8b140e26d7a748f Mon Sep 17 00:00:00 2001 From: lthoerner Date: Wed, 30 Aug 2023 22:25:51 -0700 Subject: [PATCH] refactor(error): rename error variants --- src/errors.rs | 54 ++++++++++++++++++++-------------------- src/eval/dispatcher.rs | 2 +- src/exec/builtins.rs | 18 ++++++-------- src/exec/commands.rs | 2 +- src/state/config.rs | 16 ++++++------ src/state/environment.rs | 8 +++--- src/state/path.rs | 4 +-- 7 files changed, 50 insertions(+), 54 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index cfa987c..f8fe610 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -86,36 +86,36 @@ pub enum ErrorKind { pub enum DispatchError { UnknownCommand(String), CommandNotExecutable(u32), - FailedToReadExecutableMetadata(PathBuf), + UnreadableExecutableMetadata(PathBuf), } /// Error type for errors which occur during execution of builtins. pub enum BuiltinError { - InvalidArgumentCount(usize, usize), - InvalidArgument(String), + WrongArgCount(usize, usize), + InvalidArg(String), InvalidValue(String), + UnreadableFileType(PathBuf), + UnreadableFileName(PathBuf), + UnreadableDirectory(PathBuf), // TODO: Break this into multiple error types FailedToRun, - FailedReadingFileType(PathBuf), - FailedReadingFileName(PathBuf), - FailedReadingDir(PathBuf), } /// Error type for errors which occur during execution of executable files. pub enum ExecutableError { PathNoLongerExists(PathBuf), FailedToExecute(isize), - FailedToWait, + CouldNotWait, } /// Error type for errors which occur during state operations. pub enum StateError { - MissingEnvironmentVariable(EnvVariable), - FailedToUpdateEnvironmentVariable(EnvVariable), + MissingEnv(EnvVariable), + CouldNotUpdateEnv(EnvVariable), NoPreviousDirectory, NoNextDirectory, - FailedToOpenConfigFile(PathBuf), - FailedToReadConfigFile(PathBuf), + UnopenableConfig(PathBuf), + UnreadableConfig(PathBuf), UnsupportedTerminal, } @@ -123,8 +123,8 @@ pub enum StateError { pub enum PathError { FailedToConvertStringToPath(String), FailedToConvertPathToString(PathBuf), - FailedToCanonicalize(PathBuf), - FailedToGetParent(PathBuf), + CouldNotCanonicalize(PathBuf), + CouldNotGetParent(PathBuf), UnknownDirectory(PathBuf), } @@ -155,7 +155,7 @@ impl Display for DispatchError { permission_code ) } - FailedToReadExecutableMetadata(path) => { + UnreadableExecutableMetadata(path) => { write!( f, "Executable metadata at '{}' could not be read", @@ -170,7 +170,7 @@ impl Display for BuiltinError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { use BuiltinError::*; match self { - InvalidArgumentCount(expected, actual) => { + WrongArgCount(expected, actual) => { write!( f, "Expected {} {}, found {}", @@ -182,28 +182,28 @@ impl Display for BuiltinError { actual ) } - InvalidArgument(argument) => { + InvalidArg(argument) => { write!(f, "Argument '{}' is invalid", argument) } InvalidValue(value) => write!(f, "Argument value '{}' is invalid", value), - FailedToRun => write!(f, "Failed to run builtin"), - FailedReadingFileType(path) => { + UnreadableFileType(path) => { write!( f, "Filetype at path '{}' could not be determined", path.display() ) } - FailedReadingFileName(path) => { + UnreadableFileName(path) => { write!( f, "Filename at path '{}' could not be determined", path.display() ) } - FailedReadingDir(path) => { + UnreadableDirectory(path) => { write!(f, "Directory '{}' could not be read", path.display()) } + FailedToRun => write!(f, "Failed to run builtin"), } } } @@ -218,7 +218,7 @@ impl Display for ExecutableError { FailedToExecute(exit_code) => { write!(f, "Executable failed with exit code {}", exit_code) } - FailedToWait => write!(f, "Failed to wait for executable to complete"), + CouldNotWait => write!(f, "Failed to wait for executable to complete"), } } } @@ -227,14 +227,14 @@ impl Display for StateError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { use StateError::*; match self { - MissingEnvironmentVariable(variable) => { + MissingEnv(variable) => { write!( f, "Environment variable '{}' missing from parent process", variable ) } - FailedToUpdateEnvironmentVariable(variable) => { + CouldNotUpdateEnv(variable) => { write!( f, "Environment variable '{}' could not be updated", @@ -243,14 +243,14 @@ impl Display for StateError { } NoPreviousDirectory => write!(f, "No previous directory"), NoNextDirectory => write!(f, "No next directory"), - FailedToOpenConfigFile(path) => { + UnopenableConfig(path) => { write!( f, "Configuration file '{}' could not be openeed", path.display() ) } - FailedToReadConfigFile(path) => { + UnreadableConfig(path) => { write!( f, "Configuration file '{}' could not be read", @@ -273,10 +273,10 @@ impl Display for PathError { // ? Under what circumstances would a path fail to convert but still display? write!(f, "Failed to convert path '{}' to string", path.display()) } - FailedToCanonicalize(path) => { + CouldNotCanonicalize(path) => { write!(f, "Path '{}' could not be canonicalized", path.display()) } - FailedToGetParent(path) => { + CouldNotGetParent(path) => { write!( f, "Parent directory of path '{}' could not be determined", diff --git a/src/eval/dispatcher.rs b/src/eval/dispatcher.rs index 30346dc..9099525 100644 --- a/src/eval/dispatcher.rs +++ b/src/eval/dispatcher.rs @@ -108,7 +108,7 @@ impl Dispatcher { } } else { // If the file cannot be read, return an error - Err(dispatch_err!(FailedToReadExecutableMetadata(path.into()))) + Err(dispatch_err!(UnreadableExecutableMetadata(path.into()))) } } else { Err(dispatch_err!(UnknownCommand(command_name.to_owned()))) diff --git a/src/exec/builtins.rs b/src/exec/builtins.rs index f96cb2b..2738183 100644 --- a/src/exec/builtins.rs +++ b/src/exec/builtins.rs @@ -68,16 +68,16 @@ pub fn list_directory(shell: &mut ShellState, args: Vec<&str>) -> Result<()> { let mut files = Vec::new(); for dir_entry in read_dir_result { - let fs_object = dir_entry.replace_err(builtin_err!(FailedReadingDir(path_to_read)))?; + let fs_object = dir_entry.replace_err(builtin_err!(UnreadableDirectory(path_to_read)))?; let fs_object_name = fs_object .file_name() .to_str() - .replace_err(builtin_err!(FailedReadingFileName(path_to_read)))?; + .replace_err(builtin_err!(UnreadableFileName(path_to_read)))?; let fs_object_type = fs_object .file_type() - .replace_err(builtin_err!(FailedReadingFileType(path_to_read)))?; + .replace_err(builtin_err!(UnreadableFileType(path_to_read)))?; if fs_object_name.starts_with('.') && !show_hidden { continue; @@ -233,7 +233,7 @@ pub fn configure(shell: &mut ShellState, args: Vec<&str>) -> Result<()> { )?; } _ => { - return Err(builtin_err!(InvalidArgument(key.to_owned())) + return Err(builtin_err!(InvalidArg(key.to_owned())) .set_context(&format!("Invalid configuration key: '{}'", key))); } } @@ -253,7 +253,7 @@ pub fn environment_variable(shell: &mut ShellState, args: Vec<&str>) -> Result<( "HOME" => println!("{}", shell.environment.HOME.display()), "CWD" | "WORKING-DIRECTORY" => println!("{}", shell.environment.CWD), _ => { - return Err(builtin_err!(InvalidArgument(args[0].to_owned())) + return Err(builtin_err!(InvalidArg(args[0].to_owned())) .set_context(&format!("Invalid environment variable: '{}'", args[0]))); } } @@ -273,7 +273,7 @@ pub fn edit_path(shell: &mut ShellState, args: Vec<&str>) -> Result<()> { "append" => shell.environment.PATH.push_front(path), "prepend" => shell.environment.PATH.push_back(path), _ => { - return Err(builtin_err!(InvalidArgument(action.to_owned())) + return Err(builtin_err!(InvalidArg(action.to_owned())) .set_context(&format!("Invalid action: '{}'", action))); } } @@ -286,9 +286,7 @@ fn check_args(args: &Vec<&str>, expected_args: usize, usage: &str) -> Result<()> if args.len() == expected_args { Ok(()) } else { - Err( - builtin_err!(InvalidArgumentCount(expected_args, args.len())) - .set_context(&format!("Usage: {}", usage)), - ) + Err(builtin_err!(WrongArgCount(expected_args, args.len())) + .set_context(&format!("Usage: {}", usage))) } } diff --git a/src/exec/commands.rs b/src/exec/commands.rs index 87658f3..fe859b9 100644 --- a/src/exec/commands.rs +++ b/src/exec/commands.rs @@ -85,7 +85,7 @@ impl Runnable for Executable { .spawn() .replace_err(executable_err!(PathNoLongerExists(self.path.into())))?; - let status = process.wait().replace_err(executable_err!(FailedToWait))?; + let status = process.wait().replace_err(executable_err!(CouldNotWait))?; match status.success() { true => Ok(()), diff --git a/src/state/config.rs b/src/state/config.rs index 425d3dc..f92868c 100644 --- a/src/state/config.rs +++ b/src/state/config.rs @@ -39,18 +39,18 @@ impl Configuration { let filename = PathBuf::from(filename); let dirname = filename .parent() - .replace_err(path_err!(FailedToGetParent(filename)))?; + .replace_err(path_err!(CouldNotGetParent(filename)))?; let mut config = Self::default(); let file = File::open(filename.clone()) - .replace_err(state_err!(FailedToOpenConfigFile(filename.clone())))?; + .replace_err(state_err!(UnopenableConfig(filename.clone())))?; let reader = BufReader::new(file); for line in reader.lines() { - let line = line.replace_err(state_err!(FailedToOpenConfigFile(filename.clone())))?; + let line = line.replace_err(state_err!(UnopenableConfig(filename.clone())))?; let tokens = line.split(": ").collect::>(); if tokens.len() != 2 { - return Err(state_err!(FailedToReadConfigFile(filename))); + return Err(state_err!(UnreadableConfig(filename))); } let (key, value) = (tokens[0], tokens[1]); @@ -63,13 +63,13 @@ impl Configuration { } else if value == "false" { config.truncation_factor = None; } else { - return Err(state_err!(FailedToReadConfigFile(filename))); + return Err(state_err!(UnreadableConfig(filename))); } } "multi-line-prompt" => { config.multi_line_prompt = value .parse::() - .replace_err(state_err!(FailedToReadConfigFile(filename)))?; + .replace_err(state_err!(UnreadableConfig(filename)))?; } "history-limit" => { if let Ok(limit) = value.parse::() { @@ -81,12 +81,12 @@ impl Configuration { "show-errors" => { config.show_errors = value .parse::() - .replace_err(state_err!(FailedToReadConfigFile(filename)))?; + .replace_err(state_err!(UnreadableConfig(filename)))?; } "plugin-path" => { config.plugin_paths.push(dirname.join(value)); } - _ => return Err(state_err!(FailedToReadConfigFile(filename))), + _ => return Err(state_err!(UnreadableConfig(filename))), } } diff --git a/src/state/environment.rs b/src/state/environment.rs index 7905f66..0cfe2dd 100644 --- a/src/state/environment.rs +++ b/src/state/environment.rs @@ -102,9 +102,8 @@ impl Environment { } if vars.contains(EnvVariables::CWD) { - env::set_current_dir(self.CWD.path()).replace_err(state_err!( - FailedToUpdateEnvironmentVariable(EnvVariable::Cwd) - ))?; + env::set_current_dir(self.CWD.path()) + .replace_err(state_err!(CouldNotUpdateEnv(EnvVariable::Cwd)))?; } Ok(()) @@ -160,8 +159,7 @@ impl Environment { /// Gets the environment variables from the parent process during shell initialization fn get_parent_env_var(variable: EnvVariable) -> Result { - std::env::var(variable.to_legacy_string()) - .replace_err(state_err!(MissingEnvironmentVariable(variable))) + std::env::var(variable.to_legacy_string()).replace_err(state_err!(MissingEnv(variable))) } /// Converts the PATH environment variable from a string to a collection of `Path`s diff --git a/src/state/path.rs b/src/state/path.rs index 725e707..c0bdb80 100644 --- a/src/state/path.rs +++ b/src/state/path.rs @@ -34,7 +34,7 @@ impl Path { let expanded_path = expand_home(path, home_directory)?; // Canonicalizing a path will resolve any relative or absolute paths let absolute_path = canonicalize(expanded_path) - .replace_err(path_err!(FailedToCanonicalize(expanded_path)))?; + .replace_err(path_err!(CouldNotCanonicalize(expanded_path)))?; // If the file system can canonicalize the path, it should exist, // but this is added for extra precaution @@ -61,7 +61,7 @@ impl Path { } } - Err(path_err!(FailedToCanonicalize(PathBuf::from(name)))) + Err(path_err!(CouldNotCanonicalize(PathBuf::from(name)))) } /// Returns the absolute path