Luna/apps/ls.cpp
apio eb58b4acc8
All checks were successful
continuous-integration/drone/push Build is passing
libos: Add support for --help to ArgumentParser
2023-04-19 19:16:45 +02:00

43 lines
1.2 KiB
C++

#include <os/ArgumentParser.h>
#include <dirent.h>
#include <fcntl.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_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);
DIR* dp = opendir(pathname.chars());
if (!dp)
{
perror("opendir");
return 1;
}
int first_ent = 1;
do {
struct dirent* ent = readdir(dp);
if (!ent) break;
if (show_almost_all && (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))) continue;
if (!show_all && !show_almost_all && *ent->d_name == '.') continue;
printf(first_ent ? "%s" : " %s", ent->d_name);
first_ent = 0;
} while (1);
putchar('\n');
closedir(dp);
return 0;
}