3
Command::new(format!("git -C {} status", dir.as_path().display().to_string()));

I'm using the code above which converts my PathBuf variable to a String, but is this the best way? Is there a method to use the PathBuf variable without converting it?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Jake Ireland
  • 543
  • 4
  • 11

2 Answers2

6

Your example runs the executable git -C $dir status passing no arguments to that executable. It will error as soon as you spawn(), because such an oddly named file is not in your PATH.

Instead, run git passing your arguments:

Command::new("git").arg("-C").arg(dir).arg("status")

It also makes the question moot because there is no transformation necessary.

Jeff Garrett
  • 5,863
  • 1
  • 13
  • 12
  • You're absolutely right. I have accepted @pretzelhammer's answer as the "correct" solution assuming my original question wasn't flawed, but this is the correct (only?) way to do this. Thank you. – Jake Ireland Jan 28 '21 at 01:17
4

I'm assuming you're concerned about the PathBuf to String conversion in the scenario where PathBuf is not valid UTF-8. If that's the case I'd refactor that line into its own function and manually construct an OsString to create the Command:

use std::ffi::OsString;
use std::path::PathBuf;
use std::process::Command;

fn git_status(dir: PathBuf) -> Command {
    let mut os_string: OsString = "git -C ".into();
    os_string.push(&dir);
    os_string.push(" status");
    Command::new(os_string)
}

playground

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
  • Thank you for this. This is good. The only reason I am using PathBuf here is because what I am dealing with are paths... But if I am going to convert to string anyway, would you recommend having them as a string to begin with? – Jake Ireland Jan 28 '21 at 01:05
  • 1
    If all your paths are going to be valid UTF-8 and you won't need use any Path specific methods then sure, there's nothing wrong with using a String in that case. – pretzelhammer Jan 28 '21 at 01:40