Luna/utils/stat.cpp

57 lines
1.8 KiB
C++
Raw Permalink Normal View History

2023-04-21 16:04:17 +00:00
#include <os/ArgumentParser.h>
2023-05-12 21:47:20 +00:00
#include <os/FileSystem.h>
#include <os/Mode.h>
2023-04-21 16:04:17 +00:00
#include <stdio.h>
#include <time.h>
2023-04-21 16:04:17 +00:00
static const char* file_type(mode_t mode)
{
switch (mode & S_IFMT)
{
case S_IFREG: return "regular file";
case S_IFDIR: return "directory";
case S_IFCHR: return "character special device";
case S_IFBLK: return "block special device";
case S_IFLNK: return "symbolic link";
case S_IFIFO: return "pipe";
2023-12-04 19:42:31 +00:00
case S_IFSOCK: return "socket";
2023-04-21 16:04:17 +00:00
default: return "unknown file type";
}
}
Result<int> luna_main(int argc, char** argv)
{
StringView path;
bool follow_symlinks { false };
2023-04-21 16:04:17 +00:00
os::ArgumentParser parser;
2023-07-24 17:17:36 +00:00
parser.add_description("Display file metadata.");
parser.add_system_program_info("stat"_sv);
2023-04-21 16:04:17 +00:00
parser.add_positional_argument(path, "path", true);
parser.add_switch_argument(follow_symlinks, 'L', "dereference"_sv, "follow symlinks");
2023-04-21 16:04:17 +00:00
parser.parse(argc, argv);
struct stat st;
TRY(os::FileSystem::stat(path, st, follow_symlinks));
2023-04-21 16:04:17 +00:00
char buf[11];
os::format_mode(st.st_mode, buf);
char atime[256];
strftime(atime, sizeof(atime), "%Y-%m-%d %H:%M:%S", gmtime(&st.st_atim.tv_sec));
char mtime[256];
strftime(mtime, sizeof(mtime), "%Y-%m-%d %H:%M:%S", gmtime(&st.st_mtim.tv_sec));
char ctime[256];
strftime(ctime, sizeof(ctime), "%Y-%m-%d %H:%M:%S", gmtime(&st.st_ctim.tv_sec));
printf(" File: %s\n", path.chars());
printf(" Size: %zu (%s)\n", st.st_size, file_type(st.st_mode));
printf(" Inode: %lu Links: %lu\n", st.st_ino, st.st_nlink);
printf(" Mode: (%#o/%s) UID: %u GID: %u\n", st.st_mode & ~S_IFMT, buf, st.st_uid, st.st_gid);
printf("Access: %s.%.9ld\n", atime, st.st_atim.tv_nsec);
printf("Modify: %s.%.9ld\n", mtime, st.st_mtim.tv_nsec);
printf("Change: %s.%.9ld\n", ctime, st.st_ctim.tv_nsec);
2023-04-21 16:04:17 +00:00
return 0;
}