Skip to main content

sys_lib/
build.rs

1//! Build info: facts fixed when the application was compiled, answering
2//! "exactly which build is running?" in logs, crash reports, and health checks.
3//!
4//! The application calls [`emit`] from its own `build.rs` (with sys-lib also in
5//! `[build-dependencies]`), and [`build_info!`](crate::build_info) anywhere at
6//! run time:
7//!
8//! ```no_run
9//! // build.rs
10//! fn main() {
11//!     sys_lib::build::emit();
12//! }
13//! ```
14//!
15//! ```
16//! let build = sys_lib::build_info!();
17//! println!("{build}");               // site 0.3.0 (9db9e36, release, built 2026-10-21T18:02:11Z)
18//! println!("{}", build.public());    // site 0.3.0: safe for a public health endpoint
19//! ```
20//!
21//! This module is the only code in sys-lib that runs another program, and it
22//! does so in the application's build script, never at run time (D-004). It
23//! never fails the build: anything it cannot learn becomes `unknown`.
24
25// The examples show a build script, whose `fn main` is the point.
26#![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
37/// Values longer than this, or with characters outside printable ASCII, become
38/// `unknown` (threat T11: a branch name can contain anything).
39const MAX_VALUE: usize = 128;
40const MAX_FEATURES: usize = 512;
41const UNKNOWN: &str = "unknown";
42
43/// Emits the build facts for [`build_info!`](crate::build_info). Call it from
44/// the application's `build.rs`. Never fails and never panics.
45///
46/// It records the git commit and whether the tree was dirty, the build time
47/// (`SOURCE_DATE_EPOCH` when set, for reproducible builds), the profile,
48/// target, rustc version, and enabled features. It does not record the build
49/// machine's host name, user, or source path.
50///
51/// It asks Cargo to re-run the build script when the git `HEAD`, the current
52/// ref, the index, `src/`, `build.rs`, or `Cargo.toml` change, or when
53/// `SOURCE_DATE_EPOCH` does.
54pub fn emit() {
55    emitter().emit();
56}
57
58/// A configurable [`emit`].
59///
60/// ```no_run
61/// // Only the commit, no rustc version or feature list.
62/// sys_lib::build::emitter().rustc(false).features(false).emit();
63/// ```
64pub fn emitter() -> Emitter {
65    Emitter {
66        git: true,
67        rustc: true,
68        features: true,
69    }
70}
71
72/// What [`emit`] captures. See [`emitter`].
73#[derive(Clone, Copy, Debug)]
74#[must_use]
75pub struct Emitter {
76    git: bool,
77    rustc: bool,
78    features: bool,
79}
80
81impl Emitter {
82    /// Capture the git commit and dirty state (default true).
83    pub fn git(mut self, on: bool) -> Self {
84        self.git = on;
85        self
86    }
87
88    /// Capture the rustc version (default true).
89    pub fn rustc(mut self, on: bool) -> Self {
90        self.rustc = on;
91        self
92    }
93
94    /// Capture the enabled Cargo features (default true).
95    pub fn features(mut self, on: bool) -> Self {
96        self.features = on;
97        self
98    }
99
100    /// Prints the `cargo:` instructions.
101    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
194/// A value safe for `rustc-env`: printable ASCII, bounded; otherwise `unknown`.
195fn 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
216/// The full commit hash (40 or 64 hex characters), or `None`.
217fn 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
223/// Whether tracked files differ from the commit; untracked files (build
224/// artefacts) do not count.
225fn 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
235/// The git files whose change means a new commit or a staged change: `HEAD`,
236/// the ref it names, `packed-refs`, and the index. Worktrees keep `HEAD` and
237/// the index in their own git directory and refs in the common one (E-59).
238fn 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
262/// The ref a `HEAD` file names, when it is a well-formed branch ref: under
263/// `refs/`, bounded, and free of everything `git check-ref-format` forbids
264/// (control characters, spaces, `~^:?*[\`, `..`). A tampered `HEAD` cannot
265/// name a path outside the git directory or smuggle a line into the output
266/// (threat T11).
267fn 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
281/// A `rerun-if-changed` line, or `None` for a path that would break the line
282/// protocol (a line break, or not UTF-8).
283fn 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
288/// `Ok(None)` when unset or empty, `Err` when set to anything but a
289/// non-negative integer (E-61).
290fn 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
297/// "1.89.0" from "rustc 1.89.0 (29483883e 2025-08-04)".
298fn 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
311/// The enabled features, from the build script's `CARGO_FEATURE_*` variables:
312/// lowercase, sorted, comma-separated. Cargo turns `-` into `_` in these names,
313/// so `device-id` reads back as `device_id`.
314fn 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
326/// Seconds since the Unix epoch as an RFC 3339 UTC timestamp, to the second.
327pub(crate) fn rfc3339(secs: u64) -> String {
328    let days = (secs / 86_400) as i64;
329    let rem = secs % 86_400;
330    // Howard Hinnant's civil-from-days.
331    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/// Facts fixed when the application was compiled. Get it with
349/// [`build_info!`](crate::build_info); every field is a `&'static str` in the
350/// binary, so it costs nothing at run time.
351#[derive(Clone, Copy, Debug, PartialEq, Eq)]
352#[non_exhaustive]
353pub struct BuildInfo {
354    /// The application's `CARGO_PKG_NAME`.
355    pub name: &'static str,
356    /// The application's `CARGO_PKG_VERSION`.
357    pub version: &'static str,
358    /// The full commit hash, or `"unknown"`.
359    pub commit: &'static str,
360    /// The first 7 characters of the commit, or `"unknown"`.
361    pub commit_short: &'static str,
362    /// Whether uncommitted changes to tracked files were built; `None` when unknown.
363    pub dirty: Option<bool>,
364    /// The build time, RFC 3339 UTC, or `"unknown"`.
365    pub built_at: &'static str,
366    /// `"release"`, `"debug"`.
367    pub profile: &'static str,
368    /// The target triple, or `"unknown"`.
369    pub target: &'static str,
370    /// The rustc version, or `"unknown"`.
371    pub rustc: &'static str,
372    /// The enabled features, comma-separated and sorted.
373    pub features: &'static str,
374}
375
376impl BuildInfo {
377    /// Used by [`build_info!`](crate::build_info); not part of the API.
378    #[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    /// Only the name and version, for output that leaves your control (a public
432    /// health endpoint): commit hashes and toolchain versions help an attacker
433    /// fingerprint a deployment (threat T11).
434    ///
435    /// ```
436    /// let public = sys_lib::build_info!().public().to_string();
437    /// assert!(public.starts_with("sys-lib "));
438    /// ```
439    #[must_use]
440    pub fn public(&self) -> PublicBuild<'_> {
441        PublicBuild(self)
442    }
443
444    /// Writes `build.name=site build.version=0.3.0 ...`, without allocating.
445    ///
446    /// ```
447    /// let mut line = String::new();
448    /// sys_lib::build_info!().write_kv(&mut line)?;
449    /// assert!(line.starts_with("build.name=sys-lib "));
450    /// # Ok::<(), std::fmt::Error>(())
451    /// ```
452    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    /// Writes one JSON object, without allocating; `dirty` is `null` when unknown.
480    ///
481    /// ```
482    /// let mut json = String::new();
483    /// sys_lib::build_info!().write_json(&mut json)?;
484    /// assert!(json.starts_with(r#"{"name":"sys-lib","#));
485    /// # Ok::<(), std::fmt::Error>(())
486    /// ```
487    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
525/// `site 0.3.0 (9db9e36, release, built 2026-10-21T18:02:11Z)`; unknown parts
526/// are left out, and a dirty build shows `9db9e36-dirty`.
527impl 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/// The name and version only: `site 0.3.0`. See [`BuildInfo::public`].
546#[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/// The application's build info, as a `&'static BuildInfo`. Expands in the
556/// calling crate, so the name and version are the **application's**. An
557/// application that never called [`build::emit`](crate::build::emit) still
558/// compiles, with the commit, time, target, and rustc `unknown` (E-60).
559///
560/// ```
561/// let build: &'static sys_lib::BuildInfo = sys_lib::build_info!();
562/// assert_eq!(build.name, env!("CARGO_PKG_NAME"));
563/// if build.dirty == Some(true) {
564///     eprintln!("warning: built from uncommitted changes");
565/// }
566/// ```
567#[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        // E-60: this crate's own build script never calls emit().
614        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        // T11: the public view has the name and version only.
667        assert_eq!(b.public().to_string(), "site 0.3.0");
668    }
669
670    #[test]
671    fn test_build_hostile_values_become_unknown() {
672        // T11: a branch or tag name can contain newlines, quotes, or 10 KB.
673        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        // T11: HEAD is read as text; a tampered one must not name a path
697        // outside the git directory or add a line to the output.
698        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        // E-61: invalid or negative values are ignored with a warning.
739        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        // Outside a build script every value is unknown, and nothing panics.
773        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        // E-59: in a git checkout the commit is found; elsewhere it is None.
786        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}