1use core::fmt;
19use std::sync::OnceLock;
20
21use crate::parse;
22
23#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
25#[non_exhaustive]
26pub enum Kind {
27 Linux,
29 Windows,
31 MacOs,
33 Android,
35 Ios,
37 FreeBsd,
39 OpenBsd,
41 NetBsd,
43 Other,
45}
46
47impl Kind {
48 #[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#[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#[must_use]
101pub const fn is_windows() -> bool {
102 cfg!(target_os = "windows")
103}
104
105#[must_use]
107pub const fn is_linux() -> bool {
108 cfg!(target_os = "linux")
109}
110
111#[must_use]
113pub const fn is_macos() -> bool {
114 cfg!(target_os = "macos")
115}
116
117#[must_use]
119pub const fn is_mac() -> bool {
120 is_macos()
121}
122
123#[must_use]
125pub const fn is_android() -> bool {
126 cfg!(target_os = "android")
127}
128
129#[must_use]
131pub const fn is_ios() -> bool {
132 cfg!(target_os = "ios")
133}
134
135#[must_use]
137pub const fn is_unix() -> bool {
138 cfg!(unix)
139}
140
141#[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#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
162#[non_exhaustive]
163pub struct Version {
164 pub major: u32,
166 pub minor: u32,
168 pub patch: u32,
170 pub build: Option<u32>,
172 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#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
184#[non_exhaustive]
185pub enum Source {
186 OsRelease,
188 UsrLibOsRelease,
190 LegacyRelease,
192 Sysctl,
194 Registry,
196 SystemProperty,
198 Fallback,
200}
201
202#[derive(Clone, Copy, Debug)]
210#[non_exhaustive]
211pub struct OsRelease {
212 pub id: &'static str,
214 pub id_like: &'static [&'static str],
216 pub name: &'static str,
218 pub pretty_name: &'static str,
220 pub version: Option<&'static str>,
222 pub version_id: Option<&'static str>,
224 pub codename: Option<&'static str>,
226 pub variant_id: Option<&'static str>,
228 pub build_id: Option<&'static str>,
230 pub source: Source,
232}
233
234#[derive(Clone, Copy, Debug)]
236#[non_exhaustive]
237pub struct OsInfo {
238 pub kind: Kind,
240 pub name: &'static str,
242 pub version: Option<&'static Version>,
244 pub kernel: &'static str,
246 pub distro: &'static str,
248 pub distro_id: &'static str,
250 pub os_release: Option<&'static OsRelease>,
252 pub name_source: Source,
254}
255
256#[must_use]
260pub fn name() -> &'static str {
261 info().name
262}
263
264#[must_use]
267pub fn version() -> Option<&'static Version> {
268 info().version
269}
270
271#[must_use]
273pub fn kernel() -> &'static str {
274 info().kernel
275}
276
277#[must_use]
288pub fn distro() -> &'static str {
289 info().distro
290}
291
292#[must_use]
295pub fn distro_id() -> &'static str {
296 info().distro_id
297}
298
299#[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#[must_use]
320pub fn os_release() -> Option<&'static OsRelease> {
321 info().os_release
322}
323
324#[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
331pub(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 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}