Luna/apps/ls.cpp

71 lines
2.0 KiB
C++
Raw Normal View History

#include <os/ArgumentParser.h>
2023-04-28 19:15:41 +00:00
#include <os/Directory.h>
#include <os/File.h>
2023-05-01 18:01:05 +00:00
#include <os/FileSystem.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
2023-03-28 23:07:58 +00:00
2023-04-13 15:04:59 +00:00
Result<int> luna_main(int argc, char** argv)
2023-03-28 23:07:58 +00:00
{
StringView pathname;
bool show_all { false };
bool show_almost_all { false };
2023-05-01 18:01:05 +00:00
bool long_list { 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);
2023-05-01 18:01:05 +00:00
parser.add_switch_argument(long_list, 'l', ""_sv, "use a long listing format"_sv);
parser.parse(argc, argv);
2023-03-28 23:07:58 +00:00
2023-05-01 18:01:05 +00:00
Vector<String> files;
int dirfd = AT_FDCWD;
SharedPtr<os::Directory> dir;
if (os::FileSystem::is_directory(pathname))
{
dir = TRY(os::Directory::open(pathname));
dirfd = dir->fd();
auto filter = os::Directory::Filter::Hidden;
if (show_almost_all) filter = os::Directory::Filter::ParentAndBase;
else if (show_all)
filter = os::Directory::Filter::None;
2023-04-28 19:15:41 +00:00
2023-05-01 18:01:05 +00:00
files = TRY(dir->list(filter));
}
else
{
auto str = TRY(String::from_cstring(pathname.chars()));
TRY(files.try_append(move(str)));
}
2023-03-28 23:07:58 +00:00
2023-05-01 18:01:05 +00:00
if (!long_list)
{
auto list = TRY(String::join(files, " "_sv));
os::println("%s", list.chars());
}
else
{
for (const auto& file : files)
{
struct stat st;
if (fstatat(dirfd, file.chars(), &st, 0) < 0)
{
perror(file.chars());
return 1;
}
2023-04-28 20:41:44 +00:00
2023-05-01 18:01:05 +00:00
os::println("%6o %u %4u %4u %10lu %s", st.st_mode, st.st_nlink, st.st_uid, st.st_gid, st.st_size,
file.chars());
}
}
2023-03-28 23:07:58 +00:00
return 0;
}