How to create a new project from the program?

In vscode terminal I can create a project:
> cargo new my_project; cd my_project
If I have the path and name of a new project in my variables, how to do this in program?

something like

use std::process::Command;

fn main() {

    Command::new("cargo")
         .args(&["new", "my_project;", "cd", "my_project"])
         .arg("C:/path/to/mydir")
         .spawn()
         .expect("err");
}

A process cannot change the current directory of the shell (or other parent process) that started it. You can do this with a shell alias (at least in Unix shells) but not with a regular program.

1 Like

Thank you.
If for os win10 and vscode:
create file c://users/test.sh
and rust code

use std::process::Command;

fn main() {
    Command::new ("sh")
         .arg("-C").arg("/Users/test.sh")
         .spawn()
         .expect("err...");
}

will not help?

Why am I getting an error?
'err...: Error { kind: NotFound, message: "program not found" }'

if my code:
Command::new ("/bin/sh").arg("-C").arg("/Users/test.sh")
error:
The system cannot find the specified path.

Please, how to correctly set the path in my case?

To make sure that the code from the file works:
what should I put in file (for example) and how to call it?

Sorry, I can't help further — it seems like your problem has to do with Windows pathnames and WSL, and I don't have a Windows machine to experiment with myself.

1 Like

the windows path is converted differently depending on what sh you are using. for sh from wsl, the windows path C:\Users\test.sh should be converted to /mnt/c/Users/test.sh. for sh of msys2/mingw, IIRC, it should be /c/Users/test.sh, but I have not been using msys2 for a long time, I can be wrong on this.

but the original problem can be solved without using a shell script. you run cargo command using std::process::Command, and then you change the working directory using std::env::set_current_dir().

2 Likes

main.rs

use std::process::Command;

fn main() {

    Command::new("cargo")
         .args(&["new", "my_project;", "cd", "my_project"])
         .arg("-C")
         .arg("/path/to/mydir") 
         // .arg("\\path\\to\\mydir") 
         // .current_dir(/path/to/mydir")
         .spawn()
         .expect("err");
}

I tried the options: '/' or '\'
I run main.rs from the location directory with comand cargo run in vscode.
How can I change the example code to get the result?
Maybe another way to check if the path is correct?

I only need to create a new project. No to run it in this process. If I get you right.

So I have:

use std::process::Command;

fn main() {

    Command::new("cargo")
           .args(&["new", "my_project"])    // <- delete:  "cd", "my_project"
           .current_dir("C:/to/my/folder/")
           .spawn()
           .expect("error:");
}

image