From 8b84a0ff69eb4be0d9434da867fcfaccd322d373 Mon Sep 17 00:00:00 2001 From: Marcus Nilsson Date: Fri, 11 Jun 2021 19:38:56 +0200 Subject: [PATCH] Utilities/du: Add -h option Add -h/--human-readable option to du. --- Userland/Utilities/du.cpp | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/Userland/Utilities/du.cpp b/Userland/Utilities/du.cpp index 964eb0c7b9..f1ab20d4a7 100644 --- a/Userland/Utilities/du.cpp +++ b/Userland/Utilities/du.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +31,7 @@ struct DuOption { Status }; + bool human_readable = false; bool all = false; bool apparent_size = false; int threshold = 0; @@ -89,6 +91,7 @@ int parse_args(int argc, char** argv, Vector& files, DuOption& du_option args_parser.set_general_help("Display actual or apparent disk usage of files or directories."); args_parser.add_option(du_option.all, "Write counts for all files, not just directories", "all", 'a'); args_parser.add_option(du_option.apparent_size, "Print apparent sizes, rather than disk usage", "apparent-size", 0); + args_parser.add_option(du_option.human_readable, "Print human-readable sizes", "human-readable", 'h'); args_parser.add_option(max_depth, "Print the total for a directory or file only if it is N or fewer levels below the command line argument", "max-depth", 'd', "N"); args_parser.add_option(summarize, "Display only a total for each argument", "summarize", 's'); args_parser.add_option(du_option.threshold, "Exclude entries smaller than size if positive, or entries greater than size if negative", "threshold", 't', "size"); @@ -163,12 +166,17 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep if ((du_option.threshold > 0 && size < du_option.threshold) || (du_option.threshold < 0 && size > -du_option.threshold)) return 0; - const long long block_size = 1024; - size = size / block_size + (size % block_size != 0); + if (du_option.human_readable) { + out("{}", human_readable_size(size)); + } else { + const long long block_size = 1024; + size = size / block_size + (size % block_size != 0); + out("{}", size); + } - if (du_option.time_type == DuOption::TimeType::NotUsed) - outln("{}\t{}", size, path); - else { + if (du_option.time_type == DuOption::TimeType::NotUsed) { + outln("\t{}", path); + } else { auto time = path_stat.st_mtime; switch (du_option.time_type) { case DuOption::TimeType::Access: @@ -181,7 +189,7 @@ int print_space_usage(const String& path, const DuOption& du_option, int max_dep } const auto formatted_time = Core::DateTime::from_timestamp(time).to_string(); - outln("{}\t{}\t{}", size, formatted_time, path); + outln("\t{}\t{}", formatted_time, path); } return 0;