Luna/apps/ls.cpp

40 lines
1.2 KiB
C++

#include <os/ArgumentParser.h>
#include <os/Directory.h>
#include <stdio.h>
#include <unistd.h>
Result<int> luna_main(int argc, char** argv)
{
StringView pathname;
bool show_all { false };
bool show_almost_all { false };
os::ArgumentParser parser;
parser.add_description("List files contained in a directory (defaults to '.', the current directory)"_sv);
parser.add_system_program_info("ls"_sv);
parser.add_positional_argument(pathname, "directory"_sv, "."_sv);
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.parse(argc, argv);
auto dir = TRY(os::Directory::open(pathname));
auto filter = os::Directory::Filter::Hidden;
if (show_almost_all) filter = os::Directory::Filter::ParentAndBase;
else if (show_all)
filter = os::Directory::Filter::None;
int first_ent = 1;
do {
auto ent = TRY(dir->next(filter));
if (ent.is_empty()) break;
printf(first_ent ? "%s" : " %s", ent.chars());
first_ent = 0;
} while (1);
putchar('\n');
return 0;
}