nushell/src/plugins/match.rs

107 lines
3.1 KiB
Rust
Raw Normal View History

2019-10-02 18:56:28 +00:00
use nu::{
2019-10-02 20:41:52 +00:00
serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature,
SyntaxShape, Tagged, Value,
2019-10-02 18:56:28 +00:00
};
use regex::Regex;
struct Match {
column: String,
regex: Regex,
}
impl Match {
fn new() -> Self {
2019-10-02 20:41:52 +00:00
Match {
column: String::new(),
2019-10-02 18:56:28 +00:00
regex: Regex::new("").unwrap(),
}
}
}
impl Plugin for Match {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("match")
.desc("filter rows by regex")
.required("member", SyntaxShape::Member)
.required("regex", SyntaxShape::String)
.filter())
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if let Some(args) = call_info.args.positional {
match &args[0] {
Tagged {
item: Value::Primitive(Primitive::String(s)),
..
} => {
self.column = s.clone();
}
_ => {
return Err(ShellError::string(format!(
2019-10-02 20:41:52 +00:00
"Unrecognized type in params: {:?}",
args[0]
)));
2019-10-02 18:56:28 +00:00
}
}
match &args[1] {
Tagged {
item: Value::Primitive(Primitive::String(s)),
..
} => {
self.regex = Regex::new(s).unwrap();
}
_ => {
2019-10-02 20:41:52 +00:00
return Err(ShellError::string(format!(
"Unrecognized type in params: {:?}",
2019-10-03 06:21:24 +00:00
args[1]
2019-10-02 20:41:52 +00:00
)));
2019-10-02 18:56:28 +00:00
}
}
}
Ok(vec![])
}
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
let flag: bool;
match &input {
Tagged {
item: Value::Row(dict),
..
} => {
if let Some(val) = dict.entries.get(&self.column) {
match val {
Tagged {
item: Value::Primitive(Primitive::String(s)),
..
} => {
flag = self.regex.is_match(s);
}
_ => {
return Err(ShellError::string(format!(
2019-10-02 20:41:52 +00:00
"value is not a string! {:?}",
&val
)));
2019-10-02 18:56:28 +00:00
}
}
} else {
return Err(ShellError::string(format!(
2019-10-02 20:41:52 +00:00
"column not in row! {:?} {:?}",
&self.column, dict
)));
2019-10-02 18:56:28 +00:00
}
}
_ => {
2019-10-02 20:41:52 +00:00
return Err(ShellError::string(format!("Not a row! {:?}", &input)));
2019-10-02 18:56:28 +00:00
}
}
if flag {
2019-10-02 20:41:52 +00:00
Ok(vec![Ok(ReturnSuccess::Value(input))])
2019-10-02 18:56:28 +00:00
} else {
Ok(vec![])
}
}
}
fn main() {
serve_plugin(&mut Match::new());
}