oconnor663 / duct.rs

a Rust library for running child processes
MIT License
819 stars 34 forks source link

Support optional arguments and sequences in cmd! #113

Open swlynch99 opened 1 year ago

swlynch99 commented 1 year ago

This PR allows the cmd! macro to also splice in any sequence which implements IntoIterator<Item: Into<OsString>>. This requires a bit of extra syntax in the cmd! macro since it would be possible for a type to implement both Into<OsString> and IntoIterator. I ran into this pretty quickly once I started using this crate. It can be worked around by using before_spawn or directly using the cmd function but it would be nice if it worked with cmd!.

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 ...<expr> 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 as 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