ls: Show file modes visually
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-05-26 18:22:50 +02:00
parent 4dcee8f828
commit 38fae0c97b
Signed by: apio
GPG Key ID: B8A7D06E42258954
4 changed files with 48 additions and 2 deletions

View File

@ -4,6 +4,7 @@
#include <os/Directory.h>
#include <os/File.h>
#include <os/FileSystem.h>
#include <os/Mode.h>
#include <pwd.h>
void find_user_and_group(struct stat& st, StringView& owner, StringView& group)
@ -92,15 +93,18 @@ Result<int> luna_main(int argc, char** argv)
find_user_and_group(st, owner, group);
char formatted_mode[11];
os::format_mode(st.st_mode, formatted_mode);
if (!human_readable && !si)
{
os::println("%6o %u %4s %4s %10lu %s%s%s", st.st_mode, st.st_nlink, owner.chars(), group.chars(),
os::println("%s %u %4s %4s %10lu %s%s%s", formatted_mode, st.st_nlink, owner.chars(), group.chars(),
st.st_size, file.chars(), link.is_empty() ? "" : " -> ", link.chars());
}
else
{
auto size = TRY(to_dynamic_unit(st.st_size, 10, false, si ? Unit::SI : Unit::Binary, false));
os::println("%6o %u %4s %4s %6s %s%s%s", st.st_mode, st.st_nlink, owner.chars(), group.chars(),
os::println("%s %u %4s %4s %6s %s%s%s", formatted_mode, st.st_nlink, owner.chars(), group.chars(),
size.chars(), file.chars(), link.is_empty() ? "" : " -> ", link.chars());
}
}

View File

@ -11,6 +11,7 @@ set(SOURCES
src/Directory.cpp
src/Main.cpp
src/Path.cpp
src/Mode.cpp
)
add_library(os ${SOURCES})

8
libos/include/os/Mode.h Normal file
View File

@ -0,0 +1,8 @@
#pragma once
#include <sys/types.h>
namespace os
{
void format_mode(mode_t mode, char out[11]);
}

33
libos/src/Mode.cpp Normal file
View File

@ -0,0 +1,33 @@
#include <os/Mode.h>
#include <sys/stat.h>
namespace os
{
static char filetype(mode_t mode)
{
if (S_ISREG(mode)) return '-';
if (S_ISDIR(mode)) return 'd';
if (S_ISCHR(mode)) return 'c';
if (S_ISLNK(mode)) return 'l';
if (S_ISFIFO(mode)) return 'p';
return '?';
}
void format_mode(mode_t mode, char out[11])
{
out[0] = filetype(mode);
out[1] = (mode & S_IRUSR) ? 'r' : '-';
out[2] = (mode & S_IWUSR) ? 'w' : '-';
out[3] = (mode & S_ISUID) ? ((mode & S_IXUSR) ? 's' : 'S') : ((mode & S_IXUSR) ? 'x' : '-');
out[4] = (mode & S_IRGRP) ? 'r' : '-';
out[5] = (mode & S_IWGRP) ? 'w' : '-';
out[6] = (mode & S_ISGID) ? ((mode & S_IXGRP) ? 's' : 'S') : ((mode & S_IXGRP) ? 'x' : '-');
out[7] = (mode & S_IROTH) ? 'r' : '-';
out[8] = (mode & S_IWOTH) ? 'w' : '-';
// FIXME: Support the sticky bit.
out[9] = (mode & S_IXOTH) ? 'x' : '-';
out[10] = '\0';
}
}