Command args are concated

use std::process::{Command, Output};

fn get_stdout(output: &Output) -> String {
    return (String::from_utf8(output.stdout.clone())).unwrap();
}
fn test(input: &str) -> String {
    input.to_string()
}

fn main() {
    let mut git_command = Command::new("git");
    // detect whether given upstream name exists
    let first_call = get_stdout(
        &git_command
            .args(["remote", "get-url", "origin"])
            .output()
            .unwrap(),
    );
    let second_call = get_stdout(
        &git_command
            .args(["remote", "get-url", "origin"])
            .output()
            .unwrap(),
    );
    println!("first call is {first_call}");
    println!("second call is {second_call}"); // the second call returns nothing
}

Your examples are not even remotely correct Rust code. Please give some examples that actually compile.

You seem to have corrected your examples so they look like good rust code, but now I don't see any difference between your two calls, so I don't know what your question is really about?

updated, but you need to put in a git project.
I try to reproduce it through ls here

but it shows another situation that the first call used

you can put this code into your own git project, here's the output

Oh, I see. The problem is that args will modify the git_command object you called it on, so the second call is actually the following:

git remote get-url origin remote get-url origin
1 Like

I was about to say the same thing as @alice just said, but I can add this; I modified your ls example to use echo, that should make it clear what happens.

I guess so, it's not very intuitive for the developers

True, it is a bit uncommon. But the fact that you had to declare the the command with mut is a strong hint that it changes after beeing initialized.

Given that it's possible to do command.args(["--param1", "value1"]).args(["--param2", "value2"]) - would you say it would be more intuitive to have only the second parameter in the resulting command?

1 Like

this code is more explicit and easy to understand, but for the example I give above, it's kind of hard to tell :sweat_smile:

by the way, how to reuse the Command (i.e. git_command in example)
do I have to Command::new every time?

You can't reuse it. Just make it from scratch each time.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.