Created
April 28, 2020 21:59
-
-
Save NBonaparte/531d01e24a9b00828a54c3d84891b0b5 to your computer and use it in GitHub Desktop.
gets arch package sizes and sorts in increasing order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::error::Error; | |
use std::fs::{File, read_dir}; | |
use std::io::{BufRead, BufReader}; | |
use std::cmp::Ordering; | |
use std::fmt; | |
#[derive(Eq)] | |
struct Package { | |
name: String, | |
size: usize, | |
} | |
impl Ord for Package { | |
fn cmp(&self, other: &Self) -> Ordering { | |
self.size.cmp(&other.size) | |
} | |
} | |
impl PartialOrd for Package { | |
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | |
Some(self.cmp(other)) | |
} | |
} | |
impl PartialEq for Package { | |
fn eq(&self, other: &Self) -> bool { | |
self.size == other.size | |
} | |
} | |
impl fmt::Display for Package { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
if self.size > 2_usize.pow(30) { | |
write!(f, "{:>5.1} GiB", self.size as f32 / 2_usize.pow(30) as f32)?; | |
} else if self.size > 2_usize.pow(20) { | |
write!(f, "{:>5} MiB", self.size / 2_usize.pow(20))?; | |
} else if self.size > 2_usize.pow(10) { | |
write!(f, "{:>5} KiB", self.size / 2_usize.pow(10))?; | |
} else { | |
write!(f, "{:>5} B", self.size)?; | |
} | |
write!(f, ": {}", self.name) | |
} | |
} | |
fn main() -> Result<(), Box<dyn Error>> { | |
let pkgs = read_dir("/var/lib/pacman/local/")?; | |
let mut pkg_data: Vec<Package> = Vec::with_capacity(2048); | |
for pkg in pkgs { | |
let pkg = pkg?; | |
if pkg.file_type()?.is_dir() { | |
let mut desc_path = pkg.path(); | |
desc_path.push("desc"); | |
let desc = File::open(desc_path)?; | |
let reader = BufReader::new(desc); | |
let mut lines = reader.lines().skip_while(|line| line.as_ref().unwrap() != "%SIZE%"); | |
if let Some(size_str) = lines.nth(1) { | |
let size_str = size_str?; | |
let size = size_str.parse::<usize>()?; | |
pkg_data.push(Package{name: pkg.file_name().into_string().unwrap(), size}); | |
} | |
} | |
} | |
pkg_data.sort(); | |
for i in pkg_data { | |
println!("{}", i); | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment