add custom filesystem shell errors

This commit is contained in:
xiuxiu62 2021-10-04 20:43:07 -07:00
parent b2148e32b8
commit 1b96da5e5b
2 changed files with 53 additions and 34 deletions

View file

@ -49,29 +49,33 @@ impl Command for Mv {
glob::glob(&source.to_string_lossy()).map_or_else(|_| Vec::new(), Iterator::collect); glob::glob(&source.to_string_lossy()).map_or_else(|_| Vec::new(), Iterator::collect);
if sources.is_empty() { if sources.is_empty() {
return Err(ShellError::InternalError(format!( return Err(ShellError::FileNotFound(
"source \"{:?}\" does not exist", call.positional.first().unwrap().span,
source ));
)));
} }
if (destination.exists() && !destination.is_dir() && sources.len() > 1) if (destination.exists() && !destination.is_dir() && sources.len() > 1)
|| (!destination.exists() && sources.len() > 1) || (!destination.exists() && sources.len() > 1)
{ {
return Err(ShellError::InternalError( return Err(ShellError::MoveNotPossible {
"can only move multiple sources if destination is a directory".to_string(), source_message: "Can't move many files".to_string(),
)); source_span: call.positional[0].span,
destination_message: "into single file".to_string(),
destination_span: call.positional[1].span,
});
} }
let some_if_source_is_destination = sources let some_if_source_is_destination = sources
.iter() .iter()
.find(|f| matches!(f, Ok(f) if destination.starts_with(f))); .find(|f| matches!(f, Ok(f) if destination.starts_with(f)));
if destination.exists() && destination.is_dir() && sources.len() == 1 { if destination.exists() && destination.is_dir() && sources.len() == 1 {
if let Some(Ok(filename)) = some_if_source_is_destination { if let Some(Ok(_filename)) = some_if_source_is_destination {
return Err(ShellError::InternalError(format!( return Err(ShellError::MoveNotPossible {
"Not possible to move {:?} to itself", source_message: "Can't move directory".to_string(),
filename.file_name().expect("Invalid file name") source_span: call.positional[0].span,
))); destination_message: "into itself".to_string(),
destination_span: call.positional[1].span,
});
} }
} }
@ -83,19 +87,21 @@ impl Command for Mv {
} }
for entry in sources.into_iter().flatten() { for entry in sources.into_iter().flatten() {
move_file(&entry, &destination)? move_file(call, &entry, &destination)?
} }
Ok(Value::Nothing { span: call.head }) Ok(Value::Nothing { span: call.head })
} }
} }
fn move_file(from: &PathBuf, to: &PathBuf) -> Result<(), ShellError> { fn move_file(call: &Call, from: &PathBuf, to: &PathBuf) -> Result<(), ShellError> {
if to.exists() && from.is_dir() && to.is_file() { if to.exists() && from.is_dir() && to.is_file() {
return Err(ShellError::InternalError(format!( return Err(ShellError::MoveNotPossible {
"Cannot rename {:?} to a file", source_message: "Can't move a directory".to_string(),
from.file_name().expect("Invalid directory name") source_span: call.positional[0].span,
))); destination_message: "to a file".to_string(),
destination_span: call.positional[1].span,
});
} }
let destination_dir_exists = if to.is_dir() { let destination_dir_exists = if to.is_dir() {
@ -105,37 +111,31 @@ fn move_file(from: &PathBuf, to: &PathBuf) -> Result<(), ShellError> {
}; };
if !destination_dir_exists { if !destination_dir_exists {
return Err(ShellError::InternalError(format!( return Err(ShellError::DirectoryNotFound(call.positional[1].span));
"{:?} does not exist",
to.file_name().expect("Invalid directory name")
)));
} }
let mut to = to.clone(); let mut to = to.clone();
if to.is_dir() { if to.is_dir() {
let from_file_name = match from.file_name() { let from_file_name = match from.file_name() {
Some(name) => name, Some(name) => name,
None => { None => return Err(ShellError::DirectoryNotFound(call.positional[1].span)),
return Err(ShellError::InternalError(format!(
"{:?} is not a valid entry",
from.file_name().expect("Invalid directory name")
)))
}
}; };
to.push(from_file_name); to.push(from_file_name);
} }
move_item(&from, &to) move_item(call, &from, &to)
} }
fn move_item(from: &Path, to: &Path) -> Result<(), ShellError> { fn move_item(call: &Call, from: &Path, to: &Path) -> Result<(), ShellError> {
// We first try a rename, which is a quick operation. If that doesn't work, we'll try a copy // We first try a rename, which is a quick operation. If that doesn't work, we'll try a copy
// and remove the old file/folder. This is necessary if we're moving across filesystems or devices. // and remove the old file/folder. This is necessary if we're moving across filesystems or devices.
std::fs::rename(&from, &to).or_else(|_| { std::fs::rename(&from, &to).or_else(|_| {
Err(ShellError::InternalError(format!( Err(ShellError::MoveNotPossible {
"Could not move {:?} to {:?}", source_message: "failed to move".to_string(),
from, to, source_span: call.positional[0].span,
))) destination_message: "into".to_string(),
destination_span: call.positional[1].span,
})
}) })
} }

View file

@ -78,4 +78,23 @@ pub enum ShellError {
#[error("Flag not found")] #[error("Flag not found")]
#[diagnostic(code(nu::shell::flag_not_found), url(docsrs))] #[diagnostic(code(nu::shell::flag_not_found), url(docsrs))]
FlagNotFound(String, #[label("{0} not found")] Span), FlagNotFound(String, #[label("{0} not found")] Span),
#[error("File not found")]
#[diagnostic(code(nu::shell::file_not_found), url(docsrs))]
FileNotFound(#[label("file not found")] Span),
#[error("Directory not found")]
#[diagnostic(code(nu::shell::directory_not_found), url(docsrs))]
DirectoryNotFound(#[label("directory not found")] Span),
#[error("Move not possible")]
#[diagnostic(code(nu::shell::move_not_possible), url(docsrs))]
MoveNotPossible {
source_message: String,
#[label("{source_message}")]
source_span: Span,
destination_message: String,
#[label("{destination_message}")]
destination_span: Span,
},
} }