hb/src/main.rs

139 lines
3.3 KiB
Rust

#![feature(io_error_more, fs_try_exists)]
use clap::{Parser, ArgAction};
mod directory;
mod unit;
use directory::Directory;
use unit::Unit;
use std::process::ExitCode;
#[allow(clippy::struct_excessive_bools)]
#[derive(Parser, Debug, Clone)]
pub struct Args {
#[arg(
short, long, default_value_t = false,
help = "keep going if an error occurs",
long_help = "keep going if an error occurs (ex. unreadable subdirectories in a readable directory)"
)]
persistant: bool,
#[arg(
short, long,
help = "minimize output",
long_help = "print nothing but the total size for all directories, without a newline. Also supresses all error messages",
conflicts_with = "total",
default_value_t = false,
)]
minimal: bool,
#[arg(
short='T', long,
help = "display in tree",
default_value_t = false,
conflicts_with = "minimal",
)]
tree: bool,
#[arg(
short, long,
help = "display the total size",
conflicts_with = "minimal",
default_value_t = false,
)]
total: bool,
#[arg(
short='2', long,
help = "alias for --unit 1024",
default_value_t = false,
conflicts_with_all = ["si","unit"],
)]
base_two: bool,
#[arg(
short='0', long,
help = "alias for --unit 1000",
default_value_t = false,
conflicts_with_all = ["base_two","unit"],
)]
si: bool,
#[arg(
short, long,
help = "unit to print in",
long_help = "printing unit (case insensitive): b = bytes, kb = kilobytes, ki = kibibytes, gb = gigabytes, gi = gibibytes, tb = terabytes, ti = tibibytes",
value_parser = Unit::parse,
default_value_t = Unit::Byte,
conflicts_with_all = ["base_two","si"],
)]
unit: Unit,
#[arg(
value_parser = validate_path,
help = "items to summate",
action = ArgAction::Append,
num_args = 1..
)]
path: Vec<String>,
}
fn validate_path(s: &str) -> Result<String, String> {
// try to access it's metadata, since that is what is used
// to get its length
std::fs::metadata(s)
.map(|_| s.to_string())
.map_err(|e| e.to_string())
}
fn main() -> ExitCode {
let mut args = Args::parse();
if args.base_two {
args.unit = Unit::Kibi;
} else if args.si {
args.unit = Unit::Kilo;
}
let mut total = 0;
for path in args.path {
let dir_structure = match Directory::new(path) {
Ok(ds) => ds,
Err(e) => {
if !args.minimal {
eprintln!("hb: {e}");
}
return ExitCode::FAILURE;
}
};
total += dir_structure.size();
if args.minimal {
// skip printing (this is a matter of indentation)
continue;
}
if args.tree {
println!("{}", dir_structure.display(args.unit));
} else {
println!(
"{}: {}",
dir_structure.path().display(),
dir_structure.scale(args.unit),
);
}
}
let total = args.unit.convert(total);
if args.total {
println!("total: {total}");
}
else if args.minimal {
print!("{total}");
}
ExitCode::SUCCESS
}