Merge pull request #268 from androbtech/additive-nushellacturing

Additive nushellacturing.
This commit is contained in:
Jonathan Turner 2019-08-11 14:03:15 +12:00 committed by GitHub
commit 72aa433802
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 574 additions and 155 deletions

View file

@ -1,62 +1,94 @@
use indexmap::IndexMap;
use nu::{
serve_plugin, CallInfo, NamedType, Plugin, PositionalType, Primitive, ReturnSuccess,
serve_plugin, CallInfo, NamedType, Plugin, Primitive, ReturnSuccess,
ReturnValue, ShellError, Signature, Tagged, TaggedItem, Value,
};
enum Action {
SemVerAction(SemVerAction),
Default,
}
pub enum SemVerAction {
Major,
Minor,
Patch,
}
struct Inc {
field: Option<String>,
major: bool,
minor: bool,
patch: bool,
error: Option<String>,
action: Option<Action>,
}
impl Inc {
fn new() -> Inc {
Inc {
field: None,
major: false,
minor: false,
patch: false,
error: None,
action: None,
}
}
fn inc(
&self,
value: Tagged<Value>,
field: &Option<String>,
) -> Result<Tagged<Value>, ShellError> {
fn apply(&self, input: &str) -> Value {
match &self.action {
Some(Action::SemVerAction(act_on)) => {
let ver = semver::Version::parse(&input);
if ver.is_err() {
return Value::string(input.to_string());
}
let mut ver = ver.unwrap();
match act_on {
SemVerAction::Major => ver.increment_major(),
SemVerAction::Minor => ver.increment_minor(),
SemVerAction::Patch => ver.increment_patch(),
}
Value::string(ver.to_string())
}
Some(Action::Default) | None => match input.parse::<u64>() {
Ok(v) => Value::string(format!("{}", v + 1)),
Err(_) => Value::string(input),
},
}
}
fn for_semver(&mut self, part: SemVerAction) {
if self.permit() {
self.action = Some(Action::SemVerAction(part));
} else {
self.log_error("can only apply one");
}
}
fn permit(&mut self) -> bool {
self.action.is_none()
}
fn log_error(&mut self, message: &str) {
self.error = Some(message.to_string());
}
fn usage(&self) -> &'static str {
"Usage: inc field [--major|--minor|--patch]"
}
fn inc(&self, value: Tagged<Value>) -> Result<Tagged<Value>, ShellError> {
match value.item {
Value::Primitive(Primitive::Int(i)) => Ok(Value::int(i + 1).tagged(value.tag())),
Value::Primitive(Primitive::Bytes(b)) => {
Ok(Value::bytes(b + 1 as u64).tagged(value.tag()))
}
Value::Primitive(Primitive::String(ref s)) => {
if let Ok(i) = s.parse::<u64>() {
Ok(Tagged::from_item(
Value::string(format!("{}", i + 1)),
value.tag(),
))
} else if let Ok(mut ver) = semver::Version::parse(&s) {
if self.major {
ver.increment_major();
} else if self.minor {
ver.increment_minor();
} else {
self.patch;
ver.increment_patch();
}
Ok(Tagged::from_item(
Value::string(ver.to_string()),
value.tag(),
))
} else {
Err(ShellError::string("string could not be incremented"))
}
Ok(Tagged::from_item(self.apply(&s), value.tag()))
}
Value::Object(_) => match field {
Some(f) => {
Value::Object(_) => match self.field {
Some(ref f) => {
let replacement = match value.item.get_data_by_path(value.tag(), f) {
Some(result) => self.inc(result.map(|x| x.clone()), &None)?,
Some(result) => self.inc(result.map(|x| x.clone()))?,
None => {
return Err(ShellError::string("inc could not find field to replace"))
}
@ -92,7 +124,7 @@ impl Plugin for Inc {
Ok(Signature {
name: "inc".to_string(),
positional: vec![PositionalType::optional_any("Field")],
positional: vec![],
is_filter: true,
named,
rest_positional: true,
@ -100,13 +132,13 @@ impl Plugin for Inc {
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if call_info.args.has("major") {
self.major = true;
self.for_semver(SemVerAction::Major);
}
if call_info.args.has("minor") {
self.minor = true;
self.for_semver(SemVerAction::Minor);
}
if call_info.args.has("patch") {
self.patch = true;
self.for_semver(SemVerAction::Patch);
}
if let Some(args) = call_info.args.positional {
@ -128,14 +160,249 @@ impl Plugin for Inc {
}
}
Ok(vec![])
if self.action.is_none() {
self.action = Some(Action::Default);
}
match &self.error {
Some(reason) => {
return Err(ShellError::string(format!("{}: {}", reason, self.usage())))
}
None => Ok(vec![]),
}
}
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(self.inc(input, &self.field)?)])
Ok(vec![ReturnSuccess::value(self.inc(input)?)])
}
}
fn main() {
serve_plugin(&mut Inc::new());
}
#[cfg(test)]
mod tests {
use super::{Inc, SemVerAction};
use indexmap::IndexMap;
use nu::{
CallInfo, EvaluatedArgs, Plugin, ReturnSuccess, SourceMap, Span, Tag, Tagged, TaggedDictBuilder,
TaggedItem, Value,
};
struct CallStub {
positionals: Vec<Tagged<Value>>,
flags: IndexMap<String, Tagged<Value>>,
}
impl CallStub {
fn new() -> CallStub {
CallStub {
positionals: vec![],
flags: indexmap::IndexMap::new(),
}
}
fn with_long_flag(&mut self, name: &str) -> &mut Self {
self.flags.insert(
name.to_string(),
Value::boolean(true).simple_spanned(Span::unknown()),
);
self
}
fn with_parameter(&mut self, name: &str) -> &mut Self {
self.positionals
.push(Value::string(name.to_string()).simple_spanned(Span::unknown()));
self
}
fn create(&self) -> CallInfo {
CallInfo {
args: EvaluatedArgs::new(Some(self.positionals.clone()), Some(self.flags.clone())),
source_map: SourceMap::new(),
name_span: Span::unknown(),
}
}
}
fn cargo_sample_record(with_version: &str) -> Tagged<Value> {
let mut package = TaggedDictBuilder::new(Tag::unknown());
package.insert("version", Value::string(with_version));
package.into_tagged_value()
}
#[test]
fn inc_plugin_configuration_flags_wired() {
let mut plugin = Inc::new();
let configured = plugin.config().unwrap();
for action_flag in &["major", "minor", "patch"] {
assert!(configured.named.get(*action_flag).is_some());
}
}
#[test]
fn inc_plugin_accepts_major() {
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(CallStub::new().with_long_flag("major").create())
.is_ok());
assert!(plugin.action.is_some());
}
#[test]
fn inc_plugin_accepts_minor() {
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(CallStub::new().with_long_flag("minor").create())
.is_ok());
assert!(plugin.action.is_some());
}
#[test]
fn inc_plugin_accepts_patch() {
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(CallStub::new().with_long_flag("patch").create())
.is_ok());
assert!(plugin.action.is_some());
}
#[test]
fn inc_plugin_accepts_only_one_action() {
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_long_flag("major")
.with_long_flag("minor")
.create(),
)
.is_err());
assert_eq!(plugin.error, Some("can only apply one".to_string()));
}
#[test]
fn inc_plugin_accepts_field() {
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(CallStub::new().with_parameter("package.version").create())
.is_ok());
assert_eq!(plugin.field, Some("package.version".to_string()));
}
#[test]
fn incs_major() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Major);
assert_eq!(inc.apply("0.1.3"), Value::string("1.0.0"));
}
#[test]
fn incs_minor() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Minor);
assert_eq!(inc.apply("0.1.3"), Value::string("0.2.0"));
}
#[test]
fn incs_patch() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Patch);
assert_eq!(inc.apply("0.1.3"), Value::string("0.1.4"));
}
#[test]
fn inc_plugin_applies_major() {
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_long_flag("major")
.with_parameter("version")
.create()
)
.is_ok());
let subject = cargo_sample_record("0.1.3");
let output = plugin.filter(subject).unwrap();
match output[0].as_ref().unwrap() {
ReturnSuccess::Value(Tagged {
item: Value::Object(o),
..
}) => assert_eq!(
*o.get_data(&String::from("version")).borrow(),
Value::string(String::from("1.0.0"))
),
_ => {}
}
}
#[test]
fn inc_plugin_applies_minor() {
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_long_flag("minor")
.with_parameter("version")
.create()
)
.is_ok());
let subject = cargo_sample_record("0.1.3");
let output = plugin.filter(subject).unwrap();
match output[0].as_ref().unwrap() {
ReturnSuccess::Value(Tagged {
item: Value::Object(o),
..
}) => assert_eq!(
*o.get_data(&String::from("version")).borrow(),
Value::string(String::from("0.2.0"))
),
_ => {}
}
}
#[test]
fn inc_plugin_applies_patch() {
let field = String::from("version");
let mut plugin = Inc::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_long_flag("patch")
.with_parameter(&field)
.create()
)
.is_ok());
let subject = cargo_sample_record("0.1.3");
let output = plugin.filter(subject).unwrap();
match output[0].as_ref().unwrap() {
ReturnSuccess::Value(Tagged {
item: Value::Object(o),
..
}) => assert_eq!(
*o.get_data(&field).borrow(),
Value::string(String::from("0.1.4"))
),
_ => {}
}
}
}

View file

@ -1,6 +1,6 @@
use indexmap::IndexMap;
use nu::{
serve_plugin, CallInfo, NamedType, Plugin, PositionalType, Primitive, ReturnSuccess,
serve_plugin, CallInfo, NamedType, Plugin, Primitive, ReturnSuccess,
ReturnValue, ShellError, Signature, Tagged, Value,
};
@ -79,19 +79,15 @@ impl Str {
}
impl Str {
fn strutils(
&self,
value: Tagged<Value>,
field: &Option<String>,
) -> Result<Tagged<Value>, ShellError> {
fn strutils(&self, value: Tagged<Value>) -> Result<Tagged<Value>, ShellError> {
match value.item {
Value::Primitive(Primitive::String(ref s)) => {
Ok(Tagged::from_item(self.apply(&s), value.tag()))
}
Value::Object(_) => match field {
Some(f) => {
Value::Object(_) => match self.field {
Some(ref f) => {
let replacement = match value.item.get_data_by_path(value.tag(), f) {
Some(result) => self.strutils(result.map(|x| x.clone()), &None)?,
Some(result) => self.strutils(result.map(|x| x.clone()))?,
None => {
return Err(ShellError::string("str could not find field to replace"))
}
@ -129,7 +125,7 @@ impl Plugin for Str {
Ok(Signature {
name: "str".to_string(),
positional: vec![PositionalType::optional_any("Field")],
positional: vec![],
is_filter: true,
named,
rest_positional: true,
@ -177,9 +173,7 @@ impl Plugin for Str {
}
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(
self.strutils(input, &self.field)?,
)])
Ok(vec![ReturnSuccess::value(self.strutils(input)?)])
}
}
@ -224,11 +218,11 @@ mod tests {
self
}
fn create(&self, name_span: Span) -> CallInfo {
fn create(&self) -> CallInfo {
CallInfo {
args: EvaluatedArgs::new(Some(self.positionals.clone()), Some(self.flags.clone())),
source_map: SourceMap::new(),
name_span,
name_span: Span::unknown(),
}
}
}
@ -255,11 +249,7 @@ mod tests {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_long_flag("downcase")
.create(Span::unknown())
)
.begin_filter(CallStub::new().with_long_flag("downcase").create())
.is_ok());
assert!(plugin.action.is_some());
}
@ -269,11 +259,7 @@ mod tests {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_long_flag("upcase")
.create(Span::unknown())
)
.begin_filter(CallStub::new().with_long_flag("upcase").create())
.is_ok());
assert!(plugin.action.is_some());
}
@ -283,11 +269,7 @@ mod tests {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_long_flag("to-int")
.create(Span::unknown())
)
.begin_filter(CallStub::new().with_long_flag("to-int").create())
.is_ok());
assert!(plugin.action.is_some());
}
@ -300,7 +282,7 @@ mod tests {
.begin_filter(
CallStub::new()
.with_parameter("package.description")
.create(Span::unknown())
.create()
)
.is_ok());
@ -317,7 +299,7 @@ mod tests {
.with_long_flag("upcase")
.with_long_flag("downcase")
.with_long_flag("to-int")
.create(Span::unknown()),
.create(),
)
.is_err());
assert_eq!(plugin.error, Some("can only apply one".to_string()));
@ -353,7 +335,7 @@ mod tests {
CallStub::new()
.with_long_flag("upcase")
.with_parameter("name")
.create(Span::unknown())
.create()
)
.is_ok());
@ -381,7 +363,7 @@ mod tests {
CallStub::new()
.with_long_flag("downcase")
.with_parameter("name")
.create(Span::unknown())
.create()
)
.is_ok());
@ -409,7 +391,7 @@ mod tests {
CallStub::new()
.with_long_flag("to-int")
.with_parameter("Nu_birthday")
.create(Span::unknown())
.create()
)
.is_ok());

View file

@ -146,7 +146,7 @@ fn deep_copies_with_recursive_flag() {
}
#[test]
fn copies_using_globs() {
fn copies_using_path_with_wildcard() {
let sandbox = Playground::setup_for("cp_test_6").test_dir_name();
let expected_copies_path = format!("{}/{}", Playground::root(), sandbox);
@ -167,3 +167,26 @@ fn copies_using_globs() {
PathBuf::from(&expected_copies_path)
));
}
#[test]
fn copies_using_a_glob() {
let sandbox = Playground::setup_for("cp_test_7").test_dir_name();
let expected_copies_path = format!("{}/{}", Playground::root(), sandbox);
nu!(
_output,
cwd("tests/fixtures/formats"),
"cp * ../nuplayground/cp_test_7"
);
assert!(h::files_exist_at(
vec![
Path::new("caco3_plastics.csv"),
Path::new("cargo_sample.toml"),
Path::new("jonathan.xml"),
Path::new("sample.ini"),
Path::new("sgml_description.json")
],
PathBuf::from(&expected_copies_path)
));
}

136
tests/filter_inc_tests.rs Normal file
View file

@ -0,0 +1,136 @@
mod helpers;
use h::{in_directory as cwd, Playground, Stub::*};
use helpers as h;
#[test]
fn can_only_apply_one() {
nu_error!(
output,
cwd("tests/fixtures/formats"),
"open cargo_sample.toml | first 1 | inc package.version --major --minor"
);
assert!(output.contains("Usage: inc field [--major|--minor|--patch]"));
}
#[test]
fn regular_field_by_one() {
Playground::setup_for("plugin_inc_test_1")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
edition = "2018"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_inc_test_1"),
"open sample.toml | inc package.edition | get package.edition | echo $it"
);
assert_eq!(output, "2019");
}
#[test]
fn by_one_without_passing_field() {
Playground::setup_for("plugin_inc_test_2")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
contributors = "2"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_inc_test_2"),
"open sample.toml | get package.contributors | inc | echo $it"
);
assert_eq!(output, "3");
}
#[test]
fn semversion_major_inc() {
Playground::setup_for("plugin_inc_test_3")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_inc_test_3"),
"open sample.toml | inc package.version --major | get package.version | echo $it"
);
assert_eq!(output, "1.0.0");
}
#[test]
fn semversion_minor_inc() {
Playground::setup_for("plugin_inc_test_4")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_inc_test_4"),
"open sample.toml | inc package.version --minor | get package.version | echo $it"
);
assert_eq!(output, "0.2.0");
}
#[test]
fn semversion_patch_inc() {
Playground::setup_for("plugin_inc_test_5")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_inc_test_5"),
"open sample.toml | inc package.version --patch | get package.version | echo $it"
);
assert_eq!(output, "0.1.4");
}
#[test]
fn semversion_without_passing_field() {
Playground::setup_for("plugin_inc_test_6")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
version = "0.1.3"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_inc_test_6"),
"open sample.toml | get package.version | inc --patch | echo $it"
);
assert_eq!(output, "0.1.4");
}

87
tests/filter_str_tests.rs Normal file
View file

@ -0,0 +1,87 @@
mod helpers;
use h::{in_directory as cwd, Playground, Stub::*};
use helpers as h;
#[test]
fn 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 field [--downcase|--upcase|--to-int]"));
}
#[test]
fn acts_without_passing_field() {
Playground::setup_for("plugin_str_test_without_passing_field")
.with_files(vec![FileWithContent(
"sample.yml",
r#"
environment:
global:
PROJECT_NAME: nushell
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_str_test_without_passing_field"),
"open sample.yml | get environment.global.PROJECT_NAME | str --upcase | echo $it"
);
assert_eq!(output, "NUSHELL");
}
#[test]
fn downcases() {
Playground::setup_for("plugin_str_test_downcases")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[dependency]
name = "LIGHT"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_str_test_downcases"),
"open sample.toml | str dependency.name --downcase | get dependency.name | echo $it"
);
assert_eq!(output, "light");
}
#[test]
fn upcases() {
Playground::setup_for("plugin_str_test_upcases")
.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
name = "nushell"
"#,
)]);
nu!(
output,
cwd("tests/fixtures/nuplayground/plugin_str_test_upcases"),
"open sample.toml | str package.name --upcase | get package.name | echo $it"
);
assert_eq!(output, "NUSHELL");
}
#[test]
fn converts_to_int() {
nu!(
output,
cwd("tests/fixtures/formats"),
"open caco3_plastics.csv | first 1 | str tariff_item --to-int | where tariff_item == 2509000000 | get tariff_item | echo $it"
);
assert_eq!(output, "2509000000");
}

View file

@ -68,72 +68,6 @@ 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 field [--downcase|--upcase|--to-int]"));
}
#[test]
fn str_downcases() {
nu!(
output,
cwd("tests/fixtures/formats"),
"open caco3_plastics.csv | first 1 | str origin --downcase | get origin | echo $it"
);
assert_eq!(output, "spain");
}
#[test]
fn str_upcases() {
nu!(
output,
cwd("tests/fixtures/formats"),
"open appveyor.yml | str environment.global.PROJECT_NAME --upcase | get environment.global.PROJECT_NAME | echo $it"
);
assert_eq!(output, "NUSHELL");
}
#[test]
fn str_converts_to_int() {
nu!(
output,
cwd("tests/fixtures/formats"),
"open caco3_plastics.csv | first 1 | str tariff_item --to-int | where tariff_item == 2509000000 | get tariff_item | echo $it"
);
assert_eq!(output, "2509000000");
}
#[test]
fn can_inc_version() {
nu!(
output,
cwd("tests/fixtures/formats"),
"open cargo_sample.toml | inc package.version --minor | get package.version | echo $it"
);
assert_eq!(output, "0.2.0");
}
#[test]
fn can_inc_field() {
nu!(
output,
cwd("tests/fixtures/formats"),
"open cargo_sample.toml | inc package.edition | get package.edition | echo $it"
);
assert_eq!(output, "2019");
}
#[test]
fn can_sum() {
nu!(
@ -144,6 +78,7 @@ fn can_sum() {
assert_eq!(output, "203")
}
#[test]
fn can_filter_by_unit_size_comparison() {
nu!(

View file

@ -23,17 +23,6 @@ fn external_has_correct_quotes() {
assert_eq!(output, r#""hello world""#);
}
#[test]
fn inc_plugin() {
nu!(
output,
cwd("tests/fixtures/formats"),
"open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.Height | inc | echo $it"
);
assert_eq!(output, "11");
}
#[test]
fn add_plugin() {
nu!(output,