use crate::grapheme_flags;
use fancy_regex::Regex;
use nu_engine::CallExt;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack},
Category, Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
};
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"split words"
}
fn signature(&self) -> Signature {
Signature::build("split words")
.input_output_types(vec![(Type::String, Type::List(Box::new(Type::String)))])
.vectorizes_over_list(true)
.category(Category::Strings)
.named(
"min-word-length",
SyntaxShape::Int,
"The minimum word length",
Some('l'),
)
.switch(
"grapheme-clusters",
"measure word length in grapheme clusters (requires -l)",
Some('g'),
)
.switch(
"utf-8-bytes",
"measure word length in UTF-8 bytes (default; requires -l; non-ASCII chars are length 2+)",
Some('b'),
)
}
fn usage(&self) -> &str {
"Split a string's words into separate rows"
}
fn search_terms(&self) -> Vec<&str> {
vec!["separate", "divide"]
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Split the string's words into separate rows",
example: "'hello world' | split words",
result: Some(Value::List {
vals: vec![Value::test_string("hello"), Value::test_string("world")],
span: Span::test_data(),
}),
},
Example {
description:
"Split the string's words, of at least 3 characters, into separate rows",
example: "'hello to the world' | split words -l 3",
result: Some(Value::List {
vals: vec![
Value::test_string("hello"),
Value::test_string("the"),
Value::test_string("world"),
],
span: Span::test_data(),
}),
},
Example {
description:
"A real-world example of splitting words",
example: "http get https://www.gutenberg.org/files/11/11-0.txt | str downcase | split words -l 2 | uniq -c | sort-by count --reverse | first 10",
result: None,
},
]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
split_words(engine_state, stack, call, input)
}
}
fn split_words(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let span = call.head;
let word_length: Option<usize> = call.get_flag(engine_state, stack, "min-word-length")?;
if matches!(word_length, None) {
if call.has_flag("grapheme-clusters") {
return Err(ShellError::IncompatibleParametersSingle(
"--grapheme-clusters (-g) requires --min-word-length (-l)".to_string(),
span,
));
}
if call.has_flag("utf-8-bytes") {
return Err(ShellError::IncompatibleParametersSingle(
"--utf-8-bytes (-b) requires --min-word-length (-l)".to_string(),
span,
));
}
}
let graphemes = grapheme_flags(call)?;
input.flat_map(
move |x| split_words_helper(&x, word_length, span, graphemes),
engine_state.ctrlc.clone(),
)
}
fn split_words_helper(
v: &Value,
word_length: Option<usize>,
span: Span,
graphemes: bool,
) -> Vec<Value> {
let regex_replace = Regex::new(r"[^\p{L}\']").expect("regular expression error");
match v.span() {
Ok(v_span) => {
if let Ok(s) = v.as_string() {
let replaced_string = regex_replace.replace_all(&s, " ").to_string();
replaced_string
.split(' ')
.filter_map(|s| {
if s.trim() != "" {
if let Some(len) = word_length {
if if graphemes {
s.graphemes(true).count()
} else {
s.len()
} >= len
{
Some(Value::string(s, v_span))
} else {
None
}
} else {
Some(Value::string(s, v_span))
}
} else {
None
}
})
.collect::<Vec<Value>>()
} else {
vec![Value::Error {
error: ShellError::PipelineMismatch("string".into(), span, v_span),
}]
}
}
Err(error) => vec![Value::Error { error }],
}
}
#[cfg(test)]
mod test {
use super::*;
use nu_test_support::{nu, pipeline};
#[test]
fn test_incompat_flags() {
let out = nu!(cwd: ".", pipeline("'a' | split words -bg -l 2"));
assert!(out.err.contains("incompatible_parameters"));
}
#[test]
fn test_incompat_flags_2() {
let out = nu!(cwd: ".", pipeline("'a' | split words -g"));
assert!(out.err.contains("incompatible_parameters"));
}
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}