2019-07-17 19:51:18 +00:00
|
|
|
use crate::errors::ShellError;
|
|
|
|
use crate::parser::hir::SyntaxType;
|
2019-07-20 02:27:10 +00:00
|
|
|
use crate::prelude::*;
|
2019-08-01 21:00:08 +00:00
|
|
|
|
|
|
|
use glob::glob;
|
2019-08-02 19:15:07 +00:00
|
|
|
use std::path::PathBuf;
|
2019-07-17 19:51:18 +00:00
|
|
|
|
|
|
|
pub struct Remove;
|
|
|
|
|
2019-08-15 05:02:02 +00:00
|
|
|
impl PerItemCommand for Remove {
|
2019-07-17 19:51:18 +00:00
|
|
|
fn name(&self) -> &str {
|
|
|
|
"rm"
|
|
|
|
}
|
|
|
|
|
2019-08-02 19:15:07 +00:00
|
|
|
fn signature(&self) -> Signature {
|
|
|
|
Signature::build("rm")
|
|
|
|
.required("path", SyntaxType::Path)
|
|
|
|
.switch("recursive")
|
|
|
|
}
|
2019-07-17 19:51:18 +00:00
|
|
|
|
2019-08-02 19:15:07 +00:00
|
|
|
fn run(
|
|
|
|
&self,
|
2019-08-15 05:02:02 +00:00
|
|
|
call_info: &CallInfo,
|
|
|
|
_registry: &CommandRegistry,
|
|
|
|
shell_manager: &ShellManager,
|
|
|
|
_input: Tagged<Value>,
|
|
|
|
) -> Result<VecDeque<ReturnValue>, ShellError> {
|
|
|
|
rm(call_info, shell_manager)
|
2019-07-17 19:51:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-23 22:22:11 +00:00
|
|
|
pub fn rm(
|
2019-08-15 05:02:02 +00:00
|
|
|
call_info: &CallInfo,
|
|
|
|
shell_manager: &ShellManager,
|
|
|
|
) -> Result<VecDeque<ReturnValue>, ShellError> {
|
|
|
|
let mut full_path = PathBuf::from(shell_manager.path());
|
2019-07-20 02:27:10 +00:00
|
|
|
|
2019-08-15 05:02:02 +00:00
|
|
|
match call_info
|
|
|
|
.args
|
|
|
|
.nth(0)
|
|
|
|
.ok_or_else(|| ShellError::string(&format!("No file or directory specified")))?
|
|
|
|
.as_string()?
|
|
|
|
.as_str()
|
|
|
|
{
|
2019-07-20 02:27:10 +00:00
|
|
|
"." | ".." => return Err(ShellError::string("\".\" and \"..\" may not be removed")),
|
|
|
|
file => full_path.push(file),
|
2019-07-17 19:51:18 +00:00
|
|
|
}
|
|
|
|
|
2019-08-01 21:55:49 +00: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 {
|
2019-08-01 21:00:08 +00:00
|
|
|
match entry {
|
|
|
|
Ok(path) => {
|
|
|
|
if path.is_dir() {
|
2019-08-15 05:02:02 +00:00
|
|
|
if !call_info.args.has("recursive") {
|
2019-08-09 20:49:43 +00:00
|
|
|
return Err(ShellError::labeled_error(
|
2019-08-07 14:45:50 +00:00
|
|
|
"is a directory",
|
2019-08-09 20:49:43 +00:00
|
|
|
"is a directory",
|
2019-08-15 05:02:02 +00:00
|
|
|
call_info.name_span,
|
2019-08-01 21:00:08 +00:00
|
|
|
));
|
|
|
|
}
|
|
|
|
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 19:51:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-15 05:02:02 +00:00
|
|
|
Ok(VecDeque::new())
|
2019-07-17 19:51:18 +00:00
|
|
|
}
|