nushell/src/plugins/inc.rs

403 lines
11 KiB
Rust
Raw Normal View History

2019-07-03 17:37:09 +00:00
use nu::{
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 19:21:03 +00:00
serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature,
SyntaxType, Tagged, TaggedItem, Value,
2019-07-03 17:37:09 +00:00
};
2019-06-27 04:56:48 +00:00
2019-08-10 08:54:49 +00:00
enum Action {
SemVerAction(SemVerAction),
Default,
}
pub enum SemVerAction {
Major,
Minor,
Patch,
}
2019-07-02 07:56:20 +00:00
struct Inc {
2019-07-18 01:32:19 +00:00
field: Option<String>,
2019-08-10 08:54:49 +00:00
error: Option<String>,
action: Option<Action>,
2019-06-27 04:56:48 +00:00
}
2019-08-10 08:54:49 +00:00
2019-07-02 07:56:20 +00:00
impl Inc {
fn new() -> Inc {
2019-07-18 01:49:12 +00:00
Inc {
field: None,
2019-08-10 08:54:49 +00:00
error: None,
action: None,
}
}
fn apply(&self, input: &str) -> Result<Value, ShellError> {
let applied = match &self.action {
2019-08-10 08:54:49 +00:00
Some(Action::SemVerAction(act_on)) => {
let mut ver = match semver::Version::parse(&input) {
Ok(parsed_ver) => parsed_ver,
Err(_) => return Ok(Value::string(input.to_string())),
};
2019-08-10 08:54:49 +00:00
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),
},
};
Ok(applied)
2019-08-10 08:54:49 +00:00
}
fn for_semver(&mut self, part: SemVerAction) {
if self.permit() {
self.action = Some(Action::SemVerAction(part));
} else {
self.log_error("can only apply one");
2019-07-18 01:49:12 +00:00
}
2019-07-18 01:32:19 +00:00
}
2019-08-10 08:54:49 +00:00
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 {
2019-08-10 08:54:49 +00:00
"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())),
2019-07-18 01:32:19 +00:00
Value::Primitive(Primitive::Bytes(b)) => {
Ok(Value::bytes(b + 1 as u64).tagged(value.tag()))
2019-07-18 01:32:19 +00:00
}
2019-08-01 01:58:42 +00:00
Value::Primitive(Primitive::String(ref s)) => {
Ok(Tagged::from_item(self.apply(&s)?, value.tag()))
2019-07-18 01:32:19 +00:00
}
2019-08-10 08:54:49 +00:00
Value::Object(_) => match self.field {
Some(ref f) => {
let replacement = match value.item.get_data_by_path(value.tag(), f) {
2019-08-10 08:54:49 +00:00
Some(result) => self.inc(result.map(|x| x.clone()))?,
2019-07-18 01:32:19 +00:00
None => {
return Err(ShellError::string("inc could not find field to replace"))
}
};
match value
.item
.replace_data_at_path(value.tag(), f, replacement.item.clone())
2019-07-18 01:32:19 +00:00
{
Some(v) => return Ok(v),
None => {
return Err(ShellError::string("inc could not find field to replace"))
}
}
}
None => Err(ShellError::string(
"inc needs a field when incrementing a column in a table",
2019-07-18 01:32:19 +00:00
)),
},
x => Err(ShellError::string(format!(
"Unrecognized type in stream: {:?}",
x
))),
}
2019-06-27 04:56:48 +00:00
}
}
2019-07-13 02:07:06 +00:00
impl Plugin for Inc {
2019-08-02 19:15:07 +00:00
fn config(&mut self) -> Result<Signature, ShellError> {
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 19:21:03 +00:00
Ok(Signature::build("inc")
.desc("Increment a value or version. Optionally use the column of a table.")
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 19:21:03 +00:00
.switch("major")
.switch("minor")
.switch("patch")
.rest(SyntaxType::String)
.filter())
2019-07-13 02:07:06 +00:00
}
Add support for ~ expansion This ended up being a bit of a yak shave. The basic idea in this commit is to expand `~` in paths, but only in paths. The way this is accomplished is by doing the expansion inside of the code that parses literal syntax for `SyntaxType::Path`. As a quick refresher: every command is entitled to expand its arguments in a custom way. While this could in theory be used for general-purpose macros, today the expansion facility is limited to syntactic hints. For example, the syntax `where cpu > 0` expands under the hood to `where { $it.cpu > 0 }`. This happens because the first argument to `where` is defined as a `SyntaxType::Block`, and the parser coerces binary expressions whose left-hand-side looks like a member into a block when the command is expecting one. This is mildly more magical than what most programming languages would do, but we believe that it makes sense to allow commands to fine-tune the syntax because of the domain nushell is in (command-line shells). The syntactic expansions supported by this facility are relatively limited. For example, we don't allow `$it` to become a bare word, simply because the command asks for a string in the relevant position. That would quickly become more confusing than it's worth. This PR adds a new `SyntaxType` rule: `SyntaxType::Path`. When a command declares a parameter as a `SyntaxType::Path`, string literals and bare words passed as an argument to that parameter are processed using the path expansion rules. Right now, that only means that `~` is expanded into the home directory, but additional rules are possible in the future. By restricting this expansion to a syntactic expansion when passed as an argument to a command expecting a path, we avoid making `~` a generally reserved character. This will also allow us to give good tab completion for paths with `~` characters in them when a command is expecting a path. In order to accomplish the above, this commit changes the parsing functions to take a `Context` instead of just a `CommandRegistry`. From the perspective of macro expansion, you can think of the `CommandRegistry` as a dictionary of in-scope macros, and the `Context` as the compile-time state used in expansion. This could gain additional functionality over time as we find more uses for the expansion system.
2019-08-26 19:21:03 +00:00
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if call_info.args.has("major") {
2019-08-10 08:54:49 +00:00
self.for_semver(SemVerAction::Major);
2019-07-18 01:49:12 +00:00
}
if call_info.args.has("minor") {
2019-08-10 08:54:49 +00:00
self.for_semver(SemVerAction::Minor);
2019-07-18 01:49:12 +00:00
}
if call_info.args.has("patch") {
2019-08-10 08:54:49 +00:00
self.for_semver(SemVerAction::Patch);
2019-07-18 01:49:12 +00:00
}
if let Some(args) = call_info.args.positional {
2019-07-13 02:07:06 +00:00
for arg in args {
match arg {
2019-08-01 01:58:42 +00:00
Tagged {
2019-07-18 01:32:19 +00:00
item: Value::Primitive(Primitive::String(s)),
2019-07-13 02:07:06 +00:00
..
} => {
2019-07-18 01:32:19 +00:00
self.field = Some(s);
}
_ => {
return Err(ShellError::string(format!(
"Unrecognized type in params: {:?}",
arg
)))
2019-06-27 04:56:48 +00:00
}
}
}
2019-07-13 02:07:06 +00:00
}
2019-08-10 08:54:49 +00:00
if self.action.is_none() {
self.action = Some(Action::Default);
}
match &self.error {
Some(reason) => {
return Err(ShellError::string(format!("{}: {}", reason, Inc::usage())))
2019-08-10 08:54:49 +00:00
}
None => Ok(vec![]),
}
2019-07-13 02:07:06 +00:00
}
2019-08-01 01:58:42 +00:00
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
2019-08-10 08:54:49 +00:00
Ok(vec![ReturnSuccess::value(self.inc(input)?)])
2019-06-27 04:56:48 +00:00
}
2019-07-02 07:56:20 +00:00
}
2019-06-27 04:56:48 +00:00
2019-07-02 07:56:20 +00:00
fn main() {
serve_plugin(&mut Inc::new());
2019-06-27 04:56:48 +00:00
}
2019-08-10 08:54:49 +00:00
#[cfg(test)]
mod tests {
use super::{Inc, SemVerAction};
use indexmap::IndexMap;
use nu::{
CallInfo, EvaluatedArgs, Plugin, ReturnSuccess, SourceMap, Span, Tag, Tagged,
TaggedDictBuilder, TaggedItem, Value,
2019-08-10 08:54:49 +00:00
};
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().expect("Can not configure plugin");
2019-08-10 08:54:49 +00:00
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").unwrap(), Value::string("1.0.0"));
2019-08-10 08:54:49 +00:00
}
#[test]
fn incs_minor() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Minor);
assert_eq!(inc.apply("0.1.3").unwrap(), Value::string("0.2.0"));
2019-08-10 08:54:49 +00:00
}
#[test]
fn incs_patch() {
let mut inc = Inc::new();
inc.for_semver(SemVerAction::Patch);
assert_eq!(inc.apply("0.1.3").unwrap(), Value::string("0.1.4"));
2019-08-10 08:54:49 +00:00
}
#[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"))
),
_ => {}
}
}
}