2019-08-06 16:26:33 +00:00
|
|
|
use crate::commands::StaticCommand;
|
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-02 19:15:07 +00:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
pub struct RemoveArgs {
|
2019-08-09 04:51:21 +00:00
|
|
|
path: Tagged<PathBuf>,
|
2019-08-02 19:15:07 +00:00
|
|
|
recursive: bool,
|
|
|
|
}
|
2019-07-17 19:51:18 +00:00
|
|
|
|
2019-08-02 19:15:07 +00:00
|
|
|
impl StaticCommand 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,
|
|
|
|
args: CommandArgs,
|
|
|
|
registry: &CommandRegistry,
|
|
|
|
) -> Result<OutputStream, ShellError> {
|
|
|
|
args.process(registry, rm)?.run()
|
2019-07-17 19:51:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-23 22:22:11 +00:00
|
|
|
pub fn rm(
|
2019-08-02 19:15:07 +00:00
|
|
|
RemoveArgs { path, recursive }: RemoveArgs,
|
|
|
|
context: RunnableContext,
|
2019-07-23 22:22:11 +00:00
|
|
|
) -> Result<OutputStream, ShellError> {
|
2019-08-02 19:15:07 +00:00
|
|
|
let mut full_path = context.cwd();
|
2019-07-20 02:27:10 +00:00
|
|
|
|
2019-08-02 19:15:07 +00:00
|
|
|
match path.item.to_str().unwrap() {
|
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-09 04:51:21 +00:00
|
|
|
if !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",
|
|
|
|
context.name,
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(OutputStream::empty())
|
|
|
|
}
|