Luna/libos/src/FileSystem.cpp
apio 02f8a50b9d
All checks were successful
continuous-integration/drone/push Build is passing
kernel: Replace unlink() with unlinkat()
2023-04-18 19:36:29 +02:00

72 lines
1.5 KiB
C++

#include <luna/Ignore.h>
#include <luna/String.h>
#include <os/FileSystem.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
namespace os::FileSystem
{
bool exists(StringView path)
{
struct stat st;
if (stat(path.chars(), &st) < 0) return false;
return true;
}
bool is_directory(StringView path)
{
struct stat st;
if (stat(path.chars(), &st) < 0) return false;
return S_ISDIR(st.st_mode);
}
Result<void> create_directory(StringView path, mode_t mode)
{
long rc = syscall(SYS_mkdir, path.chars(), mode);
return Result<void>::from_syscall(rc);
}
Result<void> remove(StringView path)
{
long rc = syscall(SYS_unlinkat, AT_FDCWD, path.chars(), 0);
return Result<void>::from_syscall(rc);
}
Result<String> working_directory()
{
char* ptr = getcwd(NULL, 0);
if (!ptr) return err(errno);
return String { ptr };
}
Result<String> home_directory()
{
char* home = getenv("HOME");
if (home) return String::from_cstring(home);
struct passwd* pw = getpwuid(getuid());
if (!pw) return err(ENOENT);
return String::from_cstring(pw->pw_dir);
}
Result<void> change_directory(StringView path)
{
long rc = syscall(SYS_chdir, path.chars());
return Result<void>::from_syscall(rc);
}
}