Debian Codegraph @

src/environment.rs

raw
1 use crate::util::{self, ArrayDisplay};
2 use crate::{fmt_option_str, write_str_variable, write_variable};
3 use std::{cell, collections, env, ffi, fmt, fs, io, process};
4
5 const BUILT_OVERRIDE_PREFIX: &str = "BUILT_OVERRIDE_";
6
7 #[derive(Debug, Default)]
8 enum EnvironmentValue {
9 #[default]
10 Unused,
11 Queried,
12 Used,
13 }
14
15 impl EnvironmentValue {
16 fn upgrade_to_queried(&mut self) {
17 if matches!(self, EnvironmentValue::Unused) {
18 *self = EnvironmentValue::Queried;
19 }
20 }
21
22 fn upgrade_to_used(&mut self) {
23 *self = EnvironmentValue::Used;
24 }
25
26 pub fn is_unused(&self) -> bool {
27 matches!(self, EnvironmentValue::Unused)
28 }
29
30 pub fn is_used(&self) -> bool {
31 matches!(self, EnvironmentValue::Used)
32 }
33 }
34
35 pub struct EnvironmentMap {
36 map: collections::HashMap<String, (String, cell::RefCell<EnvironmentValue>)>,
37 override_prefix: String,
38 }
39
40 fn get_version_from_cmd(executable: &ffi::OsStr) -> io::Result<String> {
41 let output = process::Command::new(executable).arg("-V").output()?;
42 let mut v = String::from_utf8(output.stdout).unwrap();
43 v.pop(); // remove newline
44 Ok(v)
45 }
46
47 impl EnvironmentMap {
48 pub fn new() -> Self {
49 let map = env::vars_os()
50 .filter_map(|(k, v)| match (k.into_string(), v.into_string()) {
51 (Ok(k), Ok(v)) => Some((k, (v, cell::RefCell::default()))),
52 _ => None,
53 })
54 .collect::<collections::HashMap<_, _>>();
55 let cargo_pkg_name = map["CARGO_PKG_NAME"].0.replace("-", "_");
56 let override_prefix = format!("{}{}_", BUILT_OVERRIDE_PREFIX, cargo_pkg_name);
57 Self {
58 map,
59 override_prefix,
60 }
61 }
62
63 fn override_key(&self, key: &str) -> String {
64 let mut prefixed_key = self.override_prefix.clone();
65 prefixed_key.push_str(key);
66 prefixed_key
67 }
68
69 pub fn get(&self, key: &str) -> Option<&str> {
70 self.map.get(key).map(|v| {
71 v.1.borrow_mut().upgrade_to_queried();
72 v.0.as_str()
73 })
74 }
75
76 pub fn contains_key(&self, key: &str) -> bool {
77 self.get(key).is_some()
78 }
79
80 pub fn filter_map_keys<F>(&self, mut f: F) -> impl Iterator<Item = &str>
81 where
82 F: FnMut(&str) -> Option<&str>,
83 {
84 self.map.iter().filter_map(move |v| match f(v.0.as_str()) {
85 Some(w) => {
86 v.1.1.borrow_mut().upgrade_to_queried();
87 Some(w)
88 }
89 None => None,
90 })
91 }
92
93 pub fn get_override_var<'a, T>(&'a self, key: &str) -> Option<T>
94 where
95 T: util::ParseFromEnv<'a>,
96 {
97 self.map.get(&self.override_key(key)).map(|v| {
98 v.1.borrow_mut().upgrade_to_queried();
99 match T::parse_from_env(v.0.as_str()) {
100 Ok(t) => {
101 v.1.borrow_mut().upgrade_to_used();
102 t
103 }
104 Err(e) => {
105 panic!("Failed to parse `{key}`=`{0}`: {e:?}", v.0);
106 }
107 }
108 })
109 }
110
111 pub fn unused_override_vars(&self) -> impl Iterator<Item = &str> {
112 self.map.iter().filter_map(|(k, v)| {
113 if k.starts_with(&self.override_prefix) && v.1.borrow().is_unused() {
114 Some(k.as_str())
115 } else {
116 None
117 }
118 })
119 }
120
121 pub fn used_override_vars(&self) -> impl Iterator<Item = &str> {
122 self.map.iter().filter_map(|(k, v)| {
123 if v.1.borrow().is_used() {
124 Some(k.strip_prefix(&self.override_prefix).unwrap())
125 } else {
126 None
127 }
128 })
129 }
130
131 pub fn write_ci(&self, mut w: &fs::File) -> io::Result<()> {
132 use io::Write;
133
134 let ci = match self.get_override_var("CI_PLATFORM") {
135 Some(v) => v,
136 None => self.detect_ci().map(|ci| ci.to_string()),
137 };
138 write_variable!(
139 w,
140 "CI_PLATFORM",
141 "Option<&str>",
142 fmt_option_str(ci),
143 "The Continuous Integration platform detected during compilation."
144 );
145 Ok(())
146 }
147
148 pub fn write_env(&self, mut w: &fs::File) -> io::Result<()> {
149 use io::Write;
150 macro_rules! write_env_str {
151 ($(($name:ident, $env_name:expr, $doc:expr)),*) => {$(
152 let v = match self.get_override_var(stringify!($name)) {
153 Some(v) => v,
154 None => self.get($env_name).expect(stringify!(Missing expected environment variable $env_name)),
155 };
156 write_str_variable!(
157 w,
158 stringify!($name),
159 v,
160 $doc
161 );
162 )*}
163 }
164
165 write_env_str!(
166 (PKG_VERSION, "CARGO_PKG_VERSION", "The full version."),
167 (
168 PKG_VERSION_MAJOR,
169 "CARGO_PKG_VERSION_MAJOR",
170 "The major version."
171 ),
172 (
173 PKG_VERSION_MINOR,
174 "CARGO_PKG_VERSION_MINOR",
175 "The minor version."
176 ),
177 (
178 PKG_VERSION_PATCH,
179 "CARGO_PKG_VERSION_PATCH",
180 "The patch version."
181 ),
182 (
183 PKG_VERSION_PRE,
184 "CARGO_PKG_VERSION_PRE",
185 "The pre-release version."
186 ),
187 (
188 PKG_AUTHORS,
189 "CARGO_PKG_AUTHORS",
190 "A colon-separated list of authors."
191 ),
192 (PKG_NAME, "CARGO_PKG_NAME", "The name of the package."),
193 (PKG_DESCRIPTION, "CARGO_PKG_DESCRIPTION", "The description."),
194 (PKG_HOMEPAGE, "CARGO_PKG_HOMEPAGE", "The homepage."),
195 (PKG_LICENSE, "CARGO_PKG_LICENSE", "The license."),
196 (
197 PKG_REPOSITORY,
198 "CARGO_PKG_REPOSITORY",
199 "The source repository as advertised in Cargo.toml."
200 ),
201 (
202 TARGET,
203 "TARGET",
204 "The target triple that was being compiled for."
205 ),
206 (HOST, "HOST", "The host triple of the rust compiler."),
207 (
208 PROFILE,
209 "PROFILE",
210 "`release` for release builds, `debug` for other builds."
211 ),
212 (RUSTC, "RUSTC", "The compiler that cargo resolved to use."),
213 (
214 RUSTDOC,
215 "RUSTDOC",
216 "The documentation generator that cargo resolved to use."
217 )
218 );
219
220 write_str_variable!(
221 w,
222 "OPT_LEVEL",
223 self.get_override_var("OPT_LEVEL")
224 .unwrap_or_else(|| env::var("OPT_LEVEL").unwrap()),
225 "Value of `OPT_LEVEL` for the profile used during compilation."
226 );
227
228 write_variable!(
229 w,
230 "NUM_JOBS",
231 "u32",
232 self.get_override_var("NUM_JOBS").unwrap_or_else(|| {
233 if env::var(crate::SOURCE_DATE_EPOCH).is_ok() {
234 1u32
235 } else {
236 env::var("NUM_JOBS").unwrap().parse().unwrap()
237 }
238 }),
239 "The parallelism that was specified during compilation."
240 );
241
242 write_variable!(
243 w,
244 "DEBUG",
245 "bool",
246 self.get_override_var("DEBUG")
247 .unwrap_or_else(|| env::var("DEBUG").unwrap() == "true"),
248 "Value of DEBUG for the profile used during compilation."
249 );
250 Ok(())
251 }
252
253 pub fn write_features(&self, mut w: &fs::File) -> io::Result<()> {
254 use io::Write;
255
256 let mut features: Vec<String> = self
257 .get_override_var("FEATURES")
258 .unwrap_or_else(|| {
259 Some(
260 std::env::var("CARGO_CFG_FEATURE")
261 .ok()?
262 .split(',')
263 .map(|s| s.to_owned())
264 .collect(),
265 )
266 })
267 .unwrap_or_else(|| {
268 self.filter_map_keys(|k| k.strip_prefix("CARGO_FEATURE_"))
269 .map(|f| f.to_owned())
270 .collect::<Vec<_>>()
271 });
272 features.sort_unstable();
273
274 write_variable!(
275 w,
276 "FEATURES",
277 format_args!("[&str; {}]", features.len()),
278 ArrayDisplay(&features, |t, f| write!(f, "\"{}\"", t.escape_default())),
279 "The features that were enabled during compilation."
280 );
281 let features_str = features.join(", ");
282 write_str_variable!(
283 w,
284 "FEATURES_STR",
285 features_str,
286 "The features as a comma-separated string."
287 );
288
289 let mut lowercase_features = features
290 .iter()
291 .map(|name| name.to_lowercase())
292 .collect::<Vec<_>>();
293 lowercase_features.sort_unstable();
294
295 write_variable!(
296 w,
297 "FEATURES_LOWERCASE",
298 format_args!("[&str; {}]", lowercase_features.len()),
299 ArrayDisplay(&lowercase_features, |val, fmt| write!(
300 fmt,
301 "\"{}\"",
302 val.escape_default()
303 )),
304 "The features as above, as lowercase strings."
305 );
306 let lowercase_features_str = lowercase_features.join(", ");
307 write_str_variable!(
308 w,
309 "FEATURES_LOWERCASE_STR",
310 lowercase_features_str,
311 "The feature-string as above, from lowercase strings."
312 );
313
314 Ok(())
315 }
316
317 pub fn write_cfg(&self, mut w: &fs::File) -> io::Result<()> {
318 use io::Write;
319
320 write_str_variable!(
321 w,
322 "CFG_TARGET_ARCH",
323 self.get_override_var("CFG_TARGET_ARCH")
324 .unwrap_or_else(|| self.get("CARGO_CFG_TARGET_ARCH").unwrap()),
325 "The target architecture, given by `CARGO_CFG_TARGET_ARCH`."
326 );
327
328 write_str_variable!(
329 w,
330 "CFG_ENDIAN",
331 self.get_override_var("CFG_ENDIAN")
332 .unwrap_or_else(|| self.get("CARGO_CFG_TARGET_ENDIAN").unwrap()),
333 "The endianness, given by `CARGO_CFG_TARGET_ENDIAN`."
334 );
335
336 write_str_variable!(
337 w,
338 "CFG_ENV",
339 self.get_override_var("CFG_ENV")
340 .unwrap_or_else(|| self.get("CARGO_CFG_TARGET_ENV").unwrap()),
341 "The toolchain-environment, given by `CARGO_CFG_TARGET_ENV`."
342 );
343
344 write_str_variable!(
345 w,
346 "CFG_FAMILY",
347 self.get_override_var("CFG_FAMILY")
348 .unwrap_or_else(|| self.get("CARGO_CFG_TARGET_FAMILY").unwrap_or_default()),
349 "The OS-family, given by `CARGO_CFG_TARGET_FAMILY`."
350 );
351
352 write_str_variable!(
353 w,
354 "CFG_OS",
355 self.get_override_var("CFG_OS")
356 .unwrap_or_else(|| self.get("CARGO_CFG_TARGET_OS").unwrap()),
357 "The operating system, given by `CARGO_CFG_TARGET_OS`."
358 );
359
360 write_str_variable!(
361 w,
362 "CFG_POINTER_WIDTH",
363 self.get_override_var("CFG_POINTER_WIDTH")
364 .unwrap_or_else(|| self.get("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap()),
365 "The pointer width, given by `CARGO_CFG_TARGET_POINTER_WIDTH`."
366 );
367
368 Ok(())
369 }
370
371 pub fn write_compiler_version(&self, mut w: &fs::File) -> io::Result<()> {
372 use std::io::Write;
373
374 let rustc;
375 let rustc_version;
376 match self.get_override_var("RUSTC") {
377 Some(v) => {
378 rustc = v;
379 rustc_version = self
380 .get_override_var("RUSTC_VERSION")
381 .expect("RUSTC_VERSION must be overridden if RUSTC is")
382 }
383 None => {
384 rustc = self.get("RUSTC").unwrap();
385 rustc_version = get_version_from_cmd(rustc.as_ref())?;
386 }
387 }
388
389 let rustdoc;
390 let rustdoc_version;
391 match self.get_override_var("RUSTDOC") {
392 Some(v) => {
393 rustdoc = v;
394 rustdoc_version = self.get_override_var("RUSTDOC_VERSION").unwrap_or_default();
395 }
396 None => {
397 rustdoc = self.get("RUSTDOC").unwrap();
398 rustdoc_version = get_version_from_cmd(rustdoc.as_ref()).unwrap_or_default();
399 }
400 }
401
402 write_str_variable!(
403 w,
404 "RUSTC_VERSION",
405 rustc_version,
406 format_args!("The output of `{rustc} -V`")
407 );
408
409 write_str_variable!(
410 w,
411 "RUSTDOC_VERSION",
412 rustdoc_version,
413 format_args!(
414 "The output of `{rustdoc} -V`; empty string if `{rustdoc} -V` failed to execute"
415 )
416 );
417 Ok(())
418 }
419
420 pub fn detect_ci(&self) -> Option<CIPlatform> {
421 macro_rules! detect {
422 ($(($k:expr, $v:expr, $i:ident)),*) => {$(
423 if self.get($k).map_or(false, |v| v == $v) {
424 return Some(CIPlatform::$i);
425 }
426 )*};
427 ($(($k:expr, $i:ident)),*) => {$(
428 if self.contains_key($k) {
429 return Some(CIPlatform::$i);
430 }
431 )*};
432 ($($k:expr),*) => {$(
433 if self.contains_key($k) {
434 return Some(CIPlatform::Generic);
435 }
436 )*};
437 }
438 // Variable names collected by watson/ci-info
439 detect!(
440 ("TRAVIS", Travis),
441 ("CIRCLECI", Circle),
442 ("GITLAB_CI", GitLab),
443 ("APPVEYOR", AppVeyor),
444 ("DRONE", Drone),
445 ("MAGNUM", Magnum),
446 ("SEMAPHORE", Semaphore),
447 ("JENKINS_URL", Jenkins),
448 ("bamboo_planKey", Bamboo),
449 ("TF_BUILD", TFS),
450 ("TEAMCITY_VERSION", TeamCity),
451 ("BUILDKITE", Buildkite),
452 ("HUDSON_URL", Hudson),
453 ("GO_PIPELINE_LABEL", GoCD),
454 ("BITBUCKET_COMMIT", BitBucket),
455 ("GITHUB_ACTIONS", GitHubActions)
456 );
457
458 if self.contains_key("TASK_ID") && self.contains_key("RUN_ID") {
459 return Some(CIPlatform::TaskCluster);
460 }
461
462 detect!(("CI_NAME", "codeship", Codeship));
463
464 detect!(
465 "CI", // Could be Travis, Circle, GitLab, AppVeyor or CodeShip
466 "CONTINUOUS_INTEGRATION", // Probably Travis
467 "BUILD_NUMBER" // Jenkins, TeamCity
468 );
469 None
470 }
471 }
472
473 /// Various Continuous Integration platforms whose presence can be detected.
474 pub enum CIPlatform {
475 /// <https://travis-ci.org>
476 Travis,
477 /// <https://circleci.com>
478 Circle,
479 /// <https://about.gitlab.com/gitlab-ci>
480 GitLab,
481 /// <https://www.appveyor.com>
482 AppVeyor,
483 /// <https://codeship.com>
484 Codeship,
485 /// <https://github.com/drone/drone>
486 Drone,
487 /// <https://magnum-ci.com>
488 Magnum,
489 /// <https://semaphoreci.com>
490 Semaphore,
491 /// <https://jenkins.io>
492 Jenkins,
493 /// <https://www.atlassian.com/software/bamboo>
494 Bamboo,
495 /// <https://www.visualstudio.com/de/tfs>
496 TFS,
497 /// <https://www.jetbrains.com/teamcity>
498 TeamCity,
499 /// <https://buildkite.com>
500 Buildkite,
501 /// <http://hudson-ci.org>
502 Hudson,
503 /// <https://github.com/taskcluster>
504 TaskCluster,
505 /// <https://www.gocd.io>
506 GoCD,
507 /// <https://bitbucket.org>
508 BitBucket,
509 /// <https://github.com/features/actions>
510 GitHubActions,
511 /// Unspecific
512 Generic,
513 }
514
515 impl fmt::Display for CIPlatform {
516 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
517 f.write_str(match *self {
518 CIPlatform::Travis => "Travis CI",
519 CIPlatform::Circle => "CircleCI",
520 CIPlatform::GitLab => "GitLab",
521 CIPlatform::AppVeyor => "AppVeyor",
522 CIPlatform::Codeship => "CodeShip",
523 CIPlatform::Drone => "Drone",
524 CIPlatform::Magnum => "Magnum",
525 CIPlatform::Semaphore => "Semaphore",
526 CIPlatform::Jenkins => "Jenkins",
527 CIPlatform::Bamboo => "Bamboo",
528 CIPlatform::TFS => "Team Foundation Server",
529 CIPlatform::TeamCity => "TeamCity",
530 CIPlatform::Buildkite => "Buildkite",
531 CIPlatform::Hudson => "Hudson",
532 CIPlatform::TaskCluster => "TaskCluster",
533 CIPlatform::GoCD => "GoCD",
534 CIPlatform::BitBucket => "BitBucket",
535 CIPlatform::GitHubActions => "GitHub Actions",
536 CIPlatform::Generic => "Generic CI",
537 })
538 }
539 }