58 lines
1.4 KiB
C++
58 lines
1.4 KiB
C++
#pragma once
|
|||
|
|
#include <cerrno>
|
||
|
|
#include <filesystem>
|
||
|
|
#include <stdexcept>
|
||
|
|
#include <string>
|
||
|
|
|
||
|
|
namespace doos {
|
||
|
|
|
||
|
|
class SysError : public std::runtime_error {
|
||
|
|
public:
|
||
|
|
explicit SysError(const std::string& what, int err = errno);
|
||
|
|
int code() const { return code_; }
|
||
|
|
|
||
|
|
private:
|
||
|
|
int code_;
|
||
|
|
};
|
||
|
|
|
||
|
|
class Fd {
|
||
|
|
public:
|
||
|
|
Fd() = default;
|
||
|
|
explicit Fd(int fd) : fd_(fd) {}
|
||
|
|
Fd(Fd&& o) noexcept : fd_(o.release()) {}
|
||
|
|
Fd& operator=(Fd&& o) noexcept;
|
||
|
|
Fd(const Fd&) = delete;
|
||
|
|
Fd& operator=(const Fd&) = delete;
|
||
|
|
~Fd() { reset(); }
|
||
|
|
int get() const { return fd_; }
|
||
|
|
int release();
|
||
|
|
void reset(int fd = -1);
|
||
|
|
bool valid() const { return fd_ >= 0; }
|
||
|
|
|
||
|
|
private:
|
||
|
|
int fd_ = -1;
|
||
|
|
};
|
||
|
|
|
||
|
|
// flock(2) on a file for the lifetime of the object, bounded wait.
|
||
|
|
class FileLock {
|
||
|
|
public:
|
||
|
|
FileLock(const std::filesystem::path& file, int timeoutMs);
|
||
|
|
~FileLock() = default;
|
||
|
|
void unlock() { fd_.reset(); }
|
||
|
|
int fd() const { return fd_.get(); }
|
||
|
|
|
||
|
|
private:
|
||
|
|
Fd fd_;
|
||
|
|
};
|
||
|
|
|
||
|
|
namespace fsutil {
|
||
|
|
void mkdirs(const std::filesystem::path& p, mode_t mode = 0755);
|
||
|
|
void writeFile(const std::filesystem::path& p, const std::string& content);
|
||
|
|
std::string readFile(const std::filesystem::path& p);
|
||
|
|
// Removes a tree without following symlinks; bounded depth.
|
||
|
|
void removeTree(const std::filesystem::path& p, std::size_t depth = 0);
|
||
|
|
std::size_t countEntries(const std::filesystem::path& p, std::size_t cap);
|
||
|
|
} // namespace fsutil
|
||
|
|
|
||
|
|
} // namespace doos
|