add touch command

This commit is contained in:
xiuxiu62 2021-10-07 14:18:03 -07:00
parent 5021d61800
commit adabc839bf
4 changed files with 63 additions and 0 deletions

View File

@ -41,6 +41,7 @@ pub fn create_default_context() -> Rc<RefCell<EngineState>> {
working_set.add_decl(Box::new(Select));
working_set.add_decl(Box::new(Sys));
working_set.add_decl(Box::new(Table));
working_set.add_decl(Box::new(Touch));
working_set.add_decl(Box::new(Use));
working_set.add_decl(Box::new(Where));
working_set.add_decl(Box::new(Wrap));

View File

@ -2,9 +2,11 @@ mod cd;
mod cp;
mod ls;
mod mv;
mod touch;
mod util;
pub use cd::Cd;
pub use cp::Cp;
pub use ls::Ls;
pub use mv::Mv;
pub use touch::Touch;

View File

@ -0,0 +1,56 @@
use std::fs::OpenOptions;
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
use nu_protocol::{ShellError, Signature, SyntaxShape, Value};
pub struct Touch;
impl Command for Touch {
fn name(&self) -> &str {
"touch"
}
fn signature(&self) -> Signature {
Signature::build("touch")
.required(
"filename",
SyntaxShape::Filepath,
"the path of the file you want to create",
)
.rest("rest", SyntaxShape::Filepath, "additional files to create")
}
fn usage(&self) -> &str {
"Creates one or more files."
}
fn run(
&self,
context: &EvaluationContext,
call: &Call,
_input: Value,
) -> Result<Value, ShellError> {
touch(context, call)
}
}
fn touch(context: &EvaluationContext, call: &Call) -> Result<Value, ShellError> {
let target: String = call.req(context, 0)?;
let rest: Vec<String> = call.rest(context, 1)?;
for (index, item) in vec![target].into_iter().chain(rest).enumerate() {
match OpenOptions::new().write(true).create(true).open(&item) {
Ok(_) => continue,
Err(err) => {
return Err(ShellError::CreateNotPossible(
format!("Failed to create file: {}", err),
call.positional[index].span,
));
}
}
}
Ok(Value::Nothing { span: call.head })
}

View File

@ -109,6 +109,10 @@ pub enum ShellError {
#[error("Move not possible")]
#[diagnostic(code(nu::shell::move_not_possible_single), url(docsrs))]
MoveNotPossibleSingle(String, #[label("{0}")] Span),
#[error("Create not possible")]
#[diagnostic(code(nu::shell::move_not_possible_single), url(docsrs))]
CreateNotPossible(String, #[label("{0}")] Span),
}
impl From<std::io::Error> for ShellError {