nushell/src/commands/rm.rs

61 lines
1.5 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::*;
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 {
path: Spanned<PathBuf>,
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
}
if full_path.is_dir() {
2019-08-02 21:15:07 +02:00
if !recursive {
return Err(ShellError::maybe_labeled_error(
"is a directory",
"",
2019-08-02 21:15:07 +02:00
context.name,
));
2019-07-17 21:51:18 +02:00
}
std::fs::remove_dir_all(&full_path).expect("can not remove directory");
} else if full_path.is_file() {
std::fs::remove_file(&full_path).expect("can not remove file");
}
Ok(OutputStream::empty())
}