riscfetch_core/
system.rs

1//! General system information (memory, uptime, kernel, OS)
2
3use std::fs;
4use std::process::Command;
5use sysinfo::System;
6
7/// Get memory usage as formatted string
8#[must_use]
9#[allow(clippy::cast_precision_loss)]
10pub fn get_memory_info() -> String {
11    let mut sys = System::new();
12    sys.refresh_memory();
13
14    let total_mem = sys.total_memory();
15    let used_mem = sys.used_memory();
16
17    let total_gb = total_mem as f64 / 1_073_741_824.0;
18    let used_gb = used_mem as f64 / 1_073_741_824.0;
19
20    format!("{used_gb:.2} GiB / {total_gb:.2} GiB")
21}
22
23/// Get memory information as bytes
24#[must_use]
25pub fn get_memory_bytes() -> (u64, u64) {
26    let mut sys = System::new();
27    sys.refresh_memory();
28    (sys.used_memory(), sys.total_memory())
29}
30
31/// Get kernel version
32#[must_use]
33pub fn get_kernel_info() -> String {
34    if let Ok(output) = Command::new("uname").arg("-r").output() {
35        let kernel = String::from_utf8_lossy(&output.stdout).trim().to_string();
36        if !kernel.is_empty() {
37            return kernel;
38        }
39    }
40    "Unknown".to_string()
41}
42
43/// Get OS name from /etc/os-release
44#[must_use]
45pub fn get_os_info() -> String {
46    if let Ok(content) = fs::read_to_string("/etc/os-release") {
47        for line in content.lines() {
48            if line.starts_with("PRETTY_NAME=") {
49                if let Some(name) = line.split('=').nth(1) {
50                    return name.trim_matches('"').to_string();
51                }
52            }
53        }
54    }
55
56    "Linux".to_string()
57}
58
59/// Get uptime as formatted string
60#[must_use]
61pub fn get_uptime() -> String {
62    let uptime_secs = System::uptime();
63    let hours = uptime_secs / 3600;
64    let minutes = (uptime_secs % 3600) / 60;
65
66    if hours > 0 {
67        format!("{hours}h {minutes}m")
68    } else {
69        format!("{minutes}m")
70    }
71}
72
73/// Get uptime in seconds
74#[must_use]
75pub fn get_uptime_seconds() -> u64 {
76    System::uptime()
77}