feat(system,config,sqlite): implement VL-001, VL-003, VL-010, VL-011

This commit is contained in:
faumaray committed 2026-11-26 20:45:52 +03:00
1 parent adfc8548dc
commit b50131f52e
14 files changed
+2660 -139

No files matched your search

+85 -5
View File
@@ -2,7 +2,10 @@
#include <Void/Core/Meta.hpp>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
@@ -11,23 +14,56 @@
namespace Void::Argparse
{
enum class ParseOutcome : std::uint8_t {
Ok,
Help,
Error,
};
struct ParseResult {
ParseOutcome outcome{ParseOutcome::Ok};
std::string message{};
std::vector<std::string> matched_command_path{};
[[nodiscard]] bool ok() const noexcept
{
return outcome == ParseOutcome::Ok;
}
[[nodiscard]] bool is_help() const noexcept
{
return outcome == ParseOutcome::Help;
}
[[nodiscard]] bool is_error() const noexcept
{
return outcome == ParseOutcome::Error;
}
};
// ── Parser
// ────────────────────────────────────────────────────────────────────
// Fluent command-line argument parser.
//
// Supports:
// --flag, -f boolean flag (default false, set to true by
// presence)
// presence)
// --key=value option with value (= or space separator)
// --key value option with value
// option_many(...) repeatable option collecting all occurrences
// subcommand(...) nested subcommand parsers (e.g. "compdb use")
// positional args collected in declaration order
// --help / -h auto-generated help text
// --help / -h auto-generated help text (ParseOutcome::Help)
class Parser
{
public:
explicit Parser(std::string program, std::string description = {});
~Parser();
Parser(const Parser&) = delete;
Parser& operator=(const Parser&) = delete;
Parser(Parser&&) noexcept;
Parser& operator=(Parser&&) noexcept;
// Add a boolean flag.
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name
@@ -43,6 +79,12 @@ namespace Void::Argparse
std::string_view description,
std::optional<std::string>& out);
// Add a repeatable option collecting all occurrences into `out`.
Parser& option_many(std::string_view long_name,
std::string_view short_name,
std::string_view description,
std::vector<std::string>& out);
// Add an option with a default value. out is always set after
// parse().
Parser& option_default(std::string_view long_name,
@@ -55,7 +97,28 @@ namespace Void::Argparse
Parser& positional(std::string_view name,
std::string_view description, std::string& out);
// Parse argc/argv. Returns error message on failure.
// Add a variadic trailing positional argument list.
Parser& positional_many(std::string_view name,
std::string_view description,
std::vector<std::string>& out,
bool required = false);
// Register a nested subcommand and return a reference to its
// Parser. The returned reference remains valid for the lifetime of
// the parent Parser.
Parser& subcommand(std::string name, std::string description = {},
std::function<void()> on_selected = {});
// Control whether a parser with subcommands requires one to be
// selected (default: true when any subcommand is registered).
Parser& require_subcommand(bool required = true) noexcept;
// Parse argc/argv with explicit Ok / Help / Error classification.
[[nodiscard]] ParseResult
parse_detailed(int argc, const char* const* argv) const;
// Parse argc/argv. Returns error message (or help text) on
// non-Ok outcome for 1.x compatibility.
[[nodiscard]] std::expected<void, std::string>
parse(int argc, const char* const* argv) const;
@@ -70,18 +133,33 @@ namespace Void::Argparse
};
struct OptionEntry {
std::string lng, sht, desc, def;
std::optional<std::string>* out_opt;
std::string* out_str;
std::optional<std::string>* out_opt{nullptr};
std::string* out_str{nullptr};
std::vector<std::string>* out_many{nullptr};
};
struct PosEntry {
std::string name, desc;
std::string* out;
};
struct MultiPosEntry {
std::string name, desc;
std::vector<std::string>* out{nullptr};
bool required{false};
};
struct SubcommandEntry {
std::string name;
std::unique_ptr<Parser> parser;
std::function<void()> on_selected;
};
std::string program_, description_;
std::vector<FlagEntry> flags_;
std::vector<OptionEntry> options_;
std::vector<PosEntry> positionals_;
std::optional<MultiPosEntry> positional_many_;
std::vector<SubcommandEntry> subcommands_;
bool has_explicit_require_sub_{false};
bool require_subcommand_{true};
};
// ── reflective options struct
@@ -147,6 +225,8 @@ namespace Void::Argparse
parser.flag(lng, sht, desc, out.[:m:]);
} else if constexpr (Void::Meta::is_optional_v<MT>) {
parser.option(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
parser.option_many(lng, sht, desc, out.[:m:]);
} else if constexpr (std::same_as<MT, std::string>) {
const std::string def = out.[:m:];
parser.option_default(lng, sht, desc, out.[:m:], def);
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/System/Types.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace Void::FileSystem
{
enum class DirectoryEventKind : std::uint8_t {
Created,
Modified,
Deleted,
Renamed,
AttributeChanged,
RescanRequired,
};
struct DirectoryEvent {
DirectoryEventKind kind{DirectoryEventKind::Modified};
std::filesystem::path path{};
std::filesystem::path old_path{};
bool is_directory{false};
std::string detail{};
};
/// Predicate queried for every discovered/modified path. Returning true skips
/// watching (for directories) and suppresses event delivery for that path.
using IgnorePredicate =
std::function<bool(const std::filesystem::path& path, bool is_directory)>;
struct DirectoryWatcherOptions {
IgnorePredicate ignore{};
std::size_t max_watches{65536};
std::size_t max_queued_events{4096};
std::chrono::milliseconds rename_pair_window{std::chrono::milliseconds{50}};
};
/// Kernel-event (Linux inotify) recursive directory watcher with auto-watch
/// attachment on new subdirectories, rename pairing, ignore filtering, and
/// explicit RescanRequired signaling on queue overflow or watch exhaustion.
class DirectoryWatcher final
{
public:
~DirectoryWatcher() noexcept;
DirectoryWatcher(const DirectoryWatcher&) = delete;
DirectoryWatcher& operator=(const DirectoryWatcher&) = delete;
DirectoryWatcher(DirectoryWatcher&&) noexcept;
DirectoryWatcher& operator=(DirectoryWatcher&&) noexcept;
[[nodiscard]] static Void::Result::Result<DirectoryWatcher,
Void::Result::Error>
create(const std::filesystem::path& root,
DirectoryWatcherOptions options = {});
[[nodiscard]] Void::Result::Result<std::vector<DirectoryEvent>,
Void::Result::Error>
poll(std::chrono::milliseconds timeout = std::chrono::milliseconds{0});
/// Re-walk `root()` and rebuild all inotify watches from scratch.
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> rescan();
/// Wake any thread blocked inside poll().
void wake() noexcept;
/// Enqueue a RescanRequired event and wake waiters (deterministic test hook).
void simulate_overflow_for_test();
[[nodiscard]] const std::filesystem::path& root() const noexcept;
[[nodiscard]] std::size_t watch_count() const noexcept;
[[nodiscard]] int native_handle() const noexcept;
private:
struct Impl;
std::unique_ptr<Impl> impl_{};
explicit DirectoryWatcher(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::FileSystem
+592
View File
@@ -24,10 +24,17 @@
#ifndef _WIN32
#include <fcntl.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#if defined(__linux__)
#include <sys/random.h>
#if __has_include(<linux/fs.h>)
#include <linux/fs.h>
#endif
#endif
#endif
@@ -548,4 +555,589 @@ namespace detail
return {};
}
// ── VL-010: File Locks, Atomic Symlink Swap, Reflink Copy, Timestamps ────────
enum class LockMode : std::uint8_t {
Shared,
Exclusive,
};
/// RAII advisory file lock backed by POSIX flock(2).
class FileLock final
{
public:
FileLock() noexcept = default;
~FileLock() noexcept { unlock(); }
FileLock(const FileLock&) = delete;
FileLock& operator=(const FileLock&) = delete;
FileLock(FileLock&& other) noexcept
: fd_(std::move(other.fd_))
, mode_(other.mode_)
{
}
FileLock& operator=(FileLock&& other) noexcept
{
if (this != &other) {
unlock();
fd_ = std::move(other.fd_);
mode_ = other.mode_;
}
return *this;
}
[[nodiscard]] bool locked() const noexcept { return fd_.valid(); }
[[nodiscard]] LockMode mode() const noexcept { return mode_; }
[[nodiscard]] int native_handle() const noexcept { return fd_.get(); }
void unlock() noexcept
{
#ifndef _WIN32
if (fd_.valid()) {
while (::flock(fd_.get(), LOCK_UN) != 0 && errno == EINTR) {
}
fd_.reset();
}
#endif
}
[[nodiscard]] static Void::Result::Result<FileLock, Void::Result::Error>
lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
auto res = acquire(path, mode, false);
if (!res.has_value()) {
return std::unexpected{std::move(res.error())};
}
if (!res->has_value()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::internal,
"FileSystem::FileLock::lock: unexpected empty result")};
}
return std::move(**res);
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
try_lock(const std::filesystem::path& path,
LockMode mode = LockMode::Exclusive)
{
return acquire(path, mode, true);
}
private:
explicit FileLock(Void::System::OwnedFd fd, LockMode mode) noexcept
: fd_(std::move(fd))
, mode_(mode)
{
}
[[nodiscard]] static Void::Result::Result<std::optional<FileLock>,
Void::Result::Error>
acquire(const std::filesystem::path& path,
LockMode mode,
bool nonblocking)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::FileLock: empty path")};
}
int raw = ::open(path.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0666);
if (raw < 0 && mode == LockMode::Shared &&
(errno == EACCES || errno == EROFS)) {
raw = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
}
if (raw < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: cannot open '{}'",
path.string()),
err)};
}
Void::System::OwnedFd fd{raw};
const int op = (mode == LockMode::Shared ? LOCK_SH : LOCK_EX) |
(nonblocking ? LOCK_NB : 0);
for (;;) {
if (::flock(fd.get(), op) == 0) {
return std::optional<FileLock>{
FileLock{std::move(fd), mode}};
}
const int err = errno;
if (err == EINTR) {
continue;
}
if (nonblocking && (err == EWOULDBLOCK || err == EAGAIN)) {
return std::optional<FileLock>{std::nullopt};
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::FileLock: flock failed for '{}'",
path.string()),
err)};
}
#else
(void)path;
(void)mode;
(void)nonblocking;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::FileLock: unsupported platform")};
#endif
}
Void::System::OwnedFd fd_{};
LockMode mode_{LockMode::Exclusive};
};
/// Atomically create or replace symlink at `link_path` pointing to `target`
/// (symlinkat temp -> renameat -> optional parent dir fsync).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
atomic_symlink_swap(
const std::filesystem::path& link_path,
const std::filesystem::path& target,
ReplaceDurability durability = ReplaceDurability::durable_sync)
{
#ifndef _WIN32
if (link_path.empty() || !link_path.has_filename() || target.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: empty link or target path")};
}
const std::string target_name = link_path.filename().string();
if (target_name == "." || target_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::atomic_symlink_swap: invalid link filename")};
}
const std::filesystem::path parent =
link_path.parent_path().empty() ? std::filesystem::path{"."}
: link_path.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
std::string tmp_name;
bool created = false;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_lnk_{:016x}", target_name, detail::next_temp_entropy());
if (::symlinkat(target.c_str(), dir_fd.get(), tmp_name.c_str()) == 0) {
created = true;
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format(
"FileSystem::atomic_symlink_swap: symlinkat failed in '{}'",
parent.string()),
last_err)};
}
}
if (!created) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::atomic_symlink_swap: exhausted temporary link names",
last_err)};
}
bool cleanup = true;
struct CleanupGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~CleanupGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} cleanup_guard{dir_fd.get(), &tmp_name, &cleanup};
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
target_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::atomic_symlink_swap: renameat failed for '{}'",
link_path.string()),
err)};
}
cleanup = false;
if (durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::atomic_symlink_swap: parent dir fsync failed for '{}'",
link_path.string()),
err)};
}
}
return {};
#else
(void)link_path;
(void)target;
(void)durability;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::atomic_symlink_swap: unsupported platform")};
#endif
}
enum class CopyMethod : std::uint8_t {
Reflink,
PrivateCopy,
};
struct CopyResult {
std::uint64_t bytes{0};
CopyMethod method{CopyMethod::PrivateCopy};
};
struct CopyOptions {
bool overwrite{true};
bool preserve_permissions{true};
ReplaceDurability durability{ReplaceDurability::atomic_visibility};
};
/// Copy a regular file using CoW reflink (`ioctl(FICLONE)`) with atomic
/// staging and private-copy fallback. Explicitly never creates hardlinks.
[[nodiscard]] inline Void::Result::Result<CopyResult, Void::Result::Error>
reflink_copy_file(const std::filesystem::path& src,
const std::filesystem::path& dst,
CopyOptions options = {})
{
#ifndef _WIN32
if (src.empty() || dst.empty() || !dst.has_filename()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid source or destination path")};
}
const std::string dst_name = dst.filename().string();
if (dst_name == "." || dst_name == "..") {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::reflink_copy_file: invalid destination filename")};
}
const int raw_src = ::open(src.c_str(), O_RDONLY | O_CLOEXEC);
if (raw_src < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open '{}'",
src.string()),
err)};
}
Void::System::OwnedFd src_fd{raw_src};
struct stat src_st {};
if (::fstat(src_fd.get(), &src_st) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: fstat failed on '{}'",
src.string()),
err)};
}
if (!S_ISREG(src_st.st_mode)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
std::format("FileSystem::reflink_copy_file: '{}' is not a regular file",
src.string()))};
}
const std::filesystem::path parent =
dst.parent_path().empty() ? std::filesystem::path{"."}
: dst.parent_path();
const int raw_dir =
::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (raw_dir < 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: cannot open parent '{}'",
parent.string()),
err)};
}
Void::System::OwnedFd dir_fd{raw_dir};
const mode_t create_mode = options.preserve_permissions
? static_cast<mode_t>(src_st.st_mode & 0777)
: static_cast<mode_t>(0644);
std::string tmp_name;
Void::System::OwnedFd tmp_fd;
int last_err = 0;
for (int attempt = 0; attempt < 32; ++attempt) {
tmp_name = std::format(
".{}.void_cp_{:016x}", dst_name, detail::next_temp_entropy());
const int fd = ::openat(dir_fd.get(),
tmp_name.c_str(),
O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW |
O_CLOEXEC,
create_mode);
if (fd >= 0) {
tmp_fd.reset(fd);
break;
}
last_err = errno;
if (last_err != EEXIST) {
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(last_err),
std::format("FileSystem::reflink_copy_file: create temp in '{}'",
parent.string()),
last_err)};
}
}
if (!tmp_fd.valid()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::already_exists,
"FileSystem::reflink_copy_file: exhausted temp names",
last_err)};
}
bool cleanup_tmp = true;
struct TempGuard {
int dfd{-1};
const std::string* name{nullptr};
bool* active{nullptr};
~TempGuard() noexcept
{
if (active != nullptr && *active && dfd >= 0 && name != nullptr) {
(void)::unlinkat(dfd, name->c_str(), 0);
}
}
} temp_guard{dir_fd.get(), &tmp_name, &cleanup_tmp};
CopyResult result;
result.bytes = static_cast<std::uint64_t>(src_st.st_size);
bool cloned = false;
#if defined(__linux__) && defined(FICLONE)
for (;;) {
if (::ioctl(tmp_fd.get(), FICLONE, src_fd.get()) == 0) {
cloned = true;
result.method = CopyMethod::Reflink;
break;
}
if (errno == EINTR) {
continue;
}
const int err = errno;
if (err == EOPNOTSUPP || err == EXDEV || err == EINVAL ||
err == ENOTTY || err == ENOSYS || err == EBADF || err == ETXTBSY
#if defined(ENOTSUP) && (!defined(EOPNOTSUPP) || ENOTSUP != EOPNOTSUPP)
|| err == ENOTSUP
#endif
) {
break;
}
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: FICLONE failed for '{}'",
dst.string()),
err)};
}
#endif
if (!cloned) {
result.method = CopyMethod::PrivateCopy;
std::vector<char> buf(64ULL * 1024ULL);
std::uint64_t copied = 0;
for (;;) {
const ssize_t r = ::read(src_fd.get(), buf.data(), buf.size());
if (r > 0) {
std::size_t off = 0;
const auto ur = static_cast<std::size_t>(r);
while (off < ur) {
const ssize_t w =
::write(tmp_fd.get(), buf.data() + off, ur - off);
if (w < 0) {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: write failed for '{}'",
dst.string()),
err)};
}
off += static_cast<std::size_t>(w);
}
copied += ur;
} else if (r == 0) {
break;
} else {
if (errno == EINTR) {
continue;
}
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format(
"FileSystem::reflink_copy_file: read failed on '{}'",
src.string()),
err)};
}
}
result.bytes = copied;
}
if (options.preserve_permissions) {
(void)::fchmod(tmp_fd.get(), create_mode);
}
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(tmp_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::sync_failed,
std::format("FileSystem::reflink_copy_file: fsync failed for '{}'",
dst.string()),
err)};
}
}
if (auto closed = tmp_fd.close(); !closed.has_value()) {
return std::unexpected{std::move(closed.error())};
}
if (options.overwrite) {
if (::renameat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str()) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: rename failed for '{}'",
dst.string()),
err)};
}
} else {
if (::linkat(dir_fd.get(),
tmp_name.c_str(),
dir_fd.get(),
dst_name.c_str(),
0) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::reflink_copy_file: publish failed for '{}'",
dst.string()),
err)};
}
(void)::unlinkat(dir_fd.get(), tmp_name.c_str(), 0);
}
cleanup_tmp = false;
if (options.durability == ReplaceDurability::durable_sync) {
if (const int err = detail::fsync_eintr(dir_fd.get()); err != 0) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::durability_unknown,
std::format(
"FileSystem::reflink_copy_file: parent fsync failed for '{}'",
dst.string()),
err)};
}
}
return result;
#else
(void)src;
(void)dst;
(void)options;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::reflink_copy_file: unsupported platform")};
#endif
}
/// Set access and modification timestamps without dereferencing symlinks.
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_timestamps_nofollow(const std::filesystem::path& path,
std::int64_t atime_sec,
std::int32_t atime_nsec,
std::int64_t mtime_sec,
std::int32_t mtime_nsec)
{
#ifndef _WIN32
if (path.empty()) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: empty path")};
}
auto valid_nsec = [](std::int32_t ns) noexcept {
return (ns >= 0 && ns < 1'000'000'000) || ns == UTIME_NOW ||
ns == UTIME_OMIT;
};
if (!valid_nsec(atime_nsec) || !valid_nsec(mtime_nsec)) {
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::invalid_argument,
"FileSystem::set_timestamps_nofollow: nanoseconds out of range")};
}
struct timespec ts[2]{};
ts[0].tv_sec = static_cast<time_t>(atime_sec);
ts[0].tv_nsec = static_cast<long>(atime_nsec);
ts[1].tv_sec = static_cast<time_t>(mtime_sec);
ts[1].tv_nsec = static_cast<long>(mtime_nsec);
if (::utimensat(AT_FDCWD, path.c_str(), ts, AT_SYMLINK_NOFOLLOW) != 0) {
const int err = errno;
return std::unexpected{Void::System::make_system_error(
Void::System::map_errno_to_system_code(err),
std::format("FileSystem::set_timestamps_nofollow: utimensat failed for '{}'",
path.string()),
err)};
}
return {};
#else
(void)path;
(void)atime_sec;
(void)atime_nsec;
(void)mtime_sec;
(void)mtime_nsec;
return std::unexpected{Void::System::make_system_error(
Void::System::SystemErrorCode::unsupported,
"FileSystem::set_timestamps_nofollow: unsupported platform")};
#endif
}
/// Set canonical modification and access timestamps (default UNIX epoch 0)
/// without following symlinks (`utimensat(..., AT_SYMLINK_NOFOLLOW)`).
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::int64_t unix_seconds = 0,
std::int32_t nanoseconds = 0)
{
return set_timestamps_nofollow(
path, unix_seconds, nanoseconds, unix_seconds, nanoseconds);
}
[[nodiscard]] inline Void::Result::Result<void, Void::Result::Error>
set_canonical_mtime(const std::filesystem::path& path,
std::chrono::sys_seconds tp)
{
return set_canonical_mtime(path, tp.time_since_epoch().count(), 0);
}
} // namespace Void::FileSystem
+7
View File
@@ -116,6 +116,7 @@ public:
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] bool process_group_alive() const noexcept;
[[nodiscard]] long long pid() const noexcept;
[[nodiscard]] long long pgid() const noexcept;
[[nodiscard]] bool owns_process_group() const noexcept;
@@ -201,4 +202,10 @@ private:
const std::vector<std::string>& arguments,
bool close_extra_fds);
/// Opt the current process into Linux PR_SET_CHILD_SUBREAPER so orphaned
/// descendant processes in spawned process groups reparent to this process
/// and can be reaped directly via waitpid(-pgid, ...).
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
enable_subreaper() noexcept;
} // namespace Void::Process