What is the best way to use PathBuf in a command call in Rust?

Viewed 888
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?

2 Answers

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.

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

Related