Str plugin promoted to built-in Nu command.

This commit is contained in:
Andrés N. Robalino
2020-05-26 17:19:18 -05:00
parent 0a6692ac44
commit fe01a223a4
33 changed files with 2112 additions and 1331 deletions

View File

@ -0,0 +1,144 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::Tag;
use nu_value_ext::ValueExt;
#[derive(Deserialize)]
struct Arguments {
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str capitalize"
}
fn signature(&self) -> Signature {
Signature::build("str capitalize").rest(
SyntaxShape::ColumnPath,
"optionally capitalize text by column paths",
)
}
fn usage(&self) -> &str {
"capitalizes text"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Capitalize contents",
example: "echo 'good day' | str capitalize",
result: Some(vec![Value::from("Good day")]),
}]
}
}
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { rest }, mut input) = args.process(&registry).await?;
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
let mut capitalized = String::new();
for (idx, character) in s.chars().enumerate() {
let out = if idx == 0 {
character.to_uppercase().to_string()
} else {
character.to_lowercase().to_string()
};
capitalized.push_str(&out);
}
Ok(UntaggedValue::string(capitalized).into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, SubCommand};
use nu_plugin::test_helpers::value::string;
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn capitalizes() {
let word = string("andres");
let expected = string("Andres");
let actual = action(&word, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,51 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, UntaggedValue};
pub struct Command;
impl WholeStreamCommand for Command {
fn name(&self) -> &str {
"str"
}
fn signature(&self) -> Signature {
Signature::build("str").rest(
SyntaxShape::ColumnPath,
"optionally convert by column paths",
)
}
fn usage(&self) -> &str {
"Apply string function."
}
fn run(
&self,
_args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
yield Ok(ReturnSuccess::Value(
UntaggedValue::string(crate::commands::help::get_help(&Command, &registry))
.into_value(Tag::unknown()),
));
};
Ok(stream.to_output_stream())
}
}
#[cfg(test)]
mod tests {
use super::Command;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(Command {})
}
}

View File

@ -0,0 +1,132 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::Tag;
use nu_value_ext::ValueExt;
#[derive(Deserialize)]
struct Arguments {
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str downcase"
}
fn signature(&self) -> Signature {
Signature::build("str downcase").rest(
SyntaxShape::ColumnPath,
"optionally downcase text by column paths",
)
}
fn usage(&self) -> &str {
"downcases text"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Downcase contents",
example: "echo 'NU' | str downcase",
result: Some(vec![Value::from("nu")]),
}]
}
}
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { rest }, mut input) = args.process(&registry).await?;
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
Ok(UntaggedValue::string(s.to_ascii_lowercase()).into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, SubCommand};
use nu_plugin::test_helpers::value::string;
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn downcases() {
let word = string("ANDRES");
let expected = string("andres");
let actual = action(&word, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,159 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::{Tag, Tagged};
use nu_value_ext::ValueExt;
use regex::Regex;
#[derive(Deserialize)]
struct Arguments {
find: Tagged<String>,
replace: Tagged<String>,
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str find-replace"
}
fn signature(&self) -> Signature {
Signature::build("str find-replace")
.required("find", SyntaxShape::String, "the pattern to find")
.required("replace", SyntaxShape::String, "the replacement pattern")
.rest(
SyntaxShape::ColumnPath,
"optionally find and replace text by column paths",
)
}
fn usage(&self) -> &str {
"finds and replaces text"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Find and replace contents with capture group",
example: "echo 'my_library.rb' | str find-replace '(.+).rb' '$1.nu'",
result: Some(vec![Value::from("my_library.nu")]),
}]
}
}
#[derive(Clone)]
struct FindReplace(String, String);
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { find, replace, rest }, mut input) = args.process(&registry).await?;
let options = FindReplace(find.item, replace.item);
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, &options, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let options = options.clone();
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| {
action(old, &options, old.tag())
}));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, options: &FindReplace, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
let find = &options.0;
let replacement = &options.1;
let regex = Regex::new(find.as_str());
let out = match regex {
Ok(re) => UntaggedValue::string(re.replace(s, replacement.as_str()).to_owned()),
Err(_) => UntaggedValue::string(s),
};
Ok(out.into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, FindReplace, SubCommand};
use nu_plugin::test_helpers::value::string;
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn can_have_capture_groups() {
let word = string("Cargo.toml");
let expected = string("Carga.toml");
let find_replace_options = FindReplace("Cargo.(.+)".to_string(), "Carga.$1".to_string());
let actual = action(&word, &find_replace_options, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,23 @@
mod capitalize;
mod command;
mod downcase;
mod find_replace;
mod set;
mod substring;
mod to_datetime;
mod to_float;
mod to_integer;
mod trim;
mod upcase;
pub use capitalize::SubCommand as StrCapitalize;
pub use command::Command as Str;
pub use downcase::SubCommand as StrDowncase;
pub use find_replace::SubCommand as StrFindReplace;
pub use set::SubCommand as StrSet;
pub use substring::SubCommand as StrSubstring;
pub use to_datetime::SubCommand as StrToDatetime;
pub use to_float::SubCommand as StrToFloat;
pub use to_integer::SubCommand as StrToInteger;
pub use trim::SubCommand as StrTrim;
pub use upcase::SubCommand as StrUpcase;

View File

@ -0,0 +1,135 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{ColumnPath, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::{Tag, Tagged};
use nu_value_ext::ValueExt;
#[derive(Deserialize)]
struct Arguments {
replace: Tagged<String>,
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str set"
}
fn signature(&self) -> Signature {
Signature::build("str set")
.required("set", SyntaxShape::String, "the new string to set")
.rest(
SyntaxShape::ColumnPath,
"optionally set text by column paths",
)
}
fn usage(&self) -> &str {
"sets text"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Set contents with preferred string",
example: "echo 'good day' | str set 'good bye'",
result: Some(vec![Value::from("good bye")]),
},
Example {
description: "Set the contents on preferred column paths",
example: "open Cargo.toml | str set '255' package.version",
result: None,
},
]
}
}
#[derive(Clone)]
struct Replace(String);
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { replace, rest }, mut input) = args.process(&registry).await?;
let options = Replace(replace.item);
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, &options, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let options = options.clone();
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, &options, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(_input: &Value, options: &Replace, tag: impl Into<Tag>) -> Result<Value, ShellError> {
let replacement = &options.0;
Ok(UntaggedValue::string(replacement.as_str()).into_value(tag))
}
#[cfg(test)]
mod tests {
use super::{action, Replace, SubCommand};
use nu_plugin::test_helpers::value::string;
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn sets() {
let word = string("andres");
let expected = string("robalino");
let set_options = Replace(String::from("robalino"));
let actual = action(&word, &set_options, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,215 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::{Tag, Tagged};
use nu_value_ext::ValueExt;
use std::cmp;
#[derive(Deserialize)]
struct Arguments {
range: Tagged<String>,
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str substring"
}
fn signature(&self) -> Signature {
Signature::build("str substring")
.required(
"range",
SyntaxShape::String,
"the indexes to substring \"start, end\"",
)
.rest(
SyntaxShape::ColumnPath,
"optionally substring text by column paths",
)
}
fn usage(&self) -> &str {
"substrings text"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Get a substring from the text",
example: "echo 'good nushell' | str substring '5,12'",
result: Some(vec![Value::from("nushell")]),
},
Example {
description: "Get the remaining characters from a starting index",
example: "echo 'good nushell' | str substring '5,'",
result: Some(vec![Value::from("nushell")]),
},
Example {
description: "Get the characters from the beginning until ending index",
example: "echo 'good nushell' | str substring ',7'",
result: Some(vec![Value::from("good nu")]),
},
]
}
}
#[derive(Clone)]
struct Substring(usize, usize);
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let name = args.call_info.name_tag.clone();
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { range, rest }, mut input) = args.process(&registry).await?;
let v: Vec<&str> = range.item.split(',').collect();
let start = match v[0] {
"" => 0,
_ => v[0]
.trim()
.parse()
.map_err(|_| {
ShellError::labeled_error(
"could not perform substring",
"could not perform substring",
name.span,
)
})?
};
let end = match v[1] {
"" => usize::max_value(),
_ => v[1]
.trim()
.parse()
.map_err(|_| {
ShellError::labeled_error(
"could not perform substring",
"could not perform substring",
name.span,
)
})?
};
if start > end {
yield Err(ShellError::labeled_error(
"End must be greater than or equal to Start",
"End must be greater than or equal to Start",
name.span,
));
return;
}
let options = Substring(start, end);
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, &options, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let options = options.clone();
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, &options, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, options: &Substring, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
let start = options.0;
let end: usize = cmp::min(options.1, s.len());
let out = {
if start > s.len() - 1 {
UntaggedValue::string("")
} else {
UntaggedValue::string(
s.chars().skip(start).take(end - start).collect::<String>(),
)
}
};
Ok(out.into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, SubCommand, Substring};
use nu_plugin::test_helpers::value::string;
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn given_start_and_end_indexes() {
let word = string("andresS");
let expected = string("andres");
let substring_options = Substring(0, 6);
let actual = action(&word, &substring_options, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,169 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, ShellTypeName, Signature, SyntaxShape, UntaggedValue,
Value,
};
use nu_source::{Tag, Tagged};
use nu_value_ext::ValueExt;
use chrono::DateTime;
#[derive(Deserialize)]
struct Arguments {
format: Option<Tagged<String>>,
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str to-datetime"
}
fn signature(&self) -> Signature {
Signature::build("str to-datetime")
.named(
"format",
SyntaxShape::String,
"Specify date and time formatting",
Some('f'),
)
.rest(
SyntaxShape::ColumnPath,
"optionally convert text into datetime by column paths",
)
}
fn usage(&self) -> &str {
"converts text into datetime"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Convert to datetime",
example: "echo '16.11.1984 8:00 am +0000' | str to-datetime",
result: None,
}]
}
}
#[derive(Clone)]
struct DatetimeFormat(String);
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { format, rest }, mut input) = args.process(&registry).await?;
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
let options = if let Some(Tagged { item: fmt, tag }) = format {
DatetimeFormat(fmt)
} else {
DatetimeFormat(String::from("%d.%m.%Y %H:%M %P %z"))
};
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, &options, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let options = options.clone();
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, &options, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(
input: &Value,
options: &DatetimeFormat,
tag: impl Into<Tag>,
) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
let dt = &options.0;
let out = match DateTime::parse_from_str(s, dt) {
Ok(d) => UntaggedValue::date(d),
Err(_) => UntaggedValue::string(s),
};
Ok(out.into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, DatetimeFormat, SubCommand};
use nu_plugin::test_helpers::value::string;
use nu_protocol::{Primitive, UntaggedValue};
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn takes_a_date_format() {
let date_str = string("16.11.1984 8:00 am +0000");
let fmt_options = DatetimeFormat("%d.%m.%Y %H:%M %P %z".to_string());
let actual = action(&date_str, &fmt_options, Tag::unknown()).unwrap();
match actual.value {
UntaggedValue::Primitive(Primitive::Date(_)) => {}
_ => panic!("Didn't convert to date"),
}
}
}

View File

@ -0,0 +1,141 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::Tag;
use nu_value_ext::ValueExt;
use bigdecimal::BigDecimal;
use std::str::FromStr;
#[derive(Deserialize)]
struct Arguments {
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str to-float"
}
fn signature(&self) -> Signature {
Signature::build("str to-float").rest(
SyntaxShape::ColumnPath,
"optionally convert text into float by column paths",
)
}
fn usage(&self) -> &str {
"converts text into float"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Convert to float",
example: "echo '3.1415' | str to-float",
result: None,
}]
}
}
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { rest }, mut input) = args.process(&registry).await?;
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
let other = s.trim();
let out = match BigDecimal::from_str(other) {
Ok(v) => UntaggedValue::decimal(v),
Err(_) => UntaggedValue::string(s),
};
Ok(out.into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, SubCommand};
use nu_plugin::test_helpers::value::{decimal, string};
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
#[allow(clippy::approx_constant)]
fn turns_to_integer() {
let word = string("3.1415");
let expected = decimal(3.1415);
let actual = action(&word, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,140 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::Tag;
use nu_value_ext::ValueExt;
use num_bigint::BigInt;
use std::str::FromStr;
#[derive(Deserialize)]
struct Arguments {
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str to-int"
}
fn signature(&self) -> Signature {
Signature::build("str to-int").rest(
SyntaxShape::ColumnPath,
"optionally convert text into integer by column paths",
)
}
fn usage(&self) -> &str {
"converts text into integer"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Convert to an integer",
example: "echo '255' | str to-int",
result: None,
}]
}
}
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { rest }, mut input) = args.process(&registry).await?;
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
let other = s.trim();
let out = match BigInt::from_str(other) {
Ok(v) => UntaggedValue::int(v),
Err(_) => UntaggedValue::string(s),
};
Ok(out.into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, SubCommand};
use nu_plugin::test_helpers::value::{int, string};
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn turns_to_integer() {
let word = string("10");
let expected = int(10);
let actual = action(&word, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,132 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::Tag;
use nu_value_ext::ValueExt;
#[derive(Deserialize)]
struct Arguments {
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str trim"
}
fn signature(&self) -> Signature {
Signature::build("str trim").rest(
SyntaxShape::ColumnPath,
"optionally trim text by column paths",
)
}
fn usage(&self) -> &str {
"trims text"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Trim contents",
example: "echo 'Nu shell ' | str trim",
result: Some(vec![Value::from("Nu shell")]),
}]
}
}
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { rest }, mut input) = args.process(&registry).await?;
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
Ok(UntaggedValue::string(s.trim()).into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, SubCommand};
use nu_plugin::test_helpers::value::string;
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn trims() {
let word = string("andres ");
let expected = string("andres");
let actual = action(&word, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}

View File

@ -0,0 +1,132 @@
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::ShellTypeName;
use nu_protocol::{
ColumnPath, Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::Tag;
use nu_value_ext::ValueExt;
#[derive(Deserialize)]
struct Arguments {
rest: Vec<ColumnPath>,
}
pub struct SubCommand;
impl WholeStreamCommand for SubCommand {
fn name(&self) -> &str {
"str upcase"
}
fn signature(&self) -> Signature {
Signature::build("str upcase").rest(
SyntaxShape::ColumnPath,
"optionally upcase text by column paths",
)
}
fn usage(&self) -> &str {
"upcases text"
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
operate(args, registry)
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Upcase contents",
example: "echo 'nu' | str upcase",
result: Some(vec![Value::from("NU")]),
}]
}
}
fn operate(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (Arguments { rest }, mut input) = args.process(&registry).await?;
let column_paths: Vec<_> = rest.iter().map(|x| x.clone()).collect();
while let Some(v) = input.next().await {
if column_paths.is_empty() {
match action(&v, v.tag()) {
Ok(out) => yield ReturnSuccess::value(out),
Err(err) => {
yield Err(err);
return;
}
}
} else {
let mut ret = v.clone();
for path in &column_paths {
let swapping = ret.swap_data_by_column_path(path, Box::new(move |old| action(old, old.tag())));
match swapping {
Ok(new_value) => {
ret = new_value;
}
Err(err) => {
yield Err(err);
return;
}
}
}
yield ReturnSuccess::value(ret);
}
}
};
Ok(stream.to_output_stream())
}
fn action(input: &Value, tag: impl Into<Tag>) -> Result<Value, ShellError> {
match &input.value {
UntaggedValue::Primitive(Primitive::Line(s))
| UntaggedValue::Primitive(Primitive::String(s)) => {
Ok(UntaggedValue::string(s.to_ascii_uppercase()).into_value(tag))
}
other => {
let got = format!("got {}", other.type_name());
Err(ShellError::labeled_error(
"value is not string",
got,
tag.into().span,
))
}
}
}
#[cfg(test)]
mod tests {
use super::{action, SubCommand};
use nu_plugin::test_helpers::value::string;
use nu_source::Tag;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(SubCommand {})
}
#[test]
fn upcases() {
let word = string("andres");
let expected = string("ANDRES");
let actual = action(&word, Tag::unknown()).unwrap();
assert_eq!(actual, expected);
}
}