ls: Add the --human-readable flag

This commit is contained in:
apio 2023-05-13 11:15:28 +02:00
parent 300d68088b
commit a5ad8e16de
Signed by: apio
GPG Key ID: B8A7D06E42258954

View File

@ -1,4 +1,5 @@
#include <grp.h>
#include <luna/Units.h>
#include <os/ArgumentParser.h>
#include <os/Directory.h>
#include <os/File.h>
@ -61,6 +62,7 @@ Result<int> luna_main(int argc, char** argv)
bool show_all { false };
bool show_almost_all { false };
bool long_list { false };
bool human_readable { false };
os::ArgumentParser parser;
parser.add_description("List files contained in a directory (defaults to '.', the current directory)"_sv);
@ -69,6 +71,8 @@ Result<int> luna_main(int argc, char** argv)
parser.add_switch_argument(show_all, 'a', "all"_sv, "also list hidden files (whose filename begins with a dot)"_sv);
parser.add_switch_argument(show_almost_all, 'A', "almost-all"_sv, "list all files except '.' and '..'"_sv);
parser.add_switch_argument(long_list, 'l', ""_sv, "use a long listing format"_sv);
parser.add_switch_argument(human_readable, 'h', "human-readable"_sv,
"with -l, show human-readable sizes e.g. 2KiB, 6GiB"_sv);
parser.parse(argc, argv);
Vector<String> files;
@ -112,8 +116,17 @@ Result<int> luna_main(int argc, char** argv)
TRY(find_user_and_group(st, owner, group));
os::println("%6o %u %4s %4s %10lu %s", st.st_mode, st.st_nlink, owner.chars(), group.chars(), st.st_size,
file.chars());
if (!human_readable)
{
os::println("%6o %u %4s %4s %10lu %s", st.st_mode, st.st_nlink, owner.chars(), group.chars(),
st.st_size, file.chars());
}
else
{
auto size = TRY(to_dynamic_unit(st.st_size));
os::println("%6o %u %4s %4s %10s %s", st.st_mode, st.st_nlink, owner.chars(), group.chars(),
size.chars(), file.chars());
}
}
}