sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
#[cfg(target_os = "android")]
use crate::sys::ffi;
use crate::sys::utils::get_all_utf8_data;

#[cfg(target_os = "android")]
use std::ffi::CStr;
#[cfg(not(target_os = "android"))]
use std::fs::File;
#[cfg(not(target_os = "android"))]
use std::io::Read;
#[cfg(not(target_os = "android"))]
use std::path::Path;
use std::str::FromStr;

pub(super) fn read_table<F>(filename: &str, colsep: char, mut f: F)
where
    F: FnMut(&str, u64),
{
    if let Ok(content) = get_all_utf8_data(filename, 16_635) {
        content
            .split('\n')
            .flat_map(|line| {
                let mut split = line.split(colsep);
                let key = split.next()?;
                let value = split.next()?;
                let value0 = value.trim_start().split(' ').next()?;
                let value0_u64 = u64::from_str(value0).ok()?;
                Some((key, value0_u64))
            })
            .for_each(|(k, v)| f(k, v));
    }
}

#[derive(PartialEq, Eq)]
pub(super) enum InfoType {
    /// End-user friendly name: - Android: the device model
    Name,
    OsVersion,
    /// Machine-parseable distribution ID; see https://www.freedesktop.org/software/systemd/man/os-release.html#ID=
    DistributionID,
    /// Machine-parseable ID_LIKE of related distributions; see <https://www.freedesktop.org/software/systemd/man/latest/os-release.html#ID_LIKE=>
    DistributionIDLike,
}

#[cfg(not(target_os = "android"))]
pub(super) fn get_system_info_linux(
    info: InfoType,
    path: &Path,
    fallback_path: &Path,
) -> Option<String> {
    if let Ok(buf) = File::open(path).and_then(|mut f| {
        let mut buf = String::new();
        f.read_to_string(&mut buf)?;
        Ok(buf)
    }) {
        let info_str = match info {
            InfoType::Name => "NAME=",
            InfoType::OsVersion => "VERSION_ID=",
            InfoType::DistributionID => "ID=",
            InfoType::DistributionIDLike => "ID_LIKE=",
        };

        for line in buf.lines() {
            if let Some(stripped) = line.strip_prefix(info_str) {
                return Some(stripped.replace('"', ""));
            }
        }
    }

    // Fall back to `/etc/lsb-release` when VERSION_ID is absent.
    let buf = File::open(fallback_path)
        .and_then(|mut f| {
            let mut buf = String::new();
            f.read_to_string(&mut buf)?;
            Ok(buf)
        })
        .ok()?;

    let info_str = match info {
        InfoType::OsVersion => "DISTRIB_RELEASE=",
        InfoType::Name => "DISTRIB_ID=",
        InfoType::DistributionID => {
            // lsb-release is inconsistent with os-release and unsupported here.
            return None;
        }
        InfoType::DistributionIDLike => {
            // lsb-release does not support ID_LIKE.
            return None;
        }
    };
    for line in buf.lines() {
        if let Some(stripped) = line.strip_prefix(info_str) {
            return Some(stripped.replace('"', ""));
        }
    }
    None
}

/// Returns a system info value as a list of strings.
pub(super) fn system_info_as_list(sinf: Option<String>) -> Vec<String> {
    match sinf {
        Some(value) => value.split_ascii_whitespace().map(String::from).collect(),
        // For list fields, a missing field is equivalent to an empty list.
        None => Vec::new(),
    }
}

#[cfg(target_os = "android")]
pub(super) fn get_system_info_android(info: InfoType) -> Option<String> {
    // https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/Build.java#58
    let name: &'static [u8] = match info {
        InfoType::Name => b"ro.product.model\0",
        InfoType::OsVersion => b"ro.build.version.release\0",
        InfoType::DistributionID => {
            // Not supported.
            return None;
        }
        InfoType::DistributionIDLike => {
            // Not supported.
            return None;
        }
    };

    let name = CStr::from_bytes_with_nul(name).ok()?;
    ffi::system_property(name)
}