Removes regex crate dependency.

This commit is contained in:
Andrés N. Robalino 2019-09-11 22:20:42 -05:00
parent 4edc7422cd
commit b35549adac
6 changed files with 61 additions and 354 deletions

1
Cargo.lock generated
View file

@ -1542,7 +1542,6 @@ dependencies = [
"prettytable-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "prettytable-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"ptree 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "ptree 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rawkey 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "rawkey 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"roxmltree 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "roxmltree 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rusqlite 0.20.0 (registry+https://github.com/rust-lang/crates.io-index)", "rusqlite 0.20.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rustyline 5.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "rustyline 5.0.2 (registry+https://github.com/rust-lang/crates.io-index)",

View file

@ -59,7 +59,6 @@ unicode-xid = "0.2.0"
serde_ini = "0.2.0" serde_ini = "0.2.0"
subprocess = "0.1.18" subprocess = "0.1.18"
mime = "0.3.13" mime = "0.3.13"
regex = "1.2.1"
pretty-hex = "0.1.0" pretty-hex = "0.1.0"
hex = "0.3.2" hex = "0.3.2"
tempfile = "3.1.0" tempfile = "3.1.0"

View file

@ -15,7 +15,6 @@ use crate::parser::{hir, CallNode, Pipeline, PipelineElement, TokenNode};
use crate::prelude::*; use crate::prelude::*;
use log::{debug, trace}; use log::{debug, trace};
use regex::Regex;
use rustyline::error::ReadlineError; use rustyline::error::ReadlineError;
use rustyline::{self, config::Configurer, config::EditMode, ColorMode, Config, Editor}; use rustyline::{self, config::Configurer, config::EditMode, ColorMode, Config, Editor};
use std::env; use std::env;
@ -98,38 +97,12 @@ fn load_plugin(path: &std::path::Path, context: &mut Context) -> Result<(), Shel
result result
} }
fn load_plugins_in_dir(path: &std::path::PathBuf, context: &mut Context) -> Result<(), ShellError> { fn search_paths() -> Vec<std::path::PathBuf> {
let re_bin = Regex::new(r"^nu_plugin_[A-Za-z_]+$")?; let mut search_paths = Vec::new();
let re_exe = Regex::new(r"^nu_plugin_[A-Za-z_]+\.(exe|bat)$")?;
trace!("Looking for plugins in {:?}", path);
match std::fs::read_dir(path) {
Ok(p) => {
for entry in p {
let entry = entry?;
let filename = entry.file_name();
let f_name = filename.to_string_lossy();
if re_bin.is_match(&f_name) || re_exe.is_match(&f_name) {
let mut load_path = path.clone();
trace!("Found {:?}", f_name);
load_path.push(f_name.to_string());
load_plugin(&load_path, context)?;
}
}
}
_ => {}
}
Ok(())
}
fn load_plugins(context: &mut Context) -> Result<(), ShellError> {
match env::var_os("PATH") { match env::var_os("PATH") {
Some(paths) => { Some(paths) => {
for path in env::split_paths(&paths) { search_paths = env::split_paths(&paths).collect::<Vec<_>>();
let _ = load_plugins_in_dir(&path, context);
}
} }
None => println!("PATH is not defined in the environment."), None => println!("PATH is not defined in the environment."),
} }
@ -140,7 +113,7 @@ fn load_plugins(context: &mut Context) -> Result<(), ShellError> {
let mut path = std::path::PathBuf::from("."); let mut path = std::path::PathBuf::from(".");
path.push("target"); path.push("target");
path.push("debug"); path.push("debug");
let _ = load_plugins_in_dir(&path, context); search_paths.push(path);
} }
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
@ -150,7 +123,58 @@ fn load_plugins(context: &mut Context) -> Result<(), ShellError> {
path.push("target"); path.push("target");
path.push("release"); path.push("release");
let _ = load_plugins_in_dir(&path, context); search_paths.push(path);
}
search_paths
}
fn load_plugins(context: &mut Context) -> Result<(), ShellError> {
let opts = glob::MatchOptions {
case_sensitive: false,
require_literal_separator: false,
require_literal_leading_dot: false,
};
for path in search_paths() {
let pattern = path.join("nu_plugin_[a-z][a-z]*").clone();
trace!("Trying {:?}", pattern.display());
match glob::glob_with(&pattern.to_string_lossy(), opts) {
Err(_) => {}
Ok(binaries) => {
for bin in binaries.filter_map(Result::ok) {
if !bin.is_file() {
continue;
}
trace!("Found {:?}", bin.display());
let bin_name = bin.file_name().unwrap().to_string_lossy();
let is_valid_name = bin_name
.chars()
.all(|c| c.is_ascii_alphabetic() || c == '_');
let is_executable = {
#[cfg(windows)]
{
bin_name.ends_with(".exe") || bin_name.ends_with(".bat")
}
#[cfg(not(windows))]
{
true
}
};
if is_valid_name && is_executable {
load_plugin(&bin, context)?;
}
}
}
}
} }
Ok(()) Ok(())

View file

@ -555,16 +555,6 @@ impl std::convert::From<serde_json::Error> for ShellError {
} }
} }
impl std::convert::From<regex::Error> for ShellError {
fn from(input: regex::Error) -> ShellError {
ProximateShellError::String(StringError {
title: format!("{:?}", input),
error: Value::nothing(),
})
.start()
}
}
impl std::convert::From<Box<dyn std::error::Error + Send + Sync>> for ShellError { impl std::convert::From<Box<dyn std::error::Error + Send + Sync>> for ShellError {
fn from(input: Box<dyn std::error::Error + Send + Sync>) -> ShellError { fn from(input: Box<dyn std::error::Error + Send + Sync>) -> ShellError {
ProximateShellError::String(StringError { ProximateShellError::String(StringError {

View file

@ -2,20 +2,12 @@ use nu::{
serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature, serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature,
SyntaxType, Tagged, Value, SyntaxType, Tagged, Value,
}; };
use regex::Regex;
#[derive(Debug, Eq, PartialEq)] #[derive(Debug, Eq, PartialEq)]
enum Action { enum Action {
Downcase, Downcase,
Upcase, Upcase,
ToInteger, ToInteger,
Replace(ReplaceAction),
}
#[derive(Debug, Eq, PartialEq)]
enum ReplaceAction {
Direct,
FindAndReplace,
} }
struct Str { struct Str {
@ -45,41 +37,12 @@ impl Str {
Err(_) => Value::string(input), Err(_) => Value::string(input),
}, },
}, },
Some(Action::Replace(ref mode)) => match mode {
ReplaceAction::Direct => Value::string(self.first_param()),
ReplaceAction::FindAndReplace => {
let regex = Regex::new(self.first_param());
match regex {
Ok(re) => Value::string(re.replace(input, self.second_param()).to_owned()),
Err(_) => Value::string(input),
}
}
},
None => Value::string(input), None => Value::string(input),
}; };
Ok(applied) Ok(applied)
} }
fn did_supply_field(&self) -> bool {
self.field.is_some()
}
fn first_param(&self) -> &str {
let idx = if self.did_supply_field() { 1 } else { 0 };
self.get_param(idx)
}
fn second_param(&self) -> &str {
let idx = if self.did_supply_field() { 2 } else { 1 };
self.get_param(idx)
}
fn get_param(&self, idx: usize) -> &str {
self.params.as_ref().unwrap().get(idx).unwrap().as_str()
}
fn for_field(&mut self, field: &str) { fn for_field(&mut self, field: &str) {
self.field = Some(String::from(field)); self.field = Some(String::from(field));
} }
@ -92,14 +55,6 @@ impl Str {
self.error = Some(message.to_string()); self.error = Some(message.to_string());
} }
fn for_replace(&mut self, mode: ReplaceAction) {
if self.permit() {
self.action = Some(Action::Replace(mode));
} else {
self.log_error("can only apply one");
}
}
fn for_to_int(&mut self) { fn for_to_int(&mut self) {
if self.permit() { if self.permit() {
self.action = Some(Action::ToInteger); self.action = Some(Action::ToInteger);
@ -125,7 +80,7 @@ impl Str {
} }
pub fn usage() -> &'static str { pub fn usage() -> &'static str {
"Usage: str field [--downcase|--upcase|--to-int|--replace|--find-replace]" "Usage: str field [--downcase|--upcase|--to-int]"
} }
} }
@ -172,8 +127,6 @@ impl Plugin for Str {
.switch("downcase") .switch("downcase")
.switch("upcase") .switch("upcase")
.switch("to-int") .switch("to-int")
.switch("replace")
.switch("find-replace")
.rest(SyntaxType::Member) .rest(SyntaxType::Member)
.filter()) .filter())
} }
@ -190,12 +143,6 @@ impl Plugin for Str {
if args.has("to-int") { if args.has("to-int") {
self.for_to_int(); self.for_to_int();
} }
if args.has("replace") {
self.for_replace(ReplaceAction::Direct);
}
if args.has("find-replace") {
self.for_replace(ReplaceAction::FindAndReplace);
}
if let Some(possible_field) = args.nth(0) { if let Some(possible_field) = args.nth(0) {
match possible_field { match possible_field {
@ -203,16 +150,6 @@ impl Plugin for Str {
item: Value::Primitive(Primitive::String(s)), item: Value::Primitive(Primitive::String(s)),
.. ..
} => match self.action { } => match self.action {
Some(Action::Replace(ReplaceAction::Direct)) => {
if args.len() == 2 {
self.for_field(&s);
}
}
Some(Action::Replace(ReplaceAction::FindAndReplace)) => {
if args.len() == 3 {
self.for_field(&s);
}
}
Some(Action::Downcase) Some(Action::Downcase)
| Some(Action::Upcase) | Some(Action::Upcase)
| Some(Action::ToInteger) | Some(Action::ToInteger)
@ -258,7 +195,7 @@ fn main() {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{Action, ReplaceAction, Str}; use super::{Action, Str};
use indexmap::IndexMap; use indexmap::IndexMap;
use nu::{ use nu::{
CallInfo, EvaluatedArgs, Plugin, Primitive, ReturnSuccess, SourceMap, Span, Tag, Tagged, CallInfo, EvaluatedArgs, Plugin, Primitive, ReturnSuccess, SourceMap, Span, Tag, Tagged,
@ -266,16 +203,6 @@ mod tests {
}; };
use num_bigint::BigInt; use num_bigint::BigInt;
impl Str {
fn replace_with(&mut self, value: &str) {
self.params.as_mut().unwrap().push(value.to_string());
}
fn find_with(&mut self, search: &str) {
self.params.as_mut().unwrap().push(search.to_string());
}
}
struct CallStub { struct CallStub {
positionals: Vec<Tagged<Value>>, positionals: Vec<Tagged<Value>>,
flags: IndexMap<String, Tagged<Value>>, flags: IndexMap<String, Tagged<Value>>,
@ -328,7 +255,7 @@ mod tests {
let configured = plugin.config().unwrap(); let configured = plugin.config().unwrap();
for action_flag in &["downcase", "upcase", "to-int", "replace", "find-replace"] { for action_flag in &["downcase", "upcase", "to-int"] {
assert!(configured.named.get(*action_flag).is_some()); assert!(configured.named.get(*action_flag).is_some());
} }
} }
@ -362,33 +289,6 @@ mod tests {
.is_ok()); .is_ok());
assert_eq!(plugin.action.unwrap(), Action::ToInteger); assert_eq!(plugin.action.unwrap(), Action::ToInteger);
} }
#[test]
fn str_plugin_accepts_replace() {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(CallStub::new().with_long_flag("replace").create())
.is_ok());
assert_eq!(
plugin.action.unwrap(),
Action::Replace(ReplaceAction::Direct)
);
}
#[test]
fn str_plugin_accepts_find_replace() {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(CallStub::new().with_long_flag("find-replace").create())
.is_ok());
assert_eq!(
plugin.action.unwrap(),
Action::Replace(ReplaceAction::FindAndReplace)
);
}
#[test] #[test]
fn str_plugin_accepts_field() { fn str_plugin_accepts_field() {
let mut plugin = Str::new(); let mut plugin = Str::new();
@ -441,26 +341,6 @@ mod tests {
assert_eq!(strutils.apply("9999").unwrap(), Value::int(9999 as i64)); assert_eq!(strutils.apply("9999").unwrap(), Value::int(9999 as i64));
} }
#[test]
fn str_replace() {
let mut strutils = Str::new();
strutils.for_replace(ReplaceAction::Direct);
strutils.replace_with("robalino");
assert_eq!(strutils.apply("andres").unwrap(), Value::string("robalino"));
}
#[test]
fn str_find_replace() {
let mut strutils = Str::new();
strutils.for_replace(ReplaceAction::FindAndReplace);
strutils.find_with(r"kittens");
strutils.replace_with("jotandrehuda");
assert_eq!(
strutils.apply("wykittens").unwrap(),
Value::string("wyjotandrehuda")
);
}
#[test] #[test]
fn str_plugin_applies_upcase_with_field() { fn str_plugin_applies_upcase_with_field() {
let mut plugin = Str::new(); let mut plugin = Str::new();
@ -604,114 +484,4 @@ mod tests {
_ => {} _ => {}
} }
} }
#[test]
fn str_plugin_applies_replace_with_field() {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_parameter("rustconf")
.with_parameter("22nd August 2019")
.with_long_flag("replace")
.create()
)
.is_ok());
let subject = structured_sample_record("rustconf", "1st January 1970");
let output = plugin.filter(subject).unwrap();
match output[0].as_ref().unwrap() {
ReturnSuccess::Value(Tagged {
item: Value::Row(o),
..
}) => assert_eq!(
*o.get_data(&String::from("rustconf")).borrow(),
Value::string(String::from("22nd August 2019"))
),
_ => {}
}
}
#[test]
fn str_plugin_applies_replace_without_field() {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_parameter("22nd August 2019")
.with_long_flag("replace")
.create()
)
.is_ok());
let subject = unstructured_sample_record("1st January 1970");
let output = plugin.filter(subject).unwrap();
match output[0].as_ref().unwrap() {
ReturnSuccess::Value(Tagged {
item: Value::Primitive(Primitive::String(s)),
..
}) => assert_eq!(*s, String::from("22nd August 2019")),
_ => {}
}
}
#[test]
fn str_plugin_applies_find_replace_with_field() {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_parameter("staff")
.with_parameter("kittens")
.with_parameter("jotandrehuda")
.with_long_flag("find-replace")
.create()
)
.is_ok());
let subject = structured_sample_record("staff", "wykittens");
let output = plugin.filter(subject).unwrap();
match output[0].as_ref().unwrap() {
ReturnSuccess::Value(Tagged {
item: Value::Row(o),
..
}) => assert_eq!(
*o.get_data(&String::from("staff")).borrow(),
Value::string(String::from("wyjotandrehuda"))
),
_ => {}
}
}
#[test]
fn str_plugin_applies_find_replace_without_field() {
let mut plugin = Str::new();
assert!(plugin
.begin_filter(
CallStub::new()
.with_parameter("kittens")
.with_parameter("jotandrehuda")
.with_long_flag("find-replace")
.create()
)
.is_ok());
let subject = unstructured_sample_record("wykittens");
let output = plugin.filter(subject).unwrap();
match output[0].as_ref().unwrap() {
ReturnSuccess::Value(Tagged {
item: Value::Primitive(Primitive::String(s)),
..
}) => assert_eq!(*s, String::from("wyjotandrehuda")),
_ => {}
}
}
} }

View file

@ -11,7 +11,7 @@ fn can_only_apply_one() {
); );
assert!( assert!(
actual.contains("Usage: str field [--downcase|--upcase|--to-int|--replace|--find-replace]") actual.contains("Usage: str field [--downcase|--upcase|--to-int")
); );
} }
@ -92,78 +92,3 @@ fn converts_to_int() {
assert_eq!(actual, "2509000000"); assert_eq!(actual, "2509000000");
} }
#[test]
fn replaces() {
Playground::setup("plugin_str_test_4", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContent(
"sample.toml",
r#"
[package]
name = "nushell"
"#,
)]);
let actual = nu!(
cwd: dirs.test(), h::pipeline(
r#"
open sample.toml
| str package.name --replace wykittenshell
| get package.name
| echo $it
"#
));
assert_eq!(actual, "wykittenshell");
})
}
#[test]
fn find_and_replaces() {
Playground::setup("plugin_str_test_5", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContent(
"sample.toml",
r#"
[fortune.teller]
phone = "1-800-KATZ"
"#,
)]);
let actual = nu!(
cwd: dirs.test(), h::pipeline(
r#"
open sample.toml
| str fortune.teller.phone --find-replace KATZ "5289"
| get fortune.teller.phone
| echo $it
"#
));
assert_eq!(actual, "1-800-5289");
})
}
#[test]
fn find_and_replaces_without_passing_field() {
Playground::setup("plugin_str_test_6", |dirs, sandbox| {
sandbox.with_files(vec![FileWithContent(
"sample.toml",
r#"
[fortune.teller]
phone = "1-800-KATZ"
"#,
)]);
let actual = nu!(
cwd: dirs.test(), h::pipeline(
r#"
open sample.toml
| get fortune.teller.phone
| str --find-replace KATZ "5289"
| echo $it
"#
));
assert_eq!(actual, "1-800-5289");
})
}