Skip to main content

macrotest/
rustflags.rs

1use std::env;
2use std::process::Command;
3
4const CARGO_ENCODED_RUSTFLAGS: &str = "CARGO_ENCODED_RUSTFLAGS";
5const RUSTFLAGS: &str = "RUSTFLAGS";
6const IGNORED_LINTS: &[&str] = &["dead_code"];
7
8pub fn make_vec() -> Vec<String> {
9    let mut rustflags = Vec::new();
10
11    for &lint in IGNORED_LINTS {
12        rustflags.push("-A".to_owned());
13        rustflags.push(lint.to_owned());
14    }
15
16    rustflags
17}
18
19pub fn set_env(cmd: &mut Command) {
20    // The precedence of rustflags is:
21    // 1. CARGO_ENCODED_RUSTFLAGS
22    // 2. RUSTFLAGS
23    // 3. target.<triple>.rustflags (CARGO_TARGET_<triple>_RUSTFLAGS) and target.<cfg>.rustflags
24    // 4. build.rustflags (CARGO_BUILD_RUSTFLAGS)
25    // Refs: https://doc.rust-lang.org/nightly/cargo/reference/config.html#buildrustflags
26    // For now, skip 3 and 4 because 3 is complex and handling 4 without 3 incorrectly overwrite rustflags.
27    // TODO: Consider using cargo-config2 crate that implements it.
28    let (key, mut val, separator) = match env::var_os(CARGO_ENCODED_RUSTFLAGS) {
29        Some(val) => (CARGO_ENCODED_RUSTFLAGS, val, "\x1f"),
30        None => match env::var_os(RUSTFLAGS) {
31            Some(val) => (RUSTFLAGS, val, " "),
32            None => return,
33        },
34    };
35
36    for flag in make_vec() {
37        if !val.is_empty() {
38            val.push(separator);
39        }
40        val.push(flag);
41    }
42
43    cmd.env(key, val);
44}