assert_cmd icon indicating copy to clipboard operation
assert_cmd copied to clipboard

Allow serializing a constructed Command

Open mcky opened this issue 1 year ago • 4 comments

I'm trying to convert some tests to use rexpect::spawn to work around some issues with tty handling, but I'm having trouble re-using all my existing assert_cmd as I can't construct a single string with the constructed command as the cmd field on Command is private.

With the following code

let mut cmd = Command::cargo_bin("my-cmd").unwrap();

cmd.current_dir("/tmp")
  .arg("--foo")
  .arg("bar")
  .env("FOO", "BAR");

I'd like to be able to get a string like

cd /tmp && FOO="BAR" ~the-cargo-path/target/debug/my-cmd --foo bar

Calling format!("{:?}", cmd) prints the following, with cmd in the format I'd like, but also stdin/stdout etc

Command { cmd: cd \"/tmp\" && FOO=\"BAR\" \"~the-cargo-path/target/debug/my-cmd\" \"--foo\" \"bar\", stdin: None, timeout: None }

I'm not sure what the most rust-y solution would be, but it would help if either:

  • cmd was marked public
  • a method was added to get cmd in a serialized form
  • a method was added to Command to get the underlying cmd, at which point I think I can serialize it myself

I'm happy to attempt a PR if an option from the above is chosen / another suggested

mcky avatar Aug 08 '24 15:08 mcky

I'd be open to a PR that added the same getters that std::process::Command has plus ones specialized for the extra content in assert_cmd::Command.

epage avatar Aug 08 '24 15:08 epage

Ah yes I was just looking at those when I made the PR, so I can implement these wrappers:

pub fn get_args(&self) -> CommandArgs<'_> {
}
pub fn get_current_dir(&self) -> Option<&Path> {
}
pub fn get_envs(&self) -> CommandEnvs<'_> {
}
pub fn get_program(&self) -> &OsStr {
}

and introduce this (or under another name, with the same signature?)

pub fn get_cmd(&self) -> process::Command {
}

mcky avatar Aug 08 '24 16:08 mcky

pub fn get_cmd(&self) -> process::Command

I scoped it to just what std::process::Command provides.

epage avatar Aug 08 '24 16:08 epage

@epage I realised I don't actually need any of those getters as this achieves everything I need

format!("{:?}", process::Command::from(cmd));

But since you were receptive I tried raising the PR anyway. If reviewing and giving feedback is more hassle than it's worth though feel free to close it, as my use case is covered.

mcky avatar Aug 08 '24 17:08 mcky