Debian Codegraph @

debian/missing-sources/thiserror/build.rs

raw
1 use std::env;
2 use std::ffi::OsString;
3 use std::fs;
4 use std::io::ErrorKind;
5 use std::iter;
6 use std::path::{Path, PathBuf};
7 use std::process::{self, Command, Stdio};
8 use std::str;
9
10 const PRIVATE: &str = "\
11 #[doc(hidden)]
12 pub mod __private$$ {
13 #[doc(hidden)]
14 pub use crate::private::*;
15 }
16 ";
17
18 fn main() {
19 println!("cargo:rerun-if-changed=build/probe.rs");
20
21 println!("cargo:rustc-check-cfg=cfg(error_generic_member_access)");
22 println!("cargo:rustc-check-cfg=cfg(thiserror_nightly_testing)");
23 println!("cargo:rustc-check-cfg=cfg(thiserror_no_backtrace_type)");
24
25 let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
26 let patch_version = env::var("CARGO_PKG_VERSION_PATCH").unwrap();
27 let module = PRIVATE.replace("$$", &patch_version);
28 fs::write(out_dir.join("private.rs"), module).unwrap();
29
30 let error_generic_member_access;
31 let consider_rustc_bootstrap;
32 if compile_probe(false) {
33 // This is a nightly or dev compiler, so it supports unstable features
34 // regardless of RUSTC_BOOTSTRAP. No need to rerun build script if
35 // RUSTC_BOOTSTRAP is changed.
36 error_generic_member_access = true;
37 consider_rustc_bootstrap = false;
38 } else if let Some(rustc_bootstrap) = env::var_os("RUSTC_BOOTSTRAP") {
39 if compile_probe(true) {
40 // This is a stable or beta compiler for which the user has set
41 // RUSTC_BOOTSTRAP to turn on unstable features. Rerun build script
42 // if they change it.
43 error_generic_member_access = true;
44 consider_rustc_bootstrap = true;
45 } else if rustc_bootstrap == "1" {
46 // This compiler does not support the generic member access API in
47 // the form that thiserror expects. No need to pay attention to
48 // RUSTC_BOOTSTRAP.
49 error_generic_member_access = false;
50 consider_rustc_bootstrap = false;
51 } else {
52 // This is a stable or beta compiler for which RUSTC_BOOTSTRAP is
53 // set to restrict the use of unstable features by this crate.
54 error_generic_member_access = false;
55 consider_rustc_bootstrap = true;
56 }
57 } else {
58 // Without RUSTC_BOOTSTRAP, this compiler does not support the generic
59 // member access API in the form that thiserror expects, but try again
60 // if the user turns on unstable features.
61 error_generic_member_access = false;
62 consider_rustc_bootstrap = true;
63 }
64
65 if error_generic_member_access {
66 println!("cargo:rustc-cfg=error_generic_member_access");
67 }
68
69 if consider_rustc_bootstrap {
70 println!("cargo:rerun-if-env-changed=RUSTC_BOOTSTRAP");
71 }
72
73 // core::error::Error stabilized in Rust 1.81
74 // https://blog.rust-lang.org/2024/09/05/Rust-1.81.0.html#coreerrorerror
75 let rustc = rustc_minor_version();
76 if cfg!(not(feature = "std")) && rustc.map_or(false, |rustc| rustc < 81) {
77 println!("cargo:rustc-cfg=feature=\"std\"");
78 }
79
80 let Some(rustc) = rustc else {
81 return;
82 };
83
84 // std::backtrace::Backtrace stabilized in Rust 1.65
85 // https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#stabilized-apis
86 if rustc < 65 {
87 println!("cargo:rustc-cfg=thiserror_no_backtrace_type");
88 }
89 }
90
91 fn compile_probe(rustc_bootstrap: bool) -> bool {
92 if env::var_os("RUSTC_STAGE").is_some() {
93 // We are running inside rustc bootstrap. This is a highly non-standard
94 // environment with issues such as:
95 //
96 // https://github.com/rust-lang/cargo/issues/11138
97 // https://github.com/rust-lang/rust/issues/114839
98 //
99 // Let's just not use nightly features here.
100 return false;
101 }
102
103 let rustc = cargo_env_var("RUSTC");
104 let out_dir = cargo_env_var("OUT_DIR");
105 let out_subdir = Path::new(&out_dir).join("probe");
106 let probefile = Path::new("build").join("probe.rs");
107
108 if let Err(err) = fs::create_dir(&out_subdir) {
109 if err.kind() != ErrorKind::AlreadyExists {
110 eprintln!("Failed to create {}: {}", out_subdir.display(), err);
111 process::exit(1);
112 }
113 }
114
115 let rustc_wrapper = env::var_os("RUSTC_WRAPPER").filter(|wrapper| !wrapper.is_empty());
116 let rustc_workspace_wrapper =
117 env::var_os("RUSTC_WORKSPACE_WRAPPER").filter(|wrapper| !wrapper.is_empty());
118 let mut rustc = rustc_wrapper
119 .into_iter()
120 .chain(rustc_workspace_wrapper)
121 .chain(iter::once(rustc));
122 let mut cmd = Command::new(rustc.next().unwrap());
123 cmd.args(rustc);
124
125 if !rustc_bootstrap {
126 cmd.env_remove("RUSTC_BOOTSTRAP");
127 }
128
129 cmd.stderr(Stdio::null())
130 .arg("--edition=2018")
131 .arg("--crate-name=thiserror")
132 .arg("--crate-type=lib")
133 .arg("--cap-lints=allow")
134 .arg("--emit=dep-info,metadata")
135 .arg("--out-dir")
136 .arg(&out_subdir)
137 .arg(probefile);
138
139 if let Some(target) = env::var_os("TARGET") {
140 cmd.arg("--target").arg(target);
141 }
142
143 // If Cargo wants to set RUSTFLAGS, use that.
144 if let Ok(rustflags) = env::var("CARGO_ENCODED_RUSTFLAGS") {
145 if !rustflags.is_empty() {
146 for arg in rustflags.split('\x1f') {
147 cmd.arg(arg);
148 }
149 }
150 }
151
152 let success = match cmd.status() {
153 Ok(status) => status.success(),
154 Err(_) => false,
155 };
156
157 // Clean up to avoid leaving nondeterministic absolute paths in the dep-info
158 // file in OUT_DIR, which causes nonreproducible builds in build systems
159 // that treat the entire OUT_DIR as an artifact.
160 if let Err(err) = fs::remove_dir_all(&out_subdir) {
161 // libc::ENOTEMPTY
162 // Some filesystems (NFSv3) have timing issues under load where '.nfs*'
163 // dummy files can continue to get created for a short period after the
164 // probe command completes, breaking remove_dir_all.
165 // To be replaced with ErrorKind::DirectoryNotEmpty (Rust 1.83+).
166 const ENOTEMPTY: i32 = 39;
167
168 if !(err.kind() == ErrorKind::NotFound
169 || (cfg!(target_os = "linux") && err.raw_os_error() == Some(ENOTEMPTY)))
170 {
171 eprintln!("Failed to clean up {}: {}", out_subdir.display(), err);
172 process::exit(1);
173 }
174 }
175
176 success
177 }
178
179 fn rustc_minor_version() -> Option<u32> {
180 let rustc = cargo_env_var("RUSTC");
181 let output = Command::new(rustc).arg("--version").output().ok()?;
182 let version = str::from_utf8(&output.stdout).ok()?;
183 let mut pieces = version.split('.');
184 if pieces.next() != Some("rustc 1") {
185 return None;
186 }
187 pieces.next()?.parse().ok()
188 }
189
190 fn cargo_env_var(key: &str) -> OsString {
191 env::var_os(key).unwrap_or_else(|| {
192 eprintln!("Environment variable ${key} is not set during execution of build script");
193 process::exit(1);
194 })
195 }