Skip to main content

sys_lib/
os.rs

1//! The operating system: kind, name, version, kernel, and distribution.
2//!
3//! The kind and the `is_*` checks are compile-time constants. Everything else
4//! is a static fact, read once on first use and cached for the life of the
5//! process (about a nanosecond afterwards).
6//!
7//! ```
8//! use sys_lib as sys;
9//!
10//! println!("{} (kernel {})", sys::os::name(), sys::os::kernel());
11//! println!("{} ({})", sys::os::distro(), sys::os::distro_id());   // "Ubuntu (ubuntu)", "Windows (windows)"
12//! if sys::os::is_like("debian") {
13//!     // apt-based: Debian, Ubuntu, Mint, Pop!_OS, ...
14//! }
15//! const ON_WINDOWS: bool = sys::os::is_windows();
16//! ```
17
18use core::fmt;
19use std::sync::OnceLock;
20
21use crate::parse;
22
23/// The operating system family, fixed when the program was compiled.
24#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
25#[non_exhaustive]
26pub enum Kind {
27    /// Linux (not Android).
28    Linux,
29    /// Windows.
30    Windows,
31    /// macOS.
32    MacOs,
33    /// Android.
34    Android,
35    /// iOS and iPadOS.
36    Ios,
37    /// FreeBSD.
38    FreeBsd,
39    /// OpenBSD.
40    OpenBsd,
41    /// NetBSD.
42    NetBsd,
43    /// Anything else.
44    Other,
45}
46
47impl Kind {
48    /// The lowercase name: `"linux"`, `"windows"`, `"macos"`, ...
49    ///
50    /// ```
51    /// assert_eq!(sys_lib::os::Kind::MacOs.name(), "macos");
52    /// ```
53    #[must_use]
54    pub const fn name(self) -> &'static str {
55        match self {
56            Self::Linux => "linux",
57            Self::Windows => "windows",
58            Self::MacOs => "macos",
59            Self::Android => "android",
60            Self::Ios => "ios",
61            Self::FreeBsd => "freebsd",
62            Self::OpenBsd => "openbsd",
63            Self::NetBsd => "netbsd",
64            Self::Other => "other",
65        }
66    }
67}
68
69/// The operating system family this program was compiled for.
70///
71/// ```
72/// # use sys_lib as sys;
73/// #[cfg(target_os = "linux")]
74/// assert_eq!(sys::os::kind(), sys::os::Kind::Linux);
75/// ```
76#[must_use]
77pub const fn kind() -> Kind {
78    if cfg!(target_os = "android") {
79        Kind::Android
80    } else if cfg!(target_os = "linux") {
81        Kind::Linux
82    } else if cfg!(target_os = "windows") {
83        Kind::Windows
84    } else if cfg!(target_os = "macos") {
85        Kind::MacOs
86    } else if cfg!(target_os = "ios") {
87        Kind::Ios
88    } else if cfg!(target_os = "freebsd") {
89        Kind::FreeBsd
90    } else if cfg!(target_os = "openbsd") {
91        Kind::OpenBsd
92    } else if cfg!(target_os = "netbsd") {
93        Kind::NetBsd
94    } else {
95        Kind::Other
96    }
97}
98
99/// Windows.
100#[must_use]
101pub const fn is_windows() -> bool {
102    cfg!(target_os = "windows")
103}
104
105/// The Linux kernel, not Android.
106#[must_use]
107pub const fn is_linux() -> bool {
108    cfg!(target_os = "linux")
109}
110
111/// macOS.
112#[must_use]
113pub const fn is_macos() -> bool {
114    cfg!(target_os = "macos")
115}
116
117/// macOS; the same as [`is_macos`].
118#[must_use]
119pub const fn is_mac() -> bool {
120    is_macos()
121}
122
123/// Android.
124#[must_use]
125pub const fn is_android() -> bool {
126    cfg!(target_os = "android")
127}
128
129/// iOS and iPadOS.
130#[must_use]
131pub const fn is_ios() -> bool {
132    cfg!(target_os = "ios")
133}
134
135/// A Unix: Linux, Android, macOS, iOS, the BSDs, ...
136#[must_use]
137pub const fn is_unix() -> bool {
138    cfg!(unix)
139}
140
141/// FreeBSD, OpenBSD, NetBSD, or DragonFly BSD.
142#[must_use]
143pub const fn is_bsd() -> bool {
144    cfg!(any(
145        target_os = "freebsd",
146        target_os = "openbsd",
147        target_os = "netbsd",
148        target_os = "dragonfly"
149    ))
150}
151
152/// A version number, with the original text kept: `24.04` stays `24.04`.
153///
154/// Ordering compares the numbers, then the text.
155///
156/// ```
157/// if let Some(v) = sys_lib::os::version() {
158///     println!("{v} = {}.{}.{}", v.major, v.minor, v.patch);
159/// }
160/// ```
161#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
162#[non_exhaustive]
163pub struct Version {
164    /// The first number.
165    pub major: u32,
166    /// The second number, 0 when absent.
167    pub minor: u32,
168    /// The third number, 0 when absent.
169    pub patch: u32,
170    /// A fourth number (the Windows update revision, for example).
171    pub build: Option<u32>,
172    /// The text the numbers came from.
173    pub text: &'static str,
174}
175
176impl fmt::Display for Version {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        f.pad(self.text)
179    }
180}
181
182/// Where a fact came from.
183#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
184#[non_exhaustive]
185pub enum Source {
186    /// `/etc/os-release`.
187    OsRelease,
188    /// `/usr/lib/os-release`.
189    UsrLibOsRelease,
190    /// A legacy release file (`/etc/redhat-release`, `/etc/lsb-release`, ...).
191    LegacyRelease,
192    /// A `sysctl` value (macOS, iOS).
193    Sysctl,
194    /// The Windows registry or `RtlGetVersion`.
195    Registry,
196    /// An Android system property.
197    SystemProperty,
198    /// None of the above: the answer names the OS family only.
199    Fallback,
200}
201
202/// The fields of os-release (Linux), or their legacy-file equivalents.
203///
204/// ```
205/// if let Some(r) = sys_lib::os::os_release() {
206///     println!("{} {:?} {:?}", r.pretty_name, r.version_id, r.codename);
207/// }
208/// ```
209#[derive(Clone, Copy, Debug)]
210#[non_exhaustive]
211pub struct OsRelease {
212    /// `ID`: `ubuntu`, `fedora`; `linux` when the file names none.
213    pub id: &'static str,
214    /// `ID_LIKE`: the families this one derives from, closest first.
215    pub id_like: &'static [&'static str],
216    /// `NAME`: "Ubuntu", "Fedora Linux".
217    pub name: &'static str,
218    /// `PRETTY_NAME`: "Ubuntu 24.04.1 LTS".
219    pub pretty_name: &'static str,
220    /// `VERSION`: "24.04.1 LTS (Noble Numbat)".
221    pub version: Option<&'static str>,
222    /// `VERSION_ID`: "24.04".
223    pub version_id: Option<&'static str>,
224    /// `VERSION_CODENAME`: "noble".
225    pub codename: Option<&'static str>,
226    /// `VARIANT_ID`: "server", "workstation".
227    pub variant_id: Option<&'static str>,
228    /// `BUILD_ID`, on rolling distributions.
229    pub build_id: Option<&'static str>,
230    /// Which file the fields came from.
231    pub source: Source,
232}
233
234/// Everything this module knows, in one value.
235#[derive(Clone, Copy, Debug)]
236#[non_exhaustive]
237pub struct OsInfo {
238    /// [`kind`].
239    pub kind: Kind,
240    /// [`name`].
241    pub name: &'static str,
242    /// [`version`].
243    pub version: Option<&'static Version>,
244    /// [`kernel`].
245    pub kernel: &'static str,
246    /// [`distro`].
247    pub distro: &'static str,
248    /// [`distro_id`].
249    pub distro_id: &'static str,
250    /// [`os_release`].
251    pub os_release: Option<&'static OsRelease>,
252    /// Where `name` came from.
253    pub name_source: Source,
254}
255
256/// The operating system's name and version: "Ubuntu 24.04.1 LTS",
257/// "macOS 15.1 Sequoia", "Windows 11 Pro". Never empty, never fails: a minimal
258/// container without os-release gives "Linux" (E-47).
259#[must_use]
260pub fn name() -> &'static str {
261    info().name
262}
263
264/// The version: `24.04` on Ubuntu, `15.1` on macOS, `10.0.26200.6899` on Windows.
265/// `None` on rolling distributions, which have none.
266#[must_use]
267pub fn version() -> Option<&'static Version> {
268    info().version
269}
270
271/// The kernel release: "6.8.0-45-generic", "24.1.0" (Darwin), "10.0.26200.6899".
272#[must_use]
273pub fn kernel() -> &'static str {
274    info().kernel
275}
276
277/// The distribution's name on Linux ("Ubuntu", "Fedora Linux", "Arch Linux"),
278/// and the operating system's elsewhere ("Windows", "macOS", "Android", "iOS").
279/// Never empty; "Linux" when a Linux system says nothing about itself.
280///
281/// ```
282/// let d = sys_lib::os::distro();
283/// assert!(!d.is_empty());
284/// #[cfg(windows)]
285/// assert_eq!(d, "Windows");
286/// ```
287#[must_use]
288pub fn distro() -> &'static str {
289    info().distro
290}
291
292/// The distribution's lowercase id on Linux (`ubuntu`, `fedora`, `arch`), and
293/// the operating system's elsewhere (`windows`, `macos`, `android`, `ios`).
294#[must_use]
295pub fn distro_id() -> &'static str {
296    info().distro_id
297}
298
299/// Whether the distribution is `id` or derives from it (its `ID` or `ID_LIKE`):
300/// `is_like("debian")` is true on Debian, Ubuntu, Mint, and Pop!_OS. Off Linux
301/// it compares with [`distro_id`] (`is_like("windows")` on Windows).
302///
303/// ```
304/// let apt = sys_lib::os::is_like("debian");
305/// let dnf = sys_lib::os::is_like("fedora") || sys_lib::os::is_like("rhel");
306/// # let _ = (apt, dnf);
307/// ```
308#[must_use]
309pub fn is_like(id: &str) -> bool {
310    let info = info();
311    info.distro_id == id
312        || info
313            .os_release
314            .is_some_and(|r| r.id == id || r.id_like.contains(&id))
315}
316
317/// Every os-release field (Linux). `None` elsewhere, and on a Linux system with
318/// neither os-release nor a legacy release file.
319#[must_use]
320pub fn os_release() -> Option<&'static OsRelease> {
321    info().os_release
322}
323
324/// Everything above in one value.
325#[must_use]
326pub fn info() -> &'static OsInfo {
327    static INFO: OnceLock<OsInfo> = OnceLock::new();
328    INFO.get_or_init(|| from_facts(crate::sys::os()))
329}
330
331/// A static fact's text, kept for the life of the process. Called only from
332/// `OnceLock` initialisers, so each string is stored once.
333pub(crate) fn keep(s: String) -> &'static str {
334    Box::leak(s.into_boxed_str())
335}
336
337fn keep_opt(s: Option<String>) -> Option<&'static str> {
338    s.map(keep)
339}
340
341pub(crate) fn from_facts(f: crate::sys::OsFacts) -> OsInfo {
342    let version = f.version.as_deref().and_then(|text| {
343        let (major, minor, patch, build) = parse::version::parse(text)?;
344        Some(&*Box::leak(Box::new(Version {
345            major,
346            minor,
347            patch,
348            build,
349            text: keep(text.to_owned()),
350        })))
351    });
352    let os_release = f.release.map(|r| {
353        let id_like: Vec<&'static str> = r.id_like.into_iter().map(keep).collect();
354        let name = r.name.unwrap_or_else(|| "Linux".to_owned());
355        &*Box::leak(Box::new(OsRelease {
356            id: keep(r.id.unwrap_or_else(|| "linux".to_owned())),
357            id_like: Box::leak(id_like.into_boxed_slice()),
358            pretty_name: keep(r.pretty_name.unwrap_or_else(|| name.clone())),
359            name: keep(name),
360            version: keep_opt(r.version),
361            version_id: keep_opt(r.version_id),
362            codename: keep_opt(r.codename),
363            variant_id: keep_opt(r.variant_id),
364            build_id: keep_opt(r.build_id),
365            source: r.source,
366        }))
367    });
368    OsInfo {
369        kind: kind(),
370        name: keep(f.name),
371        version,
372        kernel: keep(f.kernel),
373        distro: keep(f.distro),
374        distro_id: keep(f.distro_id),
375        os_release,
376        name_source: f.name_source,
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn test_os_constants_are_consistent() {
386        assert_eq!(is_mac(), is_macos());
387        assert!(!(is_linux() && is_android()));
388        assert_eq!(kind() == Kind::Windows, is_windows());
389        assert_eq!(kind() == Kind::Linux, is_linux());
390        if is_linux() || is_macos() || is_android() || is_ios() {
391            assert!(is_unix());
392        }
393    }
394
395    #[test]
396    fn test_os_live_answers_are_never_empty() {
397        assert!(!name().is_empty());
398        assert!(!distro().is_empty());
399        assert!(!distro_id().is_empty());
400        assert!(is_like(distro_id()));
401        assert!(!is_like("not-a-distribution"));
402        if is_windows() {
403            assert_eq!((distro(), distro_id()), ("Windows", "windows"));
404        }
405        if is_macos() {
406            assert_eq!((distro(), distro_id()), ("macOS", "macos"));
407        }
408    }
409
410    #[test]
411    fn test_os_info_is_cached() {
412        assert!(std::ptr::eq(info(), info()));
413        assert!(std::ptr::eq(name(), info().name));
414    }
415
416    #[test]
417    fn test_os_from_facts_fills_defaults() {
418        let info = from_facts(crate::sys::OsFacts {
419            name: "X 1".into(),
420            version: Some("8.10-beta".into()),
421            kernel: "k".into(),
422            distro: "X".into(),
423            distro_id: "x".into(),
424            release: Some(crate::sys::ReleaseFacts {
425                id: None,
426                id_like: vec!["rhel".into(), "fedora".into()],
427                name: None,
428                pretty_name: None,
429                version: None,
430                version_id: None,
431                codename: None,
432                variant_id: None,
433                build_id: None,
434                source: Source::OsRelease,
435            }),
436            name_source: Source::OsRelease,
437        });
438        let v = info.version.unwrap();
439        assert_eq!(
440            (v.major, v.minor, v.patch, v.build, v.text),
441            (8, 10, 0, None, "8.10-beta")
442        );
443        assert_eq!(v.to_string(), "8.10-beta");
444        let r = info.os_release.unwrap();
445        assert_eq!((r.id, r.name, r.pretty_name), ("linux", "Linux", "Linux"));
446        assert_eq!(r.id_like, &["rhel", "fedora"]);
447    }
448
449    #[test]
450    fn test_os_concurrent_first_use_sees_one_value() {
451        // 64 threads at first use all see the same cached value (concurrency plan).
452        let ptrs: Vec<usize> = std::thread::scope(|s| {
453            let handles: Vec<_> = (0..64)
454                .map(|_| s.spawn(|| core::ptr::from_ref(info()) as usize))
455                .collect();
456            handles.into_iter().map(|h| h.join().unwrap_or(0)).collect()
457        });
458        assert!(ptrs.windows(2).all(|w| w[0] == w[1]));
459    }
460}