10#include <nlohmann/json.hpp>
11#include <SDL3/SDL_misc.h>
21 std::optional<std::string>
extension(
const std::string& filepath)
noexcept
23 const auto path = std::filesystem::path(filepath);
24 if (path.has_extension())
26 return std::make_optional(path.extension().string());
32 std::expected<std::string, FileError>
read(
const std::string& filepath)
34 const auto path = std::filesystem::path(filepath);
35 if (!std::filesystem::exists(path))
37 return std::unexpected(
FileError(
"read",
"File does not exist.", path));
40 if (!std::filesystem::is_regular_file(path))
42 return std::unexpected(
FileError(
"read",
"Path is an irregular file or a directory", path));
45 std::ifstream input {path, std::ifstream::in};
48 return std::unexpected(
FileError(
"read",
"Permission denied.", path));
51 std::string buffer(std::filesystem::file_size(path),
'\0');
52 input.read(buffer.data(), buffer.size());
56 return std::unexpected(
FileError(
"read",
"Failed to read file.", path));
62 std::optional<FileError>
write(
const std::string& filepath,
const std::string& data)
64 const auto path = std::filesystem::path(filepath);
65 if (std::filesystem::exists(path))
67 if (std::filesystem::is_directory(path))
69 return std::make_optional(
FileError(
"write",
"Tried to write to a directory not a file.", path));
73 std::ofstream ofs {path, std::ofstream::out | std::ofstream::trunc};
76 return std::make_optional(
FileError(
"write",
"Permission denied.", path));
83 return std::make_optional(
FileError(
"write",
"Failed to write into file.", path));
89 std::optional<nlohmann::json>
read_json(
const std::string& filepath)
94 return std::make_optional(nlohmann::json::parse(
read.value()));
103 bool write_json(
const std::string& filepath,
const nlohmann::json& json)
117 if (!SDL_OpenURL(url.c_str()))
#define GALAXY_LOG(level, msg,...)
Stores information about a File I/O error.
std::optional< FileError > write(const std::string &filepath, const std::string &data)
Writes a non-binary file to disk.
void open_url(const std::string &url) noexcept
Open URL in default webbrowser.
std::optional< std::string > extension(const std::string &filepath) noexcept
Get a file or path's extension.
bool write_json(const std::string &filepath, const nlohmann::json &json)
Write json to disk.
std::expected< std::string, FileError > read(const std::string &filepath)
Read a non-binary file on disk.
std::optional< nlohmann::json > read_json(const std::string &filepath)
Read a json file from disk.