Inc refactoring, Value helper test method extractions, and more integration helpers. (#1135)

* Manifests check. Ignore doctests for now.

* We continue with refactorings towards the separation of concerns between
crates. `nu_plugin_inc` and `nu_plugin_str` common test helpers usage
has been refactored into `nu-plugin` value test helpers.

Inc also uses the new API for integration tests.
This commit is contained in:
Andrés N. Robalino 2019-12-29 00:17:24 -05:00 committed by GitHub
parent 21e508009f
commit 0615adac94
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
34 changed files with 527 additions and 1031 deletions

3
Cargo.lock generated
View File

@ -1986,7 +1986,6 @@ dependencies = [
"roxmltree",
"rusqlite",
"rustyline",
"semver",
"serde 1.0.103",
"serde-hjson 0.9.1",
"serde_bytes",
@ -2215,7 +2214,6 @@ dependencies = [
name = "nu_plugin_inc"
version = "0.7.0"
dependencies = [
"indexmap",
"nu-build",
"nu-errors",
"nu-plugin",
@ -2275,7 +2273,6 @@ dependencies = [
name = "nu_plugin_str"
version = "0.7.0"
dependencies = [
"indexmap",
"nu-build",
"nu-errors",
"nu-plugin",

View File

@ -134,7 +134,6 @@ onig_sys = {version = "=69.1.0", optional = true }
crossterm = {version = "0.10.2", optional = true}
futures-timer = {version = "1.0.2", optional = true}
url = {version = "2.1.0", optional = true}
semver = {version = "0.9.0", optional = true}
[features]
default = ["sys", "ps", "textview", "inc", "str"]
@ -144,7 +143,7 @@ stable = ["sys", "ps", "textview", "inc", "str", "starship-prompt", "binaryview"
sys = ["heim", "battery"]
ps = ["heim", "futures-timer"]
textview = ["crossterm", "syntect", "onig_sys", "url"]
inc = ["semver"]
inc = ["nu_plugin_inc"]
str = ["nu_plugin_str"]
# Stable
@ -173,6 +172,7 @@ nu-build = { version = "0.7.0", path = "./crates/nu-build" }
[lib]
name = "nu"
doctest = false
path = "src/lib.rs"
# Core plugins that ship with `cargo install nu` by default

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "Core build system for nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
serde = { version = "1.0.103", features = ["derive"] }

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "Core error subsystem for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-source = { path = "../nu-source", version = "0.7.0" }

View File

@ -1,12 +1,13 @@
[package]
name = "nu-macros"
version = "0.7.0"
authors = ["Yehuda Katz <wycats@gmail.com>"]
authors = ["Yehuda Katz <wycats@gmail.com>", "Jonathan Turner <jonathan.d.turner@gmail.com>", "Andrés N. Robalino <andres@androbtech.com>"]
edition = "2018"
description = "Core macros for building Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "Core parser used in Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-errors = { path = "../nu-errors", version = "0.7.0" }

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "Nushell Plugin"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -1,9 +1,8 @@
use crate::Plugin;
use indexmap::IndexMap;
use nu_errors::ShellError;
use nu_protocol::{CallInfo, EvaluatedArgs, Primitive, ReturnValue, UntaggedValue, Value};
use nu_protocol::{CallInfo, EvaluatedArgs, ReturnSuccess, ReturnValue, UntaggedValue, Value};
use nu_source::Tag;
use nu_value_ext::ValueExt;
pub struct PluginTest<'a, T: Plugin> {
plugin: &'a mut T,
@ -100,20 +99,6 @@ impl<'a, T: Plugin> PluginTest<'a, T> {
pub fn plugin<T: Plugin>(plugin: &mut T) -> PluginTest<T> {
PluginTest::for_plugin(plugin)
}
pub fn table(list: &Vec<Value>) -> Value {
UntaggedValue::table(list).into_untagged_value()
}
pub fn column_path(paths: &Vec<Value>) -> Value {
UntaggedValue::Primitive(Primitive::ColumnPath(
table(&paths.iter().cloned().collect())
.as_column_path()
.unwrap()
.item,
))
.into_untagged_value()
}
pub struct CallStub {
positionals: Vec<Value>,
flags: IndexMap<String, Value>,
@ -146,7 +131,7 @@ impl CallStub {
.map(|s| UntaggedValue::string(s.to_string()).into_value(Tag::unknown()))
.collect();
self.positionals.push(column_path(&fields));
self.positionals.push(value::column_path(&fields));
self
}
@ -157,3 +142,71 @@ impl CallStub {
}
}
}
pub fn expect_return_value_at(
for_results: Result<Vec<Result<ReturnSuccess, ShellError>>, ShellError>,
at: usize,
) -> Value {
let return_values = for_results
.expect("Failed! This seems to be an error getting back the results from the plugin.");
for (idx, item) in return_values.iter().enumerate() {
let item = match item {
Ok(return_value) => return_value,
Err(reason) => panic!(format!("{}", reason)),
};
if idx == at {
return item.raw_value().unwrap();
}
}
panic!(format!(
"Couldn't get return value from stream at {}. (There are {} items)",
at,
return_values.len() - 1
))
}
pub mod value {
use nu_protocol::{Primitive, TaggedDictBuilder, UntaggedValue, Value};
use nu_source::Tag;
use nu_value_ext::ValueExt;
use num_bigint::BigInt;
pub fn get_data(for_value: Value, key: &str) -> Value {
for_value.get_data(&key.to_string()).borrow().clone()
}
pub fn int(i: impl Into<BigInt>) -> Value {
UntaggedValue::Primitive(Primitive::Int(i.into())).into_untagged_value()
}
pub fn string(input: impl Into<String>) -> Value {
UntaggedValue::string(input.into()).into_untagged_value()
}
pub fn structured_sample_record(key: &str, value: &str) -> Value {
let mut record = TaggedDictBuilder::new(Tag::unknown());
record.insert_untagged(key.clone(), UntaggedValue::string(value));
record.into_value()
}
pub fn unstructured_sample_record(value: &str) -> Value {
UntaggedValue::string(value).into_value(Tag::unknown())
}
pub fn table(list: &Vec<Value>) -> Value {
UntaggedValue::table(list).into_untagged_value()
}
pub fn column_path(paths: &Vec<Value>) -> Value {
UntaggedValue::Primitive(Primitive::ColumnPath(
table(&paths.iter().cloned().collect())
.as_column_path()
.unwrap()
.item,
))
.into_untagged_value()
}
}

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "Core values and protocols for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-source = { path = "../nu-source", version = "0.7.0" }

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "A source string characterizer for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
serde = { version = "1.0.103", features = ["derive"] }

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "A source string characterizer for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
app_dirs = "1.2.1"

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "Extension traits for values in Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-source = { path = "../nu-source", version = "0.7.0" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "An average value plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "A binary viewer plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
ansi_term = "0.12.1"
crossterm = { version = "0.10.2" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "A URL fetch plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "A version incrementer plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
@ -15,7 +16,6 @@ nu-source = { path = "../nu-source", version = "0.7.0" }
nu-errors = { path = "../nu-errors", version = "0.7.0" }
nu-value-ext = { path = "../nu-value-ext", version = "0.7.0" }
semver = "0.9.0"
indexmap = "1.3.0"
[build-dependencies]
nu-build = { version = "0.7.0", path = "../nu-build" }

View File

@ -0,0 +1,179 @@
use nu_errors::ShellError;
use nu_protocol::{did_you_mean, ColumnPath, Primitive, ShellTypeName, UntaggedValue, Value};
use nu_source::{span_for_spanned_list, HasSpan, SpannedItem, Tagged};
use nu_value_ext::ValueExt;
#[derive(Debug, Eq, PartialEq)]
pub enum Action {
SemVerAction(SemVerAction),
Default,
}
#[derive(Debug, Eq, PartialEq)]
pub enum SemVerAction {
Major,
Minor,
Patch,
}
pub struct Inc {
pub field: Option<Tagged<ColumnPath>>,
pub error: Option<String>,
pub action: Option<Action>,
}
impl Inc {
pub fn new() -> Inc {
Inc {
field: None,
error: None,
action: None,
}
}
fn apply(&self, input: &str) -> Result<UntaggedValue, ShellError> {
let applied = match &self.action {
Some(Action::SemVerAction(act_on)) => {
let mut ver = match semver::Version::parse(&input) {
Ok(parsed_ver) => parsed_ver,
Err(_) => return Ok(UntaggedValue::string(input.to_string())),
};
match act_on {
SemVerAction::Major => ver.increment_major(),
SemVerAction::Minor => ver.increment_minor(),
SemVerAction::Patch => ver.increment_patch(),
}
UntaggedValue::string(ver.to_string())
}
Some(Action::Default) | None => match input.parse::<u64>() {
Ok(v) => UntaggedValue::string(format!("{}", v + 1)),
Err(_) => UntaggedValue::string(input),
},
};
Ok(applied)
}
pub 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());
}
pub fn usage() -> &'static str {
"Usage: inc field [--major|--minor|--patch]"
}
pub fn inc(&self, value: Value) -> Result<Value, ShellError> {
match &value.value {
UntaggedValue::Primitive(Primitive::Int(i)) => {
Ok(UntaggedValue::int(i + 1).into_value(value.tag()))
}
UntaggedValue::Primitive(Primitive::Bytes(b)) => {
Ok(UntaggedValue::bytes(b + 1 as u64).into_value(value.tag()))
}
UntaggedValue::Primitive(Primitive::String(ref s)) => {
Ok(self.apply(&s)?.into_value(value.tag()))
}
UntaggedValue::Table(values) => {
if values.len() == 1 {
Ok(UntaggedValue::Table(vec![self.inc(values[0].clone())?])
.into_value(value.tag()))
} else {
Err(ShellError::type_error(
"incrementable value",
value.type_name().spanned(value.span()),
))
}
}
UntaggedValue::Row(_) => match self.field {
Some(ref f) => {
let fields = f.clone();
let replace_for = value.get_data_by_column_path(
&f,
Box::new(move |(obj_source, column_path_tried, _)| {
match did_you_mean(&obj_source, &column_path_tried) {
Some(suggestions) => ShellError::labeled_error(
"Unknown column",
format!("did you mean '{}'?", suggestions[0].1),
span_for_spanned_list(fields.iter().map(|p| p.span)),
),
None => ShellError::labeled_error(
"Unknown column",
"row does not contain this column",
span_for_spanned_list(fields.iter().map(|p| p.span)),
),
}
}),
);
let got = replace_for?;
let replacement = self.inc(got.clone())?;
match value.replace_data_at_column_path(
&f,
replacement.value.clone().into_untagged_value(),
) {
Some(v) => Ok(v),
None => Err(ShellError::labeled_error(
"inc could not find field to replace",
"column name",
value.tag(),
)),
}
}
None => Err(ShellError::untagged_runtime_error(
"inc needs a field when incrementing a column in a table",
)),
},
_ => Err(ShellError::type_error(
"incrementable value",
value.type_name().spanned(value.span()),
)),
}
}
}
#[cfg(test)]
mod tests {
mod semver {
use crate::inc::SemVerAction;
use crate::Inc;
use nu_plugin::test_helpers::value::string;
#[test]
fn major() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Major);
assert_eq!(inc.apply("0.1.3").unwrap(), string("1.0.0").value);
}
#[test]
fn minor() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Minor);
assert_eq!(inc.apply("0.1.3").unwrap(), string("0.2.0").value);
}
#[test]
fn patch() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Patch);
assert_eq!(inc.apply("0.1.3").unwrap(), string("0.1.4").value);
}
}
}

View File

@ -0,0 +1,38 @@
mod inc;
mod nu_plugin_inc;
pub use inc::Inc;
#[cfg(test)]
mod tests {
use super::Inc;
use crate::inc::Action;
use nu_protocol::Value;
use nu_value_ext::ValueExt;
impl Inc {
pub fn expect_action(&self, action: Action) {
match &self.action {
Some(set) if set == &action => {}
Some(other) => panic!(format!("\nExpected {:#?}\n\ngot {:#?}", action, other)),
None => panic!(format!("\nAction {:#?} not found.", action)),
}
}
pub fn expect_field(&self, field: Value) {
let field = match field.as_column_path() {
Ok(column_path) => column_path,
Err(reason) => panic!(format!(
"\nExpected {:#?} to be a ColumnPath, \n\ngot {:#?}",
field, reason
)),
};
match &self.field {
Some(column_path) if column_path == &field => {}
Some(other) => panic!(format!("\nExpected {:#?} \n\ngot {:#?}", field, other)),
None => panic!(format!("\nField {:#?} not found.", field)),
}
}
}
}

View File

@ -1,457 +1,6 @@
use nu_errors::ShellError;
use nu_plugin::{serve_plugin, Plugin};
use nu_protocol::{
did_you_mean, CallInfo, ColumnPath, Primitive, ReturnSuccess, ReturnValue, ShellTypeName,
Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::{span_for_spanned_list, HasSpan, SpannedItem, Tagged};
use nu_value_ext::ValueExt;
enum Action {
SemVerAction(SemVerAction),
Default,
}
pub enum SemVerAction {
Major,
Minor,
Patch,
}
struct Inc {
field: Option<Tagged<ColumnPath>>,
error: Option<String>,
action: Option<Action>,
}
impl Inc {
fn new() -> Inc {
Inc {
field: None,
error: None,
action: None,
}
}
fn apply(&self, input: &str) -> Result<UntaggedValue, ShellError> {
let applied = match &self.action {
Some(Action::SemVerAction(act_on)) => {
let mut ver = match semver::Version::parse(&input) {
Ok(parsed_ver) => parsed_ver,
Err(_) => return Ok(UntaggedValue::string(input.to_string())),
};
match act_on {
SemVerAction::Major => ver.increment_major(),
SemVerAction::Minor => ver.increment_minor(),
SemVerAction::Patch => ver.increment_patch(),
}
UntaggedValue::string(ver.to_string())
}
Some(Action::Default) | None => match input.parse::<u64>() {
Ok(v) => UntaggedValue::string(format!("{}", v + 1)),
Err(_) => UntaggedValue::string(input),
},
};
Ok(applied)
}
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());
}
pub fn usage() -> &'static str {
"Usage: inc field [--major|--minor|--patch]"
}
fn inc(&self, value: Value) -> Result<Value, ShellError> {
match &value.value {
UntaggedValue::Primitive(Primitive::Int(i)) => {
Ok(UntaggedValue::int(i + 1).into_value(value.tag()))
}
UntaggedValue::Primitive(Primitive::Bytes(b)) => {
Ok(UntaggedValue::bytes(b + 1 as u64).into_value(value.tag()))
}
UntaggedValue::Primitive(Primitive::String(ref s)) => {
Ok(self.apply(&s)?.into_value(value.tag()))
}
UntaggedValue::Table(values) => {
if values.len() == 1 {
Ok(UntaggedValue::Table(vec![self.inc(values[0].clone())?])
.into_value(value.tag()))
} else {
Err(ShellError::type_error(
"incrementable value",
value.type_name().spanned(value.span()),
))
}
}
UntaggedValue::Row(_) => match self.field {
Some(ref f) => {
let fields = f.clone();
let replace_for = value.get_data_by_column_path(
&f,
Box::new(move |(obj_source, column_path_tried, _)| {
match did_you_mean(&obj_source, &column_path_tried) {
Some(suggestions) => ShellError::labeled_error(
"Unknown column",
format!("did you mean '{}'?", suggestions[0].1),
span_for_spanned_list(fields.iter().map(|p| p.span)),
),
None => ShellError::labeled_error(
"Unknown column",
"row does not contain this column",
span_for_spanned_list(fields.iter().map(|p| p.span)),
),
}
}),
);
let got = replace_for?;
let replacement = self.inc(got.clone())?;
match value.replace_data_at_column_path(
&f,
replacement.value.clone().into_untagged_value(),
) {
Some(v) => Ok(v),
None => Err(ShellError::labeled_error(
"inc could not find field to replace",
"column name",
value.tag(),
)),
}
}
None => Err(ShellError::untagged_runtime_error(
"inc needs a field when incrementing a column in a table",
)),
},
_ => Err(ShellError::type_error(
"incrementable value",
value.type_name().spanned(value.span()),
)),
}
}
}
impl Plugin for Inc {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("inc")
.desc("Increment a value or version. Optionally use the column of a table.")
.switch("major", "increment the major version (eg 1.2.1 -> 2.0.0)")
.switch("minor", "increment the minor version (eg 1.2.1 -> 1.3.0)")
.switch("patch", "increment the patch version (eg 1.2.1 -> 1.2.2)")
.rest(SyntaxShape::ColumnPath, "the column(s) to update")
.filter())
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if call_info.args.has("major") {
self.for_semver(SemVerAction::Major);
}
if call_info.args.has("minor") {
self.for_semver(SemVerAction::Minor);
}
if call_info.args.has("patch") {
self.for_semver(SemVerAction::Patch);
}
if let Some(args) = call_info.args.positional {
for arg in args {
match arg {
table @ Value {
value: UntaggedValue::Primitive(Primitive::ColumnPath(_)),
..
} => {
self.field = Some(table.as_column_path()?);
}
value => {
return Err(ShellError::type_error(
"table",
value.type_name().spanned(value.span()),
))
}
}
}
}
if self.action.is_none() {
self.action = Some(Action::Default);
}
match &self.error {
Some(reason) => Err(ShellError::untagged_runtime_error(format!(
"{}: {}",
reason,
Inc::usage()
))),
None => Ok(vec![]),
}
}
fn filter(&mut self, input: Value) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(self.inc(input)?)])
}
}
use nu_plugin::serve_plugin;
use nu_plugin_inc::Inc;
fn main() {
serve_plugin(&mut Inc::new());
}
#[cfg(test)]
mod tests {
use super::{Inc, SemVerAction};
use indexmap::IndexMap;
use nu_plugin::Plugin;
use nu_protocol::{
CallInfo, EvaluatedArgs, PathMember, ReturnSuccess, TaggedDictBuilder, UnspannedPathMember,
UntaggedValue, Value,
};
use nu_source::{Span, Tag};
struct CallStub {
positionals: Vec<Value>,
flags: IndexMap<String, 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(),
UntaggedValue::boolean(true).into_value(Tag::unknown()),
);
self
}
fn with_parameter(&mut self, name: &str) -> &mut Self {
let fields: Vec<PathMember> = name
.split(".")
.map(|s| {
UnspannedPathMember::String(s.to_string()).into_path_member(Span::unknown())
})
.collect();
self.positionals
.push(UntaggedValue::column_path(fields).into_untagged_value());
self
}
fn create(&self) -> CallInfo {
CallInfo {
args: EvaluatedArgs::new(Some(self.positionals.clone()), Some(self.flags.clone())),
name_tag: Tag::unknown(),
}
}
}
fn cargo_sample_record(with_version: &str) -> Value {
let mut package = TaggedDictBuilder::new(Tag::unknown());
package.insert_untagged("version", UntaggedValue::string(with_version));
package.into_value()
}
#[test]
fn inc_plugin_configuration_flags_wired() {
let mut plugin = Inc::new();
let configured = plugin.config().expect("Can not configure plugin");
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
.map(|f| f.iter().map(|f| f.unspanned.clone()).collect()),
Some(vec![
UnspannedPathMember::String("package".to_string()),
UnspannedPathMember::String("version".to_string())
])
);
}
#[test]
fn incs_major() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Major);
assert_eq!(inc.apply("0.1.3").unwrap(), UntaggedValue::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").unwrap(), UntaggedValue::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").unwrap(), UntaggedValue::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(Value {
value: UntaggedValue::Row(o),
..
}) => assert_eq!(
*o.get_data(&String::from("version")).borrow(),
UntaggedValue::string(String::from("1.0.0")).into_untagged_value()
),
_ => {}
}
}
#[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(Value {
value: UntaggedValue::Row(o),
..
}) => assert_eq!(
*o.get_data(&String::from("version")).borrow(),
UntaggedValue::string(String::from("0.2.0")).into_untagged_value()
),
_ => {}
}
}
#[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(Value {
value: UntaggedValue::Row(o),
..
}) => assert_eq!(
*o.get_data(&field).borrow(),
UntaggedValue::string(String::from("0.1.4")).into_untagged_value()
),
_ => {}
}
}
serve_plugin(&mut Inc::new())
}

View File

@ -0,0 +1,73 @@
#[cfg(test)]
mod tests;
use crate::inc::{Action, SemVerAction};
use crate::Inc;
use nu_errors::ShellError;
use nu_plugin::Plugin;
use nu_protocol::{
CallInfo, Primitive, ReturnSuccess, ReturnValue, ShellTypeName, Signature, SyntaxShape,
UntaggedValue, Value,
};
use nu_source::{HasSpan, SpannedItem};
use nu_value_ext::ValueExt;
impl Plugin for Inc {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("inc")
.desc("Increment a value or version. Optionally use the column of a table.")
.switch("major", "increment the major version (eg 1.2.1 -> 2.0.0)")
.switch("minor", "increment the minor version (eg 1.2.1 -> 1.3.0)")
.switch("patch", "increment the patch version (eg 1.2.1 -> 1.2.2)")
.rest(SyntaxShape::ColumnPath, "the column(s) to update")
.filter())
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if call_info.args.has("major") {
self.for_semver(SemVerAction::Major);
}
if call_info.args.has("minor") {
self.for_semver(SemVerAction::Minor);
}
if call_info.args.has("patch") {
self.for_semver(SemVerAction::Patch);
}
if let Some(args) = call_info.args.positional {
for arg in args {
match arg {
table @ Value {
value: UntaggedValue::Primitive(Primitive::ColumnPath(_)),
..
} => {
self.field = Some(table.as_column_path()?);
}
value => {
return Err(ShellError::type_error(
"table",
value.type_name().spanned(value.span()),
))
}
}
}
}
if self.action.is_none() {
self.action = Some(Action::Default);
}
match &self.error {
Some(reason) => Err(ShellError::untagged_runtime_error(format!(
"{}: {}",
reason,
Inc::usage()
))),
None => Ok(vec![]),
}
}
fn filter(&mut self, input: Value) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(self.inc(input)?)])
}
}

View File

@ -0,0 +1,126 @@
mod integration {
use crate::inc::{Action, SemVerAction};
use crate::Inc;
use nu_plugin::test_helpers::value::{column_path, string};
use nu_plugin::test_helpers::{plugin, CallStub};
#[test]
fn picks_up_one_action_flag_only() {
plugin(&mut Inc::new())
.args(
CallStub::new()
.with_long_flag("major")
.with_long_flag("minor")
.create(),
)
.setup(|plugin, returned_values| {
let actual = format!("{}", returned_values.unwrap_err());
assert!(actual.contains("can only apply one"));
assert_eq!(plugin.error, Some("can only apply one".to_string()));
});
}
#[test]
fn picks_up_major_flag() {
plugin(&mut Inc::new())
.args(CallStub::new().with_long_flag("major").create())
.setup(|plugin, _| {
let sem_version_part = SemVerAction::Major;
plugin.expect_action(Action::SemVerAction(sem_version_part))
});
}
#[test]
fn picks_up_minor_flag() {
plugin(&mut Inc::new())
.args(CallStub::new().with_long_flag("minor").create())
.setup(|plugin, _| {
let sem_version_part = SemVerAction::Minor;
plugin.expect_action(Action::SemVerAction(sem_version_part))
});
}
#[test]
fn picks_up_patch_flag() {
plugin(&mut Inc::new())
.args(CallStub::new().with_long_flag("patch").create())
.setup(|plugin, _| {
let sem_version_part = SemVerAction::Patch;
plugin.expect_action(Action::SemVerAction(sem_version_part))
});
}
#[test]
fn picks_up_argument_for_field() {
plugin(&mut Inc::new())
.args(CallStub::new().with_parameter("package.version").create())
.setup(|plugin, _| {
plugin.expect_field(column_path(&vec![string("package"), string("version")]))
});
}
mod sem_ver {
use crate::Inc;
use nu_plugin::test_helpers::value::{get_data, string, structured_sample_record};
use nu_plugin::test_helpers::{expect_return_value_at, plugin, CallStub};
fn cargo_sample_record(with_version: &str) -> nu_protocol::Value {
structured_sample_record("version", with_version)
}
#[test]
fn major_input_using_the_field_passed_as_parameter() {
let run = plugin(&mut Inc::new())
.args(
CallStub::new()
.with_long_flag("major")
.with_parameter("version")
.create(),
)
.input(cargo_sample_record("0.1.3"))
.setup(|_, _| {})
.test();
let actual = expect_return_value_at(run, 0);
assert_eq!(get_data(actual, "version"), string("1.0.0"));
}
#[test]
fn minor_input_using_the_field_passed_as_parameter() {
let run = plugin(&mut Inc::new())
.args(
CallStub::new()
.with_long_flag("minor")
.with_parameter("version")
.create(),
)
.input(cargo_sample_record("0.1.3"))
.setup(|_, _| {})
.test();
let actual = expect_return_value_at(run, 0);
assert_eq!(get_data(actual, "version"), string("0.2.0"));
}
#[test]
fn patch_input_using_the_field_passed_as_parameter() {
let run = plugin(&mut Inc::new())
.args(
CallStub::new()
.with_long_flag("patch")
.with_parameter("version")
.create(),
)
.input(cargo_sample_record("0.1.3"))
.setup(|_, _| {})
.test();
let actual = expect_return_value_at(run, 0);
assert_eq!(get_data(actual, "version"), string("0.1.4"));
}
}
}

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "A regex match plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "An HTTP post plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "A process list plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,7 +6,8 @@ edition = "2018"
description = "A string manipulation plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
doctest = false
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
@ -14,9 +15,7 @@ nu-protocol = { path = "../nu-protocol", version = "0.7.0" }
nu-source = { path = "../nu-source", version = "0.7.0" }
nu-errors = { path = "../nu-errors", version = "0.7.0" }
nu-value-ext = { path = "../nu-value-ext", version = "0.7.0" }
regex = "1"
indexmap = "1.3.0"
num-bigint = "0.2.3"
[build-dependencies]

View File

@ -7,11 +7,8 @@ pub use strutils::Str;
mod tests {
use super::Str;
use crate::strutils::Action;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, TaggedDictBuilder, UntaggedValue, Value};
use nu_source::Tag;
use nu_protocol::Value;
use nu_value_ext::ValueExt;
use num_bigint::BigInt;
impl Str {
pub fn expect_action(&self, action: Action) {
@ -38,51 +35,4 @@ mod tests {
}
}
}
pub fn get_data(for_value: Value, key: &str) -> Value {
for_value.get_data(&key.to_string()).borrow().clone()
}
pub fn expect_return_value_at(
for_results: Result<Vec<Result<ReturnSuccess, ShellError>>, ShellError>,
at: usize,
) -> Value {
let return_values = for_results
.expect("Failed! This seems to be an error getting back the results from the plugin.");
for (idx, item) in return_values.iter().enumerate() {
let item = match item {
Ok(return_value) => return_value,
Err(reason) => panic!(format!("{}", reason)),
};
if idx == at {
return item.raw_value().unwrap();
}
}
panic!(format!(
"Couldn't get return value from stream at {}. (There are {} items)",
at,
return_values.len() - 1
))
}
pub fn int(i: impl Into<BigInt>) -> Value {
UntaggedValue::Primitive(Primitive::Int(i.into())).into_untagged_value()
}
pub fn string(input: impl Into<String>) -> Value {
UntaggedValue::string(input.into()).into_untagged_value()
}
pub fn structured_sample_record(key: &str, value: &str) -> Value {
let mut record = TaggedDictBuilder::new(Tag::unknown());
record.insert_untagged(key.clone(), UntaggedValue::string(value));
record.into_value()
}
pub fn unstructured_sample_record(value: &str) -> Value {
UntaggedValue::string(value).into_value(Tag::unknown())
}
}

View File

@ -1,11 +1,11 @@
mod integration {
use crate::strutils::{Action, ReplaceAction};
use crate::tests::{
expect_return_value_at, get_data, int, string, structured_sample_record,
use crate::Str;
use nu_plugin::test_helpers::value::{
column_path, get_data, int, string, structured_sample_record, table,
unstructured_sample_record,
};
use crate::Str;
use nu_plugin::test_helpers::{column_path, plugin, table, CallStub};
use nu_plugin::test_helpers::{expect_return_value_at, plugin, CallStub};
use nu_protocol::UntaggedValue;
#[test]
@ -24,6 +24,7 @@ mod integration {
assert_eq!(plugin.error, Some("can only apply one".to_string()));
});
}
#[test]
fn picks_up_downcase_flag() {
plugin(&mut Str::new())

View File

@ -2,7 +2,6 @@ use nu_errors::ShellError;
use nu_protocol::{did_you_mean, ColumnPath, Primitive, ShellTypeName, UntaggedValue, Value};
use nu_source::{span_for_spanned_list, Tagged};
use nu_value_ext::ValueExt;
use regex::Regex;
use std::cmp;
@ -206,42 +205,35 @@ impl Str {
#[cfg(test)]
pub mod tests {
use super::{ReplaceAction, Str};
use crate::tests::{int, string};
use super::ReplaceAction;
use super::Str;
use nu_plugin::test_helpers::value::{int, string};
#[test]
fn downcases() {
let mut strutils = Str::new();
strutils.for_downcase();
assert_eq!(strutils.apply("ANDRES").unwrap(), string("andres").value);
}
#[test]
fn upcases() {
let mut strutils = Str::new();
strutils.for_upcase();
assert_eq!(strutils.apply("andres").unwrap(), string("ANDRES").value);
}
#[test]
fn converts_to_int() {
let mut strutils = Str::new();
strutils.for_to_int();
assert_eq!(strutils.apply("9999").unwrap(), int(9999 as i64).value);
}
#[test]
fn replaces() {
let mut strutils = Str::new();
strutils.for_replace(ReplaceAction::Direct("robalino".to_string()));
assert_eq!(strutils.apply("andres").unwrap(), string("robalino").value);
}

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "A simple summation plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "A system info plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "Text viewer plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -6,8 +6,6 @@ edition = "2018"
description = "Tree viewer plugin for Nushell"
license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nu-plugin = { path = "../nu-plugin", version="0.7.0" }
nu-protocol = { path = "../nu-protocol", version = "0.7.0" }

View File

@ -1,457 +1,6 @@
use nu_errors::ShellError;
use nu_plugin::{serve_plugin, Plugin};
use nu_protocol::{
did_you_mean, CallInfo, ColumnPath, Primitive, ReturnSuccess, ReturnValue, ShellTypeName,
Signature, SyntaxShape, UntaggedValue, Value,
};
use nu_source::{span_for_spanned_list, HasSpan, SpannedItem, Tagged};
use nu_value_ext::ValueExt;
enum Action {
SemVerAction(SemVerAction),
Default,
}
pub enum SemVerAction {
Major,
Minor,
Patch,
}
struct Inc {
field: Option<Tagged<ColumnPath>>,
error: Option<String>,
action: Option<Action>,
}
impl Inc {
fn new() -> Inc {
Inc {
field: None,
error: None,
action: None,
}
}
fn apply(&self, input: &str) -> Result<UntaggedValue, ShellError> {
let applied = match &self.action {
Some(Action::SemVerAction(act_on)) => {
let mut ver = match semver::Version::parse(&input) {
Ok(parsed_ver) => parsed_ver,
Err(_) => return Ok(UntaggedValue::string(input.to_string())),
};
match act_on {
SemVerAction::Major => ver.increment_major(),
SemVerAction::Minor => ver.increment_minor(),
SemVerAction::Patch => ver.increment_patch(),
}
UntaggedValue::string(ver.to_string())
}
Some(Action::Default) | None => match input.parse::<u64>() {
Ok(v) => UntaggedValue::string(format!("{}", v + 1)),
Err(_) => UntaggedValue::string(input),
},
};
Ok(applied)
}
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());
}
pub fn usage() -> &'static str {
"Usage: inc field [--major|--minor|--patch]"
}
fn inc(&self, value: Value) -> Result<Value, ShellError> {
match &value.value {
UntaggedValue::Primitive(Primitive::Int(i)) => {
Ok(UntaggedValue::int(i + 1).into_value(value.tag()))
}
UntaggedValue::Primitive(Primitive::Bytes(b)) => {
Ok(UntaggedValue::bytes(b + 1 as u64).into_value(value.tag()))
}
UntaggedValue::Primitive(Primitive::String(ref s)) => {
Ok(self.apply(&s)?.into_value(value.tag()))
}
UntaggedValue::Table(values) => {
if values.len() == 1 {
Ok(UntaggedValue::Table(vec![self.inc(values[0].clone())?])
.into_value(value.tag()))
} else {
Err(ShellError::type_error(
"incrementable value",
value.type_name().spanned(value.span()),
))
}
}
UntaggedValue::Row(_) => match self.field {
Some(ref f) => {
let fields = f.clone();
let replace_for = value.get_data_by_column_path(
&f,
Box::new(move |(obj_source, column_path_tried, _)| {
match did_you_mean(&obj_source, &column_path_tried) {
Some(suggestions) => ShellError::labeled_error(
"Unknown column",
format!("did you mean '{}'?", suggestions[0].1),
span_for_spanned_list(fields.iter().map(|p| p.span)),
),
None => ShellError::labeled_error(
"Unknown column",
"row does not contain this column",
span_for_spanned_list(fields.iter().map(|p| p.span)),
),
}
}),
);
let got = replace_for?;
let replacement = self.inc(got.clone())?;
match value.replace_data_at_column_path(
&f,
replacement.value.clone().into_untagged_value(),
) {
Some(v) => Ok(v),
None => Err(ShellError::labeled_error(
"inc could not find field to replace",
"column name",
value.tag(),
)),
}
}
None => Err(ShellError::untagged_runtime_error(
"inc needs a field when incrementing a column in a table",
)),
},
_ => Err(ShellError::type_error(
"incrementable value",
value.type_name().spanned(value.span()),
)),
}
}
}
impl Plugin for Inc {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("inc")
.desc("Increment a value or version. Optionally use the column of a table.")
.switch("major", "increment the major version (eg 1.2.1 -> 2.0.0)")
.switch("minor", "increment the minor version (eg 1.2.1 -> 1.3.0)")
.switch("patch", "increment the patch version (eg 1.2.1 -> 1.2.2)")
.rest(SyntaxShape::ColumnPath, "the column(s) to update")
.filter())
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if call_info.args.has("major") {
self.for_semver(SemVerAction::Major);
}
if call_info.args.has("minor") {
self.for_semver(SemVerAction::Minor);
}
if call_info.args.has("patch") {
self.for_semver(SemVerAction::Patch);
}
if let Some(args) = call_info.args.positional {
for arg in args {
match arg {
table @ Value {
value: UntaggedValue::Primitive(Primitive::ColumnPath(_)),
..
} => {
self.field = Some(table.as_column_path()?);
}
value => {
return Err(ShellError::type_error(
"table",
value.type_name().spanned(value.span()),
))
}
}
}
}
if self.action.is_none() {
self.action = Some(Action::Default);
}
match &self.error {
Some(reason) => Err(ShellError::untagged_runtime_error(format!(
"{}: {}",
reason,
Inc::usage()
))),
None => Ok(vec![]),
}
}
fn filter(&mut self, input: Value) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(self.inc(input)?)])
}
}
use nu_plugin::serve_plugin;
use nu_plugin_inc::Inc;
fn main() {
serve_plugin(&mut Inc::new());
}
#[cfg(test)]
mod tests {
use super::{Inc, SemVerAction};
use indexmap::IndexMap;
use nu_plugin::Plugin;
use nu_protocol::{
CallInfo, EvaluatedArgs, PathMember, ReturnSuccess, TaggedDictBuilder, UnspannedPathMember,
UntaggedValue, Value,
};
use nu_source::{Span, Tag};
struct CallStub {
positionals: Vec<Value>,
flags: IndexMap<String, 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(),
UntaggedValue::boolean(true).into_value(Tag::unknown()),
);
self
}
fn with_parameter(&mut self, name: &str) -> &mut Self {
let fields: Vec<PathMember> = name
.split(".")
.map(|s| {
UnspannedPathMember::String(s.to_string()).into_path_member(Span::unknown())
})
.collect();
self.positionals
.push(UntaggedValue::column_path(fields).into_untagged_value());
self
}
fn create(&self) -> CallInfo {
CallInfo {
args: EvaluatedArgs::new(Some(self.positionals.clone()), Some(self.flags.clone())),
name_tag: Tag::unknown(),
}
}
}
fn cargo_sample_record(with_version: &str) -> Value {
let mut package = TaggedDictBuilder::new(Tag::unknown());
package.insert_untagged("version", UntaggedValue::string(with_version));
package.into_value()
}
#[test]
fn inc_plugin_configuration_flags_wired() {
let mut plugin = Inc::new();
let configured = plugin.config().expect("Can not configure plugin");
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
.map(|f| f.iter().map(|f| f.unspanned.clone()).collect()),
Some(vec![
UnspannedPathMember::String("package".to_string()),
UnspannedPathMember::String("version".to_string())
])
);
}
#[test]
fn incs_major() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Major);
assert_eq!(inc.apply("0.1.3").unwrap(), UntaggedValue::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").unwrap(), UntaggedValue::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").unwrap(), UntaggedValue::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(Value {
value: UntaggedValue::Row(o),
..
}) => assert_eq!(
*o.get_data(&String::from("version")).borrow(),
UntaggedValue::string(String::from("1.0.0")).into_untagged_value()
),
_ => {}
}
}
#[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(Value {
value: UntaggedValue::Row(o),
..
}) => assert_eq!(
*o.get_data(&String::from("version")).borrow(),
UntaggedValue::string(String::from("0.2.0")).into_untagged_value()
),
_ => {}
}
}
#[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(Value {
value: UntaggedValue::Row(o),
..
}) => assert_eq!(
*o.get_data(&field).borrow(),
UntaggedValue::string(String::from("0.1.4")).into_untagged_value()
),
_ => {}
}
}
}

View File

@ -1,5 +1,6 @@
use nu_plugin::serve_plugin;
use nu_plugin_str::Str;
fn main() {
serve_plugin(&mut Str::new());
}