df: allow sizes with a suffix for --block-size

Fixes #3416
This commit is contained in:
Daniel Hofstetter 2022-04-23 16:44:48 +02:00
parent ed5bd136d4
commit 0f13de4e1a
2 changed files with 29 additions and 3 deletions

View file

@ -6,7 +6,8 @@
use crate::{OPT_BLOCKSIZE, OPT_HUMAN_READABLE_BINARY, OPT_HUMAN_READABLE_DECIMAL};
use clap::ArgMatches;
use std::fmt;
use std::num::ParseIntError;
use uucore::parse_size::{parse_size, ParseSizeError};
/// The first ten powers of 1024.
const IEC_BASES: [u128; 10] = [
@ -107,14 +108,14 @@ impl Default for BlockSize {
}
}
pub(crate) fn block_size_from_matches(matches: &ArgMatches) -> Result<BlockSize, ParseIntError> {
pub(crate) fn block_size_from_matches(matches: &ArgMatches) -> Result<BlockSize, ParseSizeError> {
if matches.is_present(OPT_HUMAN_READABLE_BINARY) {
Ok(BlockSize::HumanReadableBinary)
} else if matches.is_present(OPT_HUMAN_READABLE_DECIMAL) {
Ok(BlockSize::HumanReadableDecimal)
} else if matches.is_present(OPT_BLOCKSIZE) {
let s = matches.value_of(OPT_BLOCKSIZE).unwrap();
Ok(BlockSize::Bytes(s.parse()?))
Ok(BlockSize::Bytes(parse_size(s)?))
} else {
Ok(Default::default())
}

View file

@ -394,6 +394,31 @@ fn test_block_size_1024() {
assert_eq!(get_header(34 * 1024 * 1024 * 1024), "34G-blocks");
}
#[test]
fn test_block_size_with_suffix() {
fn get_header(block_size: &str) -> String {
let output = new_ucmd!()
.args(&["-B", block_size, "--output=size"])
.succeeds()
.stdout_move_str();
output.lines().next().unwrap().to_string()
}
assert_eq!(get_header("K"), "1K-blocks");
assert_eq!(get_header("M"), "1M-blocks");
assert_eq!(get_header("G"), "1G-blocks");
assert_eq!(get_header("1K"), "1K-blocks");
assert_eq!(get_header("1M"), "1M-blocks");
assert_eq!(get_header("1G"), "1G-blocks");
assert_eq!(get_header("1KiB"), "1K-blocks");
assert_eq!(get_header("1MiB"), "1M-blocks");
assert_eq!(get_header("1GiB"), "1G-blocks");
// TODO enable the following asserts when #3193 is resolved
//assert_eq!(get_header("1KB"), "1kB-blocks");
//assert_eq!(get_header("1MB"), "1MB-blocks");
//assert_eq!(get_header("1GB"), "1GB-blocks");
}
#[test]
fn test_output_selects_columns() {
let output = new_ucmd!()