cargo rust build script - print output of command
Asked Answered
C

3

9

I am new to rust and cargo, and I am trying to do something very simple!

I have something like this (in build.rs):

use std::process::Command;

fn main() {
    Command::new("echo 123");
}

And I want to see the output of the command echo 123. I want 123 to get printed to the build output (this is mostly to debug what I am doing) and wont be part of the final project.

I have tried cargo build --verbose - this does not work.

I can't extrapolate an answer from there posts (and some others like it):

I feel this must be simple to do - but I have been stuck for hours looking on the web and not finding the answer.

Cuneate answered 9/5, 2021 at 19:9 Comment(0)
V
7

Just building a Command with Command::new does not execute it yet. It just starts a builder pattern. To actually execute it, you have to use the methods spawn, output or status. Example:

Command::new("echo")
    .arg("123")
    .spawn()
    .expect("failed to spawn process");

It's very unfortunate that this doesn't produce a warning. Someone recently tried to add the #[must_use] attribute to Command, which would make your code procude a warning. The PR closed for now but it seems like it will be added eventually.

Vaud answered 9/5, 2021 at 21:36 Comment(4)
Thanks, good to know about the command not running! - But I still do not get any output here (even if I copy/paste your answer in). I added the argument > test.out - and no test.out file was generated. I also tried with state and output... any clues?Cuneate
@Cuneate Oops, I kinda forgot about that part of the question. As mentioned in the first issue you linked, cargo build -vv does show the output of the build script. The output is also shown with a normal cargo build if the build script exits with a non 0 exit code. So std::process::exit(1) will also show the output. (Of course, only use that if there is an actual error.)Vaud
ah ha, great thanks. I Was still trying --verbose :)Cuneate
Is there any way to debug build.rs file?Antirachitic
C
6

We can use a macro and it worked form me, but there is a warning, since it uses cargo to display. but that is fine for me. I found below code from git hub discussion: Cargo doesn’t display output from a command in build.rs #985

macro_rules! p {
    ($($tokens: tt)*) => {
        println!("cargo:warning={}", format!($($tokens)*))
    }
}

fn main() {
    p!("BUILD.rs -> Starting ...");
}
Cryptozoic answered 27/1, 2023 at 21:4 Comment(0)
M
1

Specifying -vv option with cargo, lets you see the output from the build scripts. For more information, refer this.

So, you can store the output of the command in a string, and then possibly write out using println.

Marduk answered 5/7, 2023 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.