Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

free: Implement almost all functions of the free commands #35

Merged
merged 16 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 106 additions & 24 deletions src/uu/free/src/free.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,25 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

mod units;

use clap::arg;
use clap::Arg;
use clap::ArgAction;
use clap::ArgGroup;
use clap::{crate_version, Command};
use std::env;
use std::fs;
use std::io::Error;
use std::process;
use uucore::{error::UResult, format_usage, help_about, help_usage};

use crate::units::UnitMultiplier;

const ABOUT: &str = help_about!("free.md");
const USAGE: &str = help_usage!("free.md");

/// The unit of number is [UnitMultiplier::Bytes]
struct MemInfo {
total: u64,
free: u64,
Expand Down Expand Up @@ -71,6 +78,8 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let matches = uu_app().try_get_matches_from(args)?;
let wide = matches.get_flag("wide");

let human = matches.get_flag("human");

match parse_meminfo() {
Ok(mem_info) => {
let buff_cache = if wide {
Expand All @@ -79,35 +88,64 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
mem_info.buffers + mem_info.cached
};
let cache = if wide { mem_info.cached } else { 0 };
let used = mem_info.total - mem_info.free;
let used = mem_info.total - mem_info.available;

if wide {
println!(" total used free shared buffers cache available");
println!(
"Mem: {:11} {:11} {:11} {:11} {:11} {:11} {:11}",
mem_info.total,
used,
mem_info.free,
mem_info.shared,
buff_cache,
cache + mem_info.reclaimable,
mem_info.available
);
wide_header();
if human {
println!(
"{:8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}",
"Mem:",
to_human(mem_info.total),
to_human(used),
to_human(mem_info.free),
to_human(mem_info.shared),
to_human(buff_cache),
to_human(cache + mem_info.reclaimable),
to_human(mem_info.available)
)
} else {
println!(
"{:8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}",
"Mem:",
mem_info.total,
used,
mem_info.free,
mem_info.shared,
buff_cache,
cache + mem_info.reclaimable,
mem_info.available
)
}
} else {
println!(" total used free shared buff/cache available");
println!(
"Mem: {:11} {:11} {:11} {:11} {:11} {:11}",
mem_info.total,
used,
mem_info.free,
mem_info.shared,
buff_cache + mem_info.reclaimable,
mem_info.available
);
header();
if human {
println!(
"{:8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}",
"Mem:",
to_human(mem_info.total),
to_human(used),
to_human(mem_info.free),
to_human(mem_info.shared),
to_human(buff_cache + mem_info.reclaimable),
to_human(mem_info.available)
)
} else {
println!(
"{:8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}",
"Mem:",
mem_info.total,
used,
mem_info.free,
mem_info.shared,
buff_cache + mem_info.reclaimable,
mem_info.available
)
}
}
println!(
"Swap: {:11} {:11} {:11}",
mem_info.swap_total, mem_info.swap_used, mem_info.swap_free
"{:8}{:>12}{:>12}{:>12}",
"Swap:", mem_info.swap_total, mem_info.swap_used, mem_info.swap_free
);
}
Err(e) => {
Expand All @@ -125,13 +163,38 @@ pub fn uu_app() -> Command {
.about(ABOUT)
.override_usage(format_usage(USAGE))
.infer_long_args(true)
.disable_help_flag(true)
.group(ArgGroup::new("unit").args([
"bytes", "kilo", "mega", "giga", "tera", "peta", "kibi", "mebi", "gibi", "tebi", "pebi",
]))
.args([
arg!(-b --bytes "show output in bytes").action(ArgAction::SetTrue),
arg!( --kilo "show output in kilobytes").action(ArgAction::SetFalse),
arg!( --mega "show output in megabytes").action(ArgAction::SetTrue),
arg!( --giga "show output in gigabytes").action(ArgAction::SetTrue),
arg!( --tera "show output in terabytes").action(ArgAction::SetTrue),
arg!( --peta "show output in petabytes").action(ArgAction::SetTrue),
arg!(-k --kibi "show output in kibibytes").action(ArgAction::SetTrue),
arg!(-m --mebi "show output in mebibytes").action(ArgAction::SetTrue),
arg!(-g --gibi "show output in gibibytes").action(ArgAction::SetTrue),
arg!( --tebi "show output in tebibytes").action(ArgAction::SetTrue),
arg!( --pebi "show output in pebibytes").action(ArgAction::SetTrue),
arg!(-h --human "show human-readable output").action(ArgAction::SetTrue),
// arg!(-L --line "show output on a single line"),
])
.arg(
Arg::new("wide")
.short('w')
.long("wide")
.help("wide output")
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("help")
.long("help")
.action(ArgAction::Help)
.help("display this help and exit"),
)
}

fn parse_meminfo_value(value: &str) -> Result<u64, std::io::Error> {
Expand All @@ -153,3 +216,22 @@ fn parse_meminfo_value(value: &str) -> Result<u64, std::io::Error> {
})
})
}

fn to_human(kb: u64) -> String {
let unit = UnitMultiplier::detect_readable(kb * 1024);
format!("{:.1}{}", &unit.from_byte(kb * 1024), &unit.to_string())
}

fn wide_header() {
println!(
"{:8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}",
" ", "total", "used", "free", "shared", "buffers", "cache", "available",
);
}

fn header() {
println!(
"{:8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}",
" ", "total", "used", "free", "shared", "buff/cache", "available",
)
}
139 changes: 139 additions & 0 deletions src/uu/free/src/units.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
use clap::ArgMatches;
use std::fmt::{self, Display, Formatter};

#[derive(Debug, PartialEq)]
pub(crate) enum UnitMultiplier {
Krysztal112233 marked this conversation as resolved.
Show resolved Hide resolved
Bytes, // BASE UNIT
Kilobytes, // SI:10^3
Megabytes, // SI:10^6
Gigabytes, // SI:10^9
Terabytes, // SI:10^12
Petabytes, // SI:10^15
Kibibytes, // IEC:2^10
Mebibytes, // IEC:2^20
Gibibytes, // IEC:2^30
Tebibytes, // IEC:2^40
Pebibytes, // IEC:2^50
}

impl UnitMultiplier {
pub(crate) fn from_byte(&self, byte: u64) -> f64 {
(byte as f64) * Self::conversion_multiplier(&Self::Bytes, self)
}

pub(crate) fn multiplier(&self) -> u64 {
use crate::units::UnitMultiplier::*;

match self {
Bytes => 1, // BASE
Kilobytes => 1_000, // SI:10^3
Megabytes => 1_000_000, // SI:10^6
Gigabytes => 1_000_000_000, // SI:10^9
Terabytes => 1_000_000_000_000, // SI:10^12
Petabytes => 1_000_000_000_000_000, // SI:10^15
Kibibytes => 1 << 10, // IEC:2^10
Mebibytes => 1 << 20, // IEC:2^20
Gibibytes => 1 << 30, // IEC:2^30
Tebibytes => 1 << 40, // IEC:2^40
Pebibytes => 1 << 50, // IEC:2^50
}
}

// Detecting unit for `-h` and `--human` flag
pub(crate) fn detect_readable(byte: u64) -> UnitMultiplier {
use crate::units::UnitMultiplier::*;

match byte {
0..=1_000 => Bytes,
1_001..=1_000_000 => Kilobytes,
1_000_001..=1_000_000_000 => Mebibytes,
1_000_000_001..=1_000_000_000_000 => Gibibytes,
1_000_000_000_001..=1_000_000_000_000_000 => Tebibytes,
_ => Pebibytes,
}
}

fn conversion_multiplier(from: &Self, to: &Self) -> f64 {
(from.multiplier() as f64) / (to.multiplier() as f64)
}
}

impl Display for UnitMultiplier {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use crate::units::UnitMultiplier::*;
match self {
Bytes => write!(f, "B"),
Kilobytes => write!(f, "KB"),
Megabytes => write!(f, "MB"),
Gigabytes => write!(f, "GB"),
Terabytes => write!(f, "TB"),
Petabytes => write!(f, "PB"),
Kibibytes => write!(f, "Ki"),
Mebibytes => write!(f, "Mi"),
Gibibytes => write!(f, "Gi"),
Tebibytes => write!(f, "Ti"),
Pebibytes => write!(f, "Pi"),
}
}
}

impl From<ArgMatches> for UnitMultiplier {
fn from(item: ArgMatches) -> Self {
use crate::units::UnitMultiplier::*;
match item {
_ if item.get_flag("kilo") => Kilobytes,
_ if item.get_flag("mega") => Megabytes,
_ if item.get_flag("giga") => Gigabytes,
_ if item.get_flag("tera") => Terabytes,
_ if item.get_flag("peta") => Petabytes,
_ if item.get_flag("kibi") => Kibibytes,
_ if item.get_flag("mebi") => Mebibytes,
_ if item.get_flag("gibi") => Gibibytes,
_ if item.get_flag("tebi") => Tebibytes,
_ if item.get_flag("pebi") => Pebibytes,
_ => Bytes,
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_unit_conversion() {
let input = [
(
(UnitMultiplier::Bytes, 1_000_000_000_000_000 as u64),
(UnitMultiplier::Petabytes, 1 as u64),
),
((UnitMultiplier::Bytes, 1), (UnitMultiplier::Bytes, 1)),
(
(UnitMultiplier::Bytes, 1_000),
(UnitMultiplier::Kilobytes, 1),
),
(
(UnitMultiplier::Bytes, 1_000_000),
(UnitMultiplier::Megabytes, 1),
),
];

for ((_, from), (to_unit, to)) in input {
assert_eq!(to_unit.from_byte(from), to as f64)
}
}

#[test]
fn test_detect_readable() {
// Value comes from my computer's `free` outputs.
let input = [
(007_605_510_144, UnitMultiplier::Gigabytes),
(000_148_516_864, UnitMultiplier::Megabytes),
(016_923_955_200, UnitMultiplier::Gigabytes),
];

for (byte, unit) in input {
assert_eq!(UnitMultiplier::detect_readable(byte), unit)
}
}
}
Loading