treewide: format with nightly rustfmt rules

Signed-off-by: NotAShelf <raf@notashelf.dev>
Change-Id: Ib8502372dafe2e970024f606b44825af6a6a6964
This commit is contained in:
raf 2025-11-17 16:10:31 +03:00
commit 9bd4c9a70a
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
6 changed files with 220 additions and 203 deletions

View file

@ -1,26 +1,31 @@
use criterion::{Criterion, criterion_group, criterion_main}; use criterion::{Criterion, criterion_group, criterion_main};
use microfetch_lib::colors::print_dots; use microfetch_lib::{
use microfetch_lib::desktop::get_desktop_info; colors::print_dots,
use microfetch_lib::release::{get_os_pretty_name, get_system_info}; desktop::get_desktop_info,
use microfetch_lib::system::{ release::{get_os_pretty_name, get_system_info},
get_memory_usage, get_root_disk_usage, get_shell, get_username_and_hostname, system::{
get_memory_usage,
get_root_disk_usage,
get_shell,
get_username_and_hostname,
},
uptime::get_current,
}; };
use microfetch_lib::uptime::get_current;
fn main_benchmark(c: &mut Criterion) { fn main_benchmark(c: &mut Criterion) {
let utsname = nix::sys::utsname::uname().expect("lol"); let utsname = nix::sys::utsname::uname().expect("lol");
c.bench_function("user_info", |b| { c.bench_function("user_info", |b| {
b.iter(|| get_username_and_hostname(&utsname)); b.iter(|| get_username_and_hostname(&utsname));
}); });
c.bench_function("os_name", |b| b.iter(get_os_pretty_name)); c.bench_function("os_name", |b| b.iter(get_os_pretty_name));
c.bench_function("kernel_version", |b| b.iter(|| get_system_info(&utsname))); c.bench_function("kernel_version", |b| b.iter(|| get_system_info(&utsname)));
c.bench_function("shell", |b| b.iter(get_shell)); c.bench_function("shell", |b| b.iter(get_shell));
c.bench_function("desktop", |b| b.iter(get_desktop_info)); c.bench_function("desktop", |b| b.iter(get_desktop_info));
c.bench_function("uptime", |b| b.iter(get_current)); c.bench_function("uptime", |b| b.iter(get_current));
c.bench_function("memory_usage", |b| b.iter(get_memory_usage)); c.bench_function("memory_usage", |b| b.iter(get_memory_usage));
c.bench_function("storage", |b| b.iter(get_root_disk_usage)); c.bench_function("storage", |b| b.iter(get_root_disk_usage));
c.bench_function("colors", |b| b.iter(print_dots)); c.bench_function("colors", |b| b.iter(print_dots));
} }
criterion_group!(benches, main_benchmark); criterion_group!(benches, main_benchmark);

View file

@ -1,57 +1,57 @@
use std::env; use std::{env, sync::LazyLock};
use std::sync::LazyLock;
pub struct Colors { pub struct Colors {
pub reset: &'static str, pub reset: &'static str,
pub blue: &'static str, pub blue: &'static str,
pub cyan: &'static str, pub cyan: &'static str,
pub green: &'static str, pub green: &'static str,
pub yellow: &'static str, pub yellow: &'static str,
pub red: &'static str, pub red: &'static str,
pub magenta: &'static str, pub magenta: &'static str,
} }
impl Colors { impl Colors {
const fn new(is_no_color: bool) -> Self { const fn new(is_no_color: bool) -> Self {
if is_no_color { if is_no_color {
Self { Self {
reset: "", reset: "",
blue: "", blue: "",
cyan: "", cyan: "",
green: "", green: "",
yellow: "", yellow: "",
red: "", red: "",
magenta: "", magenta: "",
} }
} else { } else {
Self { Self {
reset: "\x1b[0m", reset: "\x1b[0m",
blue: "\x1b[34m", blue: "\x1b[34m",
cyan: "\x1b[36m", cyan: "\x1b[36m",
green: "\x1b[32m", green: "\x1b[32m",
yellow: "\x1b[33m", yellow: "\x1b[33m",
red: "\x1b[31m", red: "\x1b[31m",
magenta: "\x1b[35m", magenta: "\x1b[35m",
} }
}
} }
}
} }
pub static COLORS: LazyLock<Colors> = LazyLock::new(|| { pub static COLORS: LazyLock<Colors> = LazyLock::new(|| {
// check for NO_COLOR once at startup // check for NO_COLOR once at startup
let is_no_color = env::var("NO_COLOR").is_ok(); let is_no_color = env::var("NO_COLOR").is_ok();
Colors::new(is_no_color) Colors::new(is_no_color)
}); });
#[must_use]
pub fn print_dots() -> String { pub fn print_dots() -> String {
format!( format!(
"{} {} {} {} {} {} {}", "{} {} {} {} {} {} {}",
COLORS.blue, COLORS.blue,
COLORS.cyan, COLORS.cyan,
COLORS.green, COLORS.green,
COLORS.yellow, COLORS.yellow,
COLORS.red, COLORS.red,
COLORS.magenta, COLORS.magenta,
COLORS.reset, COLORS.reset,
) )
} }

View file

@ -1,28 +1,29 @@
#[must_use]
pub fn get_desktop_info() -> String { pub fn get_desktop_info() -> String {
// Retrieve the environment variables and handle Result types // Retrieve the environment variables and handle Result types
let desktop_env = std::env::var("XDG_CURRENT_DESKTOP"); let desktop_env = std::env::var("XDG_CURRENT_DESKTOP");
let display_backend_result = std::env::var("XDG_SESSION_TYPE"); let display_backend_result = std::env::var("XDG_SESSION_TYPE");
// Capitalize the first letter of the display backend value // Capitalize the first letter of the display backend value
let mut display_backend = display_backend_result.unwrap_or_default(); let mut display_backend = display_backend_result.unwrap_or_default();
if let Some(c) = display_backend.as_mut_str().get_mut(0..1) { if let Some(c) = display_backend.as_mut_str().get_mut(0..1) {
c.make_ascii_uppercase(); c.make_ascii_uppercase();
} }
// Trim "none+" from the start of desktop_env if present // Trim "none+" from the start of desktop_env if present
// Use "Unknown" if desktop_env is empty or has an error // Use "Unknown" if desktop_env is empty or has an error
let desktop_env = match desktop_env { let desktop_env = match desktop_env {
Err(_) => "Unknown".to_string(), Err(_) => "Unknown".to_owned(),
Ok(s) => s.trim_start_matches("none+").to_string(), Ok(s) => s.trim_start_matches("none+").to_owned(),
}; };
// Handle the case where display_backend might be empty after capitalization // Handle the case where display_backend might be empty after capitalization
let display_backend = if display_backend.is_empty() { let display_backend = if display_backend.is_empty() {
"Unknown" "Unknown"
} else { } else {
&display_backend &display_backend
} }
.to_string(); .to_owned();
format!("{desktop_env} ({display_backend})") format!("{desktop_env} ({display_backend})")
} }

View file

@ -1,33 +1,35 @@
use nix::sys::utsname::UtsName;
use std::{ use std::{
fs::File, fs::File,
io::{self, BufRead, BufReader}, io::{self, BufRead, BufReader},
}; };
use nix::sys::utsname::UtsName;
#[must_use]
pub fn get_system_info(utsname: &UtsName) -> String { pub fn get_system_info(utsname: &UtsName) -> String {
format!( format!(
"{} {} ({})", "{} {} ({})",
utsname.sysname().to_str().unwrap_or("Unknown"), utsname.sysname().to_str().unwrap_or("Unknown"),
utsname.release().to_str().unwrap_or("Unknown"), utsname.release().to_str().unwrap_or("Unknown"),
utsname.machine().to_str().unwrap_or("Unknown") utsname.machine().to_str().unwrap_or("Unknown")
) )
} }
pub fn get_os_pretty_name() -> Result<String, io::Error> { pub fn get_os_pretty_name() -> Result<String, io::Error> {
let file = File::open("/etc/os-release")?; let file = File::open("/etc/os-release")?;
let reader = BufReader::new(file); let reader = BufReader::new(file);
for line in reader.lines() { for line in reader.lines() {
let line = line?; let line = line?;
if let Some(pretty_name) = line.strip_prefix("PRETTY_NAME=") { if let Some(pretty_name) = line.strip_prefix("PRETTY_NAME=") {
if let Some(trimmed) = pretty_name if let Some(trimmed) = pretty_name
.strip_prefix('"') .strip_prefix('"')
.and_then(|s| s.strip_suffix('"')) .and_then(|s| s.strip_suffix('"'))
{ {
return Ok(trimmed.to_string()); return Ok(trimmed.to_owned());
} }
return Ok(pretty_name.to_string()); return Ok(pretty_name.to_owned());
}
} }
Ok("Unknown".to_string()) }
Ok("Unknown".to_owned())
} }

View file

@ -1,87 +1,96 @@
use crate::colors::COLORS;
use nix::sys::{statvfs::statvfs, utsname::UtsName};
use std::{ use std::{
env, env,
fs::File, fs::File,
io::{self, Read}, io::{self, Read},
}; };
use nix::sys::{statvfs::statvfs, utsname::UtsName};
use crate::colors::COLORS;
#[must_use]
pub fn get_username_and_hostname(utsname: &UtsName) -> String { pub fn get_username_and_hostname(utsname: &UtsName) -> String {
let username = env::var("USER").unwrap_or_else(|_| "unknown_user".to_string()); let username = env::var("USER").unwrap_or_else(|_| "unknown_user".to_owned());
let hostname = utsname let hostname = utsname
.nodename() .nodename()
.to_str() .to_str()
.unwrap_or("unknown_host") .unwrap_or("unknown_host")
.to_string(); .to_owned();
format!( format!(
"{yellow}{username}{red}@{green}{hostname}{reset}", "{yellow}{username}{red}@{green}{hostname}{reset}",
yellow = COLORS.yellow, yellow = COLORS.yellow,
red = COLORS.red, red = COLORS.red,
green = COLORS.green, green = COLORS.green,
reset = COLORS.reset, reset = COLORS.reset,
) )
} }
#[must_use]
pub fn get_shell() -> String { pub fn get_shell() -> String {
let shell_path = env::var("SHELL").unwrap_or_else(|_| "unknown_shell".to_string()); let shell_path =
let shell_name = shell_path.rsplit('/').next().unwrap_or("unknown_shell"); env::var("SHELL").unwrap_or_else(|_| "unknown_shell".to_owned());
shell_name.to_string() let shell_name = shell_path.rsplit('/').next().unwrap_or("unknown_shell");
shell_name.to_owned()
} }
pub fn get_root_disk_usage() -> Result<String, io::Error> { pub fn get_root_disk_usage() -> Result<String, io::Error> {
let vfs = statvfs("/")?; let vfs = statvfs("/")?;
let block_size = vfs.block_size() as u64; let block_size = vfs.block_size() as u64;
let total_blocks = vfs.blocks(); let total_blocks = vfs.blocks();
let available_blocks = vfs.blocks_available(); let available_blocks = vfs.blocks_available();
let total_size = block_size * total_blocks; let total_size = block_size * total_blocks;
let used_size = total_size - (block_size * available_blocks); let used_size = total_size - (block_size * available_blocks);
let total_size = total_size as f64 / (1024.0 * 1024.0 * 1024.0); let total_size = total_size as f64 / (1024.0 * 1024.0 * 1024.0);
let used_size = used_size as f64 / (1024.0 * 1024.0 * 1024.0); let used_size = used_size as f64 / (1024.0 * 1024.0 * 1024.0);
let usage = (used_size / total_size) * 100.0; let usage = (used_size / total_size) * 100.0;
Ok(format!( Ok(format!(
"{used_size:.2} GiB / {total_size:.2} GiB ({cyan}{usage:.0}%{reset})", "{used_size:.2} GiB / {total_size:.2} GiB ({cyan}{usage:.0}%{reset})",
cyan = COLORS.cyan, cyan = COLORS.cyan,
reset = COLORS.reset, reset = COLORS.reset,
)) ))
} }
pub fn get_memory_usage() -> Result<String, io::Error> { pub fn get_memory_usage() -> Result<String, io::Error> {
fn parse_memory_info() -> Result<(f64, f64), io::Error> { fn parse_memory_info() -> Result<(f64, f64), io::Error> {
let mut total_memory_kb = 0.0; let mut total_memory_kb = 0.0;
let mut available_memory_kb = 0.0; let mut available_memory_kb = 0.0;
let mut meminfo = String::with_capacity(2048); let mut meminfo = String::with_capacity(2048);
File::open("/proc/meminfo")?.read_to_string(&mut meminfo)?; File::open("/proc/meminfo")?.read_to_string(&mut meminfo)?;
for line in meminfo.lines() { for line in meminfo.lines() {
let mut split = line.split_whitespace(); let mut split = line.split_whitespace();
match split.next().unwrap_or_default() { match split.next().unwrap_or_default() {
"MemTotal:" => total_memory_kb = split.next().unwrap_or("0").parse().unwrap_or(0.0), "MemTotal:" => {
"MemAvailable:" => { total_memory_kb = split.next().unwrap_or("0").parse().unwrap_or(0.0)
available_memory_kb = split.next().unwrap_or("0").parse().unwrap_or(0.0); },
// MemTotal comes before MemAvailable, stop parsing "MemAvailable:" => {
break; available_memory_kb =
} split.next().unwrap_or("0").parse().unwrap_or(0.0);
_ => (), // MemTotal comes before MemAvailable, stop parsing
} break;
} },
_ => (),
let total_memory_gb = total_memory_kb / 1024.0 / 1024.0; }
let available_memory_gb = available_memory_kb / 1024.0 / 1024.0;
let used_memory_gb = total_memory_gb - available_memory_gb;
Ok((used_memory_gb, total_memory_gb))
} }
let (used_memory, total_memory) = parse_memory_info()?; let total_memory_gb = total_memory_kb / 1024.0 / 1024.0;
let percentage_used = (used_memory / total_memory * 100.0).round() as u64; let available_memory_gb = available_memory_kb / 1024.0 / 1024.0;
let used_memory_gb = total_memory_gb - available_memory_gb;
Ok(format!( Ok((used_memory_gb, total_memory_gb))
"{used_memory:.2} GiB / {total_memory:.2} GiB ({cyan}{percentage_used}%{reset})", }
cyan = COLORS.cyan,
reset = COLORS.reset, let (used_memory, total_memory) = parse_memory_info()?;
)) let percentage_used = (used_memory / total_memory * 100.0).round() as u64;
Ok(format!(
"{used_memory:.2} GiB / {total_memory:.2} GiB \
({cyan}{percentage_used}%{reset})",
cyan = COLORS.cyan,
reset = COLORS.reset,
))
} }

View file

@ -1,40 +1,40 @@
use std::{io, mem::MaybeUninit}; use std::{io, mem::MaybeUninit};
pub fn get_current() -> Result<String, io::Error> { pub fn get_current() -> Result<String, io::Error> {
let uptime_seconds = { let uptime_seconds = {
let mut info = MaybeUninit::uninit(); let mut info = MaybeUninit::uninit();
if unsafe { libc::sysinfo(info.as_mut_ptr()) } != 0 { if unsafe { libc::sysinfo(info.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error()); return Err(io::Error::last_os_error());
} }
unsafe { info.assume_init().uptime as u64 } unsafe { info.assume_init().uptime as u64 }
}; };
let days = uptime_seconds / 86400; let days = uptime_seconds / 86400;
let hours = (uptime_seconds / 3600) % 24; let hours = (uptime_seconds / 3600) % 24;
let minutes = (uptime_seconds / 60) % 60; let minutes = (uptime_seconds / 60) % 60;
let mut result = String::with_capacity(32); let mut result = String::with_capacity(32);
if days > 0 { if days > 0 {
result.push_str(&days.to_string()); result.push_str(&days.to_string());
result.push_str(if days == 1 { " day" } else { " days" }); result.push_str(if days == 1 { " day" } else { " days" });
}
if hours > 0 {
if !result.is_empty() {
result.push_str(", ");
} }
if hours > 0 { result.push_str(&hours.to_string());
if !result.is_empty() { result.push_str(if hours == 1 { " hour" } else { " hours" });
result.push_str(", "); }
} if minutes > 0 {
result.push_str(&hours.to_string()); if !result.is_empty() {
result.push_str(if hours == 1 { " hour" } else { " hours" }); result.push_str(", ");
}
if minutes > 0 {
if !result.is_empty() {
result.push_str(", ");
}
result.push_str(&minutes.to_string());
result.push_str(if minutes == 1 { " minute" } else { " minutes" });
}
if result.is_empty() {
result.push_str("less than a minute");
} }
result.push_str(&minutes.to_string());
result.push_str(if minutes == 1 { " minute" } else { " minutes" });
}
if result.is_empty() {
result.push_str("less than a minute");
}
Ok(result) Ok(result)
} }