mirror of
https://github.com/nushell/nushell.git
synced 2025-08-16 05:57:51 +02:00
Can remove files and directories.
This commit is contained in:
@ -175,7 +175,7 @@ pub async fn cli() -> Result<(), Box<dyn Error>> {
|
||||
command("to-toml", Box::new(to_toml::to_toml)),
|
||||
command("to-yaml", Box::new(to_yaml::to_yaml)),
|
||||
command("sort-by", Box::new(sort_by::sort_by)),
|
||||
command("sort-by", Box::new(sort_by::sort_by)),
|
||||
Arc::new(Remove),
|
||||
Arc::new(Open),
|
||||
Arc::new(Where),
|
||||
Arc::new(Config),
|
||||
|
@ -4,6 +4,7 @@ crate mod macros;
|
||||
crate mod args;
|
||||
crate mod autoview;
|
||||
crate mod cd;
|
||||
crate mod rm;
|
||||
crate mod classified;
|
||||
crate mod clip;
|
||||
crate mod command;
|
||||
@ -41,6 +42,7 @@ crate mod where_;
|
||||
|
||||
crate use command::command;
|
||||
crate use config::Config;
|
||||
crate use rm::Remove;
|
||||
crate use open::Open;
|
||||
crate use skip_while::SkipWhile;
|
||||
crate use where_::Where;
|
||||
|
63
src/commands/rm.rs
Normal file
63
src/commands/rm.rs
Normal file
@ -0,0 +1,63 @@
|
||||
use crate::errors::ShellError;
|
||||
use crate::prelude::*;
|
||||
use crate::parser::registry::{CommandConfig, NamedType, PositionalType};
|
||||
use crate::parser::hir::SyntaxType;
|
||||
use indexmap::IndexMap;
|
||||
|
||||
pub struct Remove;
|
||||
|
||||
impl Command for Remove {
|
||||
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
|
||||
rm(args)
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rm(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
||||
let mut full_path = args.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),
|
||||
}
|
||||
|
||||
|
||||
if full_path.is_dir() {
|
||||
if !args.has("recursive") {
|
||||
return Err(ShellError::labeled_error(
|
||||
"is a directory",
|
||||
"",
|
||||
args.name_span.unwrap()));
|
||||
}
|
||||
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())
|
||||
}
|
Reference in New Issue
Block a user