nushell/crates/nu-command/src/filesystem/mkdir.rs
Stefan Holderbach f7b8f97873
Document and critically review ShellError variants - Ep. 2 (#8326)
Continuation of #8229 

# Description

The `ShellError` enum at the moment is kind of messy. 

Many variants are basic tuple structs where you always have to reference
the implementation with its macro invocation to know which field serves
which purpose.
Furthermore we have both variants that are kind of redundant or either
overly broad to be useful for the user to match on or overly specific
with few uses.

So I set out to start fixing the lacking documentation and naming to
make it feasible to critically review the individual usages and fix
those.
Furthermore we can decide to join or split up variants that don't seem
to be fit for purpose.

**Everyone:** Feel free to add review comments if you spot inconsistent
use of `ShellError` variants.

- Name fields of `SE::IncorrectValue`
- Merge and name fields on `SE::TypeMismatch`
- Name fields on `SE::UnsupportedOperator`
- Name fields on `AssignmentRequires*` and fix doc
- Name fields on `SE::UnknownOperator`
- Name fields on `SE::MissingParameter`
- Name fields on `SE::DelimiterError`
- Name fields on `SE::IncompatibleParametersSingle`

# User-Facing Changes

(None now, end goal more explicit and consistent error messages)

# Tests + Formatting

(No additional tests needed so far)
2023-03-06 11:31:07 +01:00

108 lines
3.2 KiB
Rust

use std::collections::VecDeque;
use nu_engine::env::current_dir;
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature,
SyntaxShape, Type, Value,
};
#[derive(Clone)]
pub struct Mkdir;
impl Command for Mkdir {
fn name(&self) -> &str {
"mkdir"
}
fn signature(&self) -> Signature {
Signature::build("mkdir")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.rest(
"rest",
SyntaxShape::Directory,
"the name(s) of the path(s) to create",
)
.switch("verbose", "print created path(s).", Some('v'))
.category(Category::FileSystem)
}
fn usage(&self) -> &str {
"Make directories, creates intermediary directories as required."
}
fn search_terms(&self) -> Vec<&str> {
vec!["directory", "folder", "create", "make_dirs"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let path = current_dir(engine_state, stack)?;
let mut directories = call
.rest::<String>(engine_state, stack, 0)?
.into_iter()
.map(|dir| path.join(dir))
.peekable();
let is_verbose = call.has_flag("verbose");
let mut stream: VecDeque<Value> = VecDeque::new();
if directories.peek().is_none() {
return Err(ShellError::MissingParameter {
param_name: "requires directory paths".to_string(),
span: call.head,
});
}
for (i, dir) in directories.enumerate() {
let span = call
.positional_nth(i)
.expect("already checked through directories")
.span;
let dir_res = std::fs::create_dir_all(&dir);
if let Err(reason) = dir_res {
return Err(ShellError::CreateNotPossible(
format!("failed to create directory: {reason}"),
call.positional_nth(i)
.expect("already checked through directories")
.span,
));
}
if is_verbose {
let val = format!("{:}", dir.to_string_lossy());
stream.push_back(Value::String { val, span });
}
}
stream
.into_iter()
.into_pipeline_data(engine_state.ctrlc.clone())
.print_not_formatted(engine_state, false, true)?;
Ok(PipelineData::empty())
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Make a directory named foo",
example: "mkdir foo",
result: None,
},
Example {
description: "Make multiple directories and show the paths created",
example: "mkdir -v foo/bar foo2",
result: None,
},
]
}
}