4

I want to use Cargo commands (cargo build in this instance) programmatically without running the command with std::process::Command in Rust.

How can I do that?

3
  • 1
    Can you elaborate on exactly why you want to do this, as there's probably A Better Way?
    – eggyal
    Commented Sep 11, 2021 at 10:39
  • I can only have a process running due to the limitation my serverless-like container has. Commented Sep 11, 2021 at 10:56
  • 6
    Even if you drive Cargo programmatically, it doesn't call rustc in-process (and rustc doesn't call the linker in-process) so you still won't actually be able to compile anything.
    – eggyal
    Commented Sep 11, 2021 at 11:00

1 Answer 1

13

Add the cargo (docs) crate to your dependencies, and you can use Cargo as a library! It doesn't have any stability guarantees or much documentation though, so you might want to read through how the Cargo CLI tool uses the library to figure out how to use it. To do a build, cargo::ops::compile is the function to call.

But do keep in mind that the Cargo library will still run rustc in another process using Command::new, so this is really just moving where the process boundary is, not eliminating it entirely.

Not the answer you're looking for? Browse other questions tagged or ask your own question.