You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

83 lines
2.1 KiB

use crate::builtins::{Builtin, BuiltinConfig};
use crate::error::ShellError;
use colored::Colorize;
use sysinfo::{CpuExt, System, SystemExt};
use uname::uname;
use whoami::{hostname, username};
pub struct Fetch;
impl Builtin for Fetch {
fn execute(&mut self, _: &mut BuiltinConfig, _: Vec<String>) -> Result<(), ShellError> {
let mut sys = System::new();
sys.refresh_all();
let line = "-".repeat(username().len() + hostname().len() + 1);
println!(
"\n{}{}{}",
username().bright_green().bold(),
"@".bold(),
hostname().bright_green().bold()
);
println!("{}", line);
println!(
"{} {} {}",
"OS".bright_blue().bold(),
sys.name().unwrap_or_default(),
uname().unwrap().machine
);
println!(
"{} {}",
"KERNEL".yellow().bold(),
sys.kernel_version().unwrap_or_default()
);
println!("{} {}", "UPTIME".red().bold(), format_uptime(sys.uptime()));
println!("{} {}", "CPU".magenta().bold(), sys.cpus()[0].brand());
println!(
"{} {}MiB / {}MiB",
"MEMORY".cyan().bold(),
bytes_to_mebi_bytes(sys.used_memory()),
bytes_to_mebi_bytes(sys.total_memory())
);
Ok(())
}
}
fn format_uptime(uptime: u64) -> String {
let h = uptime / 3600;
let m = (uptime - h * 3600) / 60;
let s = uptime - (h * 3600 + m * 60);
format!("{:.0}h {:.0}m {:.0}s", h, m, s)
}
fn bytes_to_mebi_bytes(bytes: u64) -> u64 {
bytes / 1024 / 1024
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_uptime_seconds() {
assert_eq!(format_uptime(35), "0h 0m 35s");
}
#[test]
fn test_format_uptime_minutes() {
assert_eq!(format_uptime(135), "0h 2m 15s");
}
#[test]
fn test_format_uptime_hours() {
assert_eq!(format_uptime(3735), "1h 2m 15s");
}
#[test]
fn test_bytes_to_mebi_bytes() {
assert_eq!(bytes_to_mebi_bytes(7628144640), 7274);
}
}