aboutsummaryrefslogtreecommitdiff
path: root/mingling_core
diff options
context:
space:
mode:
Diffstat (limited to 'mingling_core')
-rw-r--r--mingling_core/src/lib.rs3
-rw-r--r--mingling_core/src/program/exec.rs9
-rw-r--r--mingling_core/src/program/hook.rs31
-rw-r--r--mingling_core/src/program/hook/hook_info.rs5
-rw-r--r--mingling_core/src/program/once_exec.rs14
-rw-r--r--mingling_core/src/program/repl_exec.rs14
-rw-r--r--mingling_core/src/utils.rs3
-rw-r--r--mingling_core/src/utils/splitter.rs (renamed from mingling_core/src/program/repl_exec/splitter.rs)78
8 files changed, 114 insertions, 43 deletions
diff --git a/mingling_core/src/lib.rs b/mingling_core/src/lib.rs
index 7048307..641118c 100644
--- a/mingling_core/src/lib.rs
+++ b/mingling_core/src/lib.rs
@@ -110,3 +110,6 @@ pub mod __private {
/// Mingling's convention metadatas, which can be bound to types using `#[metadata]`, to provide identification for types
pub mod metadata;
+
+/// Some common utilities in Mingling, providing a collection of functionality needed by many modules.
+pub mod utils;
diff --git a/mingling_core/src/program/exec.rs b/mingling_core/src/program/exec.rs
index 923b47b..b0a5b16 100644
--- a/mingling_core/src/program/exec.rs
+++ b/mingling_core/src/program/exec.rs
@@ -15,13 +15,14 @@ pub fn exec<C>(program: &'static Program<C>) -> Result<RenderResult, ProgramInte
where
C: ProgramCollect<Enum = C> + Send + Sync,
{
- might_be_async::invoke!(exec_with_args(program, &program.args))
+ let mut args = program.args.clone();
+ might_be_async::invoke!(exec_with_args(program, &mut args))
}
#[might_be_async::func]
pub fn exec_with_args<C>(
program: &'static Program<C>,
- args: &[String],
+ args: &mut Vec<String>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
C: ProgramCollect<Enum = C> + Send + Sync,
@@ -51,7 +52,9 @@ where
// Run hooks
control!(
- program.run_hook_pre_dispatch(&crate::hook::HookPreDispatchInfo { arguments: args }),
+ program.run_hook_pre_dispatch(&mut crate::hook::HookPreDispatchInfo {
+ arguments: &mut *args,
+ }),
current
);
diff --git a/mingling_core/src/program/hook.rs b/mingling_core/src/program/hook.rs
index 8fd2ba1..92106f9 100644
--- a/mingling_core/src/program/hook.rs
+++ b/mingling_core/src/program/hook.rs
@@ -64,8 +64,9 @@ where
pub begin: Option<Box<dyn Fn(&HookBeginInfo) + Send + Sync>>,
/// Executes before the program dispatches
- pub pre_dispatch:
- Option<Box<dyn for<'a> Fn(&HookPreDispatchInfo<'a>) -> ProgramControls<C> + Send + Sync>>,
+ pub pre_dispatch: Option<
+ Box<dyn for<'a> Fn(&mut HookPreDispatchInfo<'a>) -> ProgramControls<C> + Send + Sync>,
+ >,
/// Executes after the program dispatches
pub post_dispatch: Option<
@@ -162,7 +163,10 @@ where
}
}
- pub(crate) fn run_hook_pre_dispatch(&self, info: &HookPreDispatchInfo) -> ProgramControls<C> {
+ pub(crate) fn run_hook_pre_dispatch(
+ &self,
+ info: &mut HookPreDispatchInfo,
+ ) -> ProgramControls<C> {
if !self.user_context.run_hook {
return ProgramControls::Empty;
}
@@ -475,7 +479,7 @@ where
#[must_use]
pub fn on_pre_dispatch<F, R>(mut self, handler: F) -> Self
where
- F: for<'a> Fn(&HookPreDispatchInfo<'a>) -> R + 'static + Send + Sync,
+ F: for<'a> Fn(&mut HookPreDispatchInfo<'a>) -> R + 'static + Send + Sync,
R: Into<ProgramControls<C>>,
{
self.pre_dispatch = Some(Box::new(move |info| handler(info).into()));
@@ -801,16 +805,21 @@ mod tests {
#[test]
fn test_hook_on_pre_dispatch() {
static CALLED: AtomicBool = AtomicBool::new(false);
- let hook =
- ProgramHook::<MockHookEnum>::empty().on_pre_dispatch(|info: &HookPreDispatchInfo| {
- assert_eq!(info.arguments, &["a", "b"]);
+ let mut args = vec!["a".to_string(), "b".to_string()];
+ let hook = ProgramHook::<MockHookEnum>::empty().on_pre_dispatch(
+ |info: &mut HookPreDispatchInfo| {
+ assert_eq!(info.arguments.as_slice(), &["a", "b"]);
+ // The hook may rewrite the arguments before dispatch
+ info.arguments.push("c".to_string());
CALLED.store(true, Ordering::SeqCst);
- });
+ },
+ );
assert!(hook.pre_dispatch.is_some());
- (hook.pre_dispatch.as_ref().unwrap())(&HookPreDispatchInfo {
- arguments: &["a".to_string(), "b".to_string()],
+ (hook.pre_dispatch.as_ref().unwrap())(&mut HookPreDispatchInfo {
+ arguments: &mut args,
});
assert!(CALLED.load(Ordering::SeqCst));
+ assert_eq!(args.as_slice(), &["a", "b", "c"]);
}
#[test]
@@ -910,7 +919,7 @@ mod tests {
fn test_hook_builder_chaining() {
let hook = ProgramHook::<MockHookEnum>::empty()
.on_begin::<_, ()>(|_: &HookBeginInfo| ())
- .on_pre_dispatch(|_: &HookPreDispatchInfo| ())
+ .on_pre_dispatch(|_: &mut HookPreDispatchInfo| ())
.on_post_dispatch(|_: &HookPostDispatchInfo<MockHookEnum>| ())
.on_pre_chain(|_: &HookPreChainInfo<MockHookEnum>| ())
.on_post_chain(|_: &HookPostChainInfo<MockHookEnum>| ())
diff --git a/mingling_core/src/program/hook/hook_info.rs b/mingling_core/src/program/hook/hook_info.rs
index 768f652..25cf272 100644
--- a/mingling_core/src/program/hook/hook_info.rs
+++ b/mingling_core/src/program/hook/hook_info.rs
@@ -7,7 +7,10 @@ pub struct HookBeginInfo {}
/// Represents the data passed to `pre_dispatch` hook.
pub struct HookPreDispatchInfo<'a> {
/// Arguments entered by the user before dispatching
- pub arguments: &'a [String],
+ ///
+ /// The reference is mutable so the hook can rewrite the arguments before
+ /// they are matched against the registered dispatchers.
+ pub arguments: &'a mut Vec<String>,
}
/// Represents the data passed to `post_dispatch` hook.
diff --git a/mingling_core/src/program/once_exec.rs b/mingling_core/src/program/once_exec.rs
index e9927b5..203bbf5 100644
--- a/mingling_core/src/program/once_exec.rs
+++ b/mingling_core/src/program/once_exec.rs
@@ -25,15 +25,19 @@ where
self.run_hook_on_begin(&crate::hook::HookBeginInfo {});
self.args = self.args.iter().skip(1).cloned().collect();
+ let mut args = std::mem::take(&mut self.args);
#[cfg(not(feature = "async"))]
{
#[cfg(panic = "abort")]
- return self.exec_wrapper(|p| crate::exec::exec(p).map_err(|e| e.into()));
+ return self
+ .exec_wrapper(|p| crate::exec::exec_with_args(p, &mut args).map_err(|e| e.into()));
#[cfg(not(panic = "abort"))]
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- self.exec_wrapper(|p| crate::exec::exec(p).map_err(std::convert::Into::into))
+ self.exec_wrapper(|p| {
+ crate::exec::exec_with_args(p, &mut args).map_err(std::convert::Into::into)
+ })
})) {
Ok(result) => result,
Err(panic_info) => {
@@ -60,7 +64,11 @@ where
#[cfg(feature = "async")]
{
return self
- .exec_wrapper(|p| async { crate::exec::exec(p).await.map_err(Into::into) })
+ .exec_wrapper(|p| async move {
+ crate::exec::exec_with_args(p, &mut args)
+ .await
+ .map_err(Into::into)
+ })
.await;
}
}
diff --git a/mingling_core/src/program/repl_exec.rs b/mingling_core/src/program/repl_exec.rs
index 9d9be30..2db5c5a 100644
--- a/mingling_core/src/program/repl_exec.rs
+++ b/mingling_core/src/program/repl_exec.rs
@@ -7,10 +7,8 @@ use std::io::Write;
#[doc(hidden)]
pub mod res;
-mod splitter;
-
use crate::error::{ProgramInternalExecuteError, ProgramPanic};
-use crate::program::repl_exec::splitter::split_input_string;
+use crate::utils::ArgumentSplitter;
use crate::{Program, ProgramCollect, RenderResult};
use crate::{program::repl_exec::res::ResREPL, this};
@@ -58,10 +56,10 @@ where
line: &mut readline,
});
- let args = split_input_string(&readline);
+ let mut args = readline.split_args();
p.run_hook_repl_pre_exec(&crate::hook::HookREPLPreExecInfo { args: &args });
- match might_be_async::invoke!(exec_once(p, &args)) {
+ match might_be_async::invoke!(exec_once(p, &mut args)) {
Ok(r) => {
p.run_hook_repl_on_receive_result(&crate::hook::HookREPLOnReceiveResultInfo {
result: &r,
@@ -91,13 +89,13 @@ where
#[cfg(not(feature = "async"))]
fn exec_once<C>(
p: &'static Program<C>,
- args: &[String],
+ args: &mut Vec<String>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
C: ProgramCollect<Enum = C> + Send + Sync + 'static,
{
#[cfg(panic = "abort")]
- let exec_result = super::exec::exec_with_args(p, &args);
+ let exec_result = super::exec::exec_with_args(p, args);
#[cfg(not(panic = "abort"))]
let exec_result = {
@@ -130,7 +128,7 @@ where
#[cfg(feature = "async")]
async fn exec_once<C>(
p: &'static Program<C>,
- args: &[String],
+ args: &mut Vec<String>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
C: ProgramCollect<Enum = C> + Send + Sync + 'static,
diff --git a/mingling_core/src/utils.rs b/mingling_core/src/utils.rs
new file mode 100644
index 0000000..89fcd8f
--- /dev/null
+++ b/mingling_core/src/utils.rs
@@ -0,0 +1,3 @@
+mod splitter;
+
+pub use splitter::ArgumentSplitter;
diff --git a/mingling_core/src/program/repl_exec/splitter.rs b/mingling_core/src/utils/splitter.rs
index 312ad73..6b2ea11 100644
--- a/mingling_core/src/program/repl_exec/splitter.rs
+++ b/mingling_core/src/utils/splitter.rs
@@ -1,12 +1,56 @@
-// Doc Not Optimize
-/// Wraps `split_input` to work with owned `String` inputs.
-pub fn split_input_string(input: &str) -> Vec<String> {
- split_input(input)
+/// A trait for splitting strings into arguments, respecting quotes and escapes.
+///
+/// # Examples
+///
+/// ```
+/// use mingling_core::utils::ArgumentSplitter;
+///
+/// let args = "echo \"hello world\"".split_args();
+/// assert_eq!(args, vec!["echo", "hello world"]);
+/// ```
+pub trait ArgumentSplitter {
+ /// Splits the input string into a vector of argument strings.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use mingling_core::utils::ArgumentSplitter;
+ ///
+ /// let args = "a 'b c' d".split_args();
+ /// assert_eq!(args, vec!["a", "b c", "d"]);
+ /// ```
+ fn split_args(self) -> Vec<String>;
+}
+
+impl<S: AsRef<str>> ArgumentSplitter for S {
+ /// Splits the string into arguments, respecting single quotes, double
+ /// quotes, and backslash escaping.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use mingling_core::utils::ArgumentSplitter;
+ ///
+ /// let args = r#"cmd --flag "value with spaces""#.split_args();
+ /// assert_eq!(args, vec!["cmd", "--flag", "value with spaces"]);
+ /// ```
+ ///
+ /// Escaped characters are unescaped:
+ ///
+ /// ```
+ /// use mingling_core::utils::ArgumentSplitter;
+ ///
+ /// let args = r#"echo a\ b"#.split_args();
+ /// assert_eq!(args, vec!["echo", "a b"]);
+ /// ```
+ fn split_args(self) -> Vec<String> {
+ split_args(self.as_ref())
+ }
}
/// Splits a string input into arguments, respecting single quotes, double quotes,
/// and backslash escaping.
-pub fn split_input(input: &str) -> Vec<String> {
+fn split_args(input: &str) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
let mut current = String::new();
let mut chars = input.chars();
@@ -63,72 +107,72 @@ pub fn split_input(input: &str) -> Vec<String> {
#[cfg(test)]
mod splitter_tests {
- use crate::program::repl_exec::splitter::split_input;
+ use crate::utils::splitter::split_args;
#[test]
fn test_split_with_double_quotes() {
let input = r#"a "b c" d"#;
- let result = split_input(input);
+ let result = split_args(input);
assert_eq!(result, vec!["a", "b c", "d"]);
}
#[test]
fn test_split_with_single_quotes() {
let input = "a 'b c' d";
- let result = split_input(input);
+ let result = split_args(input);
assert_eq!(result, vec!["a", "b c", "d"]);
}
#[test]
fn test_empty_input() {
- assert!(split_input("").is_empty());
+ assert!(split_args("").is_empty());
}
#[test]
fn test_no_quotes() {
- let result = split_input("hello world");
+ let result = split_args("hello world");
assert_eq!(result, vec!["hello", "world"]);
}
#[test]
fn test_double_quotes_at_edges() {
- let result = split_input(r#""hello world" foo"#);
+ let result = split_args(r#""hello world" foo"#);
assert_eq!(result, vec!["hello world", "foo"]);
}
#[test]
fn test_single_quotes_at_edges() {
- let result = split_input("'hello world' foo");
+ let result = split_args("'hello world' foo");
assert_eq!(result, vec!["hello world", "foo"]);
}
#[test]
fn test_multiple_double_quoted_parts() {
- let result = split_input(r#"a "b c" d "e f g""#);
+ let result = split_args(r#"a "b c" d "e f g""#);
assert_eq!(result, vec!["a", "b c", "d", "e f g"]);
}
#[test]
fn test_multiple_single_quoted_parts() {
- let result = split_input("a 'b c' d 'e f g'");
+ let result = split_args("a 'b c' d 'e f g'");
assert_eq!(result, vec!["a", "b c", "d", "e f g"]);
}
#[test]
fn test_backslash_escaped_space() {
- let result = split_input("a b\\ c d");
+ let result = split_args("a b\\ c d");
assert_eq!(result, vec!["a", "b c", "d"]);
}
#[test]
fn test_backslash_escaped_double_quote() {
- let result = split_input(r#"a b\"c d"#);
+ let result = split_args(r#"a b\"c d"#);
assert_eq!(result, vec!["a", r#"b"c"#, "d"]);
}
#[test]
fn test_backslash_escaped_single_quote() {
- let result = split_input("a b\\'c d");
+ let result = split_args("a b\\'c d");
assert_eq!(result, vec!["a", "b'c", "d"]);
}
}