nushell/src/commands/rm.rs

78 lines
2.0 KiB
Rust
Raw Normal View History

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