簡體   English   中英

工作區目錄是否有 Cargo 環境變量?

[英]Is there a Cargo environment variable for the workspace directory?

我在工作區中有以下項目:

Workspacefolder
 |
 +-- Project A
 |    |
 |    +-- build.rs
 |
 +-- Dep
 |    |
 |    +-- test.json  
 |
 +-Cargo.toml

Project A中,有build.rs想要以不依賴平台且與 CI 配合良好的方式打開test.json

我正在尋找CARGO_WORKSPACE環境變量,因為這樣我就可以說Path::new(&workspace_dir).join("/Dep/test.json")

不,不適用於與 Rust 1.16.0 捆綁的 Cargo 版本。 您可以通過打印出構建腳本中的所有環境變量來自己驗證這一點:

use std::fs::File;
use std::io::Write;

fn main() {
    let mut dump = File::create("/tmp/dump").expect("unable to open");
    for (k, v) in std::env::vars() {
        writeln!(&mut dump, "{} -> {}", k, v).expect("unable to write")
    }
}

在我的機器上,這會產生:

$ sort /tmp/dump | grep CARGO
CARGO_CFG_DEBUG_ASSERTIONS ->
CARGO_CFG_TARGET_ARCH -> x86_64
CARGO_CFG_TARGET_ENDIAN -> little
CARGO_CFG_TARGET_ENV ->
CARGO_CFG_TARGET_FAMILY -> unix
CARGO_CFG_TARGET_OS -> macos
CARGO_CFG_TARGET_POINTER_WIDTH -> 64
CARGO_CFG_UNIX ->
CARGO_HOME -> /Users/shep/.cargo
CARGO_MANIFEST_DIR -> /private/tmp/the-workspace/project-a
CARGO_PKG_AUTHORS -> An Devloper <an.devloper@example.com>
CARGO_PKG_DESCRIPTION ->
CARGO_PKG_HOMEPAGE ->
CARGO_PKG_NAME -> project-a
CARGO_PKG_VERSION -> 0.1.0
CARGO_PKG_VERSION_MAJOR -> 0
CARGO_PKG_VERSION_MINOR -> 1
CARGO_PKG_VERSION_PATCH -> 0
CARGO_PKG_VERSION_PRE ->

我不知道為什么你不能做

Path::new(&manifest_dir).join("..").join("Dep").join("test.json")

我已經將每個目錄拆分為一個單獨的調用——完全避免了將目錄分隔符指定為與平台無關的需要。

對於 cargo 版本 1.63.0,我管理:

use std::{env, path::PathBuf, process::Command};

pub fn get_workspace_root() -> anyhow::Result<PathBuf> {
    let current_dir = env::current_dir()?;
    let cmd_output = Command::new("cargo")
        .args(["metadata", "--format-version=1"])
        .output()?;

    if !cmd_output.status.success() {
        return Ok(current_dir);
    }

    let json =
        serde_json::from_str::<serde_json::Value>(String::from_utf8(cmd_output.stdout)?.as_str())?;
    let path = match json.get("workspace_root") {
        Some(val) => match val.as_str() {
            Some(val) => val,
            None => return Ok(current_dir),
        },
        None => return Ok(current_dir),
    };
    Ok(PathBuf::from(path))
}

現在有一種更簡單的方法:

fn workspace_dir() -> PathBuf {
    let output = std::process::Command::new(env!("CARGO"))
        .arg("locate-project")
        .arg("--workspace")
        .arg("--message-format=plain")
        .output()
        .unwrap()
        .stdout;
    let cargo_path = Path::new(std::str::from_utf8(&output).unwrap().trim());
    cargo_path.parent().unwrap().to_path_buf()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM