rust Cargo可以在编译前运行外部工具吗?

oiopk7p5  于 2022-12-19  发布在  Go
关注(0)|答案(3)|浏览(101)

有没有可能在编译代码之前让cargo运行外部工具?
我遇到的确切问题是:
我有一个使用re2rust创建的解析器生成器。这个解析器生成器将一个文件作为输入并生成rust代码(一个源文件)。我需要在编译核心之前运行解析器生成器。理想情况下,只有在原始文件被修改的情况下。
我找不到货物文件说明怎么做。

zour9fqk

zour9fqk1#

您可以使用build.rs脚本。文档是here,但您的用例的要点可能类似于

fn main() {
    println!("cargo:rerun-if-changed=path/to/template");
    Command::new("re2rust")
        .arg(/*whatever*/)
        .output()
        .expect("failed to execute process")
}
bqujaahr

bqujaahr2#

你可能想创建一个build.rs文件,它可以做rust二进制文件能做的任何事情。

fn main() -> std::io::Result<()> {
    println!("cargo:rerun-if-changed=re2rust/templates");
    Command::new("re2rust").output()?;
    Ok(())
}
4nkexdtk

4nkexdtk3#

为了完整起见,下面是一个完整的build.rs,用于工具仅将输出写入stdout的情况。

use std::fs::File;
use std::process::Command;

fn main()  {
    println!("cargo:rerun-if-changed=<full path from cargo root to input file>");

    let rust_file = File::create("<output file>").expect("failed to open parser.rs");

    Command::new("re2rust")
        .current_dir("<input file dir>")
        .arg("<input file>")
        .stdout(rust_file)
        .spawn().expect("failed to execute re2rust");
}

相关问题