From 71f06a51c6b2d209cfb2e8031ee9f3853a00de24 Mon Sep 17 00:00:00 2001 From: Sean Lynch <42618346+swlynch99@users.noreply.github.com> Date: Tue, 12 Sep 2023 15:59:40 -0400 Subject: [PATCH] Support optional arguments and sequences in cmd! This commit allows the cmd! macro to also splice in any sequence which implements IntoIterator>. This requires a bit of extra syntax in the cmd! macro since it would be possible for a type to implement both Into and IntoIterator. So, in order to pass in a sequence to cmd! it needs to be prefixed with ... like this: cmd!("echo", "a", ...sequence, "b"); I have chosen ... here because ... is not a valid rust expression and so it shouldn't conflict with anything else. Unfortunately, it's not really possible to cleanly create a macro input which declaratively parses either ...$arg or $arg so the cmd! macro just takes a bunch of tokens and uses a second helper macro (cmd_expand_args!) in order to parse that into something usable. Since Option also implements IntoIterator this can also be rather easily used for optional arguments since you can just do: cmd!("echo", "a", ...Some("b")); I have tried to expand the docs with some examples to cover all of these use cases which should cover for the actual macro arguments shown in rustdoc being less readable now. Fixes #88 --- src/lib.rs | 91 +++++++++++++++++++++++++++++++++++++++++++---------- src/test.rs | 17 ++++++++++ 2 files changed, 92 insertions(+), 16 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9e2bef0..08cd62b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -145,40 +145,99 @@ where Expression::new(Cmd(argv_vec)) } -/// Create a command with any number of of positional arguments, which may be -/// different types (anything that implements -/// [`Into`](https://doc.rust-lang.org/std/convert/trait.From.html)). -/// See also the [`cmd`](fn.cmd.html) function, which takes a collection of -/// arguments. +/// Create a command with any number of positional arguments. /// -/// # Example +/// The arguments may be any type that implements [`Into`]. You may +/// also splice in any type that implements [`IntoIterator`] by adding `...` +/// in front of it (e.g. `cmd!("echo", ...["a", "b", "c"])`). /// -/// ``` +/// See also the [`cmd()`] function, which takes a collection of arguments. +/// +/// # Examples /// +/// Calling `cmd!` with differently typed arguments: +/// ``` /// use duct::cmd; /// use std::path::Path; /// -/// fn main() { -/// let arg1 = "foo"; -/// let arg2 = "bar".to_owned(); -/// let arg3 = Path::new("baz"); +/// let arg1 = "foo"; +/// let arg2 = "bar".to_owned(); +/// let arg3 = Path::new("baz"); +/// +/// let output = cmd!("echo", arg1, arg2, arg3).read()?; +/// assert_eq!("foo bar baz", output); +/// # +/// # std::io::Result::Ok(()) +/// ``` +/// +/// Calling `cmd!` with a list of arguments: +/// ``` +/// use duct::cmd; +/// +/// let args = ["a", "b", "c"]; +/// let output = cmd!("echo", ...args, "e", "f", "g").read()?; +/// +/// assert_eq!(output, "a b c e f g"); +/// # +/// # std::io::Result::Ok(()) +/// ``` +/// +/// Calling `cmd!` with an optional argument: +/// ``` +/// use duct::cmd; /// -/// let output = cmd!("echo", arg1, arg2, arg3).read(); +/// let blah = random().then_some("blah"); +/// let output = cmd!("echo", ...blah, "bleh", "blah").read()?; /// -/// assert_eq!("foo bar baz", output.unwrap()); +/// if blah.is_some() { +/// assert_eq!(output, "blah bleh blah"); +/// } else { +/// assert_eq!(output, "bleh blah"); /// } +/// # +/// # fn random() -> bool { false } +/// # std::io::Result::Ok(()) /// ``` #[macro_export] macro_rules! cmd { - ( $program:expr $(, $arg:expr )* $(,)? ) => { + ( $program:expr $(, $( $rest:tt )* )?) => { { - use std::ffi::OsString; - let args: std::vec::Vec = std::vec![$( Into::::into($arg) ),*]; + #[allow(unused_mut)] + let mut args = ::std::vec::Vec::<::std::ffi::OsString>::new(); + $( $crate::cmd_expand_args!(args, $( $rest )*); )? + $crate::cmd($program, args) } }; } +/// Helper for the [`cmd!`] macro which parses the command arguments and either +/// calls `$vec.push` or `$vec.extend`, as appropriate. +/// +/// In either case this macro works by parsing a single argument passed to the +/// command macro, somehow inserting it into `$vec`, and then repeating the +/// process with the rest of the arguments until there are none left. +#[doc(hidden)] +#[macro_export] +macro_rules! cmd_expand_args { + ($vec:expr, ... $arg:expr $(, $( $rest:tt )* )?) => {{ + use ::std::iter::{Extend, Iterator}; + + $vec.extend( + ::std::iter::IntoIterator::into_iter($arg) + .map(|elem| ::std::convert::Into::<::std::ffi::OsString>::into(elem)) + ); + + $crate::cmd_expand_args!($vec, $( $( $rest )* )?); + }}; + ($vec:expr, $arg:expr $(, $( $rest:tt )* )?) => { + $vec.push(::std::convert::Into::<::std::ffi::OsString>::into($arg)); + + $crate::cmd_expand_args!($vec, $( $( $rest )* )?); + }; + ($vec:expr, ) => {} +} + /// The central objects in Duct, Expressions are created with /// [`cmd`](fn.cmd.html) or [`cmd!`](macro.cmd.html), combined with /// [`pipe`](struct.Expression.html#method.pipe), and finally executed with diff --git a/src/test.rs b/src/test.rs index e0eef15..cf557f7 100644 --- a/src/test.rs +++ b/src/test.rs @@ -609,3 +609,20 @@ fn test_pids() -> io::Result<()> { Ok(()) } + +#[test] +fn test_command_with_iterator() -> io::Result<()> { + assert_eq!( + cmd!("echo", ...Some("a"), ...["b", "c", "d"]).read()?, + "a b c d" + ); + + Ok(()) +} + +#[test] +fn test_command_with_trailing_comma() -> io::Result<()> { + assert_eq!(cmd!("echo", ...["a"],).read()?, "a"); + + Ok(()) +}