1#![allow(clippy::needless_doctest_main)]
27
28use core::fmt::{self, Write as _};
29use std::{
30 path::{Path, PathBuf},
31 process::Command,
32 time::{SystemTime, UNIX_EPOCH},
33};
34
35use crate::fmt::{json_str, kv};
36
37const MAX_VALUE: usize = 128;
40const MAX_FEATURES: usize = 512;
41const UNKNOWN: &str = "unknown";
42
43pub fn emit() {
55 emitter().emit();
56}
57
58pub fn emitter() -> Emitter {
65 Emitter {
66 git: true,
67 rustc: true,
68 features: true,
69 }
70}
71
72#[derive(Clone, Copy, Debug)]
74#[must_use]
75pub struct Emitter {
76 git: bool,
77 rustc: bool,
78 features: bool,
79}
80
81impl Emitter {
82 pub fn git(mut self, on: bool) -> Self {
84 self.git = on;
85 self
86 }
87
88 pub fn rustc(mut self, on: bool) -> Self {
90 self.rustc = on;
91 self
92 }
93
94 pub fn features(mut self, on: bool) -> Self {
96 self.features = on;
97 self
98 }
99
100 pub fn emit(self) {
102 for line in self.instructions() {
103 println!("{line}");
104 }
105 }
106
107 fn instructions(self) -> Vec<String> {
108 let env = |k: &str| std::env::var(k).ok();
109 let dir = env("CARGO_MANIFEST_DIR").map(PathBuf::from);
110 let mut out = Vec::new();
111
112 let (commit, dirty) = match (&dir, self.git) {
113 (Some(dir), true) => (git_commit(dir), git_dirty(dir)),
114 _ => (None, None),
115 };
116 let commit = commit.unwrap_or_else(|| UNKNOWN.to_owned());
117 let short = if commit == UNKNOWN {
118 UNKNOWN.to_owned()
119 } else {
120 commit.chars().take(7).collect()
121 };
122 let built_at = match source_date_epoch(env("SOURCE_DATE_EPOCH").as_deref()) {
123 Ok(Some(secs)) => rfc3339(secs),
124 Ok(None) => rfc3339(
125 SystemTime::now()
126 .duration_since(UNIX_EPOCH)
127 .map_or(0, |d| d.as_secs()),
128 ),
129 Err(()) => {
130 out.push(
131 "cargo:warning=SOURCE_DATE_EPOCH is not a non-negative integer; ignored"
132 .to_owned(),
133 );
134 rfc3339(
135 SystemTime::now()
136 .duration_since(UNIX_EPOCH)
137 .map_or(0, |d| d.as_secs()),
138 )
139 }
140 };
141 let rustc = if self.rustc {
142 rustc_version(env("RUSTC").as_deref().unwrap_or("rustc"))
143 } else {
144 None
145 };
146 let features = if self.features {
147 features(std::env::vars().map(|(k, _)| k))
148 } else {
149 String::new()
150 };
151
152 let mut set = |key: &str, value: &str, max: usize| {
153 out.push(format!(
154 "cargo:rustc-env=SYS_LIB_BUILD_{key}={}",
155 clean(value, max)
156 ));
157 };
158 set("COMMIT", &commit, MAX_VALUE);
159 set("COMMIT_SHORT", &short, MAX_VALUE);
160 set(
161 "DIRTY",
162 dirty.map_or(UNKNOWN, |d| if d { "true" } else { "false" }),
163 MAX_VALUE,
164 );
165 set("TIME", &built_at, MAX_VALUE);
166 set(
167 "PROFILE",
168 env("PROFILE").as_deref().unwrap_or(UNKNOWN),
169 MAX_VALUE,
170 );
171 set(
172 "TARGET",
173 env("TARGET").as_deref().unwrap_or(UNKNOWN),
174 MAX_VALUE,
175 );
176 set("RUSTC", rustc.as_deref().unwrap_or(UNKNOWN), MAX_VALUE);
177 set("FEATURES", &features, MAX_FEATURES);
178
179 if let Some(dir) = &dir {
180 let mut watch = if self.git { git_watch(dir) } else { Vec::new() };
181 watch.extend(
182 ["src", "build.rs", "Cargo.toml"]
183 .iter()
184 .map(|rel| dir.join(rel))
185 .filter(|p| p.exists()),
186 );
187 out.extend(watch.iter().filter_map(|p| rerun_line(p)));
188 }
189 out.push("cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH".to_owned());
190 out
191 }
192}
193
194fn clean(value: &str, max: usize) -> String {
196 let ok = value.len() <= max && value.bytes().all(|b| (0x20..0x7f).contains(&b));
197 if ok {
198 value.to_owned()
199 } else {
200 UNKNOWN.to_owned()
201 }
202}
203
204fn git(dir: &Path, args: &[&str]) -> Option<String> {
205 let out = Command::new("git")
206 .arg("-C")
207 .arg(dir)
208 .args(args)
209 .output()
210 .ok()?;
211 out.status
212 .success()
213 .then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
214}
215
216fn git_commit(dir: &Path) -> Option<String> {
218 let commit = git(dir, &["rev-parse", "HEAD"])?;
219 let hex = commit.bytes().all(|b| b.is_ascii_hexdigit());
220 (hex && (commit.len() == 40 || commit.len() == 64)).then_some(commit)
221}
222
223fn git_dirty(dir: &Path) -> Option<bool> {
226 let out = Command::new("git")
227 .arg("-C")
228 .arg(dir)
229 .args(["status", "--porcelain", "--untracked-files=no"])
230 .output()
231 .ok()?;
232 out.status.success().then_some(!out.stdout.is_empty())
233}
234
235fn git_watch(dir: &Path) -> Vec<PathBuf> {
239 let Some(git_dir) = git(dir, &["rev-parse", "--path-format=absolute", "--git-dir"]) else {
240 return Vec::new();
241 };
242 let common = git(
243 dir,
244 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
245 )
246 .unwrap_or_else(|| git_dir.clone());
247 let (git_dir, common) = (PathBuf::from(git_dir), PathBuf::from(common));
248 let mut paths = vec![
249 git_dir.join("HEAD"),
250 git_dir.join("index"),
251 common.join("packed-refs"),
252 ];
253 if let Ok(head) = std::fs::read_to_string(git_dir.join("HEAD"))
254 && let Some(r) = head_ref(&head)
255 {
256 paths.push(common.join(r));
257 }
258 paths.retain(|p| p.exists());
259 paths
260}
261
262fn head_ref(head: &str) -> Option<&str> {
268 let r = head
269 .strip_suffix('\n')
270 .unwrap_or(head)
271 .strip_prefix("ref: ")?;
272 let ok = r.starts_with("refs/")
273 && r.len() <= 1024
274 && !r.contains("..")
275 && !r.ends_with('/')
276 && r.bytes()
277 .all(|b| b > 0x20 && b != 0x7f && !b"~^:?*[\\".contains(&b));
278 ok.then_some(r)
279}
280
281fn rerun_line(path: &Path) -> Option<String> {
284 let text = path.to_str()?;
285 (!text.contains(['\n', '\r'])).then(|| format!("cargo:rerun-if-changed={text}"))
286}
287
288fn source_date_epoch(value: Option<&str>) -> Result<Option<u64>, ()> {
291 match value.map(str::trim) {
292 None | Some("") => Ok(None),
293 Some(v) => v.parse().map(Some).map_err(|_| ()),
294 }
295}
296
297fn rustc_version(rustc: &str) -> Option<String> {
299 let out = Command::new(rustc).arg("--version").output().ok()?;
300 let text = String::from_utf8_lossy(&out.stdout).into_owned();
301 parse_rustc_version(&text)
302}
303
304fn parse_rustc_version(text: &str) -> Option<String> {
305 let version = text.split_whitespace().nth(1)?;
306 version
307 .starts_with(|c: char| c.is_ascii_digit())
308 .then_some(version.to_owned())
309}
310
311fn features(vars: impl Iterator<Item = String>) -> String {
315 let mut names: Vec<String> = vars
316 .filter_map(|k| {
317 k.strip_prefix("CARGO_FEATURE_")
318 .map(str::to_ascii_lowercase)
319 })
320 .collect();
321 names.sort();
322 names.dedup();
323 names.join(",")
324}
325
326pub(crate) fn rfc3339(secs: u64) -> String {
328 let days = (secs / 86_400) as i64;
329 let rem = secs % 86_400;
330 let z = days + 719_468;
332 let era = z.div_euclid(146_097);
333 let doe = z.rem_euclid(146_097);
334 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
335 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
336 let mp = (5 * doy + 2) / 153;
337 let day = doy - (153 * mp + 2) / 5 + 1;
338 let month = if mp < 10 { mp + 3 } else { mp - 9 };
339 let year = yoe + era * 400 + i64::from(month <= 2);
340 format!(
341 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
342 rem / 3600,
343 rem % 3600 / 60,
344 rem % 60
345 )
346}
347
348#[derive(Clone, Copy, Debug, PartialEq, Eq)]
352#[non_exhaustive]
353pub struct BuildInfo {
354 pub name: &'static str,
356 pub version: &'static str,
358 pub commit: &'static str,
360 pub commit_short: &'static str,
362 pub dirty: Option<bool>,
364 pub built_at: &'static str,
366 pub profile: &'static str,
368 pub target: &'static str,
370 pub rustc: &'static str,
372 pub features: &'static str,
374}
375
376impl BuildInfo {
377 #[doc(hidden)]
379 #[allow(clippy::too_many_arguments)]
380 #[must_use]
381 pub const fn __from_env(
382 name: &'static str,
383 version: &'static str,
384 debug: bool,
385 commit: Option<&'static str>,
386 commit_short: Option<&'static str>,
387 dirty: Option<&'static str>,
388 built_at: Option<&'static str>,
389 profile: Option<&'static str>,
390 target: Option<&'static str>,
391 rustc: Option<&'static str>,
392 features: Option<&'static str>,
393 ) -> Self {
394 const fn or_unknown(v: Option<&'static str>) -> &'static str {
395 match v {
396 Some(v) => v,
397 None => UNKNOWN,
398 }
399 }
400 let dirty = match dirty {
401 Some(d) => match d.as_bytes() {
402 b"true" => Some(true),
403 b"false" => Some(false),
404 _ => None,
405 },
406 None => None,
407 };
408 let profile = match profile {
409 Some(p) => p,
410 None if debug => "debug",
411 None => "release",
412 };
413 let features = match features {
414 Some(f) => f,
415 None => "",
416 };
417 Self {
418 name,
419 version,
420 commit: or_unknown(commit),
421 commit_short: or_unknown(commit_short),
422 dirty,
423 built_at: or_unknown(built_at),
424 profile,
425 target: or_unknown(target),
426 rustc: or_unknown(rustc),
427 features,
428 }
429 }
430
431 #[must_use]
440 pub fn public(&self) -> PublicBuild<'_> {
441 PublicBuild(self)
442 }
443
444 pub fn write_kv(&self, out: &mut impl fmt::Write) -> fmt::Result {
453 let dirty = match self.dirty {
454 Some(true) => "true",
455 Some(false) => "false",
456 None => UNKNOWN,
457 };
458 let fields = [
459 ("build.name", self.name),
460 ("build.version", self.version),
461 ("build.commit", self.commit),
462 ("build.commit_short", self.commit_short),
463 ("build.dirty", dirty),
464 ("build.built_at", self.built_at),
465 ("build.profile", self.profile),
466 ("build.target", self.target),
467 ("build.rustc", self.rustc),
468 ("build.features", self.features),
469 ];
470 for (i, (k, v)) in fields.iter().enumerate() {
471 if i > 0 {
472 out.write_char(' ')?;
473 }
474 kv(out, k, v)?;
475 }
476 Ok(())
477 }
478
479 pub fn write_json(&self, out: &mut impl fmt::Write) -> fmt::Result {
488 out.write_char('{')?;
489 let strings = [
490 ("name", self.name),
491 ("version", self.version),
492 ("commit", self.commit),
493 ("commit_short", self.commit_short),
494 ];
495 for (i, (k, v)) in strings.iter().enumerate() {
496 if i > 0 {
497 out.write_char(',')?;
498 }
499 json_str(out, k)?;
500 out.write_char(':')?;
501 json_str(out, v)?;
502 }
503 out.write_str(",\"dirty\":")?;
504 out.write_str(match self.dirty {
505 Some(true) => "true",
506 Some(false) => "false",
507 None => "null",
508 })?;
509 for (k, v) in [
510 ("built_at", self.built_at),
511 ("profile", self.profile),
512 ("target", self.target),
513 ("rustc", self.rustc),
514 ("features", self.features),
515 ] {
516 out.write_char(',')?;
517 json_str(out, k)?;
518 out.write_char(':')?;
519 json_str(out, v)?;
520 }
521 out.write_char('}')
522 }
523}
524
525impl fmt::Display for BuildInfo {
528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529 write!(f, "{} {} (", self.name, self.version)?;
530 if self.commit_short != UNKNOWN {
531 write!(f, "{}", self.commit_short)?;
532 if self.dirty == Some(true) {
533 f.write_str("-dirty")?;
534 }
535 f.write_str(", ")?;
536 }
537 f.write_str(self.profile)?;
538 if self.built_at != UNKNOWN {
539 write!(f, ", built {}", self.built_at)?;
540 }
541 f.write_char(')')
542 }
543}
544
545#[derive(Clone, Copy, Debug)]
547pub struct PublicBuild<'a>(&'a BuildInfo);
548
549impl fmt::Display for PublicBuild<'_> {
550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551 write!(f, "{} {}", self.0.name, self.0.version)
552 }
553}
554
555#[macro_export]
568macro_rules! build_info {
569 () => {{
570 static __SYS_LIB_BUILD_INFO: $crate::BuildInfo = $crate::BuildInfo::__from_env(
571 ::core::env!("CARGO_PKG_NAME"),
572 ::core::env!("CARGO_PKG_VERSION"),
573 ::core::cfg!(debug_assertions),
574 ::core::option_env!("SYS_LIB_BUILD_COMMIT"),
575 ::core::option_env!("SYS_LIB_BUILD_COMMIT_SHORT"),
576 ::core::option_env!("SYS_LIB_BUILD_DIRTY"),
577 ::core::option_env!("SYS_LIB_BUILD_TIME"),
578 ::core::option_env!("SYS_LIB_BUILD_PROFILE"),
579 ::core::option_env!("SYS_LIB_BUILD_TARGET"),
580 ::core::option_env!("SYS_LIB_BUILD_RUSTC"),
581 ::core::option_env!("SYS_LIB_BUILD_FEATURES"),
582 );
583 &__SYS_LIB_BUILD_INFO
584 }};
585}
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590
591 #[test]
592 fn test_build_rfc3339_matches_clock_lib() {
593 for secs in [
594 0u64,
595 1,
596 59,
597 86_399,
598 86_400,
599 951_782_400,
600 1_700_000_000,
601 1_761_069_731,
602 4_102_444_800,
603 253_402_300_799,
604 ] {
605 let ours = rfc3339(secs);
606 let oracle = format!("{:.0}", clock_lib::Wall::from_unix_seconds(secs).unwrap());
607 assert_eq!(ours, oracle, "{secs}");
608 }
609 }
610
611 #[test]
612 fn test_build_info_without_emit_compiles_with_unknowns() {
613 let b = crate::build_info!();
615 assert_eq!(b.name, "sys-lib");
616 assert_eq!(b.version, crate::VERSION);
617 assert_eq!(b.commit, "unknown");
618 assert_eq!(b.dirty, None);
619 assert_eq!(
620 b.profile,
621 if cfg!(debug_assertions) {
622 "debug"
623 } else {
624 "release"
625 }
626 );
627 assert_eq!(
628 b.to_string(),
629 format!("sys-lib {} ({})", crate::VERSION, b.profile)
630 );
631 assert_eq!(
632 b.public().to_string(),
633 format!("sys-lib {}", crate::VERSION)
634 );
635 assert!(std::ptr::eq(b, crate::build_info!()) || b == crate::build_info!());
636 }
637
638 #[test]
639 fn test_build_info_display_and_writers_with_every_field() {
640 let b = BuildInfo::__from_env(
641 "site",
642 "0.3.0",
643 false,
644 Some("9db9e36aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
645 Some("9db9e36"),
646 Some("true"),
647 Some("2026-10-21T18:02:11Z"),
648 Some("release"),
649 Some("x86_64-unknown-linux-gnu"),
650 Some("1.89.0"),
651 Some("default,guard"),
652 );
653 assert_eq!(
654 b.to_string(),
655 "site 0.3.0 (9db9e36-dirty, release, built 2026-10-21T18:02:11Z)"
656 );
657 let mut kv_line = String::new();
658 b.write_kv(&mut kv_line).unwrap();
659 assert!(kv_line.contains("build.dirty=true build.built_at=2026-10-21T18:02:11Z"));
660 assert!(kv_line.contains("build.features=default,guard"));
661 let mut json = String::new();
662 b.write_json(&mut json).unwrap();
663 assert!(json.starts_with(r#"{"name":"site","version":"0.3.0","commit":"9db9e36"#));
664 assert!(json.contains(r#""dirty":true,"built_at":"2026-10-21T18:02:11Z""#));
665 assert!(json.ends_with(r#""features":"default,guard"}"#));
666 assert_eq!(b.public().to_string(), "site 0.3.0");
668 }
669
670 #[test]
671 fn test_build_hostile_values_become_unknown() {
672 assert_eq!(clean("main\ncargo:rustc-env=EVIL=1", MAX_VALUE), "unknown");
674 assert_eq!(clean(&"x".repeat(10_000), MAX_VALUE), "unknown");
675 assert_eq!(clean("caf\u{e9}", MAX_VALUE), "unknown");
676 assert_eq!(clean("1.89.0", MAX_VALUE), "1.89.0");
677 let b = BuildInfo::__from_env(
678 "a",
679 "1",
680 true,
681 None,
682 None,
683 Some("maybe"),
684 None,
685 None,
686 None,
687 None,
688 None,
689 );
690 assert_eq!(b.dirty, None);
691 assert_eq!(b.profile, "debug");
692 }
693
694 #[test]
695 fn test_build_head_ref_rejects_tampered_heads() {
696 assert_eq!(head_ref("ref: refs/heads/main\n"), Some("refs/heads/main"));
699 assert_eq!(
700 head_ref("ref: refs/heads/feature/0.3-boot-kit\n"),
701 Some("refs/heads/feature/0.3-boot-kit")
702 );
703 assert_eq!(
704 head_ref("ref: refs/heads/\"quoted\"\n"),
705 Some("refs/heads/\"quoted\"")
706 );
707 assert_eq!(
708 head_ref("ref: refs/heads/x\ncargo:rustc-link-arg=evil\n"),
709 None
710 );
711 assert_eq!(head_ref("ref: refs/heads/x\r\n"), None);
712 assert_eq!(head_ref("ref: refs/../../etc/passwd\n"), None);
713 assert_eq!(head_ref("ref: /etc/passwd\n"), None);
714 assert_eq!(head_ref("ref: refs/heads/a b\n"), None);
715 assert_eq!(head_ref("ref: refs/heads/\n"), None);
716 assert_eq!(
717 head_ref(&format!("ref: refs/heads/{}\n", "x".repeat(10_000))),
718 None
719 );
720 assert_eq!(head_ref("4f2c9a1e0b7d3c5a8e6f1b2d4c7a9e0f3b5d8c1a\n"), None);
721 }
722
723 #[test]
724 fn test_build_rerun_line_refuses_line_breaks() {
725 assert_eq!(
726 rerun_line(Path::new("/src/app/.git/HEAD")).as_deref(),
727 Some("cargo:rerun-if-changed=/src/app/.git/HEAD")
728 );
729 assert_eq!(
730 rerun_line(Path::new("/src/a\ncargo:rustc-link-arg=evil")),
731 None
732 );
733 assert_eq!(rerun_line(Path::new("/src/a\rb")), None);
734 }
735
736 #[test]
737 fn test_build_source_date_epoch_rules() {
738 assert_eq!(source_date_epoch(None), Ok(None));
740 assert_eq!(source_date_epoch(Some("")), Ok(None));
741 assert_eq!(
742 source_date_epoch(Some("1700000000")),
743 Ok(Some(1_700_000_000))
744 );
745 assert_eq!(source_date_epoch(Some("-5")), Err(()));
746 assert_eq!(source_date_epoch(Some("soon")), Err(()));
747 }
748
749 #[test]
750 fn test_build_rustc_version_and_features_parsing() {
751 assert_eq!(
752 parse_rustc_version("rustc 1.89.0 (29483883e 2025-08-04)").as_deref(),
753 Some("1.89.0")
754 );
755 assert_eq!(
756 parse_rustc_version("rustc 1.92.0-nightly (abc 2025-10-01)").as_deref(),
757 Some("1.92.0-nightly")
758 );
759 assert_eq!(parse_rustc_version("garbage"), None);
760 let vars = [
761 "CARGO_FEATURE_GUARD",
762 "PATH",
763 "CARGO_FEATURE_DEFAULT",
764 "CARGO_FEATURE_DEVICE_ID",
765 ]
766 .map(String::from);
767 assert_eq!(features(vars.into_iter()), "default,device_id,guard");
768 }
769
770 #[test]
771 fn test_build_instructions_never_fail_without_cargo() {
772 let lines = emitter().git(false).rustc(false).instructions();
774 assert!(
775 lines
776 .iter()
777 .any(|l| l.starts_with("cargo:rustc-env=SYS_LIB_BUILD_COMMIT=unknown"))
778 );
779 assert!(lines.iter().all(|l| l.starts_with("cargo:")));
780 assert!(lines.contains(&"cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH".to_owned()));
781 }
782
783 #[test]
784 fn test_build_git_commit_of_this_repository() {
785 let dir = Path::new(env!("CARGO_MANIFEST_DIR"));
787 if let Some(c) = git_commit(dir) {
788 assert!(c.len() == 40 || c.len() == 64);
789 assert!(git_dirty(dir).is_some());
790 assert!(git_watch(dir).iter().any(|p| p.ends_with("HEAD")));
791 }
792 assert_eq!(git_commit(Path::new("/definitely/not/a/repository")), None);
793 }
794}