Luna/apps/ls.cpp
apio 7d69ac56e2
All checks were successful
Build and test / build (push) Successful in 1m41s
apps+libos+shell+wind: Correct a bunch of format strings
2024-03-29 14:42:38 +01:00

246 lines
8.5 KiB
C++

#include <grp.h>
#include <luna/Sort.h>
#include <luna/StringBuilder.h>
#include <luna/Units.h>
#include <os/ArgumentParser.h>
#include <os/Directory.h>
#include <os/File.h>
#include <os/FileSystem.h>
#include <os/Mode.h>
#include <pwd.h>
#include <unistd.h>
void find_user_and_group(struct stat& st, StringView& owner, StringView& group)
{
auto* pw = getpwuid(st.st_uid);
if (!pw) owner = "???";
else
owner = pw->pw_name;
auto* grp = getgrgid(st.st_gid);
if (!grp) group = "???";
else
group = grp->gr_name;
}
int sort_name(const os::Directory::Entry* a, const os::Directory::Entry* b)
{
return String::compare(&a->name, &b->name);
}
int sort_size(const os::Directory::Entry* a, const os::Directory::Entry* b)
{
return (a->size < b->size) ? -1 : ((a->size == b->size) ? 0 : 1);
}
int sort_time(const os::Directory::Entry* a, const os::Directory::Entry* b)
{
return (a->mtime < b->mtime) ? -1 : ((a->mtime == b->mtime) ? 0 : 1);
}
static int (*sort_function)(const os::Directory::Entry*, const os::Directory::Entry*) = sort_name;
int sort_reverse(const os::Directory::Entry* a, const os::Directory::Entry* b)
{
int rc = sort_function(a, b);
if (rc < 0) return 1;
if (rc > 0) return -1;
return 0;
}
#define RESET_COLORS "\x1b[m"
#define SYMLINK_COLOR "\x1b[36m"
#define FILE_COLOR "\x1b[1;32m"
#define DIR_COLOR "\x1b[1;34m"
#define SOCKET_COLOR "\x1b[33m"
#define SPECIAL_COLOR "\x1b[35m"
#define STICKY_COLOR "\x1b[30;1;42m"
#define SETUID_COLOR "\x1b[30;1;41m"
#define EXEC_COLOR "\x1b[1;31m"
static const char* file_type_color(const os::Directory::Entry& entry)
{
if (entry.mode & S_ISVTX) return STICKY_COLOR;
if (entry.mode & S_ISUID || entry.mode & S_ISGID) return SETUID_COLOR;
switch (entry.mode & S_IFMT)
{
case S_IFREG: return entry.mode & S_IXUSR ? EXEC_COLOR : FILE_COLOR;
case S_IFDIR: return DIR_COLOR;
case S_IFLNK: return SYMLINK_COLOR;
case S_IFSOCK: return SOCKET_COLOR;
default: return SPECIAL_COLOR;
}
}
static Result<String> entry_join(const Vector<os::Directory::Entry>& vec, StringView delim, bool colors)
{
if (vec.size() == 0) return String {};
StringBuilder sb;
if (colors) TRY(sb.add(StringView { file_type_color(vec[0]) }));
TRY(sb.add(vec[0].name));
if (colors) TRY(sb.add(StringView { RESET_COLORS }));
for (usize i = 1; i < vec.size(); i++)
{
TRY(sb.add(delim));
if (colors) TRY(sb.add(StringView { file_type_color(vec[i]) }));
TRY(sb.add(vec[i].name));
if (colors) TRY(sb.add(StringView { RESET_COLORS }));
}
return sb.string();
}
Result<int> luna_main(int argc, char** argv)
{
StringView pathname;
bool show_all { false };
bool show_almost_all { false };
bool long_list { false };
bool human_readable { false };
bool si { false };
bool follow_symlink_args { false };
bool one_per_line { false };
bool list_directories { false };
bool no_colors { false };
StringView sort_type { "name" };
bool reverse_sort { false };
bool should_sort { true };
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.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.add_switch_argument(si, ' ', "si"_sv, "same as -h, but show sizes in powers of 10"_sv);
parser.add_switch_argument(follow_symlink_args, 'H', "dereference-args"_sv,
"follow symbolic links listed as arguments"_sv);
parser.add_switch_argument(one_per_line, '1', ""_sv, "list one file per line"_sv);
parser.add_switch_argument(list_directories, 'd', "directory"_sv, "list directories instead of their contents"_sv);
parser.add_value_argument(sort_type, ' ', "sort"_sv, "sort by name, size or time"_sv);
parser.add_switch_argument(reverse_sort, 'r', "reverse"_sv, "reverse order while sorting"_sv);
parser.add_switch_argument(no_colors, ' ', "no-colors"_sv,
"disable coloring of output (defaults to true when not in a TTY)"_sv);
parser.parse(argc, argv);
Vector<os::Directory::Entry> files;
int dirfd = AT_FDCWD;
SharedPtr<os::Directory> dir;
if (!long_list) follow_symlink_args = true;
if (sort_type == "none"_sv) { should_sort = false; }
else if (sort_type == "name"_sv) { sort_function = sort_name; }
else if (sort_type == "size"_sv) { sort_function = sort_size; }
else if (sort_type == "time"_sv) { sort_function = sort_time; }
else
{
os::eprintln("%s: unknown sort type: %s", argv[0], sort_type.chars());
parser.short_usage(argv[0]);
}
if (os::FileSystem::is_directory(pathname, follow_symlink_args) && !list_directories)
{
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;
files = TRY(dir->list(filter));
}
else if (os::FileSystem::exists(pathname, follow_symlink_args))
{
struct stat st;
TRY(os::FileSystem::stat(pathname, st, false));
os::Directory::Entry entry = {
.name = TRY(String::from_string_view(pathname)),
.mode = st.st_mode,
.size = (usize)st.st_size,
.mtime = st.st_mtime,
};
TRY(files.try_append(move(entry)));
}
else
return err(ENOENT);
if (should_sort)
{
if (reverse_sort) sort(files.begin(), files.end(), sort_reverse);
else
sort(files.begin(), files.end(), sort_function);
}
if (!long_list)
{
auto list = TRY(entry_join(files, one_per_line ? "\n"_sv : " "_sv, !no_colors && isatty(STDIN_FILENO)));
if (!list.is_empty()) os::println("%s", list.chars());
}
else
{
bool colors = !no_colors && isatty(STDIN_FILENO);
for (const auto& file : files)
{
struct stat st;
TRY(os::FileSystem::stat({ dirfd, file.name.view() }, st, false));
auto link = TRY(os::FileSystem::readlink({ dirfd, file.name.view() }));
StringView owner;
StringView group;
find_user_and_group(st, owner, group);
char formatted_mode[11];
os::format_mode(st.st_mode, formatted_mode);
if (!human_readable && !si)
{
if (colors)
{
os::println("%s %lu %4s %4s %10lu %s%s" RESET_COLORS "%s" SYMLINK_COLOR "%s" RESET_COLORS,
formatted_mode, st.st_nlink, owner.chars(), group.chars(), st.st_size,
file_type_color(file), file.name.chars(), link.is_empty() ? "" : " -> ", link.chars());
}
else
{
os::println("%s %lu %4s %4s %10lu %s%s%s", formatted_mode, st.st_nlink, owner.chars(),
group.chars(), st.st_size, file.name.chars(), link.is_empty() ? "" : " -> ",
link.chars());
}
}
else
{
auto size = TRY(to_dynamic_unit(st.st_size, 10, false, si ? Unit::SI : Unit::Binary, false));
if (colors)
{
os::println("%s %lu %4s %4s %6s %s%s" RESET_COLORS "%s" SYMLINK_COLOR "%s" RESET_COLORS,
formatted_mode, st.st_nlink, owner.chars(), group.chars(), size.chars(),
file_type_color(file), file.name.chars(), link.is_empty() ? "" : " -> ", link.chars());
}
else
{
os::println("%s %lu %4s %4s %6s %s%s%s", formatted_mode, st.st_nlink, owner.chars(), group.chars(),
size.chars(), file.name.chars(), link.is_empty() ? "" : " -> ", link.chars());
}
}
}
}
return 0;
}