From 53bcd5bf2de8cd407f211445b6619b2fcf9de94b Mon Sep 17 00:00:00 2001 From: Adrian Groh <50576978+Gobidev@users.noreply.github.com> Date: Fri, 12 May 2023 14:13:51 +0200 Subject: [PATCH 01/39] Fix Armv7 build (#158) * Add armv7 build target * Fix mismatched types for pointer width 32 * Use `sh` instead of `python` for `which` assertion --- .github/workflows/libmacchina.yml | 7 +++++++ src/extra.rs | 2 +- src/shared/mod.rs | 3 +++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.github/workflows/libmacchina.yml b/.github/workflows/libmacchina.yml index d4de7ebd..b8e6a576 100644 --- a/.github/workflows/libmacchina.yml +++ b/.github/workflows/libmacchina.yml @@ -17,6 +17,7 @@ jobs: - x86_64-unknown-freebsd - aarch64-linux-android - aarch64-unknown-linux-gnu + - armv7-unknown-linux-gnueabihf include: - os: ubuntu-latest @@ -62,6 +63,12 @@ jobs: test: true cargo_args: --features "openwrt" + - os: ubuntu-latest + name: Linux ARMv7 + target: armv7-unknown-linux-gnueabihf + cross: true + test: true + steps: - name: Checkout uses: actions/checkout@v2 diff --git a/src/extra.rs b/src/extra.rs index 99c3b18c..9580a7fb 100644 --- a/src/extra.rs +++ b/src/extra.rs @@ -118,7 +118,7 @@ mod tests { #[test] #[cfg(not(feature = "openwrt"))] fn test_which() { - assert!(which("python")); + assert!(which("sh")); assert!(!which("not_a_real_command")); } } diff --git a/src/shared/mod.rs b/src/shared/mod.rs index 2c1ce115..5e757b7c 100644 --- a/src/shared/mod.rs +++ b/src/shared/mod.rs @@ -262,6 +262,9 @@ pub(crate) fn disk_space(path: String) -> Result<(u64, u64), ReadoutError> { let used_byte = disk_size - free; let disk_size_byte = disk_size; + #[cfg(target_pointer_width = "32")] + return Ok((used_byte.into(), disk_size_byte.into())); + #[cfg(target_pointer_width = "64")] return Ok((used_byte, disk_size_byte)); } From d67e48cb53073b4c0702612f904a26a27b0101d5 Mon Sep 17 00:00:00 2001 From: Adrian Groh <50576978+Gobidev@users.noreply.github.com> Date: Mon, 15 May 2023 14:07:24 +0200 Subject: [PATCH 02/39] Replace mach with mach2 (#157) --- Cargo.toml | 2 +- src/macos/mach_ffi.rs | 12 ++++++------ src/macos/mod.rs | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 790b9f71..da368d8b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,7 @@ regex = "1.6.0" core-foundation = "0.9.3" core-graphics = "0.22.3" core-video-sys = "0.1.4" -mach = "0.3.2" +mach2 = "0.4.1" [target.'cfg(target_family = "unix")'.dependencies] num_cpus = "1.13.1" diff --git a/src/macos/mach_ffi.rs b/src/macos/mach_ffi.rs index 39099936..b54ee1ff 100644 --- a/src/macos/mach_ffi.rs +++ b/src/macos/mach_ffi.rs @@ -1,11 +1,11 @@ #![allow(non_camel_case_types, non_upper_case_globals, dead_code, unused)] -use mach::boolean; -use mach::kern_return; -use mach::kern_return::kern_return_t; -use mach::mach_types::{host_name_port_t, host_t}; -use mach::message::mach_msg_type_number_t; -use mach::vm_types::{integer_t, natural_t}; +use mach2::boolean; +use mach2::kern_return; +use mach2::kern_return::kern_return_t; +use mach2::mach_types::{host_name_port_t, host_t}; +use mach2::message::mach_msg_type_number_t; +use mach2::vm_types::{integer_t, natural_t}; use core_foundation::array::CFArrayRef; use core_foundation::base::{mach_port_t, CFAllocatorRef, CFRelease, CFTypeRef, TCFTypeRef}; diff --git a/src/macos/mod.rs b/src/macos/mod.rs index 1cde604c..3b691cc1 100644 --- a/src/macos/mod.rs +++ b/src/macos/mod.rs @@ -17,7 +17,7 @@ use core_video_sys::{ kCVTimeIsIndefinite, CVDisplayLinkCreateWithCGDisplay, CVDisplayLinkGetNominalOutputVideoRefreshPeriod, CVDisplayLinkRef, CVDisplayLinkRelease, }; -use mach::kern_return::KERN_SUCCESS; +use mach2::kern_return::KERN_SUCCESS; use std::ffi::CString; use std::fs::DirEntry; use sysctl::{Ctl, Sysctl}; @@ -492,9 +492,9 @@ impl MemoryReadout for MacOSMemoryReadout { impl MacOSMemoryReadout { fn mach_vm_stats() -> Result { - use mach::kern_return::KERN_SUCCESS; - use mach::message::mach_msg_type_number_t; - use mach::vm_types::integer_t; + use mach2::kern_return::KERN_SUCCESS; + use mach2::message::mach_msg_type_number_t; + use mach2::vm_types::integer_t; use mach_ffi::*; const HOST_VM_INFO_COUNT: mach_msg_type_number_t = From d1903086486a02fdfeefd689b338b836a78a1e5a Mon Sep 17 00:00:00 2001 From: Silas Groh Date: Mon, 15 May 2023 14:31:06 +0200 Subject: [PATCH 03/39] feat: add support for RPM `ndb` databases (#159) * feat: add support for RPM `ndb` databases * chore: always try sqlite before librpm * chore: remove `rpm` feature * fix: librpm call not lazily evaluated --- Cargo.toml | 1 + src/linux/mod.rs | 35 ++++++++++++++++++++--------------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index da368d8b..01070111 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ dirs = "4.0" walkdir = "2.3.2" os-release = "0.1" regex = "1.6.0" +rpm-pkg-count = { version = "0.2.0", features = ["runtime"] } [target.'cfg(target_os = "netbsd")'.dependencies] nix = { version = "0.24.1", default-features = false, features = ["hostname"] } diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 81471b7b..52980a34 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -736,25 +736,30 @@ impl LinuxPackageReadout { fn count_rpm() -> Option { // Return the number of installed packages using sqlite (~1ms) // as directly calling rpm or dnf is too expensive (~500ms) - let db = "/var/lib/rpm/rpmdb.sqlite"; - if !Path::new(db).is_file() { - return None; - } + let count_sqlite = 'sqlite: { + let db = "/var/lib/rpm/rpmdb.sqlite"; + if !Path::new(db).is_file() { + break 'sqlite None; + } - let connection = sqlite::open(db); - if let Ok(con) = connection { - let statement = con.prepare("SELECT COUNT(*) FROM Installtid"); - if let Ok(mut s) = statement { - if s.next().is_ok() { - return match s.read::>(0) { - Ok(Some(count)) => Some(count as usize), - _ => None, - }; + let connection = sqlite::open(db); + if let Ok(con) = connection { + let statement = con.prepare("SELECT COUNT(*) FROM Installtid"); + if let Ok(mut s) = statement { + if s.next().is_ok() { + break 'sqlite match s.read::>(0) { + Ok(Some(count)) => Some(count as usize), + _ => None, + }; + } } } - } - None + None + }; + + // If counting with sqlite failed, try using librpm instead + count_sqlite.or_else(|| unsafe { rpm_pkg_count::count() }.map(|count| count as usize)) } /// Returns the number of installed packages for systems From 455eb1f9939e7f21fa2625e96bf0837c418a7b9e Mon Sep 17 00:00:00 2001 From: Adrian Groh <50576978+Gobidev@users.noreply.github.com> Date: Mon, 15 May 2023 18:44:48 +0200 Subject: [PATCH 04/39] Add `librpm` dependency note to README (#160) --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index b266c776..465bc34c 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,12 @@ Add the following to your project's _Cargo.toml_ file: libmacchina = "7" ``` +### Notes + +On distributions like openSUSE that use the `ndb` RPM database format, `librpm` +(which is usually provided by the `rpm-devel` package) is required for the RPM +package count readout to work. + ### Examples ```rust From d7745aa6dd2a6dd2729db8de55da026aecf7ba88 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Tue, 16 May 2023 00:33:42 +0100 Subject: [PATCH 05/39] Update the changelog --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 583c1445..7fa9ae36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## `7.1.0` + +- Silas Groh: + - Add support for `ndb` databases +- Adrian Groh: + - Replace `mach` dependency with `mach2` + - Replace `python` command with `sh` in `extra::which` unit tests + - Add armv7 to the list of build targets in the CI pipeline + - Fix compilation issues for armv7 build target + ## `7.0.0` - Rolv Apneseth: From b8e8fe1e188ed2e7eddb34d7b662a6b03b0fff48 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Tue, 16 May 2023 00:44:56 +0100 Subject: [PATCH 06/39] Bump version to 7.1.0 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 01070111..efaf8155 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.0.0" +version = "7.1.0" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." From 8b2b11c3051c549e6c9796d4779b45857a9cbbb3 Mon Sep 17 00:00:00 2001 From: Adrian Groh <50576978+Gobidev@users.noreply.github.com> Date: Mon, 29 May 2023 22:51:40 +0200 Subject: [PATCH 07/39] Fix i686 build (#162) closes #161 --- src/shared/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/mod.rs b/src/shared/mod.rs index 5e757b7c..092e5a03 100644 --- a/src/shared/mod.rs +++ b/src/shared/mod.rs @@ -256,7 +256,7 @@ pub(crate) fn disk_space(path: String) -> Result<(u64, u64), ReadoutError> { let stats: libc::statfs = unsafe { s.assume_init() }; - let disk_size = stats.f_blocks * stats.f_bsize as UInt; + let disk_size = stats.f_blocks as UInt * stats.f_bsize as UInt; let free = stats.f_bavail as UInt * stats.f_bsize as UInt; let used_byte = disk_size - free; From 49d950050eebb495eba007ca9de7865a4706238c Mon Sep 17 00:00:00 2001 From: Rex Ng Date: Sun, 9 Jul 2023 21:30:09 +0800 Subject: [PATCH 08/39] Add Sonoma to macos_version_to_name (#163) --- src/macos/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/macos/mod.rs b/src/macos/mod.rs index 3b691cc1..df4703e1 100644 --- a/src/macos/mod.rs +++ b/src/macos/mod.rs @@ -690,6 +690,7 @@ fn macos_version_to_name(version: &NSOperatingSystemVersion) -> &'static str { (11, _) | (10, 16) => "Big Sur", (12, _) => "Monterey", (13, _) => "Ventura", + (14, _) => "Sonoma", _ => "Unknown", } } From 0f151235fe24b6e3c2609992ccbf356db8cdfbe2 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Tue, 28 Mar 2023 23:32:03 +0100 Subject: [PATCH 09/39] BREAKING CHANGE: Change BatteryReadout::health return value to u8 There's no particular reason why one should allocate 64 bits for a value that can only be <= 100. As a bonus, ceil() the return value before finally casting to u8. --- src/linux/mod.rs | 10 +++++----- src/traits.rs | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 52980a34..6063dab8 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -117,7 +117,7 @@ impl BatteryReadout for LinuxBatteryReadout { Err(ReadoutError::Other("No batteries detected.".to_string())) } - fn health(&self) -> Result { + fn health(&self) -> Result { if let Some(entries) = get_entries(Path::new("/sys/class/power_supply")) { let dirs: Vec = entries .into_iter() @@ -134,20 +134,20 @@ impl BatteryReadout for LinuxBatteryReadout { if let Some(battery) = dirs.first() { let energy_full = extra::pop_newline(fs::read_to_string(battery.join("energy_full"))?) - .parse::(); + .parse::(); let energy_full_design = extra::pop_newline(fs::read_to_string(battery.join("energy_full_design"))?) - .parse::(); + .parse::(); match (energy_full, energy_full_design) { (Ok(mut ef), Ok(efd)) => { if ef > efd { ef = efd; - return Ok(((ef as f64 / efd as f64) * 100_f64) as u64); + return Ok((ef as f32 / efd as f32 * 100_f32).ceil() as u8); } - return Ok(((ef as f64 / efd as f64) * 100_f64) as u64); + return Ok((ef as f32 / efd as f32 * 100_f32).ceil() as u8); } _ => { return Err(ReadoutError::Other( diff --git a/src/traits.rs b/src/traits.rs index 13c9b7af..99cde381 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -74,7 +74,7 @@ impl BatteryReadout for MacOSBatteryReadout { Ok(BatteryState::Charging) //always charging. } - fn health(&self) -> Result{ + fn health(&self) -> Result{ //check the battery health... Ok(100) //totally healtyh } @@ -95,7 +95,7 @@ pub trait BatteryReadout { fn status(&self) -> Result; /// This function is used for querying the current battery's health in percentage. - fn health(&self) -> Result; + fn health(&self) -> Result; } /** From 7e1cb1a447daa20cd2f15e79926bb8e36a771f98 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Thu, 3 Aug 2023 10:21:25 +0100 Subject: [PATCH 10/39] Update BatteryReadout::health function signature for other operating systems besides Linux. --- src/android/mod.rs | 2 +- src/freebsd/mod.rs | 2 +- src/macos/mod.rs | 2 +- src/netbsd/mod.rs | 2 +- src/openwrt/mod.rs | 2 +- src/windows/mod.rs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/android/mod.rs b/src/android/mod.rs index 44d0471a..0d1df392 100644 --- a/src/android/mod.rs +++ b/src/android/mod.rs @@ -79,7 +79,7 @@ impl BatteryReadout for AndroidBatteryReadout { } } - fn health(&self) -> Result { + fn health(&self) -> Result { Err(ReadoutError::NotImplemented) } } diff --git a/src/freebsd/mod.rs b/src/freebsd/mod.rs index aa0c8a7b..a50e217a 100644 --- a/src/freebsd/mod.rs +++ b/src/freebsd/mod.rs @@ -80,7 +80,7 @@ impl BatteryReadout for FreeBSDBatteryReadout { Err(ReadoutError::MetricNotAvailable) } - fn health(&self) -> Result { + fn health(&self) -> Result { Err(ReadoutError::NotImplemented) } } diff --git a/src/macos/mod.rs b/src/macos/mod.rs index df4703e1..e2aa170d 100644 --- a/src/macos/mod.rs +++ b/src/macos/mod.rs @@ -93,7 +93,7 @@ impl BatteryReadout for MacOSBatteryReadout { ))) } - fn health(&self) -> Result { + fn health(&self) -> Result { Err(ReadoutError::NotImplemented) } } diff --git a/src/netbsd/mod.rs b/src/netbsd/mod.rs index 8c5c9a42..6a7ffac6 100644 --- a/src/netbsd/mod.rs +++ b/src/netbsd/mod.rs @@ -82,7 +82,7 @@ impl BatteryReadout for NetBSDBatteryReadout { Err(ReadoutError::Other("envstat is not installed".to_owned())) } - fn health(&self) -> Result { + fn health(&self) -> Result { Err(ReadoutError::NotImplemented) } } diff --git a/src/openwrt/mod.rs b/src/openwrt/mod.rs index d1ce6dd7..f09adf4c 100644 --- a/src/openwrt/mod.rs +++ b/src/openwrt/mod.rs @@ -41,7 +41,7 @@ impl BatteryReadout for OpenWrtBatteryReadout { Err(ReadoutError::NotImplemented) } - fn health(&self) -> Result { + fn health(&self) -> Result { Err(ReadoutError::NotImplemented) } } diff --git a/src/windows/mod.rs b/src/windows/mod.rs index cbf22d8f..01c2ea12 100644 --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -53,7 +53,7 @@ impl BatteryReadout for WindowsBatteryReadout { } } - fn health(&self) -> Result { + fn health(&self) -> Result { Err(ReadoutError::NotImplemented) } } From f4ea9bee392c756eefab8dc41952daf6a30f40dd Mon Sep 17 00:00:00 2001 From: Absolpega <106615943+Absolpega@users.noreply.github.com> Date: Mon, 28 Aug 2023 23:08:44 +0200 Subject: [PATCH 11/39] Added general detection for wayland compositors (#164) --- Cargo.toml | 2 ++ src/winman.rs | 71 ++++++++++++++++++++++----------------------------- 2 files changed, 32 insertions(+), 41 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index efaf8155..eadcd5d1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,8 @@ walkdir = "2.3.2" os-release = "0.1" regex = "1.6.0" rpm-pkg-count = { version = "0.2.0", features = ["runtime"] } +nix = { version = "0.26.2", features = ["socket"], default-features = false } +wayland-sys = { version = "0.31.1", features = ["dlopen", "client"] } [target.'cfg(target_os = "netbsd")'.dependencies] nix = { version = "0.24.1", default-features = false, features = ["hostname"] } diff --git a/src/winman.rs b/src/winman.rs index 1e157abb..f64241c2 100644 --- a/src/winman.rs +++ b/src/winman.rs @@ -7,56 +7,45 @@ use crate::traits::ReadoutError; use std::process::{Command, Stdio}; #[cfg(target_os = "linux")] -/// Detects if the host is using Sway. -pub fn is_running_sway() -> bool { - if let Ok(socket) = std::env::var("SWAYSOCK") { - if std::path::PathBuf::from(socket).exists() { - return true; - } - } - - false -} +use wayland_sys::{client::*, ffi_dispatch}; #[cfg(target_os = "linux")] -/// Detects if the host is using Wayfire. -pub fn is_running_wayfire() -> bool { - if let Ok(config) = std::env::var("WAYFIRE_CONFIG_FILE") { - if std::path::PathBuf::from(config).exists() { - return true; - } - } +use nix::sys::socket::{sockopt, GetSockOpt}; - false -} +#[cfg(target_os = "linux")] +use std::os::fd::AsRawFd; #[cfg(target_os = "linux")] -/// Detects if the host is using Qtile. -pub fn is_running_qtile() -> bool { - if let Some(cache) = dirs::cache_dir() { - if let Ok(display) = std::env::var("WAYLAND_DISPLAY") { - let socket = cache.join("qtile").join(format!("qtilesocket.{display}")); - - if socket.exists() { - return true; - } - } +pub fn detect_wayland_window_manager() -> Result { + if !is_lib_available() { + return Err(ReadoutError::MetricNotAvailable); } - false -} + let display_ptr = unsafe { + ffi_dispatch!( + wayland_client_handle(), + wl_display_connect, + ::std::ptr::null() + ) + }; -#[cfg(target_os = "linux")] -pub fn detect_wayland_window_manager() -> Result { - if is_running_sway() { - Ok(String::from("Sway")) - } else if is_running_qtile() { - Ok(String::from("Qtile")) - } else if is_running_wayfire() { - Ok(String::from("Wayfire")) - } else { - Err(ReadoutError::Other(String::from("Unknown window manager."))) + if display_ptr.is_null() { + return Err(ReadoutError::MetricNotAvailable); } + + let display_fd = + unsafe { ffi_dispatch!(wayland_client_handle(), wl_display_get_fd, display_ptr) } + .as_raw_fd(); + + let pid = sockopt::PeerCredentials + .get(display_fd) + .map_err(|_| ReadoutError::MetricNotAvailable)? + .pid(); + + Ok(extra::pop_newline(std::fs::read_to_string(format!( + "/proc/{}/comm", + pid + ))?)) } pub fn detect_xorg_window_manager() -> Result { From 901c1a3d13216a3ec364e2e5225a402daf21c855 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 19:20:58 +0100 Subject: [PATCH 12/39] Upgrade dependencies to their latest versions --- Cargo.toml | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index eadcd5d1..bd74916e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,40 +12,40 @@ build = "build.rs" [dependencies] cfg-if = "1.0.0" -libc = "0.2.131" -home = "0.5.3" -pciid-parser = "0.6.2" +libc = "0.2.148" +home = "0.5.5" +pciid-parser = "0.6.3" [build-dependencies.vergen] -version = "7.3.2" +version = "8.2.5" optional = true default-features = false features = ["build","cargo","git","rustc"] [target.'cfg(target_os = "linux")'.dependencies] -dirs = "4.0" -walkdir = "2.3.2" +dirs = "5.0.1" +walkdir = "2.4.0" os-release = "0.1" -regex = "1.6.0" -rpm-pkg-count = { version = "0.2.0", features = ["runtime"] } +regex = "1.9.2" +rpm-pkg-count = { version = "0.2.1", features = ["runtime"] } nix = { version = "0.26.2", features = ["socket"], default-features = false } wayland-sys = { version = "0.31.1", features = ["dlopen", "client"] } [target.'cfg(target_os = "netbsd")'.dependencies] -nix = { version = "0.24.1", default-features = false, features = ["hostname"] } -regex = "1.6.0" +nix = { version = "0.26.2", default-features = false, features = ["hostname"] } +regex = "1.9.2" [target.'cfg(target_os = "macos")'.dependencies] core-foundation = "0.9.3" -core-graphics = "0.22.3" +core-graphics = "0.23.1" core-video-sys = "0.1.4" mach2 = "0.4.1" [target.'cfg(target_family = "unix")'.dependencies] -num_cpus = "1.13.1" +num_cpus = "1.16.0" [target.'cfg(target_os = "windows")'.dependencies] -local-ip-address = "0.4.4" +local-ip-address = "0.5.6" wmi = "0.12.0" winreg = "0.10.1" windows = { version = "0.39.0", features = [ @@ -56,22 +56,22 @@ windows = { version = "0.39.0", features = [ ]} [target.'cfg(not(target_os = "windows"))'.dependencies] -if-addrs = "0.6.7" +if-addrs = "0.10.2" [target.'cfg(any(target_os="freebsd", target_os = "linux"))'.dependencies] -sqlite = "0.27.0" +sqlite = "0.31.1" [target.'cfg(any(target_os="freebsd", target_os = "netbsd"))'.dependencies] -x11rb = "0.10.1" +x11rb = "0.12.0" [target.'cfg(any(target_os = "linux", target_os = "netbsd", target_os = "android"))'.dependencies] -itertools = "0.10.3" +itertools = "0.11.0" [target.'cfg(not(any(target_os = "netbsd", target_os = "windows")))'.dependencies] -sysctl = "0.4.6" +sysctl = "0.5.4" [target.'cfg(any(target_os = "linux", target_os = "netbsd"))'.build-dependencies] -pkg-config = { version = "0.3.25", optional = true} +pkg-config = { version = "0.3.27", optional = true} [features] openwrt = [] From ae1786542bfc2d45f518fa3dca3e05369d213e5e Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 19:21:32 +0100 Subject: [PATCH 13/39] Update changelog Make some formatting changes as well. --- CHANGELOG.md | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fa9ae36..394b6ed0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,25 @@ # Changelog +## `7.2.0` + +Adrian Groh: +- Fix build errors affecting i686 (#162) + +Rex Ng: +- Recognize macOS Sonoma (#163) + +Absolpega: +- Add general detection for Wayland (#164) + +- Change the return value of BatteryReadout::health from `u64` to `u8` +- Upgrade dependencies to their latest versions + ## `7.1.0` -- Silas Groh: +Silas Groh: - Add support for `ndb` databases -- Adrian Groh: + +Adrian Groh: - Replace `mach` dependency with `mach2` - Replace `python` command with `sh` in `extra::which` unit tests - Add armv7 to the list of build targets in the CI pipeline @@ -23,15 +38,19 @@ ## `6.4.0` -- Adrian Groh: +Adrian Groh: - Use the correct kernel parameters when initializing FreeBSD `KernelReadout` (#148) - Implement uptime readout for FreeBSD systems (#138) - Use `MemAvailable` to calculate used memory (#134) - Prioritize detecting window managers with xprop (#133) -- Rolv Apneseth: Implement GPU readout for Linux systems (#140) -- Matthias Baer: Use a singleton for `COMLibrary` (#143) -- Xarblu: Change Flatpak package-counting method (#125) -- Kian-Meng Ang: Fix a typo in the documentation + +Rolv Apneseth: Implement GPU readout for Linux systems (#140) + +Matthias Baer: Use a singleton for `COMLibrary` (#143) + +Xarblu: Change Flatpak package-counting method (#125) + +Kian-Meng Ang: Fix a typo in the documentation ## `6.3.5` From 17763bce8b8c1cb49d9de0811cff378a673a6396 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 19:27:31 +0100 Subject: [PATCH 14/39] Add missing generic argument sqlite's changed a bit between releases. --- src/linux/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 6063dab8..e4fc5382 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -747,7 +747,7 @@ impl LinuxPackageReadout { let statement = con.prepare("SELECT COUNT(*) FROM Installtid"); if let Ok(mut s) = statement { if s.next().is_ok() { - break 'sqlite match s.read::>(0) { + break 'sqlite match s.read::, _>(0) { Ok(Some(count)) => Some(count as usize), _ => None, }; From c768977dab3689b8c7c035f2ea2c72a05316c15a Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 20:02:13 +0100 Subject: [PATCH 15/39] Bump version to 7.2.0 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index bd74916e..8ea24998 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.1.0" +version = "7.2.0" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." From ed89a8ade9a9d1fe259c4918fb4b9f688fd2a71f Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 20:17:33 +0100 Subject: [PATCH 16/39] Add missing second generic argument to sqlite read() call --- src/freebsd/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/freebsd/mod.rs b/src/freebsd/mod.rs index a50e217a..9746b4f8 100644 --- a/src/freebsd/mod.rs +++ b/src/freebsd/mod.rs @@ -401,7 +401,7 @@ impl FreeBSDPackageReadout { let statement = con.prepare("SELECT COUNT(*) FROM packages"); if let Ok(mut s) = statement { if s.next().is_ok() { - return match s.read::>(0) { + return match s.read::, _>(0) { Ok(Some(count)) => Some(count as usize), _ => None, }; From 1a2364eee53162b13417bbd9e43d6c5ee256fcc2 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 20:19:08 +0100 Subject: [PATCH 17/39] Remove unneeded argument to unistd::gethostname function call --- src/netbsd/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/netbsd/mod.rs b/src/netbsd/mod.rs index 6a7ffac6..7c9867b5 100644 --- a/src/netbsd/mod.rs +++ b/src/netbsd/mod.rs @@ -179,7 +179,7 @@ impl GeneralReadout for NetBSDGeneralReadout { fn hostname(&self) -> Result { let mut buf = [0u8; 64]; - let hostname_cstr = unistd::gethostname(&mut buf); + let hostname_cstr = unistd::gethostname(); match hostname_cstr { Ok(hostname_cstr) => { let hostname = hostname_cstr.to_str().unwrap_or("Unknown"); From 29f9a0bd543fde3e074fb40227508286bc13e3c5 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 20:19:44 +0100 Subject: [PATCH 18/39] Remove unused variable --- src/netbsd/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/netbsd/mod.rs b/src/netbsd/mod.rs index 7c9867b5..f9395af5 100644 --- a/src/netbsd/mod.rs +++ b/src/netbsd/mod.rs @@ -178,7 +178,6 @@ impl GeneralReadout for NetBSDGeneralReadout { } fn hostname(&self) -> Result { - let mut buf = [0u8; 64]; let hostname_cstr = unistd::gethostname(); match hostname_cstr { Ok(hostname_cstr) => { From 6853503f39c3811e0823e486408d46881897e69b Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 20:26:20 +0100 Subject: [PATCH 19/39] Refactor obsolete find_ifa function --- src/windows/mod.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/windows/mod.rs b/src/windows/mod.rs index 01c2ea12..3278e301 100644 --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -457,8 +457,10 @@ impl NetworkReadout for WindowsNetworkReadout { match interface { Some(it) => { if let Ok(addresses) = local_ip_address::list_afinet_netifas() { - if let Some((_, ip)) = local_ip_address::find_ifa(addresses, it) { - return Ok(ip.to_string()); + for (name, ip) in addresses.iter() { + if let Some(name) = interface { + return Ok(ip.to_string()); + } } } } From 6ae1304d320b830245026394aa3af11b971700b2 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 6 Oct 2023 20:37:09 +0100 Subject: [PATCH 20/39] Bump version to 7.2.1 --- CHANGELOG.md | 4 ++++ Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 394b6ed0..c7a7d913 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## `7.2.1` + +- Fix some build errors + ## `7.2.0` Adrian Groh: diff --git a/Cargo.toml b/Cargo.toml index 8ea24998..1ded2f64 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.2.0" +version = "7.2.1" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." From 81ede7235078fb602eb8063945dc5de596588464 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Tue, 19 Dec 2023 19:51:50 +0100 Subject: [PATCH 21/39] Bump vergen version --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 1ded2f64..c7b7444d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ home = "0.5.5" pciid-parser = "0.6.3" [build-dependencies.vergen] -version = "8.2.5" +version = "8.2.6" optional = true default-features = false features = ["build","cargo","git","rustc"] From 9cd0213553e3632bccc18d561f300198d3d83f13 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Tue, 19 Dec 2023 19:51:57 +0100 Subject: [PATCH 22/39] Use gitcl feature of vergen This depends on the git binary, more ubiquituous than the libgit2 bindings, so it should technically work on every platform we support. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index c7b7444d..d06aed16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ pciid-parser = "0.6.3" version = "8.2.6" optional = true default-features = false -features = ["build","cargo","git","rustc"] +features = ["build","cargo","git","gitcl","rustc"] [target.'cfg(target_os = "linux")'.dependencies] dirs = "5.0.1" From 000c5d280d41010c918a525b4414f7e4094051c2 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Tue, 19 Dec 2023 19:52:43 +0100 Subject: [PATCH 23/39] Refactor the old vergen interface --- build.rs | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/build.rs b/build.rs index 56b4037d..ef531e4b 100644 --- a/build.rs +++ b/build.rs @@ -1,16 +1,4 @@ -use std::env; - -#[cfg(feature = "version")] -fn commit_hash() { - use vergen::{Config, ShaKind}; - - let mut config = Config::default(); - *config.git_mut().sha_kind_mut() = ShaKind::Short; - - if let Err(e) = vergen::vergen(config) { - eprintln!("{}", e); - } -} +use std::{env, error::Error}; fn build_macos() { println!("cargo:rustc-link-lib=framework=Foundation"); @@ -20,7 +8,7 @@ fn build_macos() { println!("cargo:rustc-link-lib=framework=DisplayServices"); } -fn main() { +fn main() -> Result<(), Box> { match env::var("CARGO_CFG_TARGET_OS").as_ref().map(|x| &**x) { Ok("macos") => build_macos(), Ok("netbsd") => {} @@ -28,5 +16,7 @@ fn main() { } #[cfg(feature = "version")] - commit_hash() + vergen::EmitBuilder::builder().emit()?; + + Ok(()) } From 10100c287a0488e030e7c5c42c1fc629cf45dd78 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Sat, 17 Feb 2024 10:58:43 +0100 Subject: [PATCH 24/39] Add new entry to the changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7a7d913..1afb8f29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## `7.2.2` + +- Update `vergen` dependency and correct its invocation. + ## `7.2.1` - Fix some build errors From 9fb1addb29b38b08371ac23fd843e8f1def1954a Mon Sep 17 00:00:00 2001 From: grtcdr Date: Sat, 17 Feb 2024 11:00:03 +0100 Subject: [PATCH 25/39] Update version to 7.2.2 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index d06aed16..f8a4f13f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.2.1" +version = "7.2.2" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." From c357e97fa799962c90b7edb87af8923d03b5410e Mon Sep 17 00:00:00 2001 From: grtcdr Date: Sat, 17 Feb 2024 11:04:05 +0100 Subject: [PATCH 26/39] Replace flatten() calls with map_while(Result::ok) --- src/android/mod.rs | 2 +- src/dirs.rs | 8 ++++++-- src/extra.rs | 3 ++- src/linux/mod.rs | 4 ++-- src/linux/pci_devices.rs | 2 +- src/openwrt/mod.rs | 6 +++--- src/shared/mod.rs | 4 ++-- 7 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/android/mod.rs b/src/android/mod.rs index 0d1df392..d58143db 100644 --- a/src/android/mod.rs +++ b/src/android/mod.rs @@ -216,7 +216,7 @@ impl GeneralReadout for AndroidGeneralReadout { if let Ok(content) = file { let reader = BufReader::new(content); - for line in reader.lines().flatten() { + for line in reader.lines().map_while(Result::ok) { if line.starts_with("Hardware") { hardware = Some(get_value_from_line(line, "Hardware")); break; // If "Hardware" information is present, the rest is not needed. diff --git a/src/dirs.rs b/src/dirs.rs index 011b15d4..e9e80303 100644 --- a/src/dirs.rs +++ b/src/dirs.rs @@ -14,7 +14,9 @@ where /// Returns the value of PKG_DBDIR if exists or a default if not. pub fn pkgdb_dir() -> Option { if let Ok(lines) = read_lines("/etc/mk.conf") { - let line = lines.flatten().find(|l| l.starts_with("PKG_DBDIR")); + let line = lines + .map_while(Result::ok) + .find(|l| l.starts_with("PKG_DBDIR")); if let Some(pkg_dbdir) = line { if let Some(value) = pkg_dbdir.split('=').nth(1) { @@ -29,7 +31,9 @@ pub fn pkgdb_dir() -> Option { /// Returns the value of LOCALBASE if exists or a default if not. pub fn localbase_dir() -> Option { if let Ok(lines) = read_lines("/etc/mk.conf") { - let line = lines.flatten().find(|l| l.starts_with("LOCALBASE")); + let line = lines + .map_while(Result::ok) + .find(|l| l.starts_with("LOCALBASE")); if let Some(pkg_dbdir) = line { if let Some(value) = pkg_dbdir.split('=').nth(1) { diff --git a/src/extra.rs b/src/extra.rs index 9580a7fb..6974d777 100644 --- a/src/extra.rs +++ b/src/extra.rs @@ -73,7 +73,8 @@ Returns the entries of a given `Path`. pub fn get_entries(path: &Path) -> Option> { if let Ok(dir) = std::fs::read_dir(path) { let mut entries: Vec = Vec::new(); - dir.flatten().for_each(|x| entries.push(x.path())); + dir.map_while(Result::ok) + .for_each(|x| entries.push(x.path())); return Some(entries); } diff --git a/src/linux/mod.rs b/src/linux/mod.rs index e4fc5382..5bc39a41 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -391,7 +391,7 @@ impl GeneralReadout for LinuxGeneralReadout { match file { Ok(content) => { let reader = BufReader::new(content); - for line in reader.lines().flatten() { + for line in reader.lines().map_while(Result::ok) { if line.to_uppercase().starts_with("PPID") { let s_mem_kb: String = line.chars().filter(|c| c.is_ascii_digit()).collect(); @@ -478,7 +478,7 @@ impl GeneralReadout for LinuxGeneralReadout { use std::io::{BufRead, BufReader}; if let Ok(content) = File::open("/proc/cpuinfo") { let reader = BufReader::new(content); - for line in reader.lines().flatten() { + for line in reader.lines().map_while(Result::ok) { if line.to_lowercase().starts_with("cpu cores") { return Ok(line .split(':') diff --git a/src/linux/pci_devices.rs b/src/linux/pci_devices.rs index 76cad3d2..8fc7b724 100644 --- a/src/linux/pci_devices.rs +++ b/src/linux/pci_devices.rs @@ -100,7 +100,7 @@ pub fn get_pci_devices() -> Result, io::Error> { let devices_dir = read_dir("/sys/bus/pci/devices/")?; let mut devices = vec![]; - for device_entry in devices_dir.flatten() { + for device_entry in devices_dir.map_while(Result::ok) { devices.push(PciDevice::new(device_entry.path())); } diff --git a/src/openwrt/mod.rs b/src/openwrt/mod.rs index f09adf4c..79e3b5b3 100644 --- a/src/openwrt/mod.rs +++ b/src/openwrt/mod.rs @@ -92,7 +92,7 @@ impl GeneralReadout for OpenWrtGeneralReadout { let file = fs::File::open("/proc/cpuinfo"); if let Ok(content) = file { let reader = BufReader::new(content); - for line in reader.lines().into_iter().flatten() { + for line in reader.lines().into_iter().map_while(Result::ok) { if line.starts_with("machine") { return Ok(line .replace("machine", "") @@ -154,7 +154,7 @@ impl GeneralReadout for OpenWrtGeneralReadout { let file = fs::File::open("/proc/cpuinfo"); if let Ok(content) = file { let reader = BufReader::new(content); - for line in reader.lines().into_iter().flatten() { + for line in reader.lines().into_iter().map_while(Result::ok) { if line.starts_with("cpu model") { return Ok(line .replace("cpu model", "") @@ -315,7 +315,7 @@ impl OpenWrtPackageReadout { let file = fs::File::open("/usr/lib/opkg/status"); if let Ok(content) = file { let reader = BufReader::new(content); - for line in reader.lines().flatten() { + for line in reader.lines().map_while(Result::ok) { if line.starts_with("Package:") { count += 1 } diff --git a/src/shared/mod.rs b/src/shared/mod.rs index 092e5a03..4590b097 100644 --- a/src/shared/mod.rs +++ b/src/shared/mod.rs @@ -202,7 +202,7 @@ pub(crate) fn cpu_model_name() -> String { match file { Ok(content) => { let reader = BufReader::new(content); - for line in reader.lines().flatten() { + for line in reader.lines().map_while(Result::ok) { if line.starts_with("model name") { return line .replace("model name", "") @@ -281,7 +281,7 @@ pub(crate) fn get_meminfo_value(value: &str) -> u64 { match file { Ok(content) => { let reader = BufReader::new(content); - for line in reader.lines().flatten() { + for line in reader.lines().map_while(Result::ok) { if line.starts_with(value) { let s_mem_kb: String = line.chars().filter(|c| c.is_ascii_digit()).collect(); return s_mem_kb.parse::().unwrap_or(0); From 2205490ccde549c1e80ecc7bc8a6ebf23cdff3f9 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 10 May 2024 23:13:55 +0100 Subject: [PATCH 27/39] Fix Readouts struct's network field type Closes: #168 --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index b8f60e0f..d68c57fc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -93,7 +93,7 @@ pub struct Readouts { pub general: GeneralReadout, pub product: ProductReadout, pub packages: PackageReadout, - pub network: PackageReadout, + pub network: NetworkReadout, } #[cfg(feature = "version")] From 8f9154851c46f476590b8c264c240289939d264d Mon Sep 17 00:00:00 2001 From: Matthias Baer Date: Wed, 29 May 2024 22:17:49 +0200 Subject: [PATCH 28/39] Improve CI workflow (#169) * Replace discontinued actions-rs * Split cargo fmt and clippy into their own CI job --- .github/workflows/libmacchina.yml | 62 +++++++++++++++---------------- src/lib.rs | 4 +- src/openwrt/mod.rs | 40 ++++++++++---------- src/traits.rs | 54 +++++++++++++-------------- src/windows/mod.rs | 8 ++-- 5 files changed, 83 insertions(+), 85 deletions(-) diff --git a/.github/workflows/libmacchina.yml b/.github/workflows/libmacchina.yml index b8e6a576..3c3166a5 100644 --- a/.github/workflows/libmacchina.yml +++ b/.github/workflows/libmacchina.yml @@ -3,9 +3,31 @@ on: [push, pull_request] name: CI jobs: + lint: + runs-on: ubuntu-latest + name: Lint + env: + RUSTFLAGS: "-Dwarnings" + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Bootstrap + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - name: Formatting + run: cargo fmt --all -- --check + + - name: Clippy + run: cargo clippy --all-targets --all-features + checks: name: ${{ matrix.name }} (${{ matrix.target }}) runs-on: ${{ matrix.os }} + env: + PROGRAM: ${{ matrix.cross && 'cross' || 'cargo' }} strategy: fail-fast: false matrix: @@ -71,42 +93,20 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Bootstrap - uses: actions-rs/toolchain@v1 - with: - toolchain: stable - components: rustfmt, clippy - target: ${{ matrix.target }} - - - name: Formatting - uses: actions-rs/cargo@v1 + uses: dtolnay/rust-toolchain@stable with: - command: fmt - args: -- --check - use-cross: ${{ matrix.cross }} - continue-on-error: false + targets: ${{ matrix.target }} - - name: Lints - uses: actions-rs/cargo@v1 - with: - command: clippy - args: --target=${{ matrix.target }} -- --no-deps -D clippy::all - use-cross: ${{ matrix.cross }} - continue-on-error: false + - name: Install cross + run: cargo install cross + if: ${{ matrix.cross }} - name: Build - uses: actions-rs/cargo@v1 - with: - command: build - args: --target=${{ matrix.target }} ${{ matrix.cargo_args }} - use-cross: ${{ matrix.cross }} + run: ${{ env.PROGRAM }} build --target=${{ matrix.target }} ${{ matrix.cargo_args }} - - name: Test - uses: actions-rs/cargo@v1 - with: - command: test - args: --target=${{ matrix.target }} ${{ matrix.cargo_args }} - use-cross: ${{ matrix.cross }} + - name: Test + run: ${{ env.PROGRAM }} test --target=${{ matrix.target }} ${{ matrix.cargo_args }} if: ${{ matrix.test }} diff --git a/src/lib.rs b/src/lib.rs index d68c57fc..df9d5591 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -99,9 +99,9 @@ pub struct Readouts { #[cfg(feature = "version")] pub fn version() -> &'static str { if let Some(git_sha) = option_env!("VERGEN_GIT_SHA_SHORT") { - return Box::leak(format!("{} ({})", env!("CARGO_PKG_VERSION"), git_sha).into_boxed_str()); + Box::leak(format!("{} ({})", env!("CARGO_PKG_VERSION"), git_sha).into_boxed_str()) } else { - return env!("CARGO_PKG_VERSION"); + env!("CARGO_PKG_VERSION") } } diff --git a/src/openwrt/mod.rs b/src/openwrt/mod.rs index 79e3b5b3..81a26ad4 100644 --- a/src/openwrt/mod.rs +++ b/src/openwrt/mod.rs @@ -92,11 +92,11 @@ impl GeneralReadout for OpenWrtGeneralReadout { let file = fs::File::open("/proc/cpuinfo"); if let Ok(content) = file { let reader = BufReader::new(content); - for line in reader.lines().into_iter().map_while(Result::ok) { + for line in reader.lines().map_while(Result::ok) { if line.starts_with("machine") { return Ok(line .replace("machine", "") - .replace(":", "") + .replace(':', "") .trim() .to_string()); } @@ -154,11 +154,11 @@ impl GeneralReadout for OpenWrtGeneralReadout { let file = fs::File::open("/proc/cpuinfo"); if let Ok(content) = file { let reader = BufReader::new(content); - for line in reader.lines().into_iter().map_while(Result::ok) { + for line in reader.lines().map_while(Result::ok) { if line.starts_with("cpu model") { return Ok(line .replace("cpu model", "") - .replace(":", "") + .replace(':', "") .trim() .to_string()); } @@ -186,11 +186,11 @@ impl GeneralReadout for OpenWrtGeneralReadout { let f_load = 1f64 / (1 << libc::SI_LOAD_SHIFT) as f64; let cpu_usage = info.loads[0] as f64 * f_load; let cpu_usage_u = (cpu_usage / num_cpus::get() as f64 * 100.0).round() as usize; - return Ok(cpu_usage_u as usize); + Ok(cpu_usage_u as usize) } else { - return Err(ReadoutError::Other(String::from( + Err(ReadoutError::Other(String::from( "sysinfo struct returned an error.", - ))); + ))) } } @@ -199,11 +199,11 @@ impl GeneralReadout for OpenWrtGeneralReadout { let info_ptr: *mut sysinfo = &mut info; let ret = unsafe { sysinfo(info_ptr) }; if ret != -1 { - return Ok(info.uptime as usize); + Ok(info.uptime as usize) } else { - return Err(ReadoutError::Other(String::from( + Err(ReadoutError::Other(String::from( "sysinfo struct returned an error.", - ))); + ))) } } @@ -232,11 +232,11 @@ impl MemoryReadout for OpenWrtMemoryReadout { let info_ptr: *mut sysinfo = &mut info; let ret = unsafe { sysinfo(info_ptr) }; if ret != -1 { - return Ok(info.totalram as u64 * info.mem_unit as u64 / 1024); + Ok(info.totalram as u64 * info.mem_unit as u64 / 1024) } else { - return Err(ReadoutError::Other(String::from( + Err(ReadoutError::Other(String::from( "sysinfo struct returned an error.", - ))); + ))) } } @@ -245,11 +245,11 @@ impl MemoryReadout for OpenWrtMemoryReadout { let info_ptr: *mut sysinfo = &mut info; let ret = unsafe { sysinfo(info_ptr) }; if ret != -1 { - return Ok(info.freeram as u64 * info.mem_unit as u64 / 1024); + Ok(info.freeram as u64 * info.mem_unit as u64 / 1024) } else { - return Err(ReadoutError::Other(String::from( + Err(ReadoutError::Other(String::from( "sysinfo struct returned an error.", - ))); + ))) } } @@ -258,11 +258,11 @@ impl MemoryReadout for OpenWrtMemoryReadout { let info_ptr: *mut sysinfo = &mut info; let ret = unsafe { sysinfo(info_ptr) }; if ret != -1 { - return Ok(info.bufferram as u64 * info.mem_unit as u64 / 1024); + Ok(info.bufferram as u64 * info.mem_unit as u64 / 1024) } else { - return Err(ReadoutError::Other(format!( - "Failed to get system statistics" - ))); + Err(ReadoutError::Other(String::from( + "Failed to get system statistics", + ))) } } diff --git a/src/traits.rs b/src/traits.rs index 99cde381..8d193fac 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -22,17 +22,17 @@ pub enum ReadoutError { Warning(String), } -impl ToString for ReadoutError { - fn to_string(&self) -> String { +impl std::fmt::Display for ReadoutError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ReadoutError::MetricNotAvailable => { - String::from("Metric is not available on this system.") + write!(f, "Metric is not available on this system.") } ReadoutError::NotImplemented => { - String::from("This metric is not available on this platform or is not yet implemented by libmacchina.") + write!(f, "This metric is not available on this platform or is not yet implemented by libmacchina.") } - ReadoutError::Other(s) => s.clone(), - ReadoutError::Warning(s) => s.clone(), + ReadoutError::Other(s) => write!(f, "{}", s), + ReadoutError::Warning(s) => write!(f, "{}", s), } } } @@ -657,26 +657,26 @@ pub enum PackageManager { Scoop, } -impl ToString for PackageManager { - fn to_string(&self) -> String { - String::from(match self { - PackageManager::Homebrew => "Homebrew", - PackageManager::MacPorts => "MacPorts", - PackageManager::Pacman => "pacman", - PackageManager::Portage => "portage", - PackageManager::Dpkg => "dpkg", - PackageManager::Opkg => "opkg", - PackageManager::Xbps => "xbps", - PackageManager::Pkgsrc => "pkgsrc", - PackageManager::Apk => "apk", - PackageManager::Eopkg => "eopkg", - PackageManager::Rpm => "rpm", - PackageManager::Cargo => "cargo", - PackageManager::Flatpak => "flatpak", - PackageManager::Snap => "snap", - PackageManager::Android => "Android", - PackageManager::Pkg => "pkg", - PackageManager::Scoop => "Scoop", - }) +impl std::fmt::Display for PackageManager { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PackageManager::Homebrew => write!(f, "Homebrew"), + PackageManager::MacPorts => write!(f, "MacPorts"), + PackageManager::Pacman => write!(f, "pacman"), + PackageManager::Portage => write!(f, "portage"), + PackageManager::Dpkg => write!(f, "dpkg"), + PackageManager::Opkg => write!(f, "opkg"), + PackageManager::Xbps => write!(f, "xbps"), + PackageManager::Pkgsrc => write!(f, "pkgsrc"), + PackageManager::Apk => write!(f, "apk"), + PackageManager::Eopkg => write!(f, "eopkg"), + PackageManager::Rpm => write!(f, "rpm"), + PackageManager::Cargo => write!(f, "cargo"), + PackageManager::Flatpak => write!(f, "flatpak"), + PackageManager::Snap => write!(f, "snap"), + PackageManager::Android => write!(f, "Android"), + PackageManager::Pkg => write!(f, "pkg"), + PackageManager::Scoop => write!(f, "Scoop"), + } } } diff --git a/src/windows/mod.rs b/src/windows/mod.rs index 3278e301..1d399d94 100644 --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -455,12 +455,10 @@ impl NetworkReadout for WindowsNetworkReadout { fn logical_address(&self, interface: Option<&str>) -> Result { match interface { - Some(it) => { + Some(interface) => { if let Ok(addresses) = local_ip_address::list_afinet_netifas() { - for (name, ip) in addresses.iter() { - if let Some(name) = interface { - return Ok(ip.to_string()); - } + if let Some((_, ip)) = addresses.iter().find(|(name, _)| name == interface) { + return Ok(ip.to_string()); } } } From 1dca3fb67b69b571201753c19c5f0393d6a58dbc Mon Sep 17 00:00:00 2001 From: Adrian Groh <50576978+Gobidev@users.noreply.github.com> Date: Sun, 2 Jun 2024 13:42:07 +0200 Subject: [PATCH 29/39] Faster package count on Alpine Linux (#170) --- src/linux/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 5bc39a41..a29ab909 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -855,6 +855,12 @@ impl LinuxPackageReadout { /// Returns the number of installed packages for systems /// that utilize `apk` as their package manager. fn count_apk() -> Option { + // faster method for alpine: count empty lines in /lib/apk/db/installed + if let Ok(content) = fs::read_to_string(Path::new("/lib/apk/db/installed")) { + return Some(content.lines().filter(|l| l.is_empty()).count()); + } + + // fallback to command invocation if !extra::which("apk") { return None; } From 42d7cc3286cf3814b9164eee0ecd97586d363c66 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Sun, 2 Jun 2024 13:01:27 +0100 Subject: [PATCH 30/39] Bump version to 7.2.3 --- CHANGELOG.md | 10 ++++++++++ Cargo.toml | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1afb8f29..3bc933be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## `7.2.3` + +- Fix `Readouts` struct `network` field type + +Matthias Baer: +- Improve CI workflow (#169) + +Adrian Groh: +- Faster package count on Alpine Linux (#170) + ## `7.2.2` - Update `vergen` dependency and correct its invocation. diff --git a/Cargo.toml b/Cargo.toml index f8a4f13f..4a2f8062 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.2.2" +version = "7.2.3" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." From 040e9d32750f74c80a0edcbc4d9f0acf28baa4d6 Mon Sep 17 00:00:00 2001 From: Rex Ng Date: Wed, 12 Jun 2024 04:35:49 +0800 Subject: [PATCH 31/39] added macos 15 version name (#171) https://www.apple.com/newsroom/2024/06/macos-sequoia-takes-productivity-and-intelligence-on-mac-to-new-heights/ --- src/macos/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/macos/mod.rs b/src/macos/mod.rs index e2aa170d..1b612bd9 100644 --- a/src/macos/mod.rs +++ b/src/macos/mod.rs @@ -691,6 +691,7 @@ fn macos_version_to_name(version: &NSOperatingSystemVersion) -> &'static str { (12, _) => "Monterey", (13, _) => "Ventura", (14, _) => "Sonoma", + (15, _) => "Sequoia", _ => "Unknown", } } From 0be88837c30b0bdbea58ecf38fdec5fc57695c32 Mon Sep 17 00:00:00 2001 From: coolGi <57488297+coolGi2007@users.noreply.github.com> Date: Wed, 19 Jun 2024 07:09:34 +0930 Subject: [PATCH 32/39] Removed panic if local gpu db is not able to be read (#173) --- src/linux/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/linux/mod.rs b/src/linux/mod.rs index a29ab909..01ba29e8 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -550,7 +550,7 @@ impl GeneralReadout for LinuxGeneralReadout { fn gpus(&self) -> Result, ReadoutError> { let db = match Database::read() { Ok(db) => db, - _ => panic!("Could not read pci.ids file"), + _ => return Err(ReadoutError::MetricNotAvailable), }; let devices = get_pci_devices()?; From 3a5bec05e7a6fc6b5585bc1ee0a8f2583a77d9eb Mon Sep 17 00:00:00 2001 From: coolGi <57488297+coolGi2007@users.noreply.github.com> Date: Sun, 23 Jun 2024 00:32:49 +0930 Subject: [PATCH 33/39] Add support for the Nix package manager (#172) Added support for the Nix package manager using Nix' SQLite database. --- Cargo.toml | 2 +- src/linux/mod.rs | 37 +++++++++++++++++++++++++++++++++++++ src/traits.rs | 2 ++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 4a2f8062..b089b4e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,7 +59,7 @@ windows = { version = "0.39.0", features = [ if-addrs = "0.10.2" [target.'cfg(any(target_os="freebsd", target_os = "linux"))'.dependencies] -sqlite = "0.31.1" +sqlite = "0.36.0" [target.'cfg(any(target_os="freebsd", target_os = "netbsd"))'.dependencies] x11rb = "0.12.0" diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 01ba29e8..ca48b926 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -726,6 +726,10 @@ impl PackageReadout for LinuxPackageReadout { packages.push((PackageManager::Homebrew, c)); } + if let Some(c) = LinuxPackageReadout::count_nix() { + packages.push((PackageManager::Nix, c)); + } + packages } } @@ -934,4 +938,37 @@ impl LinuxPackageReadout { None } + + /// Returns the number of installed packages for systems + /// that utilize `nix` as their package manager. + fn count_nix() -> Option { + return 'sqlite: { + let db = "/nix/var/nix/db/db.sqlite"; + if !Path::new(db).is_file() { + break 'sqlite None; + } + + let connection = sqlite::Connection::open_with_flags( + // The nix store is immutable, so we need to inform sqlite about it + "file:".to_owned() + db + "?immutable=1", + sqlite::OpenFlags::new().with_read_only().with_uri(), + ); + + if let Ok(con) = connection { + let statement = + con.prepare("SELECT COUNT(path) FROM ValidPaths WHERE sigs IS NOT NULL"); + + if let Ok(mut s) = statement { + if s.next().is_ok() { + break 'sqlite match s.read::, _>(0) { + Ok(Some(count)) => Some(count as usize), + _ => None, + }; + } + } + } + + None + }; + } } diff --git a/src/traits.rs b/src/traits.rs index 8d193fac..f7eff47f 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -655,6 +655,7 @@ pub enum PackageManager { Android, Pkg, Scoop, + Nix, } impl std::fmt::Display for PackageManager { @@ -677,6 +678,7 @@ impl std::fmt::Display for PackageManager { PackageManager::Android => write!(f, "Android"), PackageManager::Pkg => write!(f, "pkg"), PackageManager::Scoop => write!(f, "Scoop"), + PackageManager::Nix => write!(f, "nix"), } } } From ef60632ac15da06e2d9d10d28bff885ac0b004d3 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Fri, 28 Jun 2024 23:25:04 +0100 Subject: [PATCH 34/39] Bump version and update changelog --- CHANGELOG.md | 10 ++++++++++ Cargo.toml | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bc933be..36ddb3bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## `7.3.0` + +coolGi2007: +- Add support for the Nix package manager +- Bump `sqlite` dependency to version `0.36.0` +- Don't panic if the `pci.ids` database could not be found + +Rex Ng: +- Recognize latest version of macOS + ## `7.2.3` - Fix `Readouts` struct `network` field type diff --git a/Cargo.toml b/Cargo.toml index b089b4e3..9d90ba7f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.2.3" +version = "7.3.0" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." From 30abf25b2c3a032ca28cb0fcb065411c8ce428c6 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Mon, 8 Jul 2024 02:08:41 +0100 Subject: [PATCH 35/39] linux: Safely exit when homebrew is not installed --- src/linux/mod.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/linux/mod.rs b/src/linux/mod.rs index ca48b926..38b19a9c 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -830,6 +830,10 @@ impl LinuxPackageReadout { base = PathBuf::from("/home/linuxbrew/.linuxbrew"); } + if !base.is_dir() { + return None; + } + match read_dir(base.join("Cellar")) { // subtract 1 as ${base}/Cellar contains a ".keepme" file Ok(dir) => Some(dir.count() - 1), From e8d86566d4a504383a94f7e0ef4e586d8a201650 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Thu, 12 Sep 2024 00:23:58 +0100 Subject: [PATCH 36/39] Improve linuxbrew keepme safeguard --- src/linux/mod.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 38b19a9c..423746fe 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -11,8 +11,10 @@ use crate::traits::*; use itertools::Itertools; use pciid_parser::Database; use regex::Regex; +use std::ffi::OsStr; use std::fs; use std::fs::read_dir; +use std::fs::DirEntry; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; @@ -825,7 +827,9 @@ impl LinuxPackageReadout { /// Returns the number of installed packages for systems /// that have `homebrew` installed. fn count_homebrew(home: &Path) -> Option { + let keepme = OsStr::new(".keepme"); let mut base = home.join(".linuxbrew"); + if !base.is_dir() { base = PathBuf::from("/home/linuxbrew/.linuxbrew"); } @@ -835,8 +839,13 @@ impl LinuxPackageReadout { } match read_dir(base.join("Cellar")) { - // subtract 1 as ${base}/Cellar contains a ".keepme" file - Ok(dir) => Some(dir.count() - 1), + Ok(dir) => Some( + dir.filter(|entry| match entry { + Err(_) => false, + Ok(file) => file.file_name() != keepme, + }) + .count(), + ), Err(_) => None, } } From 15ba3ca666bea71b157065b3ec4dd6e75df10341 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Thu, 12 Sep 2024 00:37:11 +0100 Subject: [PATCH 37/39] Remove unused import --- src/linux/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 423746fe..53a16cb0 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -14,7 +14,6 @@ use regex::Regex; use std::ffi::OsStr; use std::fs; use std::fs::read_dir; -use std::fs::DirEntry; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; From 6781ee9dc40c52f328d2551cc8134fa08153c410 Mon Sep 17 00:00:00 2001 From: grtcdr Date: Thu, 12 Sep 2024 00:37:24 +0100 Subject: [PATCH 38/39] Bump version to 7.3.1 --- CHANGELOG.md | 4 ++++ Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36ddb3bd..884169e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## `7.3.1` + +- Fix overflow affecting linux::count_homebrew() implementation + ## `7.3.0` coolGi2007: diff --git a/Cargo.toml b/Cargo.toml index 9d90ba7f..ee865135 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.3.0" +version = "7.3.1" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." From 9434b59e2aedd9687f590f2acbd136ba81cf9db5 Mon Sep 17 00:00:00 2001 From: Rolv Apneseth Date: Fri, 21 Apr 2023 14:44:52 +0100 Subject: [PATCH 39/39] Allow disk_space function to accept a path argument (#156) BREAKING CHANGE: allow disk_space function to accept a path argument - Bump version and update changelog - Change disk_space path argument to be of type &Path and check path exists in shared::disk_space - Add missing import for openwrt --- CHANGELOG.md | 5 +++++ Cargo.toml | 2 +- src/android/mod.rs | 2 +- src/freebsd/mod.rs | 4 ++-- src/linux/mod.rs | 4 ++-- src/macos/mod.rs | 5 +++-- src/netbsd/mod.rs | 18 ++++++++++++++---- src/openwrt/mod.rs | 5 +++-- src/shared/mod.rs | 14 ++++++++++++-- src/traits.rs | 7 +++++-- src/windows/mod.rs | 4 ++-- 11 files changed, 50 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 884169e4..aec76046 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## `8.0.0` + +- Rolv Apneseth: + - BREAKING CHANGE: Allow disk_space function to accept a path argument (#156) + ## `7.3.1` - Fix overflow affecting linux::count_homebrew() implementation diff --git a/Cargo.toml b/Cargo.toml index ee865135..4dfc503e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libmacchina" -version = "7.3.1" +version = "8.0.0" authors = ["grtcdr ", "Marvin Haschker ", "Uttarayan Mondal "] edition = "2021" description = "A library that can fetch all sorts of system information." diff --git a/src/android/mod.rs b/src/android/mod.rs index d58143db..aa4c7f0e 100644 --- a/src/android/mod.rs +++ b/src/android/mod.rs @@ -286,7 +286,7 @@ impl GeneralReadout for AndroidGeneralReadout { } } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { Err(ReadoutError::NotImplemented) } diff --git a/src/freebsd/mod.rs b/src/freebsd/mod.rs index 9746b4f8..5ac976d7 100644 --- a/src/freebsd/mod.rs +++ b/src/freebsd/mod.rs @@ -290,8 +290,8 @@ impl GeneralReadout for FreeBSDGeneralReadout { Err(ReadoutError::MetricNotAvailable) } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { - shared::disk_space(String::from("/")) + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { + shared::disk_space(path) } fn gpus(&self) -> Result, ReadoutError> { diff --git a/src/linux/mod.rs b/src/linux/mod.rs index 53a16cb0..173c07e5 100644 --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -544,8 +544,8 @@ impl GeneralReadout for LinuxGeneralReadout { Err(ReadoutError::NotImplemented) } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { - shared::disk_space(String::from("/")) + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { + shared::disk_space(path) } fn gpus(&self) -> Result, ReadoutError> { diff --git a/src/macos/mod.rs b/src/macos/mod.rs index 1b612bd9..b0e91705 100644 --- a/src/macos/mod.rs +++ b/src/macos/mod.rs @@ -20,6 +20,7 @@ use core_video_sys::{ use mach2::kern_return::KERN_SUCCESS; use std::ffi::CString; use std::fs::DirEntry; +use std::path::Path; use sysctl::{Ctl, Sysctl}; mod mach_ffi; @@ -400,8 +401,8 @@ impl GeneralReadout for MacOSGeneralReadout { Ok(format!("macOS {version} {major_version_name}")) } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { - shared::disk_space(String::from("/")) + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { + shared::disk_space(path) } fn gpus(&self) -> Result, ReadoutError> { diff --git a/src/netbsd/mod.rs b/src/netbsd/mod.rs index f9395af5..29019e34 100644 --- a/src/netbsd/mod.rs +++ b/src/netbsd/mod.rs @@ -9,7 +9,7 @@ use regex::Regex; use std::ffi::CString; use std::fs; use std::fs::read_dir; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; pub struct NetBSDBatteryReadout; @@ -312,9 +312,19 @@ impl GeneralReadout for NetBSDGeneralReadout { Err(ReadoutError::MetricNotAvailable) } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { + use std::os::unix::ffi::OsStrExt; + + if !path.is_dir() || !path.is_absolute() { + return Err(ReadoutError::Other(format!( + "The provided path is not valid: {:?}", + path + ))); + } + let mut s: std::mem::MaybeUninit = std::mem::MaybeUninit::uninit(); - let path = CString::new("/").expect("Could not create C string for disk usage path."); + let path = CString::new(path.as_os_str().as_bytes()) + .expect("Could not create C string for disk usage path."); if unsafe { libc::statvfs(path.as_ptr(), s.as_mut_ptr()) } == 0 { let stats: libc::statvfs = unsafe { s.assume_init() }; @@ -322,7 +332,7 @@ impl GeneralReadout for NetBSDGeneralReadout { let disk_size = stats.f_blocks * stats.f_bsize as u64; let free = stats.f_bavail * stats.f_bsize as u64; - let used_byte = (disk_size - free); + let used_byte = disk_size - free; let disk_size_byte = disk_size; return Ok((used_byte, disk_size_byte)); diff --git a/src/openwrt/mod.rs b/src/openwrt/mod.rs index 81a26ad4..90b717fe 100644 --- a/src/openwrt/mod.rs +++ b/src/openwrt/mod.rs @@ -5,6 +5,7 @@ use crate::shared; use crate::traits::*; use std::fs; use std::io::{BufRead, BufReader}; +use std::path::Path; use sysctl::{Ctl, Sysctl}; use sysinfo_ffi::sysinfo; @@ -211,8 +212,8 @@ impl GeneralReadout for OpenWrtGeneralReadout { Err(ReadoutError::NotImplemented) } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { - shared::disk_space(String::from("/")) + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { + shared::disk_space(path) } fn gpus(&self) -> Result, ReadoutError> { diff --git a/src/shared/mod.rs b/src/shared/mod.rs index 4590b097..184e7a0f 100644 --- a/src/shared/mod.rs +++ b/src/shared/mod.rs @@ -244,9 +244,19 @@ pub(crate) fn cpu_physical_cores() -> Result { } #[cfg(not(any(target_os = "netbsd", target_os = "windows")))] -pub(crate) fn disk_space(path: String) -> Result<(u64, u64), ReadoutError> { +pub(crate) fn disk_space(path: &Path) -> Result<(u64, u64), ReadoutError> { + use std::os::unix::ffi::OsStrExt; + + if !path.is_dir() || !path.is_absolute() { + return Err(ReadoutError::Other(format!( + "The provided path is not valid: {:?}", + path + ))); + } + let mut s: std::mem::MaybeUninit = std::mem::MaybeUninit::uninit(); - let path = CString::new(path).expect("Could not create C string for disk usage path."); + let path = CString::new(path.as_os_str().as_bytes()) + .expect("Could not create C string for disk usage path."); if unsafe { libc::statfs(path.as_ptr(), s.as_mut_ptr()) } == 0 { #[cfg(target_pointer_width = "32")] diff --git a/src/traits.rs b/src/traits.rs index f7eff47f..5ed9313c 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -2,6 +2,8 @@ //! different readouts from various operating systems. For each operating system, there must be an implementation of these traits. #![allow(unused_variables)] +use std::path::Path; + /// This enum contains possible error types when doing sensor & variable readouts. #[derive(Debug, Clone)] pub enum ReadoutError { @@ -398,6 +400,7 @@ information about the running operating system and current user. # Example ``` +use std::path::Path; use libmacchina::traits::GeneralReadout; use libmacchina::traits::ReadoutError; use libmacchina::traits::ShellFormat; @@ -480,7 +483,7 @@ impl GeneralReadout for MacOSGeneralReadout { Ok("macOS 11.2.2 Big Sur".to_string()) } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { Ok((50000000,1000000000)) // Used / Total } @@ -586,7 +589,7 @@ pub trait GeneralReadout { /// bytes of disk space. /// /// _e.g._ '(50000000, 1000000000)' - fn disk_space(&self) -> Result<(u64, u64), ReadoutError>; + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError>; /// This function should return the device names of any _GPU(s)_ connected to the host machine. fn gpus(&self) -> Result, ReadoutError>; diff --git a/src/windows/mod.rs b/src/windows/mod.rs index 1d399d94..1bd04269 100644 --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -1,6 +1,6 @@ use crate::traits::*; use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use winreg::enums::*; use winreg::RegKey; use wmi::WMIResult; @@ -338,7 +338,7 @@ impl GeneralReadout for WindowsGeneralReadout { )) } - fn disk_space(&self) -> Result<(u64, u64), ReadoutError> { + fn disk_space(&self, path: &Path) -> Result<(u64, u64), ReadoutError> { Err(ReadoutError::NotImplemented) }