nushell/src/commands/rm.rs

70 lines
1.9 KiB
Rust
Raw Normal View History

2019-07-23 22:22:11 +00:00
use crate::commands::EvaluatedStaticCommandArgs;
2019-07-17 19:51:18 +00:00
use crate::errors::ShellError;
use crate::parser::hir::SyntaxType;
use crate::parser::registry::{CommandConfig, NamedType, PositionalType};
use crate::prelude::*;
2019-07-17 19:51:18 +00:00
use indexmap::IndexMap;
pub struct Remove;
impl Command for Remove {
2019-07-23 22:22:11 +00:00
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let env = args.env.clone();
rm(args.evaluate_once(registry)?, env)
2019-07-17 19:51:18 +00:00
}
fn name(&self) -> &str {
"rm"
}
fn config(&self) -> CommandConfig {
let mut named: IndexMap<String, NamedType> = IndexMap::new();
named.insert("recursive".to_string(), NamedType::Switch);
CommandConfig {
name: self.name().to_string(),
positional: vec![PositionalType::mandatory("file", SyntaxType::Path)],
rest_positional: false,
named,
is_sink: true,
is_filter: false,
}
}
}
2019-07-23 22:22:11 +00:00
pub fn rm(
args: EvaluatedStaticCommandArgs,
env: Arc<Mutex<Environment>>,
) -> Result<OutputStream, ShellError> {
let mut full_path = env.lock().unwrap().path().to_path_buf();
match 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 19:51:18 +00:00
}
if full_path.is_dir() {
if !args.has("recursive") {
return Err(ShellError::labeled_error(
"is a directory",
"",
2019-07-23 22:22:11 +00:00
args.name_span().unwrap(),
));
2019-07-17 19:51:18 +00: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())
}