use std::fmt::{self, Display, Formatter};
use super::{Version};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OSInfo {
pub(crate) id: Option<String>,
pub(crate) name: Option<String>,
pub(crate) version: Version,
pub(crate) variant: Option<String>,
pub(crate) edition: Option<String>,
pub(crate) codename: Option<String>,
}
impl OSInfo {
pub fn unknown() -> Self {
Self {
id: Some(String::from("Unknown")),
name: Some(String::new()),
version: Version::Unknown,
variant: None,
edition: None,
codename: None,
}
}
pub fn get_id(&self) -> String {
self.id.clone().unwrap_or_default()
}
pub fn get_name(&self) -> String {
self.name.clone().unwrap_or_default()
}
pub fn get_version(&self) -> Version {
self.version.clone()
}
pub fn get_variant(&self) -> String {
self.variant.clone().unwrap_or_default()
}
pub fn get_edition(&self) -> String {
self.edition.clone().unwrap_or_default()
}
pub fn get_codename(&self) -> String {
self.codename.clone().unwrap_or_default()
}
pub fn with_id(id: String) -> Self {
Self {
id: Some(id),
..Default::default()
}
}
pub fn with_name(name: String) -> Self {
Self {
name: Some(name),
..Default::default()
}
}
}
impl Default for OSInfo {
fn default() -> Self {
Self::unknown()
}
}
impl Display for OSInfo {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.get_id())?;
if let Some(ref name) = self.name {
write!(f, " ({name})")?;
}
if let Some(ref variant) = self.variant {
write!(f, " ({variant})")?;
}
write!(f, "")
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn unknown() {
let info = OSInfo::unknown();
assert_eq!(String::from("Unknown"), info.get_id());
assert_eq!(String::new(), info.get_name());
assert_eq!(Version::Unknown, info.get_version());
assert_eq!(String::new(), info.get_variant());
assert_eq!(String::new(), info.get_edition());
assert_eq!(String::new(), info.get_codename());
}
#[test]
fn default() {
assert_eq!(OSInfo::default(), OSInfo::unknown());
}
#[test]
fn with_id_sets_id() {
let info = OSInfo::with_id("test_id".to_string());
assert_eq!(info.get_id(), "test_id");
assert_eq!(info.get_name(), "");
}
#[test]
fn with_name_sets_name() {
let info = OSInfo::with_name("TestOS".to_string());
assert_eq!(info.get_name(), "TestOS");
assert_eq!(info.get_id(), "Unknown");
}
#[test]
fn display_format() {
let mut info = OSInfo::with_id("linux".to_string());
info.name = Some("Ubuntu".to_string());
info.variant = Some("Server".to_string());
let display = format!("{}", info);
assert!(display.contains("linux"));
assert!(display.contains("Ubuntu"));
assert!(display.contains("Server"));
}
}