pwr 0.2.2

Check power supplies of a system
Documentation
pub mod bat;
pub mod error;
pub mod units;

use error::PwrError;
use std::path::PathBuf;

pub fn run() -> Result<(), PwrError> {
    let bat = bat::Battery::default()?;
    println!("{}", bat);
    Ok(())
}

/// Utility function to read numbers from sysfs entries.
///
/// Sysfs entries usually contain a trailing newline, which ruins the parsing. This is a
/// convenience function to read a files content into a variable, remove trailing whitespace and
/// parse it to a f32.
fn read_number(path: PathBuf) -> Result<u32, PwrError> {
    let value = std::fs::read_to_string(path)?;
    let value = value
        .trim_end()
        .parse::<u32>()
        .map_err(|_| PwrError::Error)?;
    Ok(value)
}

/// sysfs `power_supply` type enum
#[derive(Debug, PartialEq)]
pub enum Type {
    Battery,
    Mains,
    USB,
    Invalid,
}

impl std::str::FromStr for Type {
    type Err = PwrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.trim_end() {
            "Battery" => Ok(Type::Battery),
            "Mains" => Ok(Type::Mains),
            "USB" => Ok(Type::USB),
            _ => Err(PwrError::ParseTypeError(s.to_owned())),
        }
    }
}

#[cfg(test)]
mod tests {
    //! Directories used for testing.
    //!
    //! Refers to various directories that can be used for testing. Most useful is probably the
    //! `sysfs`, which doesn't point to the "real" `/sys/...`, but the dummy one in the testing
    //! assets.
    pub mod dirs {
        use std::path::PathBuf;

        /// Project base directory.
        ///
        /// Returns a PathBuf to the directory containing `Cargo.toml`.
        pub fn base() -> PathBuf {
            let base_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
            return PathBuf::from(base_dir);
        }

        /// Asset directory.
        pub fn assets() -> PathBuf {
            let mut asset_dir = base();
            asset_dir.push("assets");
            return asset_dir;
        }

        /// Dummy sysfs directory underneath `assets`.
        pub fn sysfs() -> PathBuf {
            let mut sysfs_dir = assets();
            sysfs_dir.push("sysfs");
            return sysfs_dir;
        }
    }

    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
}