use crate::{grapheme_flags, grapheme_flags_const};
use fancy_regex::Regex;
use nu_engine::command_prelude::*;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone)]
pub struct SplitWords;
impl Command for SplitWords {
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))),
(
Type::List(Box::new(Type::String)),
Type::List(Box::new(Type::List(Box::new(Type::String))))
),
])
.allow_variants_without_examples(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 description(&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(
vec![Value::test_string("hello"), Value::test_string("world")],
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 --min-word-length 3",
result: Some(Value::list(
vec![
Value::test_string("hello"),
Value::test_string("the"),
Value::test_string("world"),
],
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 --min-word-length 2 | uniq --count | sort-by count --reverse | first 10",
result: None,
},
]
}
fn is_const(&self) -> bool {
true
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let word_length: Option<usize> = call.get_flag(engine_state, stack, "min-word-length")?;
let has_grapheme = call.has_flag(engine_state, stack, "grapheme-clusters")?;
let has_utf8 = call.has_flag(engine_state, stack, "utf-8-bytes")?;
let graphemes = grapheme_flags(engine_state, stack, call)?;
let args = Arguments {
word_length,
has_grapheme,
has_utf8,
graphemes,
};
split_words(engine_state, call, input, args)
}
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
let word_length: Option<usize> = call.get_flag_const(working_set, "min-word-length")?;
let has_grapheme = call.has_flag_const(working_set, "grapheme-clusters")?;
let has_utf8 = call.has_flag_const(working_set, "utf-8-bytes")?;
let graphemes = grapheme_flags_const(working_set, call)?;
let args = Arguments {
word_length,
has_grapheme,
has_utf8,
graphemes,
};
split_words(working_set.permanent(), call, input, args)
}
}
struct Arguments {
word_length: Option<usize>,
has_grapheme: bool,
has_utf8: bool,
graphemes: bool,
}
fn split_words(
engine_state: &EngineState,
call: &Call,
input: PipelineData,
args: Arguments,
) -> Result<PipelineData, ShellError> {
let span = call.head;
if args.word_length.is_none() {
if args.has_grapheme {
return Err(ShellError::IncompatibleParametersSingle {
msg: "--grapheme-clusters (-g) requires --min-word-length (-l)".to_string(),
span,
});
}
if args.has_utf8 {
return Err(ShellError::IncompatibleParametersSingle {
msg: "--utf-8-bytes (-b) requires --min-word-length (-l)".to_string(),
span,
});
}
}
input.map(
move |x| split_words_helper(&x, args.word_length, span, args.graphemes),
engine_state.signals(),
)
}
fn split_words_helper(v: &Value, word_length: Option<usize>, span: Span, graphemes: bool) -> Value {
let regex_replace = Regex::new(r"[^\p{L}\p{N}\']").expect("regular expression error");
let v_span = v.span();
match v {
Value::Error { error, .. } => Value::error(*error.clone(), v_span),
v => {
let v_span = v.span();
if let Ok(s) = v.as_str() {
let replaced_string = regex_replace.replace_all(s, " ").to_string();
let words = 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>>();
Value::list(words, v_span)
} else {
Value::error(
ShellError::OnlySupportsThisInputType {
exp_input_type: "string".into(),
wrong_type: v.get_type().to_string(),
dst_span: span,
src_span: v_span,
},
v_span,
)
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use nu_test_support::nu;
#[test]
fn test_incompat_flags() {
let out = nu!("'a' | split words -bg -l 2");
assert!(out.err.contains("incompatible_parameters"));
}
#[test]
fn test_incompat_flags_2() {
let out = nu!("'a' | split words -g");
assert!(out.err.contains("incompatible_parameters"));
}
#[test]
fn test_examples() -> nu_test_support::Result {
nu_test_support::test().examples(SplitWords)
}
#[test]
fn mixed_letter_number() {
let actual = nu!(r#"echo "a1 b2 c3" | split words | str join ','"#);
assert_eq!(actual.out, "a1,b2,c3");
}
}