nushell/src/commands/rm.rs

79 lines
2.1 KiB
Rust
Raw Normal View History

2019-07-17 21:51:18 +02:00
use crate::errors::ShellError;
use crate::parser::hir::SyntaxType;
use crate::prelude::*;
use glob::glob;
2019-08-02 21:15:07 +02:00
use std::path::PathBuf;
2019-07-17 21:51:18 +02:00
pub struct Remove;
2019-08-15 07:02:02 +02:00
impl PerItemCommand for Remove {
2019-07-17 21:51:18 +02:00
fn name(&self) -> &str {
"rm"
}
2019-08-02 21:15:07 +02:00
fn signature(&self) -> Signature {
Signature::build("rm")
.required("path", SyntaxType::Path)
.switch("recursive")
}
2019-07-17 21:51:18 +02:00
2019-08-02 21:15:07 +02:00
fn run(
&self,
2019-08-15 07:02:02 +02:00
call_info: &CallInfo,
_registry: &CommandRegistry,
shell_manager: &ShellManager,
_input: Tagged<Value>,
) -> Result<VecDeque<ReturnValue>, ShellError> {
rm(call_info, shell_manager)
2019-07-17 21:51:18 +02:00
}
}
2019-07-24 00:22:11 +02:00
pub fn rm(
2019-08-15 07:02:02 +02:00
call_info: &CallInfo,
shell_manager: &ShellManager,
) -> Result<VecDeque<ReturnValue>, ShellError> {
let mut full_path = PathBuf::from(shell_manager.path());
2019-08-15 07:02:02 +02:00
match call_info
.args
.nth(0)
.ok_or_else(|| ShellError::string(&format!("No file or directory specified")))?
.as_string()?
.as_str()
{
"." | ".." => return Err(ShellError::string("\".\" and \"..\" may not be removed")),
file => full_path.push(file),
2019-07-17 21:51:18 +02:00
}
let entries = glob(&full_path.to_string_lossy());
if entries.is_err() {
return Err(ShellError::string("Invalid pattern."));
}
let entries = entries.unwrap();
for entry in entries {
match entry {
Ok(path) => {
if path.is_dir() {
2019-08-15 07:02:02 +02:00
if !call_info.args.has("recursive") {
2019-08-09 22:49:43 +02:00
return Err(ShellError::labeled_error(
"is a directory",
2019-08-09 22:49:43 +02:00
"is a directory",
2019-08-15 07:02:02 +02:00
call_info.name_span,
));
}
std::fs::remove_dir_all(&path).expect("can not remove directory");
} else if path.is_file() {
std::fs::remove_file(&path).expect("can not remove file");
}
}
Err(e) => return Err(ShellError::string(&format!("{:?}", e))),
2019-07-17 21:51:18 +02:00
}
}
2019-08-15 07:02:02 +02:00
Ok(VecDeque::new())
2019-07-17 21:51:18 +02:00
}