libos: Add FileSystem

This commit is contained in:
apio 2023-04-13 18:33:04 +02:00
parent bd60c65e17
commit 5df16a9bff
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 91 additions and 0 deletions

View File

@ -6,6 +6,7 @@ set(SOURCES
${HEADERS} ${HEADERS}
src/ArgumentParser.cpp src/ArgumentParser.cpp
src/File.cpp src/File.cpp
src/FileSystem.cpp
src/Main.cpp src/Main.cpp
) )

View File

@ -0,0 +1,21 @@
#pragma once
#include <luna/Result.h>
#include <luna/StringView.h>
#include <sys/types.h>
namespace os
{
namespace FileSystem
{
bool exists(StringView path);
bool is_directory(StringView path);
Result<void> create_directory(StringView path, mode_t mode);
Result<void> remove(StringView path);
Result<String> working_directory();
Result<String> home_directory();
}
}

69
libos/src/FileSystem.cpp Normal file
View File

@ -0,0 +1,69 @@
#include <luna/Ignore.h>
#include <luna/String.h>
#include <os/FileSystem.h>
#include <errno.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);
int _ignore = TRY(Result<int>::from_syscall(rc));
ignore(_ignore);
return {};
}
Result<void> remove(StringView path)
{
long rc = syscall(SYS_unlink, path.chars(), 0);
int _ignore = TRY(Result<int>::from_syscall(rc));
ignore(_ignore);
return {};
}
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);
}
}