microfetch/src/uptime.rs

38 lines
1.1 KiB
Rust
Raw Normal View History

2024-08-03 20:42:48 +03:00
use std::fs::File;
2024-08-04 17:20:34 +03:00
use std::io::{self, BufRead, BufReader};
2024-08-03 20:42:48 +03:00
use std::path::Path;
2024-08-04 00:07:11 +03:00
pub fn get_current() -> Result<String, io::Error> {
2024-08-03 20:42:48 +03:00
let path = Path::new("/proc/uptime");
let file = File::open(path)?;
2024-08-04 17:20:34 +03:00
let mut reader = BufReader::new(file);
2024-08-03 20:42:48 +03:00
2024-08-04 17:20:34 +03:00
let mut line = String::new();
reader.read_line(&mut line)?;
2024-08-03 20:42:48 +03:00
let uptime_seconds: f64 = line
.split_whitespace()
.next()
.ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to parse uptime"))?
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let total_minutes = (uptime_seconds / 60.0).round() as u64;
let days = total_minutes / (60 * 24);
let hours = (total_minutes % (60 * 24)) / 60;
let minutes = total_minutes % 60;
2024-08-04 12:44:12 +03:00
let mut parts = Vec::with_capacity(3);
2024-08-03 20:42:48 +03:00
if days > 0 {
2024-08-03 23:04:26 +03:00
parts.push(format!("{days} days"));
2024-08-03 20:42:48 +03:00
}
if hours > 0 || days > 0 {
2024-08-03 23:04:26 +03:00
parts.push(format!("{hours} hours"));
2024-08-03 20:42:48 +03:00
}
if minutes > 0 || hours > 0 || days > 0 {
2024-08-03 23:04:26 +03:00
parts.push(format!("{minutes} minutes"));
2024-08-03 20:42:48 +03:00
}
Ok(parts.join(", "))
}