Validation baseline.

This commit is contained in:
Andrés N. Robalino 2019-07-28 18:34:37 -05:00
parent 59dec999b8
commit 7c4706ee50
3 changed files with 68 additions and 4 deletions

View File

@ -4,6 +4,15 @@ use std::io;
pub trait Plugin {
fn config(&mut self) -> Result<CommandConfig, ShellError>;
#[allow(unused)]
fn is_valid(&self) -> bool {
true
}
#[allow(unused)]
fn log_error(&mut self, message: &str) { }
#[allow(unused)]
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![])

View File

@ -1,11 +1,12 @@
use indexmap::IndexMap;
use nu::{
serve_plugin, CallInfo, CommandConfig, NamedType, Plugin, PositionalType, Primitive,
ReturnSuccess, ReturnValue, ShellError, Spanned, SpannedItem, Value,
ReturnSuccess, ReturnValue, ShellError, Spanned, Value,
};
struct Str {
field: Option<String>,
error: Option<String>,
downcase: bool,
upcase: bool,
}
@ -14,11 +15,32 @@ impl Str {
fn new() -> Str {
Str {
field: None,
error: None,
downcase: false,
upcase: false,
}
}
fn to_downcase(&mut self) {
self.downcase = true;
if !self.is_valid() {
self.log_error("can only apply one")
}
}
fn to_upcase(&mut self) {
self.upcase = true;
if !self.is_valid() {
self.log_error("can only apply one")
}
}
fn usage(&self) -> &'static str {
"Usage: str [--downcase, --upcase]"
}
fn strutils(
&self,
value: Spanned<Value>,
@ -84,11 +106,22 @@ impl Plugin for Str {
rest_positional: true,
})
}
fn is_valid(&self) -> bool {
(self.downcase && !self.upcase) || (!self.downcase && self.upcase)
}
fn log_error(&mut self, message: &str) {
self.error = Some(message.to_string());
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if call_info.args.has("downcase") {
self.downcase = true;
} else if call_info.args.has("upcase") {
self.upcase = true;
self.to_downcase();
}
if call_info.args.has("upcase") {
self.to_upcase();
}
if let Some(args) = call_info.args.positional {
@ -110,6 +143,17 @@ impl Plugin for Str {
}
}
match &self.error {
Some(reason) => {
return Err(ShellError::string(format!(
"{}: {}",
reason,
self.usage()
)))
}
None => {}
}
Ok(vec![])
}

View File

@ -65,6 +65,17 @@ fn can_split_by_column() {
assert_eq!(output, "name");
}
#[test]
fn str_can_only_apply_one() {
nu_error!(
output,
cwd("tests/fixtures/formats"),
"open caco3_plastics.csv | first 1 | str origin --downcase --upcase"
);
assert!(output.contains("Usage: str [--downcase, --upcase]"));
}
#[test]
fn str_downcases() {
nu!(