|
| 1 | +//! This custom build script merely checks whether we're compiling with the appropriate Rust toolchain |
| 2 | +
|
| 3 | +#![allow(clippy::string_add)] |
| 4 | + |
| 5 | +use std::error::Error; |
| 6 | +use std::process::{Command, ExitCode}; |
| 7 | + |
| 8 | +/// Current `rust-toolchain` file |
| 9 | +/// Unfortunately, directly including the actual workspace `rust-toolchain` doesn't work together with |
| 10 | +/// `cargo publish`. We need to figure out a way to do this properly, but let's hardcode it for now :/ |
| 11 | +//const REQUIRED_RUST_TOOLCHAIN: &str = include_str!("../../rust-toolchain"); |
| 12 | +const REQUIRED_RUST_TOOLCHAIN: &str = r#"[toolchain] |
| 13 | +channel = "nightly-2022-08-29" |
| 14 | +components = ["rust-src", "rustc-dev", "llvm-tools-preview"] |
| 15 | +# commit_hash = ce36e88256f09078519f8bc6b21e4dc88f88f523"#; |
| 16 | + |
| 17 | +fn get_rustc_commit_hash() -> Result<String, Box<dyn Error>> { |
| 18 | + let rustc = std::env::var("RUSTC").unwrap_or_else(|_| String::from("rustc")); |
| 19 | + String::from_utf8(Command::new(rustc).arg("-vV").output()?.stdout)? |
| 20 | + .lines() |
| 21 | + .find_map(|l| l.strip_prefix("commit-hash: ")) |
| 22 | + .map(|s| s.to_string()) |
| 23 | + .ok_or_else(|| Box::<dyn Error>::from("`commit-hash` not found in `rustc -vV` output")) |
| 24 | +} |
| 25 | + |
| 26 | +fn get_required_commit_hash() -> Result<String, Box<dyn Error>> { |
| 27 | + REQUIRED_RUST_TOOLCHAIN |
| 28 | + .lines() |
| 29 | + .find_map(|l| l.strip_prefix("# commit_hash = ")) |
| 30 | + .map(|s| s.to_string()) |
| 31 | + .ok_or_else(|| Box::<dyn Error>::from("`commit_hash` not found in `rust-toolchain`")) |
| 32 | +} |
| 33 | + |
| 34 | +fn check_toolchain_version() -> Result<(), Box<dyn Error>> { |
| 35 | + if !cfg!(feature = "skip-toolchain-check") { |
| 36 | + // gets the commit hash from current rustc |
| 37 | + |
| 38 | + let current_hash = get_rustc_commit_hash()?; |
| 39 | + let required_hash = get_required_commit_hash()?; |
| 40 | + if current_hash != required_hash { |
| 41 | + let stripped_toolchain = REQUIRED_RUST_TOOLCHAIN |
| 42 | + .lines() |
| 43 | + .filter(|l| !l.trim().is_empty() && !l.starts_with("# ")) |
| 44 | + .map(|l| l.to_string()) |
| 45 | + .reduce(|a, b| a + "\n" + &b) |
| 46 | + .unwrap_or_default(); |
| 47 | + |
| 48 | + return Err(Box::<dyn Error>::from(format!( |
| 49 | + r#" |
| 50 | +error: wrong toolchain detected (found commit hash `{current_hash}`, expected `{required_hash}`). |
| 51 | +Make sure your `rust_toolchain` file contains the following: |
| 52 | +------------- |
| 53 | +{stripped_toolchain} |
| 54 | +-------------"# |
| 55 | + ))); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + Ok(()) |
| 60 | +} |
| 61 | + |
| 62 | +fn main() -> ExitCode { |
| 63 | + match check_toolchain_version() { |
| 64 | + Ok(_) => ExitCode::SUCCESS, |
| 65 | + Err(e) => { |
| 66 | + eprint!("{}", e); |
| 67 | + ExitCode::FAILURE |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments