Jake Ireland
Jake Ireland

Reputation: 652

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

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?

Upvotes: 3

Views: 2145

Answers (2)

Jeff Garrett
Jeff Garrett

Reputation: 7383

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.

Upvotes: 7

pretzelhammer
pretzelhammer

Reputation: 15105

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

Upvotes: 5

Related Questions