Merge pull request #192 from jonathandturner/improved_inc

Improved increment
This commit is contained in:
Jonathan Turner 2019-07-18 14:14:06 +12:00 committed by GitHub
commit 6f286ba837
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 196 additions and 41 deletions

View File

@ -347,6 +347,62 @@ impl Value {
} }
} }
pub fn get_data_by_path(&'a self, span: Span, path: &str) -> Option<Spanned<&Value>> {
let mut current = self;
for p in path.split(".") {
match current.get_data_by_key(p) {
Some(v) => current = v,
None => return None,
}
}
Some(Spanned {
item: current,
span,
})
}
pub fn replace_data_at_path(
&'a self,
span: Span,
path: &str,
replaced_value: Value,
) -> Option<Spanned<Value>> {
let mut new_obj = self.clone();
let split_path: Vec<_> = path.split(".").collect();
if let Value::Object(ref mut o) = new_obj {
let mut current = o;
for idx in 0..split_path.len() {
match current.entries.get_mut(split_path[idx]) {
Some(next) => {
if idx == (split_path.len() - 1) {
*next = Spanned {
item: replaced_value,
span,
};
return Some(Spanned {
item: new_obj,
span,
});
} else {
match next.item {
Value::Object(ref mut o) => {
current = o;
}
_ => return None,
}
}
}
_ => return None,
}
}
}
None
}
pub fn get_data(&'a self, desc: &String) -> MaybeOwned<'a, Value> { pub fn get_data(&'a self, desc: &String) -> MaybeOwned<'a, Value> {
match self { match self {
p @ Value::Primitive(_) => MaybeOwned::Borrowed(p), p @ Value::Primitive(_) => MaybeOwned::Borrowed(p),

View File

@ -50,7 +50,7 @@ impl<T> Spanned<T> {
} }
} }
crate fn map<U>(self, input: impl FnOnce(T) -> U) -> Spanned<U> { pub fn map<U>(self, input: impl FnOnce(T) -> U) -> Spanned<U> {
let Spanned { span, item } = self; let Spanned { span, item } = self;
let mapped = input(item); let mapped = input(item);

View File

@ -1,57 +1,80 @@
use indexmap::IndexMap; use indexmap::IndexMap;
use nu::{ use nu::{
serve_plugin, Args, CommandConfig, Plugin, PositionalType, Primitive, ReturnSuccess, serve_plugin, Args, CommandConfig, NamedType, Plugin, PositionalType, Primitive, ReturnSuccess,
ReturnValue, ShellError, Spanned, SpannedItem, Value, ReturnValue, ShellError, Spanned, SpannedItem, Value,
}; };
struct Inc { struct Inc {
inc_by: i64, field: Option<String>,
major: bool,
minor: bool,
patch: bool,
} }
impl Inc { impl Inc {
fn new() -> Inc { fn new() -> Inc {
Inc { inc_by: 1 } Inc {
field: None,
major: false,
minor: false,
patch: false,
}
} }
}
impl Plugin for Inc { fn inc(
fn config(&mut self) -> Result<CommandConfig, ShellError> { &self,
Ok(CommandConfig { value: Spanned<Value>,
name: "inc".to_string(), field: &Option<String>,
positional: vec![PositionalType::optional_any("Increment")], ) -> Result<Spanned<Value>, ShellError> {
is_filter: true, match value.item {
is_sink: false, Value::Primitive(Primitive::Int(i)) => Ok(Value::int(i + 1).spanned(value.span)),
named: IndexMap::new(), Value::Primitive(Primitive::Bytes(b)) => {
rest_positional: true, Ok(Value::bytes(b + 1 as u64).spanned(value.span))
}) }
} Value::Primitive(Primitive::String(s)) => {
fn begin_filter(&mut self, args: Args) -> Result<(), ShellError> { if let Ok(i) = s.parse::<u64>() {
if let Some(args) = args.positional { Ok(Spanned {
for arg in args { item: Value::string(format!("{}", i + 1)),
match arg { span: value.span,
Spanned { })
item: Value::Primitive(Primitive::Int(i)), } else if let Ok(mut ver) = semver::Version::parse(&s) {
.. if self.major {
} => { ver.increment_major();
self.inc_by = i; } else if self.minor {
ver.increment_minor();
} else {
self.patch;
ver.increment_patch();
} }
_ => return Err(ShellError::string("Unrecognized type in params")), Ok(Spanned {
item: Value::string(ver.to_string()),
span: value.span,
})
} else {
Err(ShellError::string("string could not be incremented"))
} }
} }
} Value::Object(_) => match field {
Some(f) => {
Ok(()) let replacement = match value.item.get_data_by_path(value.span, f) {
} Some(result) => self.inc(result.map(|x| x.clone()), &None)?,
None => {
fn filter(&mut self, input: Spanned<Value>) -> Result<Vec<ReturnValue>, ShellError> { return Err(ShellError::string("inc could not find field to replace"))
let span = input.span; }
};
match input.item { match value
Value::Primitive(Primitive::Int(i)) => Ok(vec![ReturnSuccess::value( .item
Value::int(i + self.inc_by).spanned(span), .replace_data_at_path(value.span, f, replacement.item.clone())
)]), {
Value::Primitive(Primitive::Bytes(b)) => Ok(vec![ReturnSuccess::value( Some(v) => return Ok(v),
Value::bytes(b + self.inc_by as u64).spanned(span), None => {
)]), return Err(ShellError::string("inc could not find field to replace"))
}
}
}
None => Err(ShellError::string(
"inc needs a field when incrementing a value in an object",
)),
},
x => Err(ShellError::string(format!( x => Err(ShellError::string(format!(
"Unrecognized type in stream: {:?}", "Unrecognized type in stream: {:?}",
x x
@ -60,6 +83,60 @@ impl Plugin for Inc {
} }
} }
impl Plugin for Inc {
fn config(&mut self) -> Result<CommandConfig, ShellError> {
let mut named = IndexMap::new();
named.insert("major".to_string(), NamedType::Switch);
named.insert("minor".to_string(), NamedType::Switch);
named.insert("patch".to_string(), NamedType::Switch);
Ok(CommandConfig {
name: "inc".to_string(),
positional: vec![PositionalType::optional_any("Field")],
is_filter: true,
is_sink: false,
named,
rest_positional: true,
})
}
fn begin_filter(&mut self, args: Args) -> Result<(), ShellError> {
if args.has("major") {
self.major = true;
}
if args.has("minor") {
self.minor = true;
}
if args.has("patch") {
self.patch = true;
}
if let Some(args) = args.positional {
for arg in args {
match arg {
Spanned {
item: Value::Primitive(Primitive::String(s)),
..
} => {
self.field = Some(s);
}
_ => {
return Err(ShellError::string(format!(
"Unrecognized type in params: {:?}",
arg
)))
}
}
}
}
Ok(())
}
fn filter(&mut self, input: Spanned<Value>) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(self.inc(input, &self.field)?)])
}
}
fn main() { fn main() {
serve_plugin(&mut Inc::new()); serve_plugin(&mut Inc::new());
} }

View File

@ -51,6 +51,28 @@ fn can_split_by_column() {
assert_eq!(output, "name"); assert_eq!(output, "name");
} }
#[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] #[test]
fn can_filter_by_unit_size_comparison() { fn can_filter_by_unit_size_comparison() {
nu!( nu!(