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

  1. use crate::builtins::{Builtin, BuiltinConfig};
  2. use crate::error::ShellError;
  3. use colored::Colorize;
  4. use sysinfo::{CpuExt, System, SystemExt};
  5. use uname::uname;
  6. use whoami::{hostname, username};
  7. pub struct Fetch;
  8. impl Builtin for Fetch {
  9. fn execute(&mut self, _: &mut BuiltinConfig, _: Vec<String>) -> Result<(), ShellError> {
  10. let mut sys = System::new();
  11. sys.refresh_all();
  12. let line = "-".repeat(username().len() + hostname().len() + 1);
  13. println!(
  14. "\n{}{}{}",
  15. username().bright_green().bold(),
  16. "@".bold(),
  17. hostname().bright_green().bold()
  18. );
  19. println!("{}", line);
  20. println!(
  21. "{} {} {}",
  22. "OS".bright_blue().bold(),
  23. sys.name().unwrap_or_default(),
  24. uname().unwrap().machine
  25. );
  26. println!(
  27. "{} {}",
  28. "KERNEL".yellow().bold(),
  29. sys.kernel_version().unwrap_or_default()
  30. );
  31. println!("{} {}", "UPTIME".red().bold(), format_uptime(sys.uptime()));
  32. println!("{} {}", "CPU".magenta().bold(), sys.cpus()[0].brand());
  33. println!(
  34. "{} {}MiB / {}MiB",
  35. "MEMORY".cyan().bold(),
  36. bytes_to_mebi_bytes(sys.used_memory()),
  37. bytes_to_mebi_bytes(sys.total_memory())
  38. );
  39. Ok(())
  40. }
  41. }
  42. fn format_uptime(uptime: u64) -> String {
  43. let h = uptime / 3600;
  44. let m = (uptime - h * 3600) / 60;
  45. let s = uptime - (h * 3600 + m * 60);
  46. format!("{:.0}h {:.0}m {:.0}s", h, m, s)
  47. }
  48. fn bytes_to_mebi_bytes(bytes: u64) -> u64 {
  49. bytes / 1024 / 1024
  50. }
  51. #[cfg(test)]
  52. mod tests {
  53. use super::*;
  54. #[test]
  55. fn test_format_uptime_seconds() {
  56. assert_eq!(format_uptime(35), "0h 0m 35s");
  57. }
  58. #[test]
  59. fn test_format_uptime_minutes() {
  60. assert_eq!(format_uptime(135), "0h 2m 15s");
  61. }
  62. #[test]
  63. fn test_format_uptime_hours() {
  64. assert_eq!(format_uptime(3735), "1h 2m 15s");
  65. }
  66. #[test]
  67. fn test_bytes_to_mebi_bytes() {
  68. assert_eq!(bytes_to_mebi_bytes(7628144640), 7274);
  69. }
  70. }