project_model/
env.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//! Cargo-like environment variables injection.
use base_db::Env;
use rustc_hash::FxHashMap;
use toolchain::Tool;

use crate::{utf8_stdout, CargoWorkspace, ManifestPath, PackageData, Sysroot, TargetKind};

/// Recreates the compile-time environment variables that Cargo sets.
///
/// Should be synced with
/// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>
///
/// FIXME: ask Cargo to provide this data instead of re-deriving.
pub(crate) fn inject_cargo_package_env(env: &mut Env, package: &PackageData) {
    // FIXME: Missing variables:
    // CARGO_BIN_NAME, CARGO_BIN_EXE_<name>

    let manifest_dir = package.manifest.parent();
    env.set("CARGO_MANIFEST_DIR", manifest_dir.as_str());

    env.set("CARGO_PKG_VERSION", package.version.to_string());
    env.set("CARGO_PKG_VERSION_MAJOR", package.version.major.to_string());
    env.set("CARGO_PKG_VERSION_MINOR", package.version.minor.to_string());
    env.set("CARGO_PKG_VERSION_PATCH", package.version.patch.to_string());
    env.set("CARGO_PKG_VERSION_PRE", package.version.pre.to_string());

    env.set("CARGO_PKG_AUTHORS", package.authors.join(":").clone());

    env.set("CARGO_PKG_NAME", package.name.clone());
    env.set("CARGO_PKG_DESCRIPTION", package.description.as_deref().unwrap_or_default());
    env.set("CARGO_PKG_HOMEPAGE", package.homepage.as_deref().unwrap_or_default());
    env.set("CARGO_PKG_REPOSITORY", package.repository.as_deref().unwrap_or_default());
    env.set("CARGO_PKG_LICENSE", package.license.as_deref().unwrap_or_default());
    env.set(
        "CARGO_PKG_LICENSE_FILE",
        package.license_file.as_ref().map(ToString::to_string).unwrap_or_default(),
    );
    env.set(
        "CARGO_PKG_README",
        package.readme.as_ref().map(ToString::to_string).unwrap_or_default(),
    );

    env.set(
        "CARGO_PKG_RUST_VERSION",
        package.rust_version.as_ref().map(ToString::to_string).unwrap_or_default(),
    );
}

pub(crate) fn inject_cargo_env(env: &mut Env) {
    env.set("CARGO", Tool::Cargo.path().to_string());
}

pub(crate) fn inject_rustc_tool_env(
    env: &mut Env,
    cargo: &CargoWorkspace,
    cargo_name: &str,
    kind: TargetKind,
) {
    _ = kind;
    // FIXME
    // if kind.is_executable() {
    //     env.set("CARGO_BIN_NAME", cargo_name);
    // }
    env.set("CARGO_CRATE_NAME", cargo_name.replace('-', "_"));
    // NOTE: Technically we should set this for all crates, but that will worsen the deduplication
    // logic so for now just keeping it proc-macros ought to be fine.
    if kind.is_proc_macro() {
        env.set("CARGO_RUSTC_CURRENT_DIR", cargo.manifest_path().parent().to_string());
    }
}

pub(crate) fn cargo_config_env(
    manifest: &ManifestPath,
    extra_env: &FxHashMap<String, String>,
    sysroot: &Sysroot,
) -> FxHashMap<String, String> {
    let mut cargo_config = sysroot.tool(Tool::Cargo);
    cargo_config.envs(extra_env);
    cargo_config
        .current_dir(manifest.parent())
        .args(["-Z", "unstable-options", "config", "get", "env"])
        .env("RUSTC_BOOTSTRAP", "1");
    if manifest.is_rust_manifest() {
        cargo_config.arg("-Zscript");
    }
    // if successful we receive `env.key.value = "value" per entry
    tracing::debug!("Discovering cargo config env by {:?}", cargo_config);
    utf8_stdout(cargo_config)
        .map(parse_output_cargo_config_env)
        .inspect(|env| {
            tracing::debug!("Discovered cargo config env: {:?}", env);
        })
        .inspect_err(|err| {
            tracing::debug!("Failed to discover cargo config env: {:?}", err);
        })
        .unwrap_or_default()
}

fn parse_output_cargo_config_env(stdout: String) -> FxHashMap<String, String> {
    stdout
        .lines()
        .filter_map(|l| l.strip_prefix("env."))
        .filter_map(|l| l.split_once(" = "))
        .filter_map(|(k, v)| {
            if k.contains('.') {
                k.strip_suffix(".value").zip(Some(v))
            } else {
                Some((k, v))
            }
        })
        .map(|(key, value)| (key.to_owned(), value.trim_matches('"').to_owned()))
        .collect()
}