Skip to content
Myr

build.rs

This file

Path

build.rs

194 lines · 6.8 KiB · Rust

Last changed by

Merge pull request #440 from dtolnay/backtraceDavid Tolnaybefore adoption9b67e5d

History of this file

Take it

1#![allow(clippy::uninlined_format_args)]23use std::env;4use std::ffi::OsString;5use std::fs;6use std::io::ErrorKind;7use std::iter;8use std::path::Path;9use std::process::{self, Command, Stdio};10use std::str;1112fn main() {13    if cfg!(feature = "std") {14        println!("cargo:rerun-if-changed=src/nightly.rs");1516        let error_generic_member_access;17        let consider_rustc_bootstrap;18        if compile_probe(false) {19            // This is a nightly or dev compiler, so it supports unstable20            // features regardless of RUSTC_BOOTSTRAP. No need to rerun build21            // script if RUSTC_BOOTSTRAP is changed.22            error_generic_member_access = true;23            consider_rustc_bootstrap = false;24        } else if let Some(rustc_bootstrap) = env::var_os("RUSTC_BOOTSTRAP") {25            if compile_probe(true) {26                // This is a stable or beta compiler for which the user has set27                // RUSTC_BOOTSTRAP to turn on unstable features. Rerun build28                // script if they change it.29                error_generic_member_access = true;30                consider_rustc_bootstrap = true;31            } else if rustc_bootstrap == "1" {32                // This compiler does not support the generic member access API33                // in the form that anyhow expects. No need to pay attention to34                // RUSTC_BOOTSTRAP.35                error_generic_member_access = false;36                consider_rustc_bootstrap = false;37            } else {38                // This is a stable or beta compiler for which RUSTC_BOOTSTRAP39                // is set to restrict the use of unstable features by this40                // crate.41                error_generic_member_access = false;42                consider_rustc_bootstrap = true;43            }44        } else {45            // Without RUSTC_BOOTSTRAP, this compiler does not support the46            // generic member access API in the form that anyhow expects, but47            // try again if the user turns on unstable features.48            error_generic_member_access = false;49            consider_rustc_bootstrap = true;50        }5152        if error_generic_member_access {53            println!("cargo:rustc-cfg=error_generic_member_access");54        }5556        if consider_rustc_bootstrap {57            println!("cargo:rerun-if-env-changed=RUSTC_BOOTSTRAP");58        }59    }6061    let Some(rustc) = rustc_minor_version() else {62        return;63    };6465    if rustc >= 80 {66        println!("cargo:rustc-check-cfg=cfg(anyhow_build_probe)");67        println!("cargo:rustc-check-cfg=cfg(anyhow_nightly_testing)");68        println!("cargo:rustc-check-cfg=cfg(anyhow_no_clippy_format_args)");69        println!("cargo:rustc-check-cfg=cfg(anyhow_no_core_error)");70        println!("cargo:rustc-check-cfg=cfg(error_generic_member_access)");71    }7273    if rustc < 81 {74        // core::error::Error75        // https://blog.rust-lang.org/2024/09/05/Rust-1.81.0.html#coreerrorerror76        println!("cargo:rustc-cfg=anyhow_no_core_error");77    }7879    if rustc < 85 {80        // #[clippy::format_args]81        // https://doc.rust-lang.org/1.85.1/clippy/attribs.html#clippyformat_args82        println!("cargo:rustc-cfg=anyhow_no_clippy_format_args");83    }84}8586fn compile_probe(rustc_bootstrap: bool) -> bool {87    if env::var_os("RUSTC_STAGE").is_some() {88        // We are running inside rustc bootstrap. This is a highly non-standard89        // environment with issues such as:90        //91        //     https://github.com/rust-lang/cargo/issues/1113892        //     https://github.com/rust-lang/rust/issues/11483993        //94        // Let's just not use nightly features here.95        return false;96    }9798    let rustc = cargo_env_var("RUSTC");99    let out_dir = cargo_env_var("OUT_DIR");100    let out_subdir = Path::new(&out_dir).join("probe");101    let probefile = Path::new("src").join("nightly.rs");102103    if let Err(err) = fs::create_dir(&out_subdir) {104        if err.kind() != ErrorKind::AlreadyExists {105            eprintln!("Failed to create {}: {}", out_subdir.display(), err);106            process::exit(1);107        }108    }109110    let rustc_wrapper = env::var_os("RUSTC_WRAPPER").filter(|wrapper| !wrapper.is_empty());111    let rustc_workspace_wrapper =112        env::var_os("RUSTC_WORKSPACE_WRAPPER").filter(|wrapper| !wrapper.is_empty());113    let mut rustc = rustc_wrapper114        .into_iter()115        .chain(rustc_workspace_wrapper)116        .chain(iter::once(rustc));117    let mut cmd = Command::new(rustc.next().unwrap());118    cmd.args(rustc);119120    if !rustc_bootstrap {121        cmd.env_remove("RUSTC_BOOTSTRAP");122    }123124    cmd.stderr(Stdio::null())125        .arg("--cfg=anyhow_build_probe")126        .arg("--edition=2018")127        .arg("--crate-name=anyhow")128        .arg("--crate-type=lib")129        .arg("--cap-lints=allow")130        .arg("--emit=dep-info,metadata")131        .arg("--out-dir")132        .arg(&out_subdir)133        .arg(probefile);134135    if let Some(target) = env::var_os("TARGET") {136        cmd.arg("--target").arg(target);137    }138139    // If Cargo wants to set RUSTFLAGS, use that.140    if let Ok(rustflags) = env::var("CARGO_ENCODED_RUSTFLAGS") {141        if !rustflags.is_empty() {142            for arg in rustflags.split('\x1f') {143                cmd.arg(arg);144            }145        }146    }147148    let success = match cmd.status() {149        Ok(status) => status.success(),150        Err(_) => false,151    };152153    // Clean up to avoid leaving nondeterministic absolute paths in the dep-info154    // file in OUT_DIR, which causes nonreproducible builds in build systems155    // that treat the entire OUT_DIR as an artifact.156    if let Err(err) = fs::remove_dir_all(&out_subdir) {157        // libc::ENOTEMPTY158        // Some filesystems (NFSv3) have timing issues under load where '.nfs*'159        // dummy files can continue to get created for a short period after the160        // probe command completes, breaking remove_dir_all.161        // To be replaced with ErrorKind::DirectoryNotEmpty (Rust 1.83+).162        const ENOTEMPTY: i32 = 39;163164        if !(err.kind() == ErrorKind::NotFound165            || (cfg!(target_os = "linux") && err.raw_os_error() == Some(ENOTEMPTY)))166        {167            eprintln!("Failed to clean up {}: {}", out_subdir.display(), err);168            process::exit(1);169        }170    }171172    success173}174175fn rustc_minor_version() -> Option<u32> {176    let rustc = cargo_env_var("RUSTC");177    let output = Command::new(rustc).arg("--version").output().ok()?;178    let version = str::from_utf8(&output.stdout).ok()?;179    let mut pieces = version.split('.');180    if pieces.next() != Some("rustc 1") {181        return None;182    }183    pieces.next()?.parse().ok()184}185186fn cargo_env_var(key: &str) -> OsString {187    env::var_os(key).unwrap_or_else(|| {188        eprintln!(189            "Environment variable ${} is not set during execution of build script",190            key,191        );192        process::exit(1);193    })194}