Ian Manske c747ec75c9
Add command_prelude module (#12291)
# Description
When implementing a `Command`, one must also import all the types
present in the function signatures for `Command`. This makes it so that
we often import the same set of types in each command implementation
file. E.g., something like this:
```rust
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
    record, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
    ShellError, Signature, Span, Type, Value,
};
```

This PR adds the `nu_engine::command_prelude` module which contains the
necessary and commonly used types to implement a `Command`:
```rust
// command_prelude.rs
pub use crate::CallExt;
pub use nu_protocol::{
    ast::{Call, CellPath},
    engine::{Command, EngineState, Stack},
    record, Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, IntoSpanned,
    PipelineData, Record, ShellError, Signature, Span, Spanned, SyntaxShape, Type, Value,
};
```

This should reduce the boilerplate needed to implement a command and
also gives us a place to track the breadth of the `Command` API. I tried
to be conservative with what went into the prelude modules, since it
might be hard/annoying to remove items from the prelude in the future.
Let me know if something should be included or excluded.
2024-03-26 21:17:30 +00:00

165 lines
5.0 KiB
Rust

use crate::grapheme_flags;
use nu_engine::command_prelude::*;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"split chars"
}
fn signature(&self) -> Signature {
Signature::build("split chars")
.input_output_types(vec![
(Type::String, Type::List(Box::new(Type::String))),
(
Type::List(Box::new(Type::String)),
Type::List(Box::new(Type::List(Box::new(Type::String)))),
),
])
.allow_variants_without_examples(true)
.switch("grapheme-clusters", "split on grapheme clusters", Some('g'))
.switch(
"code-points",
"split on code points (default; splits combined characters)",
Some('c'),
)
.category(Category::Strings)
}
fn usage(&self) -> &str {
"Split a string into a list of characters."
}
fn search_terms(&self) -> Vec<&str> {
vec!["character", "separate", "divide"]
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Split the string into a list of characters",
example: "'hello' | split chars",
result: Some(Value::list(
vec![
Value::test_string("h"),
Value::test_string("e"),
Value::test_string("l"),
Value::test_string("l"),
Value::test_string("o"),
],
Span::test_data(),
)),
},
Example {
description: "Split on grapheme clusters",
example: "'🇯🇵ほげ' | split chars --grapheme-clusters",
result: Some(Value::list(
vec![
Value::test_string("🇯🇵"),
Value::test_string(""),
Value::test_string(""),
],
Span::test_data(),
)),
},
Example {
description: "Split multiple strings into lists of characters",
example: "['hello', 'world'] | split chars",
result: Some(Value::test_list(vec![
Value::test_list(vec![
Value::test_string("h"),
Value::test_string("e"),
Value::test_string("l"),
Value::test_string("l"),
Value::test_string("o"),
]),
Value::test_list(vec![
Value::test_string("w"),
Value::test_string("o"),
Value::test_string("r"),
Value::test_string("l"),
Value::test_string("d"),
]),
])),
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
split_chars(engine_state, stack, call, input)
}
}
fn split_chars(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let span = call.head;
let graphemes = grapheme_flags(engine_state, stack, call)?;
input.map(
move |x| split_chars_helper(&x, span, graphemes),
engine_state.ctrlc.clone(),
)
}
fn split_chars_helper(v: &Value, name: Span, graphemes: bool) -> Value {
let span = v.span();
match v {
Value::Error { error, .. } => Value::error(*error.clone(), span),
v => {
let v_span = v.span();
if let Ok(s) = v.coerce_str() {
Value::list(
if graphemes {
s.graphemes(true)
.collect::<Vec<_>>()
.into_iter()
.map(move |x| Value::string(x, v_span))
.collect()
} else {
s.chars()
.collect::<Vec<_>>()
.into_iter()
.map(move |x| Value::string(x, v_span))
.collect()
},
v_span,
)
} else {
Value::error(
ShellError::PipelineMismatch {
exp_input_type: "string".into(),
dst_span: name,
src_span: v_span,
},
name,
)
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}