From 07a689291bff6eb62ecdbfdb5ebae6a098b14563 Mon Sep 17 00:00:00 2001 From: Tushar Mathur Date: Wed, 11 Dec 2024 12:26:21 -0800 Subject: [PATCH] refactor(cargo): Trim and filter empty arguments in command generation --- crates/gh-workflow/src/cargo.rs | 45 ++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/crates/gh-workflow/src/cargo.rs b/crates/gh-workflow/src/cargo.rs index f536ef7..4228900 100644 --- a/crates/gh-workflow/src/cargo.rs +++ b/crates/gh-workflow/src/cargo.rs @@ -19,10 +19,12 @@ pub struct Cargo { pub toolchain: Option, /// Arguments to be passed to the cargo command. - pub args: Option, + #[setters(skip)] + pub args: Vec, } impl Cargo { + /// Creates a new `Cargo` instance with the specified command. pub fn new(cmd: T) -> Cargo { Cargo { command: cmd.to_string(), @@ -33,10 +35,38 @@ impl Cargo { } } + /// Sets the toolchain to nightly. pub fn nightly(mut self) -> Self { self.toolchain = Some(Version::Nightly); self } + + /// Sets the arguments for the cargo command. If arguments are already set, + /// it will be overwritten. + pub fn args(mut self, args: T) -> Self { + self.args = vec![args.to_string()]; + self + } + + /// Adds additional arguments to the cargo command. + pub fn add_args(mut self, args: T) -> Self { + self.args.extend( + args.to_string() + .split_whitespace() + .map(|s| s.to_string()) + .collect::>(), + ); + self + } + + /// Adds the arguments to the cargo command when a condition is met. + pub fn add_args_when(self, when: bool, args: T) -> Self { + if when { + self.add_args(args) + } else { + self + } + } } impl From for Step { @@ -49,11 +79,14 @@ impl From for Step { command.push(value.command); - if let Some(args) = value.args { - if !args.is_empty() { - command.push(args); - } - } + // Extend the command with non-empty arguments + command.extend( + value + .args + .into_iter() + .map(|arg| arg.trim().to_string()) + .filter(|arg| !arg.is_empty()), + ); let mut step = Step::run(command.join(" "));