首页 > 解决方案 > 从 rust proc-macro 中获取目标文件夹

问题描述

正如标题所示,我正在尝试检索目标文件夹以保存一些中间编译产品。我需要实际的目标文件夹,因为我想在编译之间缓存一些值以显着加快它们的速度(否则我可以只使用一个临时目录)。

我目前的方法是解析 rustc 调用的参数(通过std::env::args())并找到 --out-dir,代码如下所示:

// First we get the arguments for the rustc invocation
let mut args = std::env::args();

// Then we loop through them all, and find the value of "out-dir"
let mut out_dir = None;
while let Some(arg) = args.next() {
    if arg == "--out-dir" {
        out_dir = args.next();
    }
}

// Finally we clean out_dir by removing all trailing directories, until it ends with target 
let mut out_dir = PathBuf::from(out_dir.expect("Failed to find out_dir"));
while !out_dir.ends_with("target") {
    if !out_dir.pop() {
        // We ran out of directories...
        panic!("Failed to find out_dir");
    }
}

out_dir

通常我会使用环境变量之类的东西(想想OUT_DIR),但我找不到任何可以帮助我的东西。

那么有没有正确的方法来做到这一点?还是我应该向 rust 开发团队提出问题?

标签: rustrust-proc-macros

解决方案


OUT_DIR是正确的方法,我很困惑它并不总是固定的。如果您可以控制使用您的宏的 crate,您可以添加一个(简单的)构建脚本,这会导致 cargo 设置OUT_DIR变量。

我必须承认这有点骇人听闻。我创建了一个功能请求,要求cargo to always set OUT_DIR,这将使这个问题变得微不足道。


推荐阅读