From 5df16a9bffd28b7a64b0e8037646092acb176ef8 Mon Sep 17 00:00:00 2001 From: apio Date: Thu, 13 Apr 2023 18:33:04 +0200 Subject: [PATCH] libos: Add FileSystem --- libos/CMakeLists.txt | 1 + libos/include/os/FileSystem.h | 21 +++++++++++ libos/src/FileSystem.cpp | 69 +++++++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+) create mode 100644 libos/include/os/FileSystem.h create mode 100644 libos/src/FileSystem.cpp diff --git a/libos/CMakeLists.txt b/libos/CMakeLists.txt index 504de652..5bff51fe 100644 --- a/libos/CMakeLists.txt +++ b/libos/CMakeLists.txt @@ -6,6 +6,7 @@ set(SOURCES ${HEADERS} src/ArgumentParser.cpp src/File.cpp + src/FileSystem.cpp src/Main.cpp ) diff --git a/libos/include/os/FileSystem.h b/libos/include/os/FileSystem.h new file mode 100644 index 00000000..a9085527 --- /dev/null +++ b/libos/include/os/FileSystem.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include +#include + +namespace os +{ + namespace FileSystem + { + bool exists(StringView path); + + bool is_directory(StringView path); + + Result create_directory(StringView path, mode_t mode); + + Result remove(StringView path); + + Result working_directory(); + Result home_directory(); + } +} diff --git a/libos/src/FileSystem.cpp b/libos/src/FileSystem.cpp new file mode 100644 index 00000000..838556e9 --- /dev/null +++ b/libos/src/FileSystem.cpp @@ -0,0 +1,69 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 create_directory(StringView path, mode_t mode) + { + long rc = syscall(SYS_mkdir, path.chars(), mode); + int _ignore = TRY(Result::from_syscall(rc)); + + ignore(_ignore); + + return {}; + } + + Result remove(StringView path) + { + long rc = syscall(SYS_unlink, path.chars(), 0); + int _ignore = TRY(Result::from_syscall(rc)); + + ignore(_ignore); + + return {}; + } + + Result working_directory() + { + char* ptr = getcwd(NULL, 0); + if (!ptr) return err(errno); + return String { ptr }; + } + + Result 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); + } +}