#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #if __has_include() #include #endif #include namespace vn { namespace fs = std::filesystem; using Bytes = std::span; using MutBytes = std::span; using Id = std::array; using ChangeId = std::array; constexpr std::size_t ID_LEN = 32; constexpr std::size_t CHANGE_ID_LEN = 16; constexpr std::size_t MAX_NAME_LEN = 4096; constexpr std::size_t MAX_PATH_LEN = 65536; constexpr std::size_t MAX_MESSAGE_LEN = 16u * 1024u * 1024u; constexpr std::size_t MAX_OBJECT_BODY = 64u * 1024u * 1024u; constexpr std::size_t MAX_CHUNK_LEN = 256u * 1024u; constexpr std::size_t MAX_MANIFEST_ENTRIES = 1024; constexpr std::size_t MAX_TREE_ENTRIES = 1'000'000; constexpr std::size_t MAX_CONFLICT_TERMS = 64; constexpr std::size_t INLINE_THRESHOLD = 16u * 1024u; enum class ErrorKind { None, UnexpectedEnd, VarintOverflow, NonMinimalVarint, InvalidValue, LimitExceeded, InvalidName, Duplicate, Unsorted, TrailingBytes, UnsupportedVersion, InvalidMagic, HashMismatch, Corrupt, Io, Usage, }; std::string_view error_kind_name(ErrorKind kind); struct Error { ErrorKind kind = ErrorKind::None; std::size_t offset = 0; std::string message; Error() = default; Error(ErrorKind k, std::size_t off, std::string msg) : kind(k), offset(off), message(std::move(msg)) {} static Error decode(ErrorKind kind, std::size_t offset); static Error io(std::string message); static Error usage(std::string message); }; #if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L template using Result = std::expected; template using Unexpected = std::unexpected; #else template struct Unexpected { E err; explicit Unexpected(E value) : err(std::move(value)) {} }; template class Expected { public: Expected(T &&value) : data_(std::in_place_index<0>, std::move(value)) {} Expected(const T &value) : data_(std::in_place_index<0>, value) {} Expected(Unexpected value) : data_(std::in_place_index<1>, std::move(value.err)) {} [[nodiscard]] bool has_value() const { return data_.index() == 0; } explicit operator bool() const { return has_value(); } T &operator*() { return std::get<0>(data_); } const T &operator*() const { return std::get<0>(data_); } T *operator->() { return &std::get<0>(data_); } const T *operator->() const { return &std::get<0>(data_); } T &value() { return std::get<0>(data_); } const T &value() const { return std::get<0>(data_); } E &error() { return std::get<1>(data_); } const E &error() const { return std::get<1>(data_); } private: std::variant data_; }; template class Expected { public: Expected() = default; Expected(Unexpected value) : error_(std::move(value.err)) {} [[nodiscard]] bool has_value() const { return !error_.has_value(); } explicit operator bool() const { return has_value(); } E &error() { return *error_; } const E &error() const { return *error_; } private: std::optional error_; }; template using Result = Expected; #endif using Status = Result; inline Unexpected unexpected(Error error) { return Unexpected(std::move(error)); } inline Status ok() { return {}; } inline Unexpected fail(ErrorKind kind, std::size_t offset = 0) { return unexpected(Error::decode(kind, offset)); } inline Unexpected fail_io(std::string message) { return unexpected(Error::io(std::move(message))); } inline Unexpected fail_usage(std::string message) { return unexpected(Error::usage(std::move(message))); } // --------------------------------------------------------------------------- // Byte and string helpers // --------------------------------------------------------------------------- inline Bytes bytes_of(std::string_view s) { return Bytes(reinterpret_cast(s.data()), s.size()); } inline Bytes bytes_of(const std::vector &v) { return Bytes(v.data(), v.size()); } inline std::string_view str_of(Bytes b) { return std::string_view(reinterpret_cast(b.data()), b.size()); } inline std::string to_string(Bytes b) { return std::string(str_of(b)); } inline bool equals(Bytes a, Bytes b) { return a.size() == b.size() && (a.empty() || std::memcmp(a.data(), b.data(), a.size()) == 0); } inline int compare(Bytes a, Bytes b) { const std::size_t n = std::min(a.size(), b.size()); if (n != 0) { const int c = std::memcmp(a.data(), b.data(), n); if (c != 0) return c < 0 ? -1 : 1; } if (a.size() < b.size()) return -1; if (a.size() > b.size()) return 1; return 0; } inline bool ascii_iequals(Bytes a, Bytes b) { if (a.size() != b.size()) return false; for (std::size_t i = 0; i < a.size(); ++i) { auto lower = [](std::uint8_t c) -> std::uint8_t { return (c >= 'A' && c <= 'Z') ? static_cast(c + 32) : c; }; if (lower(a[i]) != lower(b[i])) return false; } return true; } inline bool starts_with(Bytes value, Bytes prefix) { return value.size() >= prefix.size() && equals(value.first(prefix.size()), prefix); } std::string hex_encode(Bytes data); std::string hex_encode(const Id &id); bool hex_decode(std::string_view text, MutBytes out); std::optional parse_id(std::string_view hex); std::string base32_encode(const ChangeId &id); bool base32_prefix_matches(std::string_view full, std::string_view prefix); // --------------------------------------------------------------------------- // Hashing and random bytes // --------------------------------------------------------------------------- std::array blake3_hash(Bytes data); Id object_id(std::uint8_t type_byte, Bytes body); std::array random_change_id(); std::uint64_t random_u64(); // --------------------------------------------------------------------------- // Binary reader / writer // --------------------------------------------------------------------------- class Reader { public: explicit Reader(Bytes data) : data_(data) {} [[nodiscard]] std::size_t offset() const { return pos_; } [[nodiscard]] std::size_t remaining() const { return data_.size() - pos_; } [[nodiscard]] bool at_end() const { return pos_ >= data_.size(); } Result u8(); Result u16le(); Result u32le(); Result u64le(); Result i16le(); Result i64le(); Result varint(); Result raw(std::size_t n); Result bytes(std::size_t max_len); Result string_bytes(std::size_t max_len); Result list_len(std::size_t max); Result id(); Result> opt_id(); Result finish(); struct Sig { std::string name; std::string email; std::int64_t seconds = 0; std::int16_t tz_min = 0; }; struct TimeMs { std::int64_t ms = 0; std::int16_t tz_min = 0; }; Result sig(std::size_t max_name, std::size_t max_email); Result time_ms(); static std::uint64_t read_u64le_at(Bytes data, std::size_t off); private: Bytes data_; std::size_t pos_ = 0; }; class ByteWriter { public: explicit ByteWriter(std::size_t reserve = 64) { buf_.reserve(reserve); } void u8(std::uint8_t v); void u16le(std::uint16_t v); void u32le(std::uint32_t v); void u64le(std::uint64_t v); void i16le(std::int16_t v); void i64le(std::int64_t v); void varint(std::uint64_t v); void raw(Bytes data); void raw(std::string_view s) { raw(bytes_of(s)); } void bytes(std::string_view s) { raw(s); } void length_prefixed(std::string_view s); void length_prefixed(Bytes b); void id(const Id &id); void opt_id(const std::optional &id); void sig(const Reader::Sig &s); void time_ms(const Reader::TimeMs &t); [[nodiscard]] Bytes view() const { return Bytes(buf_.data(), buf_.size()); } [[nodiscard]] const std::vector &data() const { return buf_; } [[nodiscard]] std::vector take() { return std::move(buf_); } [[nodiscard]] std::size_t size() const { return buf_.size(); } void clear() { buf_.clear(); } void append(Bytes b) { raw(b); } void reserve(std::size_t n) { buf_.reserve(n); } private: std::vector buf_; }; // --------------------------------------------------------------------------- // Dates, terminal output // --------------------------------------------------------------------------- std::string format_utc(std::int64_t seconds); std::int64_t unix_now_seconds(); std::int64_t unix_now_millis(); std::size_t available_cpu_count(); enum class Color { Default, Black, Red, Green, Yellow, Blue, Magenta, Cyan, BrightBlack, BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan, BrightWhite, }; bool colors_enabled(); void print_colored(std::string_view text, Color color, bool dim = false, bool to_stderr = false); void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr = false); void print_bold(std::string_view text, Color fg, bool to_stderr = false); void error_prefix(); void warning_prefix(); void info_prefix(); // --------------------------------------------------------------------------- // Filesystem helpers // --------------------------------------------------------------------------- fs::path path_from_bytes(std::string_view bytes); std::string path_to_bytes(const fs::path &p); std::string path_display(const fs::path &p); Result> read_file(const fs::path &p); std::optional> read_file_opt(const fs::path &p); bool write_file(const fs::path &p, Bytes data); bool append_file(const fs::path &p, Bytes data); bool write_atomic(const fs::path &final_path, Bytes data); bool write_atomic(const fs::path &tmp_path, const fs::path &final_path, Bytes data); bool ensure_directory(const fs::path &p); bool remove_file(const fs::path &p); bool remove_tree(const fs::path &p); bool path_exists(const fs::path &p); bool path_is_dir(const fs::path &p); bool path_is_file(const fs::path &p); bool path_is_symlink(const fs::path &p); std::optional path_file_size(const fs::path &p); std::optional file_mtime_ns(const fs::path &p); std::optional file_inode(const fs::path &p); bool is_executable(const fs::path &p); std::optional path_read_symlink(const fs::path &p); std::vector list_directory(const fs::path &p); bool same_or_under(const fs::path &child, const fs::path &parent); std::string basename_string(const fs::path &p); struct StatInfo { std::uint8_t kind = 0; // 0 missing, 1 file, 2 directory, 3 symlink bool executable = false; std::uint64_t size = 0; std::uint64_t mtime_ns = 0; std::uint64_t inode = 0; }; std::optional stat_path(const fs::path &p); // --------------------------------------------------------------------------- // Configuration and identity // --------------------------------------------------------------------------- std::optional repo_config_value(const fs::path &repo_root, std::string_view key); bool repo_config_set(const fs::path &repo_root, std::string_view key, std::string_view value); bool repo_config_remove(const fs::path &repo_root, std::string_view key); bool repo_config_bool(const fs::path &repo_root, std::string_view key, bool fallback); struct Sig { std::string name; std::string email; std::int64_t seconds = 0; std::int16_t tz_min = 0; }; Sig identity_signature(const fs::path &repo_root); std::optional user_config_author_name(); std::optional user_config_author_email(); bool user_config_set(std::string_view key, std::string_view value); bool user_config_remove(std::string_view key); // --------------------------------------------------------------------------- // Ignore rules // --------------------------------------------------------------------------- struct IgnoreRule { std::string pattern; bool negated = false; bool dir_only = false; bool anchored = false; bool has_slash = false; std::string base; }; struct IgnoreRules { std::vector items; }; IgnoreRules ignore_empty(); void ignore_load_file(IgnoreRules &rules, const fs::path &repo_root, std::string_view base, std::string_view name); void ignore_load_root(IgnoreRules &rules, const fs::path &repo_root); bool ignore_ignored(const IgnoreRules &rules, std::string_view path, bool is_dir); bool ignore_path_ignored(const fs::path &repo_root, std::string_view path); bool glob_match(std::string_view pattern, std::string_view text); } // namespace vn