Skip to content

Commit

Permalink
refactor(error): rename error variants
Browse files Browse the repository at this point in the history
  • Loading branch information
lthoerner committed Aug 31, 2023
1 parent 1e11712 commit 9fd4fad
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 54 deletions.
54 changes: 27 additions & 27 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,45 +86,45 @@ 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,
}

/// Error type for errors which occur during path operations.
pub enum PathError {
FailedToConvertStringToPath(String),
FailedToConvertPathToString(PathBuf),
FailedToCanonicalize(PathBuf),
FailedToGetParent(PathBuf),
CouldNotCanonicalize(PathBuf),
CouldNotGetParent(PathBuf),
UnknownDirectory(PathBuf),
}

Expand Down Expand Up @@ -155,7 +155,7 @@ impl Display for DispatchError {
permission_code
)
}
FailedToReadExecutableMetadata(path) => {
UnreadableExecutableMetadata(path) => {
write!(
f,
"Executable metadata at '{}' could not be read",
Expand All @@ -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 {}",
Expand All @@ -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"),
}
}
}
Expand All @@ -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"),
}
}
}
Expand All @@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion src/eval/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())))
Expand Down
18 changes: 8 additions & 10 deletions src/exec/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)));
}
}
Expand All @@ -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])));
}
}
Expand All @@ -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)));
}
}
Expand All @@ -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)))
}
}
2 changes: 1 addition & 1 deletion src/exec/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(()),
Expand Down
16 changes: 8 additions & 8 deletions src/state/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<&str>>();
if tokens.len() != 2 {
return Err(state_err!(FailedToReadConfigFile(filename)));
return Err(state_err!(UnreadableConfig(filename)));
}

let (key, value) = (tokens[0], tokens[1]);
Expand All @@ -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::<bool>()
.replace_err(state_err!(FailedToReadConfigFile(filename)))?;
.replace_err(state_err!(UnreadableConfig(filename)))?;
}
"history-limit" => {
if let Ok(limit) = value.parse::<usize>() {
Expand All @@ -81,12 +81,12 @@ impl Configuration {
"show-errors" => {
config.show_errors = value
.parse::<bool>()
.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))),
}
}

Expand Down
8 changes: 3 additions & 5 deletions src/state/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand Down Expand Up @@ -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<String> {
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
Expand Down
4 changes: 2 additions & 2 deletions src/state/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -61,7 +61,7 @@ impl Path {
}
}

Err(path_err!(FailedToCanonicalize(PathBuf::from(name))))
Err(path_err!(CouldNotCanonicalize(PathBuf::from(name))))
}

/// Returns the absolute path
Expand Down

0 comments on commit 9fd4fad

Please sign in to comment.