navid/veins / commit

4c5650fedc43

Navid M <navidmomtahen@gmail.com> · 2026-11-29

parents: 884b6edddf52

Browse files at this commit · Download source

all: better test coverage
--- a/xveins/CMakeLists.txt+++ b/xveins/CMakeLists.txt@@ -271,13 +271,42 @@  include(CTest) if(BUILD_TESTING)-    add_executable(vn-unit-tests tests/unit_tests.cpp)+    add_executable(vn-unit-tests+        tests/unit/main.cpp+        tests/unit/core_tests.cpp+        tests/unit/object_tests.cpp+        tests/unit/store_tests.cpp+        tests/unit/worktree_tests.cpp+        tests/unit/protocol_tests.cpp+    )     vn_configure_target(vn-unit-tests)+    target_include_directories(vn-unit-tests PRIVATE tests)     target_link_libraries(vn-unit-tests PRIVATE vn_core vn_version)     add_test(NAME vn-unit-tests COMMAND vn-unit-tests)+    set(VN_UNIT_SUITES core object store worktree protocol)+    foreach(suite IN LISTS VN_UNIT_SUITES)+        add_test(+            NAME "vn-unit-${suite}"+            COMMAND vn-unit-tests --suite "unit-${suite}"+        )+    endforeach() -    add_executable(vn-integration-tests tests/integration_tests.cpp)+    add_executable(vn-integration-tests+        tests/integration/main.cpp+        tests/integration/support.cpp+        tests/integration/core_tests.cpp+        tests/integration/worktree_tests.cpp+        tests/integration/history_tests.cpp+        tests/integration/refs_tests.cpp+        tests/integration/config_tests.cpp+        tests/integration/merge_tests.cpp+        tests/integration/rebase_tests.cpp+        tests/integration/git_tests.cpp+        tests/integration/protocol_tests.cpp+        tests/integration/errors_tests.cpp+    )     vn_configure_target(vn-integration-tests)+    target_include_directories(vn-integration-tests PRIVATE tests)     target_link_libraries(vn-integration-tests PRIVATE vn_core vn_version)      add_test(NAME vn-self-test COMMAND vn self-test)--- a/xveins/src/core/common.cpp+++ b/xveins/src/core/common.cpp@@ -356,6 +356,11 @@         return unexpected(n.error());     if (*n > max)         return fail(ErrorKind::LimitExceeded, at);+    // Every list element occupies at least one byte. Rejecting counts larger+    // than the remaining payload keeps a tiny hostile input from reserving+    // gigabytes before the first element is even read.+    if (*n > remaining())+        return fail(ErrorKind::UnexpectedEnd, at);     return static_cast<std::size_t>(*n); } @@ -424,6 +429,8 @@ }  std::uint64_t Reader::read_u64le_at(Bytes data, std::size_t off) {+    if (off > data.size() || data.size() - off < 8)+        return 0;     std::uint64_t v = 0;     for (std::size_t i = 0; i < 8; ++i)         v |= static_cast<std::uint64_t>(data[off + i]) << (i * 8);@@ -1969,63 +1976,88 @@     ignore_load_file(rules, repo_root, "", ".gitignore"); } +struct GlobState {+    std::size_t pi = 0;+    std::size_t ti = 0;+};++// Wildcards backtrack, so the naive implementation recursed once per possible+// match and could exhaust the stack on a hostile pattern. Walk the same state+// graph with an explicit stack and a work budget instead. static bool glob_here(std::string_view pattern, std::size_t pi, std::string_view text,                       std::size_t ti) {-    if (pi >= pattern.size())-        return ti >= text.size();-    const char pc = pattern[pi];-    if (pc == '*') {-        const bool dbl = pi + 1 < pattern.size() && pattern[pi + 1] == '*';-        if (dbl) {-            const std::size_t next = pi + 2;-            if (next < pattern.size() && pattern[next] == '/') {-                const std::size_t after = next + 1;-                std::size_t j = ti;-                for (;;) {-                    if (glob_here(pattern, after, text, j))-                        return true;-                    if (j >= text.size())-                        break;-                    if (text[j] == '/') {+    constexpr std::size_t max_work = 1'000'000;+    std::vector<GlobState> stack;+    std::size_t work = 0;+    auto push = [&](GlobState state) -> bool {+        if (work >= max_work)+            return false;+        ++work;+        stack.push_back(state);+        return true;+    };+    if (!push(GlobState{pi, ti}))+        return false;+    while (!stack.empty()) {+        const GlobState state = stack.back();+        stack.pop_back();+        const std::size_t p = state.pi;+        const std::size_t t = state.ti;+        if (p >= pattern.size()) {+            if (t >= text.size())+                return true;+            continue;+        }+        const char pc = pattern[p];+        if (pc == '*') {+            const bool dbl = p + 1 < pattern.size() && pattern[p + 1] == '*';+            if (dbl) {+                const std::size_t next = p + 2;+                if (next < pattern.size() && pattern[next] == '/') {+                    const std::size_t after = next + 1;+                    std::size_t j = t;+                    for (;;) {+                        if (!push(GlobState{after, j}))+                            return false;+                        if (j >= text.size())+                            break;+                        if (text[j] == '/') {+                            ++j;+                            continue;+                        }                         ++j;-                        continue;+                        while (j < text.size() && text[j] != '/')+                            ++j;                     }-                    ++j;-                    while (j < text.size() && text[j] != '/')-                        ++j;+                } else {+                    for (std::size_t j = t;; ++j) {+                        if (!push(GlobState{next, j}))+                            return false;+                        if (j >= text.size())+                            break;+                    }                 }-                return false;+            } else {+                for (std::size_t j = t;; ++j) {+                    if (!push(GlobState{p + 1, j}))+                        return false;+                    if (j >= text.size() || text[j] == '/')+                        break;+                }             }-            std::size_t j = ti;-            for (;;) {-                if (glob_here(pattern, next, text, j))-                    return true;-                if (j >= text.size())-                    break;-                ++j;-            }-            return false;+            continue;         }-        std::size_t j = ti;-        for (;;) {-            if (glob_here(pattern, pi + 1, text, j))-                return true;-            if (j >= text.size() || text[j] == '/')-                break;-            ++j;+        if (t >= text.size())+            continue;+        if (pc == '?') {+            if (text[t] != '/')+                (void)push(GlobState{p + 1, t + 1});+            continue;         }-        return false;+        if (pc == text[t])+            (void)push(GlobState{p + 1, t + 1});     }-    if (ti >= text.size())-        return false;-    if (pc == '?') {-        if (text[ti] == '/')-            return false;-        return glob_here(pattern, pi + 1, text, ti + 1);-    }-    if (pc != text[ti])-        return false;-    return glob_here(pattern, pi + 1, text, ti + 1);+    return false; }  bool glob_match(std::string_view pattern, std::string_view text) {--- a/xveins/src/git/git_object.cpp+++ b/xveins/src/git/git_object.cpp@@ -5,6 +5,7 @@  #include <algorithm> #include <cstring>+#include <limits> #include <map> #include <mutex> #include <string_view>@@ -144,9 +145,11 @@     std::size_t pos = start + 1;     bool more = (c0 & 0x80) != 0;     while (more) {-        if (pos >= data.size())+        if (pos >= data.size() || shift >= 64)             return std::nullopt;         const std::uint8_t c = data[pos++];+        if (shift == 63 && (c & 0x7f) > 1)+            return std::nullopt;         value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);         shift += 7;         more = (c & 0x80) != 0;@@ -485,7 +488,10 @@     } } -void read_ref_dir(const fs::path& base, std::string_view rel, std::vector<Ref>& refs) {+void read_ref_dir(const fs::path& base, std::string_view rel, std::vector<Ref>& refs,+                  std::size_t depth = 0) {+    if (depth > 64)+        return;     const fs::path dir = rel.empty() ? base : base / path_from_bytes(rel);     for (const auto& name : list_directory(dir)) {         std::string child_rel(rel);@@ -494,8 +500,11 @@         child_rel += name;         const fs::path child = base / path_from_bytes(child_rel);         std::error_code ec;-        if (fs::is_directory(child, ec)) {-            read_ref_dir(base, child_rel, refs);+        const auto status = fs::symlink_status(child, ec);+        if (ec || fs::is_symlink(status))+            continue;+        if (fs::is_directory(status)) {+            read_ref_dir(base, child_rel, refs, depth + 1);         } else {             auto content = read_file_opt(child);             if (!content)@@ -536,7 +545,9 @@     return std::nullopt; } -bool copy_tree(const fs::path& src, const fs::path& dst) {+bool copy_tree(const fs::path& src, const fs::path& dst, std::size_t depth = 0) {+    if (depth > 64)+        return false;     std::error_code ec;     fs::create_directories(dst, ec);     if (ec)@@ -544,10 +555,13 @@     for (const auto& name : list_directory(src)) {         const fs::path s = src / path_from_bytes(name);         const fs::path d = dst / path_from_bytes(name);-        if (fs::is_directory(s, ec)) {-            if (!copy_tree(s, d))+        const auto status = fs::symlink_status(s, ec);+        if (ec || fs::is_symlink(status))+            continue;+        if (fs::is_directory(status)) {+            if (!copy_tree(s, d, depth + 1))                 return false;-        } else if (fs::is_regular_file(s, ec)) {+        } else if (fs::is_regular_file(status)) {             fs::create_hard_link(s, d, ec);             if (ec) {                 ec.clear();@@ -663,7 +677,7 @@     const std::string_view tz_text = value.substr(tz_space + 1);     if (sec_text.empty() || tz_text.size() != 5 || (tz_text[0] != '+' && tz_text[0] != '-'))         return std::nullopt;-    std::int64_t seconds = 0;+    std::uint64_t magnitude = 0;     bool negative = false;     std::size_t i = 0;     if (sec_text[0] == '-') {@@ -675,8 +689,14 @@     for (; i < sec_text.size(); ++i) {         if (sec_text[i] < '0' || sec_text[i] > '9')             return std::nullopt;-        seconds = seconds * 10 + (sec_text[i] - '0');+        const std::uint64_t digit = static_cast<std::uint64_t>(sec_text[i] - '0');+        if (magnitude > (static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) -+                         digit) /+                            10)+            return std::nullopt;+        magnitude = magnitude * 10 + digit;     }+    std::int64_t seconds = static_cast<std::int64_t>(magnitude);     if (negative)         seconds = -seconds;     std::int64_t hh = 0;--- a/xveins/src/server/server.cpp+++ b/xveins/src/server/server.cpp@@ -182,11 +182,12 @@ }  void collect_object(Session& session, std::uint32_t request_id, blake3_hasher& hasher, const Id& id,-                    std::uint8_t kind, std::set<Id>& seen, bool send, bool& failed);+                    std::uint8_t kind, std::set<Id>& seen, bool send, bool& failed,+                    std::size_t depth);  void collect_tree(Session& session, std::uint32_t request_id, blake3_hasher& hasher, const Id& id,-                  std::set<Id>& seen, bool send, bool& failed) {-    if (!seen.insert(id).second)+                  std::set<Id>& seen, bool send, bool& failed, std::size_t depth) {+    if (depth > MAX_TREE_DEPTH || !seen.insert(id).second)         return;     auto body = session.store.read_body(id, TYPE_TREE);     if (!body) {@@ -203,13 +204,13 @@     }     for (const auto& entry : tree->entries) {         if (entry.kind == KIND_SUBTREE) {-            collect_tree(session, request_id, hasher, entry.target, seen, send, failed);+            collect_tree(session, request_id, hasher, entry.target, seen, send, failed, depth + 1);         } else if (entry.kind == KIND_CONFLICT) {             collect_object(session, request_id, hasher, entry.target, TYPE_CONFLICT, seen, send,-                           failed);+                           failed, depth + 1);         } else if (entry.kind != KIND_SUBMODULE) {             collect_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen, send,-                           failed);+                           failed, depth + 1);         }         if (failed)             return;@@ -217,8 +218,9 @@ }  void collect_object(Session& session, std::uint32_t request_id, blake3_hasher& hasher, const Id& id,-                    std::uint8_t kind, std::set<Id>& seen, bool send, bool& failed) {-    if (!seen.insert(id).second)+                    std::uint8_t kind, std::set<Id>& seen, bool send, bool& failed,+                    std::size_t depth) {+    if (depth > MAX_TREE_DEPTH || !seen.insert(id).second)         return;     auto body = session.store.read_body(id, kind);     if (!body) {@@ -237,7 +239,7 @@         if (blob->form == BlobForm::Interior) {             for (const auto& entry : blob->entries) {                 collect_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen, send,-                               failed);+                               failed, depth + 1);                 if (failed)                     return;             }@@ -254,7 +256,7 @@             const std::uint8_t child = value_kind_to_type(value.kind);             if (child != 0)                 collect_object(session, request_id, hasher, *value.target, child, seen, send,-                               failed);+                               failed, depth + 1);             if (failed)                 return;         }@@ -264,7 +266,7 @@             const std::uint8_t child = value_kind_to_type(value.kind);             if (child != 0)                 collect_object(session, request_id, hasher, *value.target, child, seen, send,-                               failed);+                               failed, depth + 1);             if (failed)                 return;         }@@ -489,7 +491,7 @@             break;         }         collect_tree(session, frame.request_id, hasher, loaded->commit.root_tree, seen, true,-                     failed);+                     failed, 0);         if (failed)             break;     }--- /dev/null+++ b/xveins/tests/integration/config_tests.cpp@@ -0,0 +1,110 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void config_local(test::Context& t) {+    VnFixture f;+    f.init();+    f.vn({"cfg", "test.key", "value"});+    t.expect_eq(trim_copy(f.vn({"cfg", "test.key"}).out), "value");+    t.expect_contains(f.vn({"cfg"}).out, "test.key = value");+    f.vn({"cfg", "set", "test.other", "two"});+    t.expect_eq(trim_copy(f.vn({"cfg", "get", "test.other"}).out), "two");+    f.vn({"cfg", "-unset", "test.key"});+    f.failed({"cfg", "test.key"}, "unknown config key");+    f.vn({"cfg", "unset", "test.other"});+    f.failed({"cfg", "test.other"}, "unknown config key");+}++void config_global_identity(test::Context& t) {+    VnFixture f;+    f.init();+    f.vn({"cfg", "-global", "user.name", "Global Tester"});+    f.vn({"cfg", "-global", "user.email", "global@example.com"});+    t.expect_eq(trim_copy(f.vn({"cfg", "-global", "user.name"}).out), "Global Tester");+    f.write("f.txt", "content\n");+    f.commit("global identity");+    t.expect_contains(f.vn({"show", f.commit_for_message("global identity")}).out, "Global Tester");+    t.expect(fs::exists(f.home / ".local" / "config" / "veins" / "veins.toml"));+}++void config_errors(test::Context& t) {+    (void)t;+    VnFixture f;+    f.init();+    f.failed({"cfg", "key", "value", "extra"}, "accepts a key and one value");+    f.failed({"cfg", "-unset"}, "requires one key");+    f.failed({"cfg", "unknown"}, "unknown config key");+}++void config_defaults(test::Context& t) {+    VnFixture f;+    const fs::path outside = f.root / "outside";+    fs::create_directories(outside);+#if defined(_WIN32)+    const std::string editor_default = "notepad";+    const std::string pager_default = "more";+#else+    const std::string editor_default = "vi";+    const std::string pager_default = "less -R";+#endif+    const std::string defaults = f.vn({"cfg", "-d"}, outside).out;+    t.expect_contains(defaults, "log.default_amount = 20");+    t.expect_contains(defaults, "rename.autodetect = similar");+    t.expect_contains(defaults, "merge.adjacent = strict");+    t.expect_contains(defaults, "user.name = (unset)");+    t.expect_contains(defaults, "editor = " + editor_default);+    t.expect_contains(defaults, "pager = " + pager_default);+    t.expect_not_contains(defaults, "bookmark.current");++    f.vn({"cfg", "-global", "log.default_amount", "50"}, outside);+    f.vn({"cfg", "-global", "editor", "code --wait"}, outside);+    const std::string with_current = f.vn({"cfg", "-d", "-global"}, outside).out;+    t.expect_contains(with_current, "log.default_amount = 20 (current: 50)");+    t.expect_contains(with_current, "editor = " + editor_default + " (current: code --wait)");++    f.init();+    f.vn({"cfg", "log.default_amount", "1"});+    const std::string local_ignored = f.vn({"cfg", "-d"}).out;+    t.expect_contains(local_ignored, "log.default_amount = 20 (current: 50)");+    t.expect_not_contains(local_ignored, "current: 1");++    const std::string internal = f.vn({"cfg", "-i", "-d"}).out;+    t.expect_contains(internal, "bookmark.current = (unset)");+    t.expect_contains(internal, "remote.<name>.url = (unset)");+    t.expect_contains(internal, "promisor = (unset)");+    const std::string long_internal = f.vn({"cfg", "-internal", "-defaults"}).out;+    t.expect_contains(long_internal, "bookmark.current = (unset)");++    f.failed({"cfg", "-d", "extra"}, "takes no operands");+    f.failed({"cfg", "-d", "-list"}, "takes no operands");+    f.failed({"cfg", "-i"}, "requires -d");+    f.failed({"cfg", "--defaults"}, "unknown flag");+    f.failed({"cfg", "--global"}, "unknown flag");+}++void config_pager(test::Context& t) {+    VnFixture f;+    f.init();+    f.vn({"cfg", "pager", "cat"});+    t.expect_eq(pager_command(f.repo), "cat");+    f.vn({"cfg", "-global", "pager", "more"});+    t.expect_eq(pager_command(f.repo), "more");+}++} // namespace++test::Suite config_suite() {+    return {"config",+            {+                {"local", config_local},+                {"global_identity", config_global_identity},+                {"errors", config_errors},+                {"defaults", config_defaults},+                {"pager", config_pager},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/core_tests.cpp@@ -0,0 +1,193 @@+#include "test_support.h"++#include "integration/support.h"++#include "store/store.h"+#include "version/version.h"++namespace vn::integration {+namespace {++void core_init_version_help(test::Context& t) {+    VnFixture f;+    f.init();+    t.expect(fs::exists(f.repo / ".veins" / "format"));+    t.expect(fs::is_directory(f.repo / ".veins" / "op-heads"));+    const std::string version = f.vn({"version"}).out;+    t.expect_contains(version, "veins v" + std::string(vn_version()));+    t.expect_contains(version, "(store v" + std::to_string(STORE_VERSION) + ")");+    t.expect_eq(f.vn({"-v"}).out, version);+    t.expect_eq(f.vn({"-version"}).out, version);+    const std::string commit = vn_commit();+    if (!commit.empty())+        t.expect_contains(version, commit);+    const std::string help_text = f.vn({"help"}).out;+    t.expect_contains(help_text, "commands:");+    t.expect_contains(help_text, "attr");+    t.expect_contains(f.vn({"help", "log"}).out, "vn log");+    t.expect_contains(f.vn({"help", "log"}).out, "-a, -all");+    t.expect_contains(f.vn({"help", "go"}).out, "aliases: commit");+    t.expect_contains(f.vn({"help", "attr"}).out, "vn attr rm");+}++void core_outside_repository(test::Context& t) {+    VnFixture f;+    const fs::path outside = f.root / "outside";+    fs::create_directories(outside);+    for (const std::vector<std::string>& command :+         std::vector<std::vector<std::string>>{{"stat"}, {"log"}, {"hash"}, {"ls"}}) {+        f.failed(command, "not a veins repository", outside);+    }+    t.expect_contains(f.vn({"version"}, outside).out, "veins");+}++void core_status_list_diff_describe(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("a.txt", "alpha\n");+    f.write("dir/b.txt", "beta\n");+    const std::string status = f.vn({"stat"}).out;+    t.expect_contains(status, "A a.txt");+    t.expect_contains(status, "A dir/b.txt");+    std::vector<std::string> plain = split_lines(f.vn({"ls", "-plain"}).out);+    plain.erase(std::remove(plain.begin(), plain.end(), ""), plain.end());+    std::sort(plain.begin(), plain.end());+    t.expect_eq(plain.size(), 2u);+    if (plain.size() == 2) {+        t.expect_eq(plain[0], "a.txt");+        t.expect_eq(plain[1], "dir/b.txt");+    }+    const std::string listed = f.vn({"ls"}).out;+    t.expect_contains(listed, "a.txt");+    t.expect_contains(listed, "b.txt");+    const std::string diff = f.vn({"diff"}).out;+    t.expect_contains(diff, "+alpha");+    t.expect_contains(diff, "+beta");+    f.vn({"desc", "-m", "draft message"});+    t.expect_contains(f.vn({"show", "@"}).out, "draft message");+    t.expect_contains(f.vn({"stat"}).out, "A a.txt");+}++void core_status_paths_relative_to_cwd(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("a.txt", "alpha\n");+    f.write("dir/b.txt", "beta\n");+    f.write("dir/sub/c.txt", "gamma\n");++    const std::string root_status = f.vn({"stat"}).out;+    t.expect_contains(root_status, "A a.txt");+    t.expect_contains(root_status, "A dir/b.txt");++    const std::string dir_status = f.vn({"stat"}, f.repo / "dir").out;+    t.expect_contains(dir_status, "A ../a.txt");+    t.expect_contains(dir_status, "A b.txt");+    t.expect_contains(dir_status, "A sub/c.txt");+    t.expect_not_contains(dir_status, "A dir/b.txt");++    const std::string sub_status = f.vn({"stat"}, f.repo / "dir" / "sub").out;+    t.expect_contains(sub_status, "A ../../a.txt");+    t.expect_contains(sub_status, "A ../b.txt");+    t.expect_contains(sub_status, "A c.txt");+}++void core_commit_log_show_hash(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("a.txt", "one\n");+    f.commit("first commit");+    t.expect_contains(f.vn({"stat"}).out, "working copy clean");+    const std::vector<LogRow> rows = f.log_rows();+    t.expect(rows.size() >= 2);+    if (!rows.empty())+        t.expect(rows.front().working_copy);+    const std::string first = f.commit_for_message("first commit");+    const auto info = f.metadata(first);+    t.expect_eq(info.at("commit").size(), 64u);+    t.expect_eq(f.short_hash(first), info.at("commit").substr(0, 12));+    t.expect_eq(f.hash(first), info.at("commit"));+    const std::string shown = f.vn({"show", first}).out;+    t.expect_contains(shown, "first commit");+    t.expect_contains(shown, "+one");+    t.expect_contains(f.vn({"show", "-no-col-titles", first}).out, "--- /dev/null");++    f.write("a.txt", "two\n");+    t.expect_contains(f.vn({"stat"}).out, "M a.txt");+    t.expect_contains(f.vn({"diff"}).out, "+two");+    f.commit("second commit");+    t.expect_contains(f.vn({"show", f.commit_for_message("second commit")}).out, "second commit");+    t.expect_contains(f.vn({"stat"}).out, "working copy clean");+}++void core_log_limits_revisions(test::Context& t) {+    VnFixture f;+    f.init();+    linear_history(f, 4);+    const std::vector<LogRow> full = f.log_rows();+    t.expect_eq(full.size(), 5u);+    t.expect_eq(split_lines(f.vn({"log", "-l2", "-no-col-titles"}).out).size(), 2u);+    const auto oldest = split_lines(f.vn({"log", "-f2", "-no-col-titles"}).out);+    t.expect_eq(oldest.size(), 2u);+    if (oldest.size() == 2) {+        t.expect_contains(oldest[0], "commit 0");+        t.expect_contains(oldest[1], "commit 1");+    }+    t.expect_eq(split_lines(f.vn({"log", "-l", "1", "-no-col-titles"}).out).size(), 1u);+    t.expect_eq(split_lines(f.vn({"log", "l2", "-no-col-titles"}).out).size(), 2u);+    const std::string one = f.commit_for_message("commit 1");+    const std::string selected = f.vn({"log", "-rev", one, "-no-col-titles"}).out;+    t.expect_contains(selected, "commit 1");+    t.expect_contains(selected, "commit 0");+    t.expect_not_contains(selected, "commit 2");+    for (const char* bad : {"-l0", "-lfoo", "-bad"})+        f.failed({"log", bad});+}++void core_checkout_materializes_and_new(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("a.txt", "one\n");+    f.vn({"bmk", "set", "main"});+    f.commit("first");+    const std::string first = f.hash("main");+    f.write("a.txt", "two\n");+    f.write("later.txt", "later\n");+    f.commit("second");+    const std::string second = f.hash("main");+    f.vn({"bmk", "set", "main", "-rev", first});+    f.vn({"bmk", "set", "feature", "-rev", second});++    f.vn({"co", "main"});+    t.expect_eq(f.read("a.txt"), "one\n");+    t.expect(!f.exists("later.txt"));+    t.expect_contains(f.vn({"stat"}).out, "working copy clean");+    t.expect_contains(f.vn({"bmk", "ls"}).out, "main");++    f.vn({"co", "feature"});+    t.expect_eq(f.read("a.txt"), "two\n");+    t.expect(f.exists("later.txt"));++    f.vn({"co", second});+    t.expect_eq(f.read("a.txt"), "two\n");+    f.vn({"new"});+    t.expect_contains(f.vn({"stat"}).out, "working copy clean");+    t.expect(!f.log_rows().empty());+    if (!f.log_rows().empty())+        t.expect(f.log_rows().front().working_copy);+}++} // namespace++test::Suite core_suite() {+    return {"core",+            {+                {"init_version_help", core_init_version_help},+                {"outside_repository", core_outside_repository},+                {"status_list_diff_describe", core_status_list_diff_describe},+                {"status_paths_relative_to_cwd", core_status_paths_relative_to_cwd},+                {"commit_log_show_hash", core_commit_log_show_hash},+                {"log_limits_revisions", core_log_limits_revisions},+                {"checkout_materializes_and_new", core_checkout_materializes_and_new},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/errors_tests.cpp@@ -0,0 +1,201 @@+#include "test_support.h"++#include "integration/support.h"++#include "store/store.h"++#include <filesystem>+#include <random>+#include <string>+#include <vector>++namespace vn::integration {+namespace {++void expect_no_exception(test::Context& t, const CommandResult& result,+                         std::string_view command) {+    (void)command;+    t.expect_not_contains(result.err, "exception:");+}++void errors_bad_arguments(test::Context& t) {+    (void)t;+    VnFixture f;+    f.init();+    for (const std::vector<std::string>& command : std::vector<std::vector<std::string>>{+             {"go"},+             {"go", "-m", ""},+             {"rm"},+             {"ex"},+             {"show", "unknown-revision"},+             {"hash", "unknown-revision"},+             {"co", "unknown-revision"},+             {"amend", "@"},+             {"rebase", "-s", "@"},+             {"new", "-bad"},+         }) {+        f.failed(command, "error:");+    }+    f.failed({"unknown-command"}, "unknown command");+    f.failed({"help", "unknown-command"}, "unknown command");+    f.failed({"cfg", "key", "value", "extra"}, "accepts a key and one value");+}++void errors_self_test_fsck_version(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "content\n");+    f.commit("content");+    t.expect_contains(f.vn({"self-test"}).out, "self-test: ok");+    t.expect_contains(f.vn({"fsck"}).out, "fsck: clean");+    t.expect_contains(f.vn({"fsck", "-verbose"}).out, "fsck: clean");+    t.expect_contains(f.vn({"version"}).out, "veins");+}++void errors_log_show_arguments(test::Context& t) {+    (void)t;+    VnFixture f;+    f.init();+    for (const std::vector<std::string>& command : std::vector<std::vector<std::string>>{+             {"log", "-l"}, {"log", "-f", "0"}, {"log", "-bad"}, {"show", "-bad"}}) {+        f.failed(command);+    }+}++void errors_command_junk(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("tracked.txt", "one\n");+    f.commit("initial");++    const std::string huge(200'000, 'x');+    const std::string binary("\x01\x7f\x80\xff", 4);+    const std::vector<std::string> tokens = {+        "",          "-",         "--",        "-x",          "-r",+        "-rev",      "-m",        "-message",  "-l",          "-f",+        "-a",        "-all",      "-short",    "-long",       "-plain",+        "-p",        "-v",        "-verbose",  "-gen",        "gen",+        "txt",       "bin",       "eol",       "-eol",        "@",+        "master",    "HEAD",      "0",         "1",           "999999999999999999999999",+        "a",         "a/b",       "..",        "../outside",  "/",+        "//",        ".",         ".veins",    "a.veins",     binary,+        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "*.txt", "set", "ls", "rm",+        "mv",        "get",       "list",      "unset",       "log",+        "restore",   "revert",    "latest",    "theirs",      "ours",+        "current",   "all()",     "unknown",   huge,+    };+    const std::vector<std::string> commands = {+        "stat",   "ls",     "inf",     "log",     "show",    "hash",    "diff",+        "new",    "desc",   "go",      "amend",   "co",      "bmk",     "tag",+        "cfg",    "attr",   "op",      "undo",    "merge",   "rebase",  "xs",+        "resolve", "fsck",  "repack",  "self-test", "version", "help",   "rm",+        "mv",     "ex",     "edit",    "init",+    };++    for (const auto& command : commands) {+        for (int shape = 0; shape < 4; ++shape) {+            std::vector<std::string> args{"vn", command};+            if (shape == 1)+                args.push_back("");+            else if (shape == 2)+                args.push_back("--");+            else if (shape == 3) {+                args.push_back("-r");+                args.push_back("");+            }+            CommandResult result = f.vn(args, {}, false);+            expect_no_exception(t, result, command);+        }+    }++    std::mt19937_64 rng(0x5eed1234ull);+    std::uniform_int_distribution<std::size_t> command_pick(0, commands.size() - 1);+    std::uniform_int_distribution<std::size_t> token_pick(0, tokens.size() - 1);+    std::uniform_int_distribution<int> count_dist(0, 5);+    for (int iteration = 0; iteration < 400; ++iteration) {+        std::vector<std::string> args{"vn", commands[command_pick(rng)]};+        const int count = count_dist(rng);+        for (int i = 0; i < count; ++i)+            args.push_back(tokens[token_pick(rng)]);+        CommandResult result = f.vn(args, {}, false);+        expect_no_exception(t, result, join_args(args));+    }+}++void errors_corrupt_repository(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("a.txt", "one\n");+    f.commit("first");++    std::string bad_config = "not a key value line\n";+    bad_config.push_back('\0');+    bad_config.append(std::string(100'000, 'x'));+    bad_config.push_back('\n');+    f.write(".veins/config", bad_config);++    std::string hostile_ignore(100'000, '*');+    hostile_ignore.push_back('\n');+    f.write(".vnexclude", hostile_ignore);+    f.write(".vnattribs", std::string(100'000, 'a') + "\n");++    for (const std::vector<std::string>& command :+         std::vector<std::vector<std::string>>{{"cfg", "list"},+                                               {"stat"},+                                               {"log"},+                                               {"inf"},+                                               {"fsck"},+                                               {"version"}}) {+        CommandResult result = f.vn(command, {}, false);+        expect_no_exception(t, result, join_args(command));+    }++    const fs::path heads = f.repo / ".veins" / "op-heads";+    if (write_file(heads / "not-a-head", bytes_of("junk")))+        (void)write_file(heads / std::string(64, 'z'), bytes_of("junk"));+    for (const std::vector<std::string>& command :+         std::vector<std::vector<std::string>>{{"stat"}, {"log"}, {"fsck"}}) {+        CommandResult result = f.vn(command, {}, false);+        expect_no_exception(t, result, join_args(command));+    }++    const fs::path packs = f.repo / ".veins" / "store" / "packs";+    std::error_code ec;+    if (fs::is_directory(packs, ec)) {+        for (const auto& entry : fs::directory_iterator(packs, ec)) {+            if (ec)+                break;+            if (entry.path().extension() != ".vpack")+                continue;+            auto data = read_file_opt(entry.path());+            if (!data || data->empty())+                continue;+            (*data)[data->size() / 2] ^= 0xff;+            (void)write_file(entry.path(), bytes_of(*data));+            break;+        }+    }++    for (const std::vector<std::string>& command :+         std::vector<std::vector<std::string>>{+             {"stat"}, {"log"}, {"fsck"}, {"show"}, {"ls"}, {"hash"}, {"inf"},+             {"self-test"}, {"repack"}}) {+        CommandResult result = f.vn(command, {}, false);+        expect_no_exception(t, result, join_args(command));+    }+}++} // namespace++test::Suite errors_suite() {+    return {"errors",+            {+                {"bad_arguments", errors_bad_arguments},+                {"self_test_fsck_version", errors_self_test_fsck_version},+                {"log_show_arguments", errors_log_show_arguments},+                {"command_junk", errors_command_junk},+                {"corrupt_repository", errors_corrupt_repository},+            }};+}+} // namespace vn::integration+--- /dev/null+++ b/xveins/tests/integration/git_tests.cpp@@ -0,0 +1,66 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void git_bridge_import_materialize_export(test::Context& t) {+#if defined(_WIN32)+    t.expect(true);+#else+    if (!git_available()) {+        t.expect(true);+        return;+    }+    VnFixture f;+    const fs::path git_repo = make_git_repository(t, f);+    const fs::path vn_repo = f.root / "vnrepo";+    f.vn({"init", vn_repo.string(), "-git-import:" + git_repo.string()}, f.root);+    std::string log = f.vn({"log", "-no-col-titles"}, vn_repo).out;+    t.expect_contains(log, "git one");+    t.expect_contains(log, "git two");+    t.expect_eq(split_lines(f.vn({"ls", "-plain"}, vn_repo).out).size(), 1u);+    f.vn({"git", "materialize"}, vn_repo);+    t.expect_contains(f.vn({"stat"}, vn_repo).out, "working copy clean");+    t.expect_eq(f.read("a.txt", vn_repo), "one\ntwo\n");++    f.write("b.txt", "native\n", vn_repo);+    f.commit("native commit", vn_repo);+    f.vn({"git", "export"}, vn_repo);+    const fs::path git_dir = vn_repo / ".veins" / "git";+    const CommandResult subjects =+        run_shell({"git", "--git-dir", git_dir.string(), "log", "--format=%s", "--all"}, f.root);+    require_shell(t, subjects, "git log");+    t.expect_contains(subjects.out, "native commit");+    const CommandResult tree =+        run_shell({"git", "--git-dir", git_dir.string(), "show", "master:b.txt"}, f.root);+    require_shell(t, tree, "git show");+    t.expect_eq(tree.out, "native\n");+    t.expect_contains(f.vn({"fsck"}, vn_repo).out, "fsck: clean");+#endif+}++void git_bridge_invalid_import(test::Context& t) {+    (void)t;+#if defined(_WIN32)+    t.expect(true);+#else+    VnFixture f;+    const fs::path not_git = f.root / "not-git";+    fs::create_directories(not_git);+    f.failed({"init", (f.root / "bad").string(), "-git-import:" + not_git.string()},+             "not a git repository root", f.root);+#endif+}++} // namespace++test::Suite git_suite() {+    return {"git",+            {+                {"import_materialize_export", git_bridge_import_materialize_export},+                {"invalid_import", git_bridge_invalid_import},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/history_tests.cpp@@ -0,0 +1,179 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void history_log_is_topological(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("base.txt", "base\n");+    f.vn({"bmk", "set", "master"});+    f.commit("base");+    f.vn({"bmk", "set", "left"});+    f.vn({"new", "left"});+    f.write("left.txt", "left\n");+    f.commit("left");+    f.vn({"bmk", "set", "right"});+    f.vn({"new", "master"});+    f.write("right.txt", "right\n");+    f.commit("right");++    const std::vector<std::string> commits = f.log_commits();+    for (std::size_t index = 0; index < commits.size(); ++index) {+        for (const std::string& parent : f.parents(commits[index])) {+            const auto found = std::find(commits.begin(), commits.end(), parent.substr(0, 12));+            if (found == commits.end())+                continue;+            const std::size_t parent_index =+                static_cast<std::size_t>(std::distance(commits.begin(), found));+            t.expect(parent_index > index);+        }+    }+}++void history_amend_rewrites_descendants(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "one\n");+    f.commit("one");+    const std::string one = f.commit_for_message("one");+    f.write("f.txt", "two\n");+    f.commit("two");+    const std::string two = f.commit_for_message("two");+    const std::string one_change = f.metadata(one).at("change");+    const std::string two_change = f.metadata(two).at("change");+    f.vn({"amend", one, "-m", "one renamed"});+    const std::string new_one = f.commit_for_message("one renamed");+    const std::string new_two = f.commit_for_message("two");+    t.expect_ne(one.substr(0, 12), new_one);+    t.expect_ne(two.substr(0, 12), new_two);+    t.expect_eq(f.metadata(new_one).at("change"), one_change);+    t.expect_eq(f.metadata(new_two).at("change"), two_change);+    t.expect_eq(f.parents(new_two).count(new_one), 1u);+}++void history_undo_and_operation_restore(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "one\n");+    f.commit("one");+    const std::string one = f.commit_for_message("one");+    f.write("f.txt", "two\n");+    f.commit("two");+    f.vn({"amend", one, "-m", "renamed"});+    t.expect_contains(f.vn({"log"}).out, "renamed");+    f.vn({"undo"});+    t.expect_not_contains(f.vn({"log"}).out, "renamed");+    const std::vector<std::string> ops = split_lines(f.vn({"op", "log"}).out);+    t.expect(ops.size() >= 2);+    if (ops.size() >= 2) {+        std::istringstream stream(ops[1]);+        std::string previous;+        stream >> previous;+        f.vn({"op", "restore", previous});+        t.expect_contains(f.vn({"log"}).out, "renamed");+    }+}++void history_log_default_amount(test::Context& t) {+    VnFixture f;+    f.init();+    linear_history(f, 22);+    t.expect_eq(f.log_rows().size(), 20u);+    const std::vector<LogRow> default_rows = f.log_rows();+    bool has_newest = false;+    bool has_oldest = false;+    for (const LogRow& row : default_rows) {+        if (row.message == "commit 21")+            has_newest = true;+        if (row.message == "commit 2")+            has_oldest = true;+    }+    t.expect(has_newest);+    t.expect(!has_oldest);++    f.vn({"cfg", "-global", "log.default_amount", "3"});+    t.expect_eq(f.log_rows().size(), 3u);+    t.expect_eq(split_lines(f.vn({"log", "-a", "-no-col-titles"}).out).size(), 23u);+    t.expect_eq(split_lines(f.vn({"log", "-all", "-no-col-titles"}).out).size(), 23u);+    t.expect_eq(split_lines(f.vn({"log", "-a", "-l5", "-no-col-titles"}).out).size(), 23u);+    t.expect_eq(split_lines(f.vn({"log", "-l5", "-a", "-no-col-titles"}).out).size(), 23u);+    f.vn({"cfg", "log.default_amount", "1"});+    t.expect_eq(f.log_rows().size(), 3u);+    t.expect_eq(split_lines(f.vn({"log", "-l5", "-no-col-titles"}).out).size(), 5u);+    const auto oldest = split_lines(f.vn({"log", "-f2", "-no-col-titles"}).out);+    t.expect_eq(oldest.size(), 2u);+    if (oldest.size() == 2) {+        t.expect_contains(oldest[0], "commit 0");+        t.expect_contains(oldest[1], "commit 1");+    }+    f.vn({"cfg", "-global", "log.default_amount", "not-a-number"});+    t.expect_eq(f.log_rows().size(), 20u);+}++void history_diff_path_filter(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("one.txt", "one\n");+    f.write("two.txt", "two\n");+    f.commit("base");+    f.write("one.txt", "one changed\n");+    f.write("two.txt", "two changed\n");++    const std::string one_diff = f.vn({"diff", "one.txt"}).out;+    t.expect_contains(one_diff, "+one changed");+    t.expect_not_contains(one_diff, "+two changed");+    const std::string all_diff = f.vn({"diff", "-a"}).out;+    t.expect_contains(all_diff, "+one changed");+    t.expect_contains(all_diff, "+two changed");+    f.failed({"diff", "--all"}, "unknown flag");+    f.failed({"show", "--all"}, "unknown flag");++    const fs::path subdir = f.repo / "sub";+    fs::create_directories(subdir);+    const std::string relative_diff = f.vn({"diff", "../one.txt"}, subdir).out;+    t.expect_contains(relative_diff, "+one changed");+    t.expect_not_contains(relative_diff, "+two changed");++    f.vn({"go", "-m", "second"});+    const std::string second = f.commit_for_message("second");+    const std::string revision_diff = f.vn({"diff", "-rev", second, "one.txt"}).out;+    t.expect_contains(revision_diff, "+one changed");+    t.expect_not_contains(revision_diff, "+two changed");+    t.expect_contains(f.vn({"diff"}).out, "no diff to show");+    t.expect_contains(f.vn({"help", "diff"}).out, "-a, -all");+}++void history_show_and_diff(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "one\n");+    f.commit("one");+    const std::string one = f.commit_for_message("one");+    f.write("f.txt", "two\n");+    f.commit("two");+    const std::string diff = f.vn({"diff", one, "@"}).out;+    t.expect_contains(diff, "-one");+    t.expect_contains(diff, "+two");+    const std::string shown = f.vn({"show", one}).out;+    t.expect_contains(shown, "one");+    t.expect_contains(f.vn({"show", "-a", one}).out, "--- /dev/null");+    t.expect_contains(f.vn({"help", "show"}).out, "-a, -all");+}++} // namespace++test::Suite history_suite() {+    return {"history",+            {+                {"log_is_topological", history_log_is_topological},+                {"log_default_amount", history_log_default_amount},+                {"amend_rewrites_descendants", history_amend_rewrites_descendants},+                {"undo_and_operation_restore", history_undo_and_operation_restore},+                {"diff_path_filter", history_diff_path_filter},+                {"show_and_diff", history_show_and_diff},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/main.cpp@@ -0,0 +1,51 @@+#include "test_support.h"++#include "cli/cli.h"+#include "integration/suites.h"++#include <iostream>+#include <string>+#include <string_view>+#include <vector>++namespace {++std::vector<vn::test::Suite> suites() {+    return {+        vn::integration::core_suite(),     vn::integration::worktree_suite(),+        vn::integration::history_suite(),  vn::integration::refs_suite(),+        vn::integration::config_suite(),   vn::integration::merge_suite(),+        vn::integration::rebase_suite(),   vn::integration::git_suite(),+        vn::integration::protocol_suite(), vn::integration::errors_suite(),+    };+}++} // namespace++int main(int argc, char** argv) {+    // The protocol tests run in-process, so the client may re-exec this binary as+    // a stdio server.+    if (argc >= 2 && std::string_view(argv[1]) == "serve") {+        std::vector<std::string> args;+        args.reserve(static_cast<std::size_t>(argc));+        for (int i = 0; i < argc; ++i)+            args.emplace_back(argv[i]);+        return vn::cli_run(args);+    }++    std::string suite;+    for (int i = 1; i < argc; ++i) {+        const std::string_view arg = argv[i];+        if (arg == "--suite" && i + 1 < argc) {+            suite = argv[++i];+        } else if (arg == "--list") {+            for (const vn::test::Suite& item : suites())+                std::cout << item.name << "\n";+            return 0;+        } else {+            std::cerr << "unknown argument: " << arg << "\n";+            return 1;+        }+    }+    return vn::test::run_tests(suites(), suite);+}--- /dev/null+++ b/xveins/tests/integration/merge_tests.cpp@@ -0,0 +1,102 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void create_diverged(VnFixture& f, bool same_file) {+    f.init();+    f.write("f.txt", "base\n");+    f.vn({"bmk", "set", "master"});+    f.commit("base");+    f.vn({"bmk", "set", "left"});+    f.vn({"new", "left"});+    f.write("f.txt", same_file ? "left\n" : "base\n");+    f.write("left.txt", "left\n");+    f.commit("left");+    f.vn({"bmk", "set", "right"});+    f.vn({"new", "master"});+    f.write("f.txt", same_file ? "right\n" : "base\n");+    f.write("right.txt", "right\n");+    f.commit("right");+}++void merge_clean(test::Context& t) {+    VnFixture f;+    create_diverged(f, false);+    f.vn({"merge", "left"});+    t.expect(f.metadata("@").at("parents").find(' ') != std::string::npos);+    t.expect(f.exists("left.txt"));+    t.expect(f.exists("right.txt"));+    f.commit("merge");+    t.expect_contains(f.vn({"log"}).out, "merge");+    t.expect_contains(f.vn({"xs"}).out, "no conflicts");+    t.expect_contains(f.vn({"fsck"}).out, "fsck: clean");+}++void merge_conflict_resolve_theirs(test::Context& t) {+    VnFixture f;+    create_diverged(f, true);+    f.vn({"merge", "left"});+    const std::string status = f.vn({"stat"}).out;+    t.expect_contains(status, "C f.txt");+    t.expect_contains(status, "1 conflict(s)");+    t.expect_contains(status, "1 conflicted commit(s) in ancestry");+    t.expect(f.exists("f.txt.base"));+    t.expect(f.exists("f.txt.ours"));+    t.expect(f.exists("f.txt.theirs"));+    t.expect_contains(f.vn({"xs", "-porcelain"}).out, "f.txt\ttext\t");+    t.expect_contains(f.vn({"show", "@"}).out, "f.txt");+    f.vn({"resolve", "-take", "theirs", "f.txt"});+    t.expect_contains(f.vn({"stat"}).out, "M f.txt");+    t.expect_eq(f.read("f.txt"), "left\n");+    t.expect_contains(f.vn({"xs"}).out, "no conflicts");+    f.commit("resolved");+    t.expect_contains(f.vn({"stat"}).out, "working copy clean");+}++void merge_conflict_resolve_ours(test::Context& t) {+    VnFixture f;+    create_diverged(f, true);+    f.vn({"merge", "left"});+    f.vn({"resolve", "-take", "ours", "f.txt"});+    t.expect_eq(f.read("f.txt"), "right\n");+    t.expect_contains(f.vn({"xs"}).out, "no conflicts");+}++void merge_conflict_resolve_current(test::Context& t) {+    VnFixture f;+    create_diverged(f, true);+    f.vn({"merge", "left"});+    f.write("f.txt", "manual resolution\n");+    f.vn({"resolve", "f.txt"});+    t.expect_eq(f.read("f.txt"), "manual resolution\n");+    t.expect_contains(f.vn({"xs"}).out, "no conflicts");+}++void merge_multiple(test::Context& t) {+    VnFixture f;+    create_diverged(f, false);+    f.vn({"merge", "left", "right"});+    std::istringstream parents(f.metadata("@").at("parents"));+    std::size_t count = 0;+    std::string parent;+    while (parents >> parent)+        ++count;+    t.expect_eq(count, 3u);+}++} // namespace++test::Suite merge_suite() {+    return {"merge",+            {+                {"clean", merge_clean},+                {"conflict_resolve_theirs", merge_conflict_resolve_theirs},+                {"conflict_resolve_ours", merge_conflict_resolve_ours},+                {"conflict_resolve_current", merge_conflict_resolve_current},+                {"multiple", merge_multiple},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/protocol_tests.cpp@@ -0,0 +1,97 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void protocol_clone_whoami(test::Context& t) {+    VnFixture f;+    make_source_repository(f);+    const fs::path source = f.root / "source";+    const fs::path clone = f.root / "clone";+    fs::create_directories(clone);+    f.vn({"clone", "file://" + source.string(), clone.string()}, f.root);+    t.expect_eq(f.read("a.txt", clone), "hello\n");+    t.expect_contains(f.vn({"log"}, clone).out, "initial");+    t.expect_contains(f.vn({"stat"}, clone).out, "working copy clean");+    t.expect_contains(f.vn({"remote", "list"}, clone).out, "origin");+    t.expect_contains(f.vn({"whoami", "origin"}, clone).out, "role: read");+}++void protocol_push_fetch(test::Context& t) {+    VnFixture f;+    make_source_repository(f);+    const fs::path source = f.root / "source";+    const std::string key_info = f.vn({"key", "generate", "integration"}, source).out;+    std::string public_key;+    for (const std::string& line : split_lines(key_info)) {+        if (line.starts_with("public key: ")) {+            public_key = line.substr(std::string("public key: ").size());+            break;+        }+    }+    t.expect(!public_key.empty());+    f.vn({"access", "add", "-role", "write", "-key", public_key, "-name", "integration"}, source);+    t.expect_contains(f.vn({"key", "show", "integration"}, source).out, "fingerprint:");+    t.expect_contains(f.vn({"key", "list"}, source).out, "integration");+    f.vn({"auth", "use", "integration"}, source);+    t.expect_contains(f.vn({"auth", "list"}, source).out, "integration");++    const fs::path clone_a = f.root / "clone-a";+    f.vn({"clone", "file://" + source.string(), clone_a.string()}, f.root);+    f.vn({"cfg", "remote.origin.key", "integration"}, clone_a);+    f.write("a.txt", "from clone a\n", clone_a);+    f.commit("clone a change", clone_a);+    f.write("c.txt", "from clone a again\n", clone_a);+    f.commit("clone a second change", clone_a);+    const CommandResult pushed = f.vn({"push", "origin", "master"}, clone_a);+    t.expect_contains(pushed.out, "pushed master");+    t.expect_contains(f.vn({"log"}, source).out, "clone a change");+    t.expect_contains(f.vn({"log"}, source).out, "clone a second change");+    t.expect_contains(f.vn({"whoami", "origin"}, clone_a).out, "role: write");++    f.vn({"tag", "set", "v0.0.1"}, clone_a);+    const CommandResult tag_pushed = f.vn({"push", "origin", "master"}, clone_a);+    t.expect_contains(tag_pushed.out, "pushed 1 tag(s)");+    t.expect_contains(f.vn({"tag", "ls"}, source).out, "v0.0.1");++    const fs::path clone_b = f.root / "clone-b";+    f.vn({"clone", "file://" + source.string(), clone_b.string()}, f.root);+    f.vn({"cfg", "remote.origin.key", "integration"}, clone_b);+    f.write("b.txt", "from clone b\n", clone_b);+    f.commit("clone b change", clone_b);+    f.vn({"push", "origin", "master"}, clone_b);+    f.vn({"fetch", "origin"}, clone_a);+    t.expect_contains(f.vn({"log", "-rev", "origin/master"}, clone_a).out, "clone b change");+}++void protocol_bad_inputs(test::Context& t) {+    (void)t;+    VnFixture f;+    f.init();+    f.failed({"clone", "not-a-url", "dest"}, "unsupported URL");+    f.failed({"clone", "file:///does/not/exist", "dest"}, "error:");++    const fs::path occupied = f.root / "occupied";+    fs::create_directories(occupied);+    if (!write_file(occupied / "keep.txt", bytes_of("keep\n")))+        throw test::Failure("cannot write occupied directory file");+    const std::string source = "file://" + f.repo.string();+    f.failed({"clone", source, occupied.string()}, "destination directory is not empty", f.root);+    f.failed({"gg", source, occupied.string()}, "destination directory is not empty", f.root);+    f.failed({"clone", source, (occupied / "keep.txt").string()},+             "destination already exists and is not a directory", f.root);+}++} // namespace++test::Suite protocol_suite() {+    return {"protocol",+            {+                {"clone_whoami", protocol_clone_whoami},+                {"push_fetch", protocol_push_fetch},+                {"bad_inputs", protocol_bad_inputs},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/rebase_tests.cpp@@ -0,0 +1,99 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void rebase_changes_parent(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("base.txt", "base\n");+    f.vn({"bmk", "set", "master"});+    f.commit("base");+    f.vn({"bmk", "set", "left"});+    f.vn({"new", "left"});+    f.write("left.txt", "left\n");+    f.commit("left");+    const std::string left_change = f.metadata("left").at("change");+    f.vn({"bmk", "set", "right"});+    f.vn({"new", "master"});+    f.write("right.txt", "right\n");+    f.commit("right");+    const std::string right = f.hash("right");+    f.vn({"rebase", "-s", "left", "-d", "right"});+    t.expect_eq(f.parents("left").count(right.substr(0, 12)), 1u);+    t.expect_eq(f.metadata("left").at("change"), left_change);+    t.expect_contains(f.vn({"show", "left"}).out, "left");+}++void rebase_rewrites_descendants(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("base.txt", "base\n");+    f.vn({"bmk", "set", "master"});+    f.commit("base");+    f.vn({"bmk", "set", "side"});+    f.vn({"new", "side"});+    f.write("one.txt", "one\n");+    f.commit("one");+    const std::string first = f.commit_for_message("one");+    const std::string first_change = f.metadata(first).at("change");+    f.write("two.txt", "two\n");+    f.commit("two");+    const std::string second = f.commit_for_message("two");+    const std::string second_change = f.metadata(second).at("change");+    f.vn({"bmk", "set", "target"});+    f.vn({"new", "master"});+    f.write("target.txt", "target\n");+    f.commit("target");+    const std::string target = f.commit_for_message("target");+    f.vn({"rebase", "-s", first, "-d", target});+    const std::string new_first = f.commit_for_message("one");+    const std::string new_second = f.commit_for_message("two");+    t.expect_eq(f.metadata(new_first).at("change"), first_change);+    t.expect_eq(f.metadata(new_second).at("change"), second_change);+    t.expect_eq(f.parents(new_first).count(target), 1u);+    t.expect_eq(f.parents(new_second).count(new_first), 1u);+}++void rebase_conflict(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "base\n");+    f.vn({"bmk", "set", "master"});+    f.commit("base");+    f.vn({"bmk", "set", "left"});+    f.vn({"new", "left"});+    f.write("f.txt", "left\n");+    f.commit("left");+    f.vn({"bmk", "set", "right"});+    f.vn({"new", "master"});+    f.write("f.txt", "right\n");+    f.commit("right");+    f.vn({"rebase", "-s", "left", "-d", "right"});+    bool conflicted = false;+    for (const LogRow& row : f.log_rows()) {+        if (row.message.find("left") != std::string::npos &&+            row.raw.find("(conflicted)") != std::string::npos)+            conflicted = true;+    }+    t.expect(conflicted);+    f.vn({"co", "left"});+    t.expect_contains(f.vn({"xs"}).out, "f.txt");+    t.expect(f.exists("f.txt.base"));+    f.vn({"resolve", "-take", "theirs", "f.txt"});+    t.expect_contains(f.vn({"xs"}).out, "no conflicts");+}++} // namespace++test::Suite rebase_suite() {+    return {"rebase",+            {+                {"changes_parent", rebase_changes_parent},+                {"rewrites_descendants", rebase_rewrites_descendants},+                {"conflict", rebase_conflict},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/refs_tests.cpp@@ -0,0 +1,85 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void refs_bookmarks(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "one\n");+    f.commit("one");+    const std::string one = f.commit_for_message("one");+    f.write("f.txt", "two\n");+    f.commit("two");+    const std::string two = f.commit_for_message("two");+    f.vn({"bmk", "set", "main", "-rev", one});+    f.vn({"bmk", "set", "feature", "-rev", two});+    std::string listing = f.vn({"bmk", "ls"}).out;+    t.expect_contains(listing, "main");+    t.expect_contains(listing, "feature");+    f.vn({"bmk", "mv", "main", "-rev", two});+    t.expect_contains(f.vn({"bmk", "ls"}).out, two.substr(0, 12));+    f.vn({"bmk", "rm", "feature"});+    t.expect_not_contains(f.vn({"bmk", "ls"}).out, "feature");+    f.failed({"bmk", "rm", "missing"}, "no such bookmark");+}++void refs_current_bookmark(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "one\n");+    f.vn({"bmk", "set", "main"});+    f.commit("one");+    const std::string one = f.hash("main");+    t.expect_contains(f.vn({"bmk", "ls"}).out, one.substr(0, 12));+    f.write("f.txt", "two\n");+    f.commit("two");+    const std::string two = f.hash("main");+    t.expect_ne(one, two);+    t.expect_contains(f.vn({"bmk", "ls"}).out, two.substr(0, 12));+    t.expect_contains(f.vn({"cfg"}).out, "bookmark.current = main");+}++void refs_tags(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("f.txt", "one\n");+    f.commit("one");+    f.vn({"tag", "set", "v0.0.9"});+    f.vn({"tag", "set", "v0.0.10"});+    const std::string listing = f.vn({"tag", "ls"}).out;+    t.expect_contains(listing, "v0.0.9");+    t.expect_contains(listing, "v0.0.10");+    t.expect_eq(trim_copy(f.vn({"tag", "latest"}).out), "v0.0.10");+    f.vn({"tag", "rm", "v0.0.9"});+    t.expect_not_contains(f.vn({"tag", "ls"}).out, "v0.0.9");+    f.failed({"tag", "rm", "missing"}, "no such tag");+}++void refs_remote_configuration(test::Context& t) {+    VnFixture f;+    f.init();+    f.vn({"remote", "add", "origin", "file:///tmp/example"});+    t.expect_contains(f.vn({"remote", "list"}).out, "origin");+    f.failed({"remote", "add", "origin", "file:///other"}, "already exists");+    f.vn({"remote", "set-url", "origin", "file:///tmp/other"});+    t.expect_contains(f.vn({"remote", "list"}).out, "file:///tmp/other");+    f.vn({"remote", "remove", "origin"});+    t.expect_not_contains(f.vn({"remote", "list"}).out, "origin");+    f.failed({"remote", "remove", "origin"}, "unknown remote");+}++} // namespace++test::Suite refs_suite() {+    return {"refs",+            {+                {"bookmarks", refs_bookmarks},+                {"current_bookmark", refs_current_bookmark},+                {"tags", refs_tags},+                {"remote_configuration", refs_remote_configuration},+            }};+}+} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/suites.h@@ -0,0 +1,18 @@+#pragma once++#include "test_support.h"++namespace vn::integration {++test::Suite core_suite();+test::Suite worktree_suite();+test::Suite history_suite();+test::Suite refs_suite();+test::Suite config_suite();+test::Suite merge_suite();+test::Suite rebase_suite();+test::Suite git_suite();+test::Suite protocol_suite();+test::Suite errors_suite();++} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/support.cpp@@ -0,0 +1,205 @@+#include "integration/support.h"+#include "test_support.h"++#include "cli/cli.h"+#include "core/common.h"+#include "store/store.h"+#include "version/version.h"++#include <algorithm>+#include <array>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <fstream>+#include <iostream>+#include <map>+#include <set>+#include <sstream>+#include <string>+#include <string_view>+#include <vector>++#if !defined(_WIN32)+#include <sys/wait.h>+#endif++namespace vn::integration {++std::string trim_copy(std::string_view text) {+    std::size_t start = 0;+    std::size_t end = text.size();+    while (start < end && (text[start] == ' ' || text[start] == '\t' || text[start] == '\r' ||+                           text[start] == '\n'))+        ++start;+    while (end > start && (text[end - 1] == ' ' || text[end - 1] == '\t' || text[end - 1] == '\r' ||+                           text[end - 1] == '\n'))+        --end;+    return std::string(text.substr(start, end - start));+}++std::vector<std::string> split_lines(std::string_view text) {+    std::vector<std::string> lines;+    std::size_t start = 0;+    while (start < text.size()) {+        const std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos) {+            lines.emplace_back(text.substr(start));+            break;+        }+        lines.emplace_back(text.substr(start, end - start));+        start = end + 1;+    }+    return lines;+}++std::vector<std::string> split_columns(std::string_view line) {+    std::vector<std::string> parts;+    std::size_t start = 0;+    while (start < line.size()) {+        while (start < line.size() && line[start] == ' ')+            ++start;+        if (start >= line.size())+            break;+        std::size_t end = start;+        while (end < line.size()) {+            if (line[end] == ' ' && end + 1 < line.size() && line[end + 1] == ' ')+                break;+            ++end;+        }+        parts.emplace_back(line.substr(start, end - start));+        start = end;+    }+    return parts;+}++std::string join_args(const std::vector<std::string>& args) {+    std::string out;+    for (std::size_t i = 0; i < args.size(); ++i) {+        if (i != 0)+            out.push_back(' ');+        out += args[i];+    }+    return out;+}++CommandResult run_cli(const std::vector<std::string>& command, const fs::path& cwd) {+    std::vector<std::string> args;+    args.reserve(command.size() + 1);+    args.emplace_back("vn");+    args.insert(args.end(), command.begin(), command.end());++    const fs::path previous = fs::current_path();+    fs::current_path(cwd);+    std::ostringstream out;+    std::ostringstream err;+    auto* old_out = std::cout.rdbuf(out.rdbuf());+    auto* old_err = std::cerr.rdbuf(err.rdbuf());+    int code = 0;+    try {+        code = cli_run(args);+    } catch (const std::exception& error) {+        code = 1;+        err << "exception: " << error.what() << "\n";+    } catch (...) {+        code = 1;+        err << "exception: unknown failure\n";+    }+    std::cout.flush();+    std::cerr.flush();+    std::cout.rdbuf(old_out);+    std::cerr.rdbuf(old_err);+    fs::current_path(previous);+    return CommandResult{code, out.str(), err.str()};+}++void set_environment(const char* key, const std::string& value) {+#if defined(_WIN32)+    _putenv_s(key, value.c_str());+#else+    setenv(key, value.c_str(), 1);+#endif+}++std::string shell_quote(std::string_view value) {+    std::string out = "'";+    for (char c : value) {+        if (c == '\'')+            out += "'\\''";+        else+            out.push_back(c);+    }+    out.push_back('\'');+    return out;+}++CommandResult run_shell(const std::vector<std::string>& command, const fs::path& cwd) {+#if defined(_WIN32)+    (void)command;+    (void)cwd;+    return CommandResult{1, {}, "shell commands are not supported on Windows\n"};+#else+    std::string line = "cd " + shell_quote(cwd.string()) + " && ";+    for (std::size_t i = 0; i < command.size(); ++i) {+        if (i != 0)+            line.push_back(' ');+        line += shell_quote(command[i]);+    }+    line += " 2>&1";+    FILE* pipe = popen(line.c_str(), "r");+    if (!pipe)+        return CommandResult{1, {}, "popen failed\n"};+    std::string out;+    std::array<char, 4096> buffer{};+    while (std::fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)+        out += buffer.data();+    const int status = pclose(pipe);+    const int code = WIFEXITED(status) ? WEXITSTATUS(status) : 1;+    return CommandResult{code, out, {}};+#endif+}++++bool git_available() {+    return run_shell({"git", "--version"}, fs::current_path()).code == 0;+}++void require_shell(test::Context& t, const CommandResult& result, std::string_view label) {+    if (result.code != 0)+        t.fail(std::string(label) + " failed:\n" + result.text());+}++fs::path make_git_repository(test::Context& t, VnFixture& f) {+    const fs::path git_repo = f.root / "gitrepo";+    fs::create_directories(git_repo);+    require_shell(t, run_shell({"git", "init", "-q"}, git_repo), "git init");+    require_shell(t, run_shell({"git", "config", "user.name", "Git Tester"}, git_repo),+                  "git config user.name");+    require_shell(t, run_shell({"git", "config", "user.email", "git@example.com"}, git_repo),+                  "git config user.email");+    f.write("a.txt", "one\n", git_repo);+    require_shell(t, run_shell({"git", "add", "a.txt"}, git_repo), "git add");+    require_shell(t, run_shell({"git", "commit", "-qm", "git one"}, git_repo), "git commit one");+    f.write("a.txt", "one\ntwo\n", git_repo);+    require_shell(t, run_shell({"git", "commit", "-qam", "git two"}, git_repo), "git commit two");+    return git_repo;+}++void linear_history(VnFixture& f, int count) {+    for (int index = 0; index < count; ++index) {+        f.write("file.txt", "line " + std::to_string(index) + "\n");+        f.commit("commit " + std::to_string(index));+    }+}+void make_source_repository(VnFixture& f) {+    const fs::path source = f.root / "source";+    fs::create_directories(source);+    f.init(source);+    f.write("a.txt", "hello\n", source);+    f.vn({"bmk", "set", "master"}, source);+    f.commit("initial", source);+    f.vn({"access", "anonymous", "on"}, source);+}++} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/support.h@@ -0,0 +1,220 @@+#pragma once++#include "test_support.h"++#include "core/common.h"++#include <array>+#include <algorithm>+#include <chrono>+#include <cstdint>+#include <map>+#include <optional>+#include <set>+#include <source_location>+#include <sstream>+#include <string>+#include <string_view>+#include <vector>++namespace vn::integration {++struct CommandResult {+    int code = 0;+    std::string out;+    std::string err;++    std::string text() const {+        return out + err;+    }+};++std::string trim_copy(std::string_view text);+std::vector<std::string> split_lines(std::string_view text);+std::vector<std::string> split_columns(std::string_view line);+std::string join_args(const std::vector<std::string>& args);++CommandResult run_cli(const std::vector<std::string>& command, const fs::path& cwd);+void set_environment(const char* key, const std::string& value);+CommandResult run_shell(const std::vector<std::string>& command, const fs::path& cwd);++struct LogRow {+    std::string commit;+    std::string message;+    std::string raw;+    bool working_copy = false;+};++struct VnFixture {+    fs::path root;+    fs::path home;+    fs::path repo;+    fs::path original_cwd;++    VnFixture() : original_cwd(fs::current_path()) {+        root = fs::temp_directory_path() /+               ("vn-test-" + std::to_string(random_u64()) + "-" ++                std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));+        home = root / "home";+        repo = root / "repo";+        fs::create_directories(home / ".config");+        fs::create_directories(repo);+        set_environment("HOME", home.string());+        set_environment("XDG_CONFIG_HOME", (home / ".config").string());+        set_environment("USER", "tester");+        set_environment("GIT_AUTHOR_NAME", "Tester");+        set_environment("GIT_AUTHOR_EMAIL", "tester@example.com");+        set_environment("GIT_COMMITTER_NAME", "Tester");+        set_environment("GIT_COMMITTER_EMAIL", "tester@example.com");+        set_environment("NO_COLOR", "1");+        set_environment("TZ", "UTC");+        set_environment("VN_EDITOR", "/bin/true");+    }++    ~VnFixture() {+        std::error_code ec;+        fs::current_path(original_cwd, ec);+        fs::remove_all(root, ec);+    }++    CommandResult vn(const std::vector<std::string>& command, const fs::path& cwd = {},+                     bool check = true,+                     const std::source_location& location = std::source_location::current()) const {+        const fs::path actual_cwd = cwd.empty() ? repo : cwd;+        CommandResult result = run_cli(command, actual_cwd);+        if (check && result.code != 0) {+            throw test::Failure(test::location_text(location) ++                                ": command failed: " + join_args(command) + "\nstdout:\n" ++                                result.out + "\nstderr:\n" + result.err);+        }+        return result;+    }++    CommandResult+    failed(const std::vector<std::string>& command, std::string_view expected = {},+           const fs::path& cwd = {},+           const std::source_location& location = std::source_location::current()) const {+        CommandResult result = vn(command, cwd, false, location);+        if (result.code == 0) {+            throw test::Failure(test::location_text(location) + ": command unexpectedly passed: " ++                                join_args(command) + "\n" + result.text());+        }+        if (!expected.empty() && result.text().find(expected) == std::string::npos) {+            throw test::Failure(test::location_text(location) + ": expected output to contain \"" ++                                std::string(expected) + "\"\n" + result.text());+        }+        return result;+    }++    void init(const fs::path& cwd = {}) {+        vn({"init", "."}, cwd);+    }++    void write(const fs::path& relative, std::string_view content, const fs::path& cwd = {}) const {+        const fs::path path = (cwd.empty() ? repo : cwd) / relative;+        fs::create_directories(path.parent_path());+        const Bytes bytes(reinterpret_cast<const std::uint8_t*>(content.data()), content.size());+        if (!write_file(path, bytes))+            throw test::Failure("cannot write test file: " + path.string());+    }++    std::string read(const fs::path& relative, const fs::path& cwd = {}) const {+        const fs::path path = (cwd.empty() ? repo : cwd) / relative;+        const auto data = read_file_opt(path);+        if (!data)+            throw test::Failure("cannot read test file: " + path.string());+        return std::string(reinterpret_cast<const char*>(data->data()), data->size());+    }++    bool exists(const fs::path& relative, const fs::path& cwd = {}) const {+        return path_exists((cwd.empty() ? repo : cwd) / relative);+    }++    void commit(std::string_view message, const fs::path& cwd = {}) const {+        vn({"go", "-m", std::string(message)}, cwd);+    }++    std::string hash(std::string_view revision = "@", const fs::path& cwd = {}) const {+        return trim_copy(vn({"hash", std::string(revision)}, cwd).out);+    }++    std::string short_hash(std::string_view revision = "@", const fs::path& cwd = {}) const {+        return trim_copy(vn({"hash", "-short", std::string(revision)}, cwd).out);+    }++    std::vector<LogRow> log_rows(const fs::path& cwd = {}) const {+        const std::string output = vn({"log", "-no-col-titles"}, cwd).out;+        std::vector<LogRow> rows;+        for (const std::string& line : split_lines(output)) {+            const std::string stripped = trim_copy(line);+            if (stripped.empty())+                continue;+            std::vector<std::string> parts = split_columns(stripped);+            if (parts.empty())+                continue;+            LogRow row;+            row.raw = line;+            row.working_copy = parts[0].starts_with("@");+            std::string first = row.working_copy ? trim_copy(parts[0].substr(1)) : parts[0];+            row.commit = first.substr(0, std::min<std::size_t>(12, first.size()));+            row.message = parts.size() > 1 ? parts.back() : std::string();+            rows.push_back(std::move(row));+        }+        return rows;+    }++    std::vector<std::string> log_commits(const fs::path& cwd = {}) const {+        std::vector<std::string> commits;+        for (const LogRow& row : log_rows(cwd))+            commits.push_back(row.commit);+        return commits;+    }++    std::string commit_for_message(std::string_view message, const fs::path& cwd = {}) const {+        for (const LogRow& row : log_rows(cwd)) {+            if (row.message.find(message) != std::string::npos)+                return row.commit;+        }+        throw test::Failure("no commit with message \"" + std::string(message) + "\"");+    }++    std::map<std::string, std::string> metadata(std::string_view revision = "@",+                                                const fs::path& cwd = {}) const {+        const std::string output = vn({"show", std::string(revision)}, cwd).out;+        std::map<std::string, std::string> values;+        for (const std::string& line : split_lines(output)) {+            if (line.empty())+                break;+            const std::size_t space = line.find(' ');+            if (space == std::string::npos)+                continue;+            const std::string key = line.substr(0, space);+            if (key == "commit" || key == "change" || key == "author" || key == "date" ||+                key == "parents") {+                values[key] = trim_copy(line.substr(space + 1));+            }+        }+        return values;+    }++    std::set<std::string> parents(std::string_view revision = "@", const fs::path& cwd = {}) const {+        std::set<std::string> result;+        const auto values = metadata(revision, cwd);+        const auto found = values.find("parents");+        if (found == values.end())+            return result;+        std::istringstream stream(found->second);+        std::string parent;+        while (stream >> parent)+            result.insert(parent);+        return result;+    }+};++bool git_available();+void require_shell(test::Context& t, const CommandResult& result, std::string_view label);+fs::path make_git_repository(test::Context& t, VnFixture& f);+void make_source_repository(VnFixture& f);+void linear_history(VnFixture& f, int count);++} // namespace vn::integration--- /dev/null+++ b/xveins/tests/integration/worktree_tests.cpp@@ -0,0 +1,286 @@+#include "test_support.h"++#include "integration/support.h"++namespace vn::integration {+namespace {++void worktree_rename_and_delete(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("a.txt", "alpha\n");+    f.write("b.txt", "beta\n");+    f.commit("base");+    f.vn({"mv", "a.txt", "renamed.txt"});+    t.expect(!f.exists("a.txt"));+    t.expect_eq(f.read("renamed.txt"), "alpha\n");+    const std::string status = f.vn({"stat"}).out;+    t.expect_contains(status, "D a.txt");+    t.expect_contains(status, "A renamed.txt");+    f.commit("rename");+    t.expect_contains(f.vn({"ls", "-plain"}).out, "renamed.txt");++    fs::remove(f.repo / "b.txt");+    t.expect_contains(f.vn({"stat"}).out, "D b.txt");+    f.commit("delete");+    t.expect_not_contains(f.vn({"ls", "-plain"}).out, "b.txt");+}++void worktree_exclude_and_remove(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("src/a.c", "a\n");+    f.write("src/b.c", "b\n");+    f.write("docs/readme.md", "docs\n");+    f.write("top.txt", "top\n");+    t.expect_contains(f.vn({"rm", "src/*.c"}).out, "will be re-added");+    f.vn({"ex", "src/*.c"});+    t.expect_contains(f.read(".vnexclude"), "src/*.c");+    const std::string tracked = f.vn({"ls", "-plain"}).out;+    t.expect_not_contains(tracked, "src/a.c");+    t.expect_not_contains(tracked, "src/b.c");+    t.expect(f.exists("src/a.c"));+    t.expect(f.exists("src/b.c"));+    f.vn({"rm", "-delete", "docs/readme.md"});+    t.expect(!f.exists("docs/readme.md"));+    t.expect_not_contains(f.vn({"ls", "-plain"}).out, "docs/readme.md");+    t.expect_contains(f.vn({"ex", "src/*.c"}).out, "no new exclude rules");+    f.failed({"rm", "missing.txt"}, "not tracked");+}++void worktree_ignore_rules(test::Context& t) {+    VnFixture f;+    f.init();+    f.write(".gitignore", "*.log\nbuild/\n");+    f.write("debug.log", "ignored\n");+    f.write("build/out.bin", "ignored\n");+    f.write("src/.gitignore", "*.tmp\n");+    f.write("src/notes.tmp", "ignored\n");+    f.write("src/main.c", "kept\n");+    std::vector<std::string> tracked = split_lines(f.vn({"ls", "-plain"}).out);+    tracked.erase(std::remove(tracked.begin(), tracked.end(), ""), tracked.end());+    std::sort(tracked.begin(), tracked.end());+    t.expect_eq(tracked.size(), 3u);+    if (tracked.size() == 3) {+        t.expect_eq(tracked[0], ".gitignore");+        t.expect_eq(tracked[1], "src/.gitignore");+        t.expect_eq(tracked[2], "src/main.c");+    }+    f.write("root.log", "ignored\n");+    t.expect_not_contains(f.vn({"stat"}).out, "root.log");+}++void worktree_checkout_removes_later_files(test::Context& t) {+    VnFixture f;+    f.init();+    f.write("keep.txt", "keep\n");+    f.commit("first");+    const std::string first = f.commit_for_message("first");+    f.write("later.txt", "later\n");+    f.write("keep.txt", "changed\n");+    f.commit("second");+    f.vn({"co", first});+    t.expect(f.exists("keep.txt"));+    t.expect(!f.exists("later.txt"));+    t.expect_eq(f.read("keep.txt"), "keep\n");+    t.expect_contains(f.vn({"stat"}).out, "working copy clean");+}++void worktree_editor(test::Context& t) {+#if defined(_WIN32)+    t.expect(true);+#else+    VnFixture f;+    f.init();+    const fs::path editor = f.root / "editor.sh";+    f.write("editor.sh", "#!/bin/sh\nprintf \"edited:%s\\n\" \"$1\" > \"$1\"\n", f.root);+    fs::permissions(editor, fs::perms::owner_exec | fs::perms::owner_read | fs::perms::owner_write,+                    fs::perm_options::add);+    f.vn({"cfg", "editor", editor.string()});+    f.write("target.txt", "before\n");+    f.vn({"edit", "target.txt"});+    t.expect_eq(f.read("target.txt"), "edited:target.txt\n");+    f.vn({"cfg", "-unset", "editor"});+#endif+}++void worktree_attributes_eol(test::Context& t) {+    VnFixture f;+    f.init();+    f.write(".vnattribs", "*.txt txt eol:lf\n*.cmd txt eol:crlf\n");+    f.write("a.txt", "a\r\nb\r\n");+    f.write("b.cmd", "x\ny\n");+    f.commit("base");+    const std::string base = f.commit_for_message("base");++    fs::remove(f.repo / "a.txt");+    fs::remove(f.repo / "b.cmd");+    f.vn({"co", base});+    t.expect_eq(f.read("a.txt"), "a\nb\n");+    t.expect_eq(f.read("b.cmd"), "x\r\ny\r\n");+}++void worktree_inf_generated(test::Context& t) {+    VnFixture f;+    f.init();+    f.write(".vnattribs", "*.ssa gen\n*.c txt eol:lf\n");+    f.write("main.c", "one\ntwo\n");+    f.write("out.ssa", "one\ntwo\nthree\n");+    f.commit("base");++    const std::string default_output = f.vn({"inf"}).out;+    t.expect_contains(default_output, "Generated");+    t.expect_contains(default_output, "1 files");+    t.expect_contains(default_output, "excluded; use -inc-gen");+    t.expect_not_contains(default_output, ".ssa");++    const std::string included_output = f.vn({"inf", "-inc-gen"}).out;+    t.expect_contains(included_output, ".ssa");+    t.expect_not_contains(included_output, "excluded; use -inc-gen");+}++void worktree_attributes_command(test::Context& t) {+    VnFixture f;+    f.init();++    t.expect_contains(f.vn({"attr", "gen", "*.ssa", "*.bin"}).out, "updated 2");+    t.expect_contains(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n");++    f.vn({"attr", "bin", "*.exe"});+    f.vn({"attr", "lf", "*.c"});+    f.vn({"attr", "crlf", "*.cmd"});+    const std::string rules = f.read(".vnattribs");+    t.expect_contains(rules, "*.exe bin\n");+    t.expect_contains(rules, "*.c eol:lf\n");+    t.expect_contains(rules, "*.cmd eol:crlf\n");++    f.vn({"attr", "txt", "*.c"});+    t.expect_contains(f.read(".vnattribs"), "*.c eol:lf txt\n");+    f.vn({"attr", "crlf", "*.c"});+    t.expect_contains(f.read(".vnattribs"), "*.c txt eol:crlf\n");+    t.expect_not_contains(f.read(".vnattribs"), "eol:lf");+    t.expect_contains(f.vn({"attr", "crlf", "*.c"}).out, "no new attribute rules");++    f.vn({"attr", "gen", "*.c"});+    t.expect_contains(f.read(".vnattribs"), "*.c txt eol:crlf gen\n");+    f.vn({"attr", "rm", "gen", "*.c"});+    t.expect_not_contains(f.read(".vnattribs"), "*.c txt eol:crlf gen");+    f.vn({"attr", "rm", "crlf", "*.c"});+    t.expect_contains(f.read(".vnattribs"), "*.c txt\n");+    f.vn({"attr", "rm", "txt", "*.c"});+    t.expect_not_contains(f.read(".vnattribs"), "*.c txt");+    t.expect_not_contains(f.read(".vnattribs"), "*.c eol");+    f.vn({"attr", "rm", "gen", "*.ssa"});+    t.expect_not_contains(f.read(".vnattribs"), "*.ssa");+    t.expect_contains(f.vn({"attr", "rm", "lf", "*.missing"}).out, "no matching attribute rules");++    fs::create_directories(f.repo / "src");+    f.vn({"attr", "gen", "*.ssa"}, f.repo / "src");+    t.expect_contains(f.read(".vnattribs"), "src/*.ssa gen\n");++    f.write(".vnattribs", "# keep this comment\n*.c gen\n\n*.c eol:lf\n*.tmp -gen\n");+    const std::string listed = f.vn({"attr", "ls"}).out;+    t.expect_contains(listed, "*.c gen\n");+    t.expect_contains(listed, "*.c eol:lf\n");+    t.expect_not_contains(listed, "# keep this comment");+    t.expect_contains(listed, "*.tmp -gen\n");++    f.vn({"attr", "rm", "gen", "*.c"});+    const std::string after_remove = f.read(".vnattribs");+    t.expect_contains(after_remove, "# keep this comment\n");+    t.expect_contains(after_remove, "*.c eol:lf\n");+    t.expect_not_contains(after_remove, "*.c gen");+    f.vn({"attr", "rm", "gen", "*.tmp"});+    t.expect_not_contains(f.read(".vnattribs"), "-gen");++    VnFixture outside;+    outside.failed({"attr", "gen", "*.c"}, "not a veins repository");+}++void worktree_attributes_command_edges(test::Context& t) {+    VnFixture f;+    f.init();++    t.expect_eq(f.vn({"attr", "ls"}).out, "");+    t.expect_contains(f.vn({"attr", "rm", "gen", "*.c"}).out, "no matching attribute rules");+    t.expect(!f.exists(".vnattribs"));++    f.write(".vnattribs", "# leading comment\r\n\r\n*.c gen\r\n*.c txt\r\n*.cmd txt eol:crlf\r\n");+    t.expect_eq(f.vn({"attr", "ls"}).out, "*.c gen\n*.c txt\n*.cmd txt eol:crlf\n");+    f.vn({"attr", "bin", "*.c"});+    t.expect_eq(f.read(".vnattribs"),+                "# leading comment\r\n\r\n*.c gen\r\n*.c bin\r\n*.cmd txt eol:crlf\r\n");+    f.vn({"attr", "rm", "gen", "*.c"});+    t.expect_eq(f.read(".vnattribs"), "# leading comment\r\n\r\n*.c bin\r\n*.cmd txt eol:crlf\r\n");+    f.vn({"attr", "rm", "bin", "*.c"});+    t.expect_eq(f.read(".vnattribs"), "# leading comment\r\n\r\n*.cmd txt eol:crlf\r\n");++    f.write(".vnattribs", "*.c future eol:cr -gen\n*.d -bin\n*.e -txt\n*.f txt -eol\n");+    f.vn({"attr", "txt", "*.c"});+    t.expect_eq(f.read(".vnattribs"),+                "*.c future eol:cr -gen txt\n*.d -bin\n*.e -txt\n*.f txt -eol\n");+    f.vn({"attr", "gen", "*.c"});+    t.expect_eq(f.read(".vnattribs"),+                "*.c future eol:cr txt gen\n*.d -bin\n*.e -txt\n*.f txt -eol\n");+    f.vn({"attr", "crlf", "*.c"});+    t.expect_eq(f.read(".vnattribs"),+                "*.c future txt gen eol:crlf\n*.d -bin\n*.e -txt\n*.f txt -eol\n");+    f.vn({"attr", "rm", "bin", "*.d"});+    f.vn({"attr", "rm", "txt", "*.e"});+    f.vn({"attr", "lf", "*.f"});+    t.expect_eq(f.read(".vnattribs"), "*.c future txt gen eol:crlf\n*.f txt eol:lf\n");++    f.write(".vnattribs", "*.c txt");+    f.vn({"attr", "gen", "*.c"});+    t.expect_eq(f.read(".vnattribs"), "*.c txt gen\n");+    f.write(".vnattribs", "*.tmp gen");+    f.vn({"attr", "gen", "*.new"});+    t.expect_eq(f.read(".vnattribs"), "*.tmp gen\n*.new gen\n");++    f.write(".vnattribs", "*.c txt\n");+    const std::string unchanged = f.read(".vnattribs");+    t.expect_contains(f.vn({"attr", "rm", "gen", "*.c"}).out, "no matching attribute rules");+    t.expect_eq(f.read(".vnattribs"), unchanged);+    t.expect_eq(f.vn({"attr", "ls", "--"}).out, "*.c txt\n");++    f.failed({"attr", "gen", "bad pattern"}, "not a valid attribute pattern");+    f.failed({"attr", "gen", "#comment"}, "not a valid attribute pattern");+    f.failed({"attr", "gen", ""}, "not a valid attribute pattern");+    t.expect_eq(f.read(".vnattribs"), unchanged);++    f.failed({"attr"}, "requires a subcommand");+    f.failed({"attr", "gen"}, "requires at least one glob");+    f.failed({"attr", "rm"}, "usage: vn attr rm");+    f.failed({"attr", "rm", "gen"}, "usage: vn attr rm");+    f.failed({"attr", "wat", "*.c"}, "unknown attr subcommand");+    f.failed({"attr", "rm", "eol", "*.c"}, "unknown attribute");+    f.failed({"attr", "gen", "-x"}, "unknown flag");+    f.failed({"attr", "ls", "extra"}, "usage: vn attr ls");++    f.write(".vnattribs", "");+    f.vn({"attr", "gen", "--", "*.c"});+    t.expect_eq(f.read(".vnattribs"), "*.c gen\n");++    VnFixture outside;+    outside.failed({"attr", "ls"}, "not a veins repository");+    outside.failed({"attr", "gen", "*.c"}, "not a veins repository");+    outside.failed({"attr", "rm", "gen", "*.c"}, "not a veins repository");+}++} // namespace++test::Suite worktree_suite() {+    return {"worktree",+            {+                {"rename_and_delete", worktree_rename_and_delete},+                {"exclude_and_remove", worktree_exclude_and_remove},+                {"ignore_rules", worktree_ignore_rules},+                {"checkout_removes_later_files", worktree_checkout_removes_later_files},+                {"attributes_eol", worktree_attributes_eol},+                {"inf_generated", worktree_inf_generated},+                {"attributes_command", worktree_attributes_command},+                {"attributes_command_edges", worktree_attributes_command_edges},+                {"editor", worktree_editor},+            }};+}+} // namespace vn::integration--- a/xveins/tests/integration_tests.cpp+++ /dev/null@@ -1,1579 +0,0 @@-#include "test_support.h"--#include "cli/cli.h"-#include "core/common.h"-#include "store/store.h"-#include "version/version.h"--#include <algorithm>-#include <array>-#include <chrono>-#include <cstdio>-#include <cstdlib>-#include <fstream>-#include <iostream>-#include <map>-#include <set>-#include <sstream>-#include <string>-#include <string_view>-#include <vector>--#if !defined(_WIN32)-#include <sys/wait.h>-#endif--namespace vn {-namespace {--namespace fs = std::filesystem;--struct CommandResult {-    int code = 0;-    std::string out;-    std::string err;--    std::string text() const {-        return out + err;-    }-};--std::string trim_copy(std::string_view text) {-    std::size_t start = 0;-    std::size_t end = text.size();-    while (start < end && (text[start] == ' ' || text[start] == '\t' || text[start] == '\r' ||-                           text[start] == '\n'))-        ++start;-    while (end > start && (text[end - 1] == ' ' || text[end - 1] == '\t' || text[end - 1] == '\r' ||-                           text[end - 1] == '\n'))-        --end;-    return std::string(text.substr(start, end - start));-}--std::vector<std::string> split_lines(std::string_view text) {-    std::vector<std::string> lines;-    std::size_t start = 0;-    while (start < text.size()) {-        const std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos) {-            lines.emplace_back(text.substr(start));-            break;-        }-        lines.emplace_back(text.substr(start, end - start));-        start = end + 1;-    }-    return lines;-}--std::vector<std::string> split_columns(std::string_view line) {-    std::vector<std::string> parts;-    std::size_t start = 0;-    while (start < line.size()) {-        while (start < line.size() && line[start] == ' ')-            ++start;-        if (start >= line.size())-            break;-        std::size_t end = start;-        while (end < line.size()) {-            if (line[end] == ' ' && end + 1 < line.size() && line[end + 1] == ' ')-                break;-            ++end;-        }-        parts.emplace_back(line.substr(start, end - start));-        start = end;-    }-    return parts;-}--std::string join_args(const std::vector<std::string>& args) {-    std::string out;-    for (std::size_t i = 0; i < args.size(); ++i) {-        if (i != 0)-            out.push_back(' ');-        out += args[i];-    }-    return out;-}--CommandResult run_cli(const std::vector<std::string>& command, const fs::path& cwd) {-    std::vector<std::string> args;-    args.reserve(command.size() + 1);-    args.emplace_back("vn");-    args.insert(args.end(), command.begin(), command.end());--    const fs::path previous = fs::current_path();-    fs::current_path(cwd);-    std::ostringstream out;-    std::ostringstream err;-    auto* old_out = std::cout.rdbuf(out.rdbuf());-    auto* old_err = std::cerr.rdbuf(err.rdbuf());-    int code = 0;-    try {-        code = cli_run(args);-    } catch (const std::exception& error) {-        code = 1;-        err << "exception: " << error.what() << "\n";-    } catch (...) {-        code = 1;-        err << "exception: unknown failure\n";-    }-    std::cout.flush();-    std::cerr.flush();-    std::cout.rdbuf(old_out);-    std::cerr.rdbuf(old_err);-    fs::current_path(previous);-    return CommandResult{code, out.str(), err.str()};-}--void set_environment(const char* key, const std::string& value) {-#if defined(_WIN32)-    _putenv_s(key, value.c_str());-#else-    setenv(key, value.c_str(), 1);-#endif-}--std::string shell_quote(std::string_view value) {-    std::string out = "'";-    for (char c : value) {-        if (c == '\'')-            out += "'\\''";-        else-            out.push_back(c);-    }-    out.push_back('\'');-    return out;-}--CommandResult run_shell(const std::vector<std::string>& command, const fs::path& cwd) {-#if defined(_WIN32)-    (void)command;-    (void)cwd;-    return CommandResult{1, {}, "shell commands are not supported on Windows\n"};-#else-    std::string line = "cd " + shell_quote(cwd.string()) + " && ";-    for (std::size_t i = 0; i < command.size(); ++i) {-        if (i != 0)-            line.push_back(' ');-        line += shell_quote(command[i]);-    }-    line += " 2>&1";-    FILE* pipe = popen(line.c_str(), "r");-    if (!pipe)-        return CommandResult{1, {}, "popen failed\n"};-    std::string out;-    std::array<char, 4096> buffer{};-    while (std::fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)-        out += buffer.data();-    const int status = pclose(pipe);-    const int code = WIFEXITED(status) ? WEXITSTATUS(status) : 1;-    return CommandResult{code, out, {}};-#endif-}--struct LogRow {-    std::string commit;-    std::string message;-    std::string raw;-    bool working_copy = false;-};--struct VnFixture {-    fs::path root;-    fs::path home;-    fs::path repo;-    fs::path original_cwd;--    VnFixture() : original_cwd(fs::current_path()) {-        root = fs::temp_directory_path() /-               ("vn-test-" + std::to_string(random_u64()) + "-" +-                std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));-        home = root / "home";-        repo = root / "repo";-        fs::create_directories(home / ".config");-        fs::create_directories(repo);-        set_environment("HOME", home.string());-        set_environment("XDG_CONFIG_HOME", (home / ".config").string());-        set_environment("USER", "tester");-        set_environment("GIT_AUTHOR_NAME", "Tester");-        set_environment("GIT_AUTHOR_EMAIL", "tester@example.com");-        set_environment("GIT_COMMITTER_NAME", "Tester");-        set_environment("GIT_COMMITTER_EMAIL", "tester@example.com");-        set_environment("NO_COLOR", "1");-        set_environment("TZ", "UTC");-        set_environment("VN_EDITOR", "/bin/true");-    }--    ~VnFixture() {-        std::error_code ec;-        fs::current_path(original_cwd, ec);-        fs::remove_all(root, ec);-    }--    CommandResult vn(const std::vector<std::string>& command, const fs::path& cwd = {},-                     bool check = true,-                     const std::source_location& location = std::source_location::current()) const {-        const fs::path actual_cwd = cwd.empty() ? repo : cwd;-        CommandResult result = run_cli(command, actual_cwd);-        if (check && result.code != 0) {-            throw test::Failure(test::location_text(location) +-                                ": command failed: " + join_args(command) + "\nstdout:\n" +-                                result.out + "\nstderr:\n" + result.err);-        }-        return result;-    }--    CommandResult-    failed(const std::vector<std::string>& command, std::string_view expected = {},-           const fs::path& cwd = {},-           const std::source_location& location = std::source_location::current()) const {-        CommandResult result = vn(command, cwd, false, location);-        if (result.code == 0) {-            throw test::Failure(test::location_text(location) + ": command unexpectedly passed: " +-                                join_args(command) + "\n" + result.text());-        }-        if (!expected.empty() && result.text().find(expected) == std::string::npos) {-            throw test::Failure(test::location_text(location) + ": expected output to contain \"" +-                                std::string(expected) + "\"\n" + result.text());-        }-        return result;-    }--    void init(const fs::path& cwd = {}) {-        vn({"init", "."}, cwd);-    }--    void write(const fs::path& relative, std::string_view content, const fs::path& cwd = {}) const {-        const fs::path path = (cwd.empty() ? repo : cwd) / relative;-        fs::create_directories(path.parent_path());-        const Bytes bytes(reinterpret_cast<const std::uint8_t*>(content.data()), content.size());-        if (!write_file(path, bytes))-            throw test::Failure("cannot write test file: " + path.string());-    }--    std::string read(const fs::path& relative, const fs::path& cwd = {}) const {-        const fs::path path = (cwd.empty() ? repo : cwd) / relative;-        const auto data = read_file_opt(path);-        if (!data)-            throw test::Failure("cannot read test file: " + path.string());-        return std::string(reinterpret_cast<const char*>(data->data()), data->size());-    }--    bool exists(const fs::path& relative, const fs::path& cwd = {}) const {-        return path_exists((cwd.empty() ? repo : cwd) / relative);-    }--    void commit(std::string_view message, const fs::path& cwd = {}) const {-        vn({"go", "-m", std::string(message)}, cwd);-    }--    std::string hash(std::string_view revision = "@", const fs::path& cwd = {}) const {-        return trim_copy(vn({"hash", std::string(revision)}, cwd).out);-    }--    std::string short_hash(std::string_view revision = "@", const fs::path& cwd = {}) const {-        return trim_copy(vn({"hash", "-short", std::string(revision)}, cwd).out);-    }--    std::vector<LogRow> log_rows(const fs::path& cwd = {}) const {-        const std::string output = vn({"log", "-no-col-titles"}, cwd).out;-        std::vector<LogRow> rows;-        for (const std::string& line : split_lines(output)) {-            const std::string stripped = trim_copy(line);-            if (stripped.empty())-                continue;-            std::vector<std::string> parts = split_columns(stripped);-            if (parts.empty())-                continue;-            LogRow row;-            row.raw = line;-            row.working_copy = parts[0].starts_with("@");-            std::string first = row.working_copy ? trim_copy(parts[0].substr(1)) : parts[0];-            row.commit = first.substr(0, std::min<std::size_t>(12, first.size()));-            row.message = parts.size() > 1 ? parts.back() : std::string();-            rows.push_back(std::move(row));-        }-        return rows;-    }--    std::vector<std::string> log_commits(const fs::path& cwd = {}) const {-        std::vector<std::string> commits;-        for (const LogRow& row : log_rows(cwd))-            commits.push_back(row.commit);-        return commits;-    }--    std::string commit_for_message(std::string_view message, const fs::path& cwd = {}) const {-        for (const LogRow& row : log_rows(cwd)) {-            if (row.message.find(message) != std::string::npos)-                return row.commit;-        }-        throw test::Failure("no commit with message \"" + std::string(message) + "\"");-    }--    std::map<std::string, std::string> metadata(std::string_view revision = "@",-                                                const fs::path& cwd = {}) const {-        const std::string output = vn({"show", std::string(revision)}, cwd).out;-        std::map<std::string, std::string> values;-        for (const std::string& line : split_lines(output)) {-            if (line.empty())-                break;-            const std::size_t space = line.find(' ');-            if (space == std::string::npos)-                continue;-            const std::string key = line.substr(0, space);-            if (key == "commit" || key == "change" || key == "author" || key == "date" ||-                key == "parents") {-                values[key] = trim_copy(line.substr(space + 1));-            }-        }-        return values;-    }--    std::set<std::string> parents(std::string_view revision = "@", const fs::path& cwd = {}) const {-        std::set<std::string> result;-        const auto values = metadata(revision, cwd);-        const auto found = values.find("parents");-        if (found == values.end())-            return result;-        std::istringstream stream(found->second);-        std::string parent;-        while (stream >> parent)-            result.insert(parent);-        return result;-    }-};--bool git_available() {-    return run_shell({"git", "--version"}, fs::current_path()).code == 0;-}--void require_shell(test::Context& t, const CommandResult& result, std::string_view label) {-    if (result.code != 0)-        t.fail(std::string(label) + " failed:\n" + result.text());-}--fs::path make_git_repository(test::Context& t, VnFixture& f) {-    const fs::path git_repo = f.root / "gitrepo";-    fs::create_directories(git_repo);-    require_shell(t, run_shell({"git", "init", "-q"}, git_repo), "git init");-    require_shell(t, run_shell({"git", "config", "user.name", "Git Tester"}, git_repo),-                  "git config user.name");-    require_shell(t, run_shell({"git", "config", "user.email", "git@example.com"}, git_repo),-                  "git config user.email");-    f.write("a.txt", "one\n", git_repo);-    require_shell(t, run_shell({"git", "add", "a.txt"}, git_repo), "git add");-    require_shell(t, run_shell({"git", "commit", "-qm", "git one"}, git_repo), "git commit one");-    f.write("a.txt", "one\ntwo\n", git_repo);-    require_shell(t, run_shell({"git", "commit", "-qam", "git two"}, git_repo), "git commit two");-    return git_repo;-}--void linear_history(VnFixture& f, int count) {-    for (int index = 0; index < count; ++index) {-        f.write("file.txt", "line " + std::to_string(index) + "\n");-        f.commit("commit " + std::to_string(index));-    }-}--void core_init_version_help(test::Context& t) {-    VnFixture f;-    f.init();-    t.expect(fs::exists(f.repo / ".veins" / "format"));-    t.expect(fs::is_directory(f.repo / ".veins" / "op-heads"));-    const std::string version = f.vn({"version"}).out;-    t.expect_contains(version, "veins v" + std::string(vn_version()));-    t.expect_contains(version, "(store v" + std::to_string(STORE_VERSION) + ")");-    t.expect_eq(f.vn({"-v"}).out, version);-    t.expect_eq(f.vn({"-version"}).out, version);-    const std::string commit = vn_commit();-    if (!commit.empty())-        t.expect_contains(version, commit);-    const std::string help_text = f.vn({"help"}).out;-    t.expect_contains(help_text, "commands:");-    t.expect_contains(help_text, "attr");-    t.expect_contains(f.vn({"help", "log"}).out, "vn log");-    t.expect_contains(f.vn({"help", "log"}).out, "-a, -all");-    t.expect_contains(f.vn({"help", "go"}).out, "aliases: commit");-    t.expect_contains(f.vn({"help", "attr"}).out, "vn attr rm");-}--void core_outside_repository(test::Context& t) {-    VnFixture f;-    const fs::path outside = f.root / "outside";-    fs::create_directories(outside);-    for (const std::vector<std::string>& command :-         std::vector<std::vector<std::string>>{{"stat"}, {"log"}, {"hash"}, {"ls"}}) {-        f.failed(command, "not a veins repository", outside);-    }-    t.expect_contains(f.vn({"version"}, outside).out, "veins");-}--void core_status_list_diff_describe(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("a.txt", "alpha\n");-    f.write("dir/b.txt", "beta\n");-    const std::string status = f.vn({"stat"}).out;-    t.expect_contains(status, "A a.txt");-    t.expect_contains(status, "A dir/b.txt");-    std::vector<std::string> plain = split_lines(f.vn({"ls", "-plain"}).out);-    plain.erase(std::remove(plain.begin(), plain.end(), ""), plain.end());-    std::sort(plain.begin(), plain.end());-    t.expect_eq(plain.size(), 2u);-    if (plain.size() == 2) {-        t.expect_eq(plain[0], "a.txt");-        t.expect_eq(plain[1], "dir/b.txt");-    }-    const std::string listed = f.vn({"ls"}).out;-    t.expect_contains(listed, "a.txt");-    t.expect_contains(listed, "b.txt");-    const std::string diff = f.vn({"diff"}).out;-    t.expect_contains(diff, "+alpha");-    t.expect_contains(diff, "+beta");-    f.vn({"desc", "-m", "draft message"});-    t.expect_contains(f.vn({"show", "@"}).out, "draft message");-    t.expect_contains(f.vn({"stat"}).out, "A a.txt");-}--void core_status_paths_relative_to_cwd(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("a.txt", "alpha\n");-    f.write("dir/b.txt", "beta\n");-    f.write("dir/sub/c.txt", "gamma\n");--    const std::string root_status = f.vn({"stat"}).out;-    t.expect_contains(root_status, "A a.txt");-    t.expect_contains(root_status, "A dir/b.txt");--    const std::string dir_status = f.vn({"stat"}, f.repo / "dir").out;-    t.expect_contains(dir_status, "A ../a.txt");-    t.expect_contains(dir_status, "A b.txt");-    t.expect_contains(dir_status, "A sub/c.txt");-    t.expect_not_contains(dir_status, "A dir/b.txt");--    const std::string sub_status = f.vn({"stat"}, f.repo / "dir" / "sub").out;-    t.expect_contains(sub_status, "A ../../a.txt");-    t.expect_contains(sub_status, "A ../b.txt");-    t.expect_contains(sub_status, "A c.txt");-}--void core_commit_log_show_hash(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("a.txt", "one\n");-    f.commit("first commit");-    t.expect_contains(f.vn({"stat"}).out, "working copy clean");-    const std::vector<LogRow> rows = f.log_rows();-    t.expect(rows.size() >= 2);-    if (!rows.empty())-        t.expect(rows.front().working_copy);-    const std::string first = f.commit_for_message("first commit");-    const auto info = f.metadata(first);-    t.expect_eq(info.at("commit").size(), 64u);-    t.expect_eq(f.short_hash(first), info.at("commit").substr(0, 12));-    t.expect_eq(f.hash(first), info.at("commit"));-    const std::string shown = f.vn({"show", first}).out;-    t.expect_contains(shown, "first commit");-    t.expect_contains(shown, "+one");-    t.expect_contains(f.vn({"show", "-no-col-titles", first}).out, "--- /dev/null");--    f.write("a.txt", "two\n");-    t.expect_contains(f.vn({"stat"}).out, "M a.txt");-    t.expect_contains(f.vn({"diff"}).out, "+two");-    f.commit("second commit");-    t.expect_contains(f.vn({"show", f.commit_for_message("second commit")}).out, "second commit");-    t.expect_contains(f.vn({"stat"}).out, "working copy clean");-}--void core_log_limits_revisions(test::Context& t) {-    VnFixture f;-    f.init();-    linear_history(f, 4);-    const std::vector<LogRow> full = f.log_rows();-    t.expect_eq(full.size(), 5u);-    t.expect_eq(split_lines(f.vn({"log", "-l2", "-no-col-titles"}).out).size(), 2u);-    const auto oldest = split_lines(f.vn({"log", "-f2", "-no-col-titles"}).out);-    t.expect_eq(oldest.size(), 2u);-    if (oldest.size() == 2) {-        t.expect_contains(oldest[0], "commit 0");-        t.expect_contains(oldest[1], "commit 1");-    }-    t.expect_eq(split_lines(f.vn({"log", "-l", "1", "-no-col-titles"}).out).size(), 1u);-    t.expect_eq(split_lines(f.vn({"log", "l2", "-no-col-titles"}).out).size(), 2u);-    const std::string one = f.commit_for_message("commit 1");-    const std::string selected = f.vn({"log", "-rev", one, "-no-col-titles"}).out;-    t.expect_contains(selected, "commit 1");-    t.expect_contains(selected, "commit 0");-    t.expect_not_contains(selected, "commit 2");-    for (const char* bad : {"-l0", "-lfoo", "-bad"})-        f.failed({"log", bad});-}--void core_checkout_materializes_and_new(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("a.txt", "one\n");-    f.vn({"bmk", "set", "main"});-    f.commit("first");-    const std::string first = f.hash("main");-    f.write("a.txt", "two\n");-    f.write("later.txt", "later\n");-    f.commit("second");-    const std::string second = f.hash("main");-    f.vn({"bmk", "set", "main", "-rev", first});-    f.vn({"bmk", "set", "feature", "-rev", second});--    f.vn({"co", "main"});-    t.expect_eq(f.read("a.txt"), "one\n");-    t.expect(!f.exists("later.txt"));-    t.expect_contains(f.vn({"stat"}).out, "working copy clean");-    t.expect_contains(f.vn({"bmk", "ls"}).out, "main");--    f.vn({"co", "feature"});-    t.expect_eq(f.read("a.txt"), "two\n");-    t.expect(f.exists("later.txt"));--    f.vn({"co", second});-    t.expect_eq(f.read("a.txt"), "two\n");-    f.vn({"new"});-    t.expect_contains(f.vn({"stat"}).out, "working copy clean");-    t.expect(!f.log_rows().empty());-    if (!f.log_rows().empty())-        t.expect(f.log_rows().front().working_copy);-}--void worktree_rename_and_delete(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("a.txt", "alpha\n");-    f.write("b.txt", "beta\n");-    f.commit("base");-    f.vn({"mv", "a.txt", "renamed.txt"});-    t.expect(!f.exists("a.txt"));-    t.expect_eq(f.read("renamed.txt"), "alpha\n");-    const std::string status = f.vn({"stat"}).out;-    t.expect_contains(status, "D a.txt");-    t.expect_contains(status, "A renamed.txt");-    f.commit("rename");-    t.expect_contains(f.vn({"ls", "-plain"}).out, "renamed.txt");--    fs::remove(f.repo / "b.txt");-    t.expect_contains(f.vn({"stat"}).out, "D b.txt");-    f.commit("delete");-    t.expect_not_contains(f.vn({"ls", "-plain"}).out, "b.txt");-}--void worktree_exclude_and_remove(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("src/a.c", "a\n");-    f.write("src/b.c", "b\n");-    f.write("docs/readme.md", "docs\n");-    f.write("top.txt", "top\n");-    t.expect_contains(f.vn({"rm", "src/*.c"}).out, "will be re-added");-    f.vn({"ex", "src/*.c"});-    t.expect_contains(f.read(".vnexclude"), "src/*.c");-    const std::string tracked = f.vn({"ls", "-plain"}).out;-    t.expect_not_contains(tracked, "src/a.c");-    t.expect_not_contains(tracked, "src/b.c");-    t.expect(f.exists("src/a.c"));-    t.expect(f.exists("src/b.c"));-    f.vn({"rm", "-delete", "docs/readme.md"});-    t.expect(!f.exists("docs/readme.md"));-    t.expect_not_contains(f.vn({"ls", "-plain"}).out, "docs/readme.md");-    t.expect_contains(f.vn({"ex", "src/*.c"}).out, "no new exclude rules");-    f.failed({"rm", "missing.txt"}, "not tracked");-}--void worktree_ignore_rules(test::Context& t) {-    VnFixture f;-    f.init();-    f.write(".gitignore", "*.log\nbuild/\n");-    f.write("debug.log", "ignored\n");-    f.write("build/out.bin", "ignored\n");-    f.write("src/.gitignore", "*.tmp\n");-    f.write("src/notes.tmp", "ignored\n");-    f.write("src/main.c", "kept\n");-    std::vector<std::string> tracked = split_lines(f.vn({"ls", "-plain"}).out);-    tracked.erase(std::remove(tracked.begin(), tracked.end(), ""), tracked.end());-    std::sort(tracked.begin(), tracked.end());-    t.expect_eq(tracked.size(), 3u);-    if (tracked.size() == 3) {-        t.expect_eq(tracked[0], ".gitignore");-        t.expect_eq(tracked[1], "src/.gitignore");-        t.expect_eq(tracked[2], "src/main.c");-    }-    f.write("root.log", "ignored\n");-    t.expect_not_contains(f.vn({"stat"}).out, "root.log");-}--void worktree_checkout_removes_later_files(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("keep.txt", "keep\n");-    f.commit("first");-    const std::string first = f.commit_for_message("first");-    f.write("later.txt", "later\n");-    f.write("keep.txt", "changed\n");-    f.commit("second");-    f.vn({"co", first});-    t.expect(f.exists("keep.txt"));-    t.expect(!f.exists("later.txt"));-    t.expect_eq(f.read("keep.txt"), "keep\n");-    t.expect_contains(f.vn({"stat"}).out, "working copy clean");-}--void worktree_editor(test::Context& t) {-#if defined(_WIN32)-    t.expect(true);-#else-    VnFixture f;-    f.init();-    const fs::path editor = f.root / "editor.sh";-    f.write("editor.sh", "#!/bin/sh\nprintf \"edited:%s\\n\" \"$1\" > \"$1\"\n", f.root);-    fs::permissions(editor, fs::perms::owner_exec | fs::perms::owner_read | fs::perms::owner_write,-                    fs::perm_options::add);-    f.vn({"cfg", "editor", editor.string()});-    f.write("target.txt", "before\n");-    f.vn({"edit", "target.txt"});-    t.expect_eq(f.read("target.txt"), "edited:target.txt\n");-    f.vn({"cfg", "-unset", "editor"});-#endif-}--void worktree_attributes_eol(test::Context& t) {-    VnFixture f;-    f.init();-    f.write(".vnattribs", "*.txt txt eol:lf\n*.cmd txt eol:crlf\n");-    f.write("a.txt", "a\r\nb\r\n");-    f.write("b.cmd", "x\ny\n");-    f.commit("base");-    const std::string base = f.commit_for_message("base");--    fs::remove(f.repo / "a.txt");-    fs::remove(f.repo / "b.cmd");-    f.vn({"co", base});-    t.expect_eq(f.read("a.txt"), "a\nb\n");-    t.expect_eq(f.read("b.cmd"), "x\r\ny\r\n");-}--void worktree_inf_generated(test::Context& t) {-    VnFixture f;-    f.init();-    f.write(".vnattribs", "*.ssa gen\n*.c txt eol:lf\n");-    f.write("main.c", "one\ntwo\n");-    f.write("out.ssa", "one\ntwo\nthree\n");-    f.commit("base");--    const std::string default_output = f.vn({"inf"}).out;-    t.expect_contains(default_output, "Generated");-    t.expect_contains(default_output, "1 files");-    t.expect_contains(default_output, "excluded; use -inc-gen");-    t.expect_not_contains(default_output, ".ssa");--    const std::string included_output = f.vn({"inf", "-inc-gen"}).out;-    t.expect_contains(included_output, ".ssa");-    t.expect_not_contains(included_output, "excluded; use -inc-gen");-}--void worktree_attributes_command(test::Context& t) {-    VnFixture f;-    f.init();--    t.expect_contains(f.vn({"attr", "gen", "*.ssa", "*.bin"}).out, "updated 2");-    t.expect_contains(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n");--    f.vn({"attr", "bin", "*.exe"});-    f.vn({"attr", "lf", "*.c"});-    f.vn({"attr", "crlf", "*.cmd"});-    const std::string rules = f.read(".vnattribs");-    t.expect_contains(rules, "*.exe bin\n");-    t.expect_contains(rules, "*.c eol:lf\n");-    t.expect_contains(rules, "*.cmd eol:crlf\n");--    f.vn({"attr", "txt", "*.c"});-    t.expect_contains(f.read(".vnattribs"), "*.c eol:lf txt\n");-    f.vn({"attr", "crlf", "*.c"});-    t.expect_contains(f.read(".vnattribs"), "*.c txt eol:crlf\n");-    t.expect_not_contains(f.read(".vnattribs"), "eol:lf");-    t.expect_contains(f.vn({"attr", "crlf", "*.c"}).out, "no new attribute rules");--    f.vn({"attr", "gen", "*.c"});-    t.expect_contains(f.read(".vnattribs"), "*.c txt eol:crlf gen\n");-    f.vn({"attr", "rm", "gen", "*.c"});-    t.expect_not_contains(f.read(".vnattribs"), "*.c txt eol:crlf gen");-    f.vn({"attr", "rm", "crlf", "*.c"});-    t.expect_contains(f.read(".vnattribs"), "*.c txt\n");-    f.vn({"attr", "rm", "txt", "*.c"});-    t.expect_not_contains(f.read(".vnattribs"), "*.c txt");-    t.expect_not_contains(f.read(".vnattribs"), "*.c eol");-    f.vn({"attr", "rm", "gen", "*.ssa"});-    t.expect_not_contains(f.read(".vnattribs"), "*.ssa");-    t.expect_contains(f.vn({"attr", "rm", "lf", "*.missing"}).out, "no matching attribute rules");--    fs::create_directories(f.repo / "src");-    f.vn({"attr", "gen", "*.ssa"}, f.repo / "src");-    t.expect_contains(f.read(".vnattribs"), "src/*.ssa gen\n");--    f.write(".vnattribs", "# keep this comment\n*.c gen\n\n*.c eol:lf\n*.tmp -gen\n");-    const std::string listed = f.vn({"attr", "ls"}).out;-    t.expect_contains(listed, "*.c gen\n");-    t.expect_contains(listed, "*.c eol:lf\n");-    t.expect_not_contains(listed, "# keep this comment");-    t.expect_contains(listed, "*.tmp -gen\n");--    f.vn({"attr", "rm", "gen", "*.c"});-    const std::string after_remove = f.read(".vnattribs");-    t.expect_contains(after_remove, "# keep this comment\n");-    t.expect_contains(after_remove, "*.c eol:lf\n");-    t.expect_not_contains(after_remove, "*.c gen");-    f.vn({"attr", "rm", "gen", "*.tmp"});-    t.expect_not_contains(f.read(".vnattribs"), "-gen");--    VnFixture outside;-    outside.failed({"attr", "gen", "*.c"}, "not a veins repository");-}--void worktree_attributes_command_edges(test::Context& t) {-    VnFixture f;-    f.init();--    t.expect_eq(f.vn({"attr", "ls"}).out, "");-    t.expect_contains(f.vn({"attr", "rm", "gen", "*.c"}).out, "no matching attribute rules");-    t.expect(!f.exists(".vnattribs"));--    f.write(".vnattribs", "# leading comment\r\n\r\n*.c gen\r\n*.c txt\r\n*.cmd txt eol:crlf\r\n");-    t.expect_eq(f.vn({"attr", "ls"}).out, "*.c gen\n*.c txt\n*.cmd txt eol:crlf\n");-    f.vn({"attr", "bin", "*.c"});-    t.expect_eq(f.read(".vnattribs"),-                "# leading comment\r\n\r\n*.c gen\r\n*.c bin\r\n*.cmd txt eol:crlf\r\n");-    f.vn({"attr", "rm", "gen", "*.c"});-    t.expect_eq(f.read(".vnattribs"), "# leading comment\r\n\r\n*.c bin\r\n*.cmd txt eol:crlf\r\n");-    f.vn({"attr", "rm", "bin", "*.c"});-    t.expect_eq(f.read(".vnattribs"), "# leading comment\r\n\r\n*.cmd txt eol:crlf\r\n");--    f.write(".vnattribs", "*.c future eol:cr -gen\n*.d -bin\n*.e -txt\n*.f txt -eol\n");-    f.vn({"attr", "txt", "*.c"});-    t.expect_eq(f.read(".vnattribs"),-                "*.c future eol:cr -gen txt\n*.d -bin\n*.e -txt\n*.f txt -eol\n");-    f.vn({"attr", "gen", "*.c"});-    t.expect_eq(f.read(".vnattribs"),-                "*.c future eol:cr txt gen\n*.d -bin\n*.e -txt\n*.f txt -eol\n");-    f.vn({"attr", "crlf", "*.c"});-    t.expect_eq(f.read(".vnattribs"),-                "*.c future txt gen eol:crlf\n*.d -bin\n*.e -txt\n*.f txt -eol\n");-    f.vn({"attr", "rm", "bin", "*.d"});-    f.vn({"attr", "rm", "txt", "*.e"});-    f.vn({"attr", "lf", "*.f"});-    t.expect_eq(f.read(".vnattribs"), "*.c future txt gen eol:crlf\n*.f txt eol:lf\n");--    f.write(".vnattribs", "*.c txt");-    f.vn({"attr", "gen", "*.c"});-    t.expect_eq(f.read(".vnattribs"), "*.c txt gen\n");-    f.write(".vnattribs", "*.tmp gen");-    f.vn({"attr", "gen", "*.new"});-    t.expect_eq(f.read(".vnattribs"), "*.tmp gen\n*.new gen\n");--    f.write(".vnattribs", "*.c txt\n");-    const std::string unchanged = f.read(".vnattribs");-    t.expect_contains(f.vn({"attr", "rm", "gen", "*.c"}).out, "no matching attribute rules");-    t.expect_eq(f.read(".vnattribs"), unchanged);-    t.expect_eq(f.vn({"attr", "ls", "--"}).out, "*.c txt\n");--    f.failed({"attr", "gen", "bad pattern"}, "not a valid attribute pattern");-    f.failed({"attr", "gen", "#comment"}, "not a valid attribute pattern");-    f.failed({"attr", "gen", ""}, "not a valid attribute pattern");-    t.expect_eq(f.read(".vnattribs"), unchanged);--    f.failed({"attr"}, "requires a subcommand");-    f.failed({"attr", "gen"}, "requires at least one glob");-    f.failed({"attr", "rm"}, "usage: vn attr rm");-    f.failed({"attr", "rm", "gen"}, "usage: vn attr rm");-    f.failed({"attr", "wat", "*.c"}, "unknown attr subcommand");-    f.failed({"attr", "rm", "eol", "*.c"}, "unknown attribute");-    f.failed({"attr", "gen", "-x"}, "unknown flag");-    f.failed({"attr", "ls", "extra"}, "usage: vn attr ls");--    f.write(".vnattribs", "");-    f.vn({"attr", "gen", "--", "*.c"});-    t.expect_eq(f.read(".vnattribs"), "*.c gen\n");--    VnFixture outside;-    outside.failed({"attr", "ls"}, "not a veins repository");-    outside.failed({"attr", "gen", "*.c"}, "not a veins repository");-    outside.failed({"attr", "rm", "gen", "*.c"}, "not a veins repository");-}--void history_log_is_topological(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("base.txt", "base\n");-    f.vn({"bmk", "set", "master"});-    f.commit("base");-    f.vn({"bmk", "set", "left"});-    f.vn({"new", "left"});-    f.write("left.txt", "left\n");-    f.commit("left");-    f.vn({"bmk", "set", "right"});-    f.vn({"new", "master"});-    f.write("right.txt", "right\n");-    f.commit("right");--    const std::vector<std::string> commits = f.log_commits();-    for (std::size_t index = 0; index < commits.size(); ++index) {-        for (const std::string& parent : f.parents(commits[index])) {-            const auto found = std::find(commits.begin(), commits.end(), parent.substr(0, 12));-            if (found == commits.end())-                continue;-            const std::size_t parent_index =-                static_cast<std::size_t>(std::distance(commits.begin(), found));-            t.expect(parent_index > index);-        }-    }-}--void history_amend_rewrites_descendants(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "one\n");-    f.commit("one");-    const std::string one = f.commit_for_message("one");-    f.write("f.txt", "two\n");-    f.commit("two");-    const std::string two = f.commit_for_message("two");-    const std::string one_change = f.metadata(one).at("change");-    const std::string two_change = f.metadata(two).at("change");-    f.vn({"amend", one, "-m", "one renamed"});-    const std::string new_one = f.commit_for_message("one renamed");-    const std::string new_two = f.commit_for_message("two");-    t.expect_ne(one.substr(0, 12), new_one);-    t.expect_ne(two.substr(0, 12), new_two);-    t.expect_eq(f.metadata(new_one).at("change"), one_change);-    t.expect_eq(f.metadata(new_two).at("change"), two_change);-    t.expect_eq(f.parents(new_two).count(new_one), 1u);-}--void history_undo_and_operation_restore(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "one\n");-    f.commit("one");-    const std::string one = f.commit_for_message("one");-    f.write("f.txt", "two\n");-    f.commit("two");-    f.vn({"amend", one, "-m", "renamed"});-    t.expect_contains(f.vn({"log"}).out, "renamed");-    f.vn({"undo"});-    t.expect_not_contains(f.vn({"log"}).out, "renamed");-    const std::vector<std::string> ops = split_lines(f.vn({"op", "log"}).out);-    t.expect(ops.size() >= 2);-    if (ops.size() >= 2) {-        std::istringstream stream(ops[1]);-        std::string previous;-        stream >> previous;-        f.vn({"op", "restore", previous});-        t.expect_contains(f.vn({"log"}).out, "renamed");-    }-}--void history_log_default_amount(test::Context& t) {-    VnFixture f;-    f.init();-    linear_history(f, 22);-    t.expect_eq(f.log_rows().size(), 20u);-    const std::vector<LogRow> default_rows = f.log_rows();-    bool has_newest = false;-    bool has_oldest = false;-    for (const LogRow& row : default_rows) {-        if (row.message == "commit 21")-            has_newest = true;-        if (row.message == "commit 2")-            has_oldest = true;-    }-    t.expect(has_newest);-    t.expect(!has_oldest);--    f.vn({"cfg", "-global", "log.default_amount", "3"});-    t.expect_eq(f.log_rows().size(), 3u);-    t.expect_eq(split_lines(f.vn({"log", "-a", "-no-col-titles"}).out).size(), 23u);-    t.expect_eq(split_lines(f.vn({"log", "-all", "-no-col-titles"}).out).size(), 23u);-    t.expect_eq(split_lines(f.vn({"log", "-a", "-l5", "-no-col-titles"}).out).size(), 23u);-    t.expect_eq(split_lines(f.vn({"log", "-l5", "-a", "-no-col-titles"}).out).size(), 23u);-    f.vn({"cfg", "log.default_amount", "1"});-    t.expect_eq(f.log_rows().size(), 3u);-    t.expect_eq(split_lines(f.vn({"log", "-l5", "-no-col-titles"}).out).size(), 5u);-    const auto oldest = split_lines(f.vn({"log", "-f2", "-no-col-titles"}).out);-    t.expect_eq(oldest.size(), 2u);-    if (oldest.size() == 2) {-        t.expect_contains(oldest[0], "commit 0");-        t.expect_contains(oldest[1], "commit 1");-    }-    f.vn({"cfg", "-global", "log.default_amount", "not-a-number"});-    t.expect_eq(f.log_rows().size(), 20u);-}--void history_diff_path_filter(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("one.txt", "one\n");-    f.write("two.txt", "two\n");-    f.commit("base");-    f.write("one.txt", "one changed\n");-    f.write("two.txt", "two changed\n");--    const std::string one_diff = f.vn({"diff", "one.txt"}).out;-    t.expect_contains(one_diff, "+one changed");-    t.expect_not_contains(one_diff, "+two changed");-    const std::string all_diff = f.vn({"diff", "-a"}).out;-    t.expect_contains(all_diff, "+one changed");-    t.expect_contains(all_diff, "+two changed");-    f.failed({"diff", "--all"}, "unknown flag");-    f.failed({"show", "--all"}, "unknown flag");--    const fs::path subdir = f.repo / "sub";-    fs::create_directories(subdir);-    const std::string relative_diff = f.vn({"diff", "../one.txt"}, subdir).out;-    t.expect_contains(relative_diff, "+one changed");-    t.expect_not_contains(relative_diff, "+two changed");--    f.vn({"go", "-m", "second"});-    const std::string second = f.commit_for_message("second");-    const std::string revision_diff = f.vn({"diff", "-rev", second, "one.txt"}).out;-    t.expect_contains(revision_diff, "+one changed");-    t.expect_not_contains(revision_diff, "+two changed");-    t.expect_contains(f.vn({"diff"}).out, "no diff to show");-    t.expect_contains(f.vn({"help", "diff"}).out, "-a, -all");-}--void history_show_and_diff(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "one\n");-    f.commit("one");-    const std::string one = f.commit_for_message("one");-    f.write("f.txt", "two\n");-    f.commit("two");-    const std::string diff = f.vn({"diff", one, "@"}).out;-    t.expect_contains(diff, "-one");-    t.expect_contains(diff, "+two");-    const std::string shown = f.vn({"show", one}).out;-    t.expect_contains(shown, "one");-    t.expect_contains(f.vn({"show", "-a", one}).out, "--- /dev/null");-    t.expect_contains(f.vn({"help", "show"}).out, "-a, -all");-}--void refs_bookmarks(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "one\n");-    f.commit("one");-    const std::string one = f.commit_for_message("one");-    f.write("f.txt", "two\n");-    f.commit("two");-    const std::string two = f.commit_for_message("two");-    f.vn({"bmk", "set", "main", "-rev", one});-    f.vn({"bmk", "set", "feature", "-rev", two});-    std::string listing = f.vn({"bmk", "ls"}).out;-    t.expect_contains(listing, "main");-    t.expect_contains(listing, "feature");-    f.vn({"bmk", "mv", "main", "-rev", two});-    t.expect_contains(f.vn({"bmk", "ls"}).out, two.substr(0, 12));-    f.vn({"bmk", "rm", "feature"});-    t.expect_not_contains(f.vn({"bmk", "ls"}).out, "feature");-    f.failed({"bmk", "rm", "missing"}, "no such bookmark");-}--void refs_current_bookmark(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "one\n");-    f.vn({"bmk", "set", "main"});-    f.commit("one");-    const std::string one = f.hash("main");-    t.expect_contains(f.vn({"bmk", "ls"}).out, one.substr(0, 12));-    f.write("f.txt", "two\n");-    f.commit("two");-    const std::string two = f.hash("main");-    t.expect_ne(one, two);-    t.expect_contains(f.vn({"bmk", "ls"}).out, two.substr(0, 12));-    t.expect_contains(f.vn({"cfg"}).out, "bookmark.current = main");-}--void refs_tags(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "one\n");-    f.commit("one");-    f.vn({"tag", "set", "v0.0.9"});-    f.vn({"tag", "set", "v0.0.10"});-    const std::string listing = f.vn({"tag", "ls"}).out;-    t.expect_contains(listing, "v0.0.9");-    t.expect_contains(listing, "v0.0.10");-    t.expect_eq(trim_copy(f.vn({"tag", "latest"}).out), "v0.0.10");-    f.vn({"tag", "rm", "v0.0.9"});-    t.expect_not_contains(f.vn({"tag", "ls"}).out, "v0.0.9");-    f.failed({"tag", "rm", "missing"}, "no such tag");-}--void refs_remote_configuration(test::Context& t) {-    VnFixture f;-    f.init();-    f.vn({"remote", "add", "origin", "file:///tmp/example"});-    t.expect_contains(f.vn({"remote", "list"}).out, "origin");-    f.failed({"remote", "add", "origin", "file:///other"}, "already exists");-    f.vn({"remote", "set-url", "origin", "file:///tmp/other"});-    t.expect_contains(f.vn({"remote", "list"}).out, "file:///tmp/other");-    f.vn({"remote", "remove", "origin"});-    t.expect_not_contains(f.vn({"remote", "list"}).out, "origin");-    f.failed({"remote", "remove", "origin"}, "unknown remote");-}--void config_local(test::Context& t) {-    VnFixture f;-    f.init();-    f.vn({"cfg", "test.key", "value"});-    t.expect_eq(trim_copy(f.vn({"cfg", "test.key"}).out), "value");-    t.expect_contains(f.vn({"cfg"}).out, "test.key = value");-    f.vn({"cfg", "set", "test.other", "two"});-    t.expect_eq(trim_copy(f.vn({"cfg", "get", "test.other"}).out), "two");-    f.vn({"cfg", "-unset", "test.key"});-    f.failed({"cfg", "test.key"}, "unknown config key");-    f.vn({"cfg", "unset", "test.other"});-    f.failed({"cfg", "test.other"}, "unknown config key");-}--void config_global_identity(test::Context& t) {-    VnFixture f;-    f.init();-    f.vn({"cfg", "-global", "user.name", "Global Tester"});-    f.vn({"cfg", "-global", "user.email", "global@example.com"});-    t.expect_eq(trim_copy(f.vn({"cfg", "-global", "user.name"}).out), "Global Tester");-    f.write("f.txt", "content\n");-    f.commit("global identity");-    t.expect_contains(f.vn({"show", f.commit_for_message("global identity")}).out, "Global Tester");-    t.expect(fs::exists(f.home / ".local" / "config" / "veins" / "veins.toml"));-}--void config_errors(test::Context& t) {-    (void)t;-    VnFixture f;-    f.init();-    f.failed({"cfg", "key", "value", "extra"}, "accepts a key and one value");-    f.failed({"cfg", "-unset"}, "requires one key");-    f.failed({"cfg", "unknown"}, "unknown config key");-}--void config_defaults(test::Context& t) {-    VnFixture f;-    const fs::path outside = f.root / "outside";-    fs::create_directories(outside);-#if defined(_WIN32)-    const std::string editor_default = "notepad";-    const std::string pager_default = "more";-#else-    const std::string editor_default = "vi";-    const std::string pager_default = "less -R";-#endif-    const std::string defaults = f.vn({"cfg", "-d"}, outside).out;-    t.expect_contains(defaults, "log.default_amount = 20");-    t.expect_contains(defaults, "rename.autodetect = similar");-    t.expect_contains(defaults, "merge.adjacent = strict");-    t.expect_contains(defaults, "user.name = (unset)");-    t.expect_contains(defaults, "editor = " + editor_default);-    t.expect_contains(defaults, "pager = " + pager_default);-    t.expect_not_contains(defaults, "bookmark.current");--    f.vn({"cfg", "-global", "log.default_amount", "50"}, outside);-    f.vn({"cfg", "-global", "editor", "code --wait"}, outside);-    const std::string with_current = f.vn({"cfg", "-d", "-global"}, outside).out;-    t.expect_contains(with_current, "log.default_amount = 20 (current: 50)");-    t.expect_contains(with_current, "editor = " + editor_default + " (current: code --wait)");--    f.init();-    f.vn({"cfg", "log.default_amount", "1"});-    const std::string local_ignored = f.vn({"cfg", "-d"}).out;-    t.expect_contains(local_ignored, "log.default_amount = 20 (current: 50)");-    t.expect_not_contains(local_ignored, "current: 1");--    const std::string internal = f.vn({"cfg", "-i", "-d"}).out;-    t.expect_contains(internal, "bookmark.current = (unset)");-    t.expect_contains(internal, "remote.<name>.url = (unset)");-    t.expect_contains(internal, "promisor = (unset)");-    const std::string long_internal = f.vn({"cfg", "-internal", "-defaults"}).out;-    t.expect_contains(long_internal, "bookmark.current = (unset)");--    f.failed({"cfg", "-d", "extra"}, "takes no operands");-    f.failed({"cfg", "-d", "-list"}, "takes no operands");-    f.failed({"cfg", "-i"}, "requires -d");-    f.failed({"cfg", "--defaults"}, "unknown flag");-    f.failed({"cfg", "--global"}, "unknown flag");-}--void config_pager(test::Context& t) {-    VnFixture f;-    f.init();-    f.vn({"cfg", "pager", "cat"});-    t.expect_eq(pager_command(f.repo), "cat");-    f.vn({"cfg", "-global", "pager", "more"});-    t.expect_eq(pager_command(f.repo), "more");-}--void create_diverged(VnFixture& f, bool same_file) {-    f.init();-    f.write("f.txt", "base\n");-    f.vn({"bmk", "set", "master"});-    f.commit("base");-    f.vn({"bmk", "set", "left"});-    f.vn({"new", "left"});-    f.write("f.txt", same_file ? "left\n" : "base\n");-    f.write("left.txt", "left\n");-    f.commit("left");-    f.vn({"bmk", "set", "right"});-    f.vn({"new", "master"});-    f.write("f.txt", same_file ? "right\n" : "base\n");-    f.write("right.txt", "right\n");-    f.commit("right");-}--void merge_clean(test::Context& t) {-    VnFixture f;-    create_diverged(f, false);-    f.vn({"merge", "left"});-    t.expect(f.metadata("@").at("parents").find(' ') != std::string::npos);-    t.expect(f.exists("left.txt"));-    t.expect(f.exists("right.txt"));-    f.commit("merge");-    t.expect_contains(f.vn({"log"}).out, "merge");-    t.expect_contains(f.vn({"xs"}).out, "no conflicts");-    t.expect_contains(f.vn({"fsck"}).out, "fsck: clean");-}--void merge_conflict_resolve_theirs(test::Context& t) {-    VnFixture f;-    create_diverged(f, true);-    f.vn({"merge", "left"});-    const std::string status = f.vn({"stat"}).out;-    t.expect_contains(status, "C f.txt");-    t.expect_contains(status, "1 conflict(s)");-    t.expect_contains(status, "1 conflicted commit(s) in ancestry");-    t.expect(f.exists("f.txt.base"));-    t.expect(f.exists("f.txt.ours"));-    t.expect(f.exists("f.txt.theirs"));-    t.expect_contains(f.vn({"xs", "-porcelain"}).out, "f.txt\ttext\t");-    t.expect_contains(f.vn({"show", "@"}).out, "f.txt");-    f.vn({"resolve", "-take", "theirs", "f.txt"});-    t.expect_contains(f.vn({"stat"}).out, "M f.txt");-    t.expect_eq(f.read("f.txt"), "left\n");-    t.expect_contains(f.vn({"xs"}).out, "no conflicts");-    f.commit("resolved");-    t.expect_contains(f.vn({"stat"}).out, "working copy clean");-}--void merge_conflict_resolve_ours(test::Context& t) {-    VnFixture f;-    create_diverged(f, true);-    f.vn({"merge", "left"});-    f.vn({"resolve", "-take", "ours", "f.txt"});-    t.expect_eq(f.read("f.txt"), "right\n");-    t.expect_contains(f.vn({"xs"}).out, "no conflicts");-}--void merge_conflict_resolve_current(test::Context& t) {-    VnFixture f;-    create_diverged(f, true);-    f.vn({"merge", "left"});-    f.write("f.txt", "manual resolution\n");-    f.vn({"resolve", "f.txt"});-    t.expect_eq(f.read("f.txt"), "manual resolution\n");-    t.expect_contains(f.vn({"xs"}).out, "no conflicts");-}--void merge_multiple(test::Context& t) {-    VnFixture f;-    create_diverged(f, false);-    f.vn({"merge", "left", "right"});-    std::istringstream parents(f.metadata("@").at("parents"));-    std::size_t count = 0;-    std::string parent;-    while (parents >> parent)-        ++count;-    t.expect_eq(count, 3u);-}--void rebase_changes_parent(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("base.txt", "base\n");-    f.vn({"bmk", "set", "master"});-    f.commit("base");-    f.vn({"bmk", "set", "left"});-    f.vn({"new", "left"});-    f.write("left.txt", "left\n");-    f.commit("left");-    const std::string left_change = f.metadata("left").at("change");-    f.vn({"bmk", "set", "right"});-    f.vn({"new", "master"});-    f.write("right.txt", "right\n");-    f.commit("right");-    const std::string right = f.hash("right");-    f.vn({"rebase", "-s", "left", "-d", "right"});-    t.expect_eq(f.parents("left").count(right.substr(0, 12)), 1u);-    t.expect_eq(f.metadata("left").at("change"), left_change);-    t.expect_contains(f.vn({"show", "left"}).out, "left");-}--void rebase_rewrites_descendants(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("base.txt", "base\n");-    f.vn({"bmk", "set", "master"});-    f.commit("base");-    f.vn({"bmk", "set", "side"});-    f.vn({"new", "side"});-    f.write("one.txt", "one\n");-    f.commit("one");-    const std::string first = f.commit_for_message("one");-    const std::string first_change = f.metadata(first).at("change");-    f.write("two.txt", "two\n");-    f.commit("two");-    const std::string second = f.commit_for_message("two");-    const std::string second_change = f.metadata(second).at("change");-    f.vn({"bmk", "set", "target"});-    f.vn({"new", "master"});-    f.write("target.txt", "target\n");-    f.commit("target");-    const std::string target = f.commit_for_message("target");-    f.vn({"rebase", "-s", first, "-d", target});-    const std::string new_first = f.commit_for_message("one");-    const std::string new_second = f.commit_for_message("two");-    t.expect_eq(f.metadata(new_first).at("change"), first_change);-    t.expect_eq(f.metadata(new_second).at("change"), second_change);-    t.expect_eq(f.parents(new_first).count(target), 1u);-    t.expect_eq(f.parents(new_second).count(new_first), 1u);-}--void rebase_conflict(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "base\n");-    f.vn({"bmk", "set", "master"});-    f.commit("base");-    f.vn({"bmk", "set", "left"});-    f.vn({"new", "left"});-    f.write("f.txt", "left\n");-    f.commit("left");-    f.vn({"bmk", "set", "right"});-    f.vn({"new", "master"});-    f.write("f.txt", "right\n");-    f.commit("right");-    f.vn({"rebase", "-s", "left", "-d", "right"});-    bool conflicted = false;-    for (const LogRow& row : f.log_rows()) {-        if (row.message.find("left") != std::string::npos &&-            row.raw.find("(conflicted)") != std::string::npos)-            conflicted = true;-    }-    t.expect(conflicted);-    f.vn({"co", "left"});-    t.expect_contains(f.vn({"xs"}).out, "f.txt");-    t.expect(f.exists("f.txt.base"));-    f.vn({"resolve", "-take", "theirs", "f.txt"});-    t.expect_contains(f.vn({"xs"}).out, "no conflicts");-}--void git_bridge_import_materialize_export(test::Context& t) {-#if defined(_WIN32)-    t.expect(true);-#else-    if (!git_available()) {-        t.expect(true);-        return;-    }-    VnFixture f;-    const fs::path git_repo = make_git_repository(t, f);-    const fs::path vn_repo = f.root / "vnrepo";-    f.vn({"init", vn_repo.string(), "-git-import:" + git_repo.string()}, f.root);-    std::string log = f.vn({"log", "-no-col-titles"}, vn_repo).out;-    t.expect_contains(log, "git one");-    t.expect_contains(log, "git two");-    t.expect_eq(split_lines(f.vn({"ls", "-plain"}, vn_repo).out).size(), 1u);-    f.vn({"git", "materialize"}, vn_repo);-    t.expect_contains(f.vn({"stat"}, vn_repo).out, "working copy clean");-    t.expect_eq(f.read("a.txt", vn_repo), "one\ntwo\n");--    f.write("b.txt", "native\n", vn_repo);-    f.commit("native commit", vn_repo);-    f.vn({"git", "export"}, vn_repo);-    const fs::path git_dir = vn_repo / ".veins" / "git";-    const CommandResult subjects =-        run_shell({"git", "--git-dir", git_dir.string(), "log", "--format=%s", "--all"}, f.root);-    require_shell(t, subjects, "git log");-    t.expect_contains(subjects.out, "native commit");-    const CommandResult tree =-        run_shell({"git", "--git-dir", git_dir.string(), "show", "master:b.txt"}, f.root);-    require_shell(t, tree, "git show");-    t.expect_eq(tree.out, "native\n");-    t.expect_contains(f.vn({"fsck"}, vn_repo).out, "fsck: clean");-#endif-}--void git_bridge_invalid_import(test::Context& t) {-    (void)t;-#if defined(_WIN32)-    t.expect(true);-#else-    VnFixture f;-    const fs::path not_git = f.root / "not-git";-    fs::create_directories(not_git);-    f.failed({"init", (f.root / "bad").string(), "-git-import:" + not_git.string()},-             "not a git repository root", f.root);-#endif-}--void make_source_repository(VnFixture& f) {-    const fs::path source = f.root / "source";-    fs::create_directories(source);-    f.init(source);-    f.write("a.txt", "hello\n", source);-    f.vn({"bmk", "set", "master"}, source);-    f.commit("initial", source);-    f.vn({"access", "anonymous", "on"}, source);-}--void protocol_clone_whoami(test::Context& t) {-    VnFixture f;-    make_source_repository(f);-    const fs::path source = f.root / "source";-    const fs::path clone = f.root / "clone";-    fs::create_directories(clone);-    f.vn({"clone", "file://" + source.string(), clone.string()}, f.root);-    t.expect_eq(f.read("a.txt", clone), "hello\n");-    t.expect_contains(f.vn({"log"}, clone).out, "initial");-    t.expect_contains(f.vn({"stat"}, clone).out, "working copy clean");-    t.expect_contains(f.vn({"remote", "list"}, clone).out, "origin");-    t.expect_contains(f.vn({"whoami", "origin"}, clone).out, "role: read");-}--void protocol_push_fetch(test::Context& t) {-    VnFixture f;-    make_source_repository(f);-    const fs::path source = f.root / "source";-    const std::string key_info = f.vn({"key", "generate", "integration"}, source).out;-    std::string public_key;-    for (const std::string& line : split_lines(key_info)) {-        if (line.starts_with("public key: ")) {-            public_key = line.substr(std::string("public key: ").size());-            break;-        }-    }-    t.expect(!public_key.empty());-    f.vn({"access", "add", "-role", "write", "-key", public_key, "-name", "integration"}, source);-    t.expect_contains(f.vn({"key", "show", "integration"}, source).out, "fingerprint:");-    t.expect_contains(f.vn({"key", "list"}, source).out, "integration");-    f.vn({"auth", "use", "integration"}, source);-    t.expect_contains(f.vn({"auth", "list"}, source).out, "integration");--    const fs::path clone_a = f.root / "clone-a";-    f.vn({"clone", "file://" + source.string(), clone_a.string()}, f.root);-    f.vn({"cfg", "remote.origin.key", "integration"}, clone_a);-    f.write("a.txt", "from clone a\n", clone_a);-    f.commit("clone a change", clone_a);-    f.write("c.txt", "from clone a again\n", clone_a);-    f.commit("clone a second change", clone_a);-    const CommandResult pushed = f.vn({"push", "origin", "master"}, clone_a);-    t.expect_contains(pushed.out, "pushed master");-    t.expect_contains(f.vn({"log"}, source).out, "clone a change");-    t.expect_contains(f.vn({"log"}, source).out, "clone a second change");-    t.expect_contains(f.vn({"whoami", "origin"}, clone_a).out, "role: write");--    f.vn({"tag", "set", "v0.0.1"}, clone_a);-    const CommandResult tag_pushed = f.vn({"push", "origin", "master"}, clone_a);-    t.expect_contains(tag_pushed.out, "pushed 1 tag(s)");-    t.expect_contains(f.vn({"tag", "ls"}, source).out, "v0.0.1");--    const fs::path clone_b = f.root / "clone-b";-    f.vn({"clone", "file://" + source.string(), clone_b.string()}, f.root);-    f.vn({"cfg", "remote.origin.key", "integration"}, clone_b);-    f.write("b.txt", "from clone b\n", clone_b);-    f.commit("clone b change", clone_b);-    f.vn({"push", "origin", "master"}, clone_b);-    f.vn({"fetch", "origin"}, clone_a);-    t.expect_contains(f.vn({"log", "-rev", "origin/master"}, clone_a).out, "clone b change");-}--void protocol_bad_inputs(test::Context& t) {-    (void)t;-    VnFixture f;-    f.init();-    f.failed({"clone", "not-a-url", "dest"}, "unsupported URL");-    f.failed({"clone", "file:///does/not/exist", "dest"}, "error:");--    const fs::path occupied = f.root / "occupied";-    fs::create_directories(occupied);-    if (!write_file(occupied / "keep.txt", bytes_of("keep\n")))-        throw test::Failure("cannot write occupied directory file");-    const std::string source = "file://" + f.repo.string();-    f.failed({"clone", source, occupied.string()}, "destination directory is not empty", f.root);-    f.failed({"gg", source, occupied.string()}, "destination directory is not empty", f.root);-    f.failed({"clone", source, (occupied / "keep.txt").string()},-             "destination already exists and is not a directory", f.root);-}--void errors_bad_arguments(test::Context& t) {-    (void)t;-    VnFixture f;-    f.init();-    for (const std::vector<std::string>& command : std::vector<std::vector<std::string>>{-             {"go"},-             {"go", "-m", ""},-             {"rm"},-             {"ex"},-             {"show", "unknown-revision"},-             {"hash", "unknown-revision"},-             {"co", "unknown-revision"},-             {"amend", "@"},-             {"rebase", "-s", "@"},-             {"new", "-bad"},-         }) {-        f.failed(command, "error:");-    }-    f.failed({"unknown-command"}, "unknown command");-    f.failed({"help", "unknown-command"}, "unknown command");-    f.failed({"cfg", "key", "value", "extra"}, "accepts a key and one value");-}--void errors_self_test_fsck_version(test::Context& t) {-    VnFixture f;-    f.init();-    f.write("f.txt", "content\n");-    f.commit("content");-    t.expect_contains(f.vn({"self-test"}).out, "self-test: ok");-    t.expect_contains(f.vn({"fsck"}).out, "fsck: clean");-    t.expect_contains(f.vn({"fsck", "-verbose"}).out, "fsck: clean");-    t.expect_contains(f.vn({"version"}).out, "veins");-}--void errors_log_show_arguments(test::Context& t) {-    (void)t;-    VnFixture f;-    f.init();-    for (const std::vector<std::string>& command : std::vector<std::vector<std::string>>{-             {"log", "-l"}, {"log", "-f", "0"}, {"log", "-bad"}, {"show", "-bad"}}) {-        f.failed(command);-    }-}--std::vector<test::Suite> suites() {-    return {-        {"core",-         {-             {"init_version_help", core_init_version_help},-             {"outside_repository", core_outside_repository},-             {"status_list_diff_describe", core_status_list_diff_describe},-             {"status_paths_relative_to_cwd", core_status_paths_relative_to_cwd},-             {"commit_log_show_hash", core_commit_log_show_hash},-             {"log_limits_revisions", core_log_limits_revisions},-             {"checkout_materializes_and_new", core_checkout_materializes_and_new},-         }},-        {"worktree",-         {-             {"rename_and_delete", worktree_rename_and_delete},-             {"exclude_and_remove", worktree_exclude_and_remove},-             {"ignore_rules", worktree_ignore_rules},-             {"checkout_removes_later_files", worktree_checkout_removes_later_files},-             {"attributes_eol", worktree_attributes_eol},-             {"inf_generated", worktree_inf_generated},-             {"attributes_command", worktree_attributes_command},-             {"attributes_command_edges", worktree_attributes_command_edges},-             {"editor", worktree_editor},-         }},-        {"history",-         {-             {"log_is_topological", history_log_is_topological},-             {"log_default_amount", history_log_default_amount},-             {"amend_rewrites_descendants", history_amend_rewrites_descendants},-             {"undo_and_operation_restore", history_undo_and_operation_restore},-             {"diff_path_filter", history_diff_path_filter},-             {"show_and_diff", history_show_and_diff},-         }},-        {"refs",-         {-             {"bookmarks", refs_bookmarks},-             {"current_bookmark", refs_current_bookmark},-             {"tags", refs_tags},-             {"remote_configuration", refs_remote_configuration},-         }},-        {"config",-         {-             {"local", config_local},-             {"global_identity", config_global_identity},-             {"errors", config_errors},-             {"defaults", config_defaults},-             {"pager", config_pager},-         }},-        {"merge",-         {-             {"clean", merge_clean},-             {"conflict_resolve_theirs", merge_conflict_resolve_theirs},-             {"conflict_resolve_ours", merge_conflict_resolve_ours},-             {"conflict_resolve_current", merge_conflict_resolve_current},-             {"multiple", merge_multiple},-         }},-        {"rebase",-         {-             {"changes_parent", rebase_changes_parent},-             {"rewrites_descendants", rebase_rewrites_descendants},-             {"conflict", rebase_conflict},-         }},-        {"git",-         {-             {"import_materialize_export", git_bridge_import_materialize_export},-             {"invalid_import", git_bridge_invalid_import},-         }},-        {"protocol",-         {-             {"clone_whoami", protocol_clone_whoami},-             {"push_fetch", protocol_push_fetch},-             {"bad_inputs", protocol_bad_inputs},-         }},-        {"errors",-         {-             {"bad_arguments", errors_bad_arguments},-             {"self_test_fsck_version", errors_self_test_fsck_version},-             {"log_show_arguments", errors_log_show_arguments},-         }},-    };-}--} // namespace-} // namespace vn--int main(int argc, char** argv) {-    // The protocol tests run in-process, so the client may re-exec this binary as-    // a stdio server.-    if (argc >= 2 && std::string_view(argv[1]) == "serve") {-        std::vector<std::string> args;-        args.reserve(static_cast<std::size_t>(argc));-        for (int i = 0; i < argc; ++i)-            args.emplace_back(argv[i]);-        return vn::cli_run(args);-    }--    std::string suite;-    for (int i = 1; i < argc; ++i) {-        const std::string_view arg = argv[i];-        if (arg == "--suite" && i + 1 < argc) {-            suite = argv[++i];-        } else if (arg == "--list") {-            for (const vn::test::Suite& item : vn::suites())-                std::cout << item.name << "\n";-            return 0;-        } else {-            std::cerr << "unknown argument: " << arg << "\n";-            return 1;-        }-    }-    return vn::test::run_tests(vn::suites(), suite);-}--- /dev/null+++ b/xveins/tests/unit/core_tests.cpp@@ -0,0 +1,337 @@+#include "test_support.h"++#include "core/common.h"+#include "unit/unit_helpers.h"++#include <cstring>+#include <string>+#include <vector>++namespace vn::unit {+namespace {++void test_varint(test::Context& t) {+    const std::vector<std::uint64_t> values = {+        0,   1,   2,         127,        128,        255,+        256, 300, 16384,     1'000'000,  0xffffffffull,+    };+    for (std::uint64_t value : values) {+        ByteWriter writer;+        writer.varint(value);+        Reader reader(writer.view());+        const auto decoded = reader.varint();+        t.expect(decoded.has_value());+        if (decoded)+            t.expect_eq(*decoded, value);+        t.expect(reader.finish().has_value());+    }++    ByteWriter max_writer;+    max_writer.varint(0xffffffffffffffffull);+    Reader max_reader(max_writer.view());+    const auto max_value = max_reader.varint();+    t.expect(max_value.has_value());+    if (max_value)+        t.expect_eq(*max_value, 0xffffffffffffffffull);++    const std::uint8_t non_minimal[] = {0x80, 0x00};+    Reader reader(Bytes(non_minimal, sizeof(non_minimal)));+    const auto decoded = reader.varint();+    t.expect(!decoded.has_value());+    if (!decoded)+        t.expect(decoded.error().kind == ErrorKind::NonMinimalVarint);++    const std::uint8_t truncated[] = {0x80};+    Reader truncated_reader(Bytes(truncated, sizeof(truncated)));+    t.expect(!truncated_reader.varint().has_value());++    const std::uint8_t overflow[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,+                                     0xff, 0xff, 0x02};+    Reader overflow_reader(Bytes(overflow, sizeof(overflow)));+    const auto overflowing = overflow_reader.varint();+    t.expect(!overflowing.has_value());+    if (!overflowing)+        t.expect(overflowing.error().kind == ErrorKind::VarintOverflow);+}++void test_reader_integers(test::Context& t) {+    const std::uint8_t one[] = {0x7f};+    const std::uint8_t two[] = {0x34, 0x12};+    const std::uint8_t four[] = {0x78, 0x56, 0x34, 0x12};+    const std::uint8_t eight[] = {0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01};++    Reader r1(Bytes(one, 1));+    t.expect_eq(*r1.u8(), 0x7f);+    t.expect(r1.finish().has_value());++    Reader r2(Bytes(two, 2));+    t.expect_eq(*r2.u16le(), 0x1234);+    t.expect(r2.finish().has_value());++    Reader r4(Bytes(four, 4));+    t.expect_eq(*r4.u32le(), 0x12345678u);+    t.expect(r4.finish().has_value());++    Reader r8(Bytes(eight, 8));+    t.expect_eq(*r8.u64le(), 0x0123456789abcdefull);+    t.expect(r8.finish().has_value());++    Reader negative(Bytes(two, 2));+    t.expect_eq(*negative.i16le(), static_cast<std::int16_t>(0x1234));++    for (std::size_t length = 0; length < 8; ++length) {+        Reader cut(Bytes(eight, length));+        t.expect(!cut.u64le().has_value());+    }+    Reader missing(Bytes{});+    t.expect(!missing.u8().has_value());+    t.expect(!missing.u16le().has_value());+    t.expect(!missing.u32le().has_value());+    t.expect(!missing.u64le().has_value());+    t.expect(!missing.i16le().has_value());+    t.expect(!missing.i64le().has_value());+    t.expect(!missing.id().has_value());+    t.expect(!missing.opt_id().has_value());+    t.expect(missing.finish().has_value());++    const std::uint8_t none_tag[] = {0};+    Reader none_reader(Bytes(none_tag, 1));+    const auto none = none_reader.opt_id();+    t.expect(none.has_value());+    if (none)+        t.expect(!none->has_value());++    const std::uint8_t bad_tag[] = {2};+    Reader tagged(Bytes(bad_tag, 1));+    t.expect(!tagged.opt_id().has_value());++    Reader read_u64(Bytes(eight, 8));+    t.expect_eq(Reader::read_u64le_at(Bytes(eight, 8), 0), 0x0123456789abcdefull);+    t.expect_eq(Reader::read_u64le_at(Bytes(eight, 8), 1), std::uint64_t{0});+    t.expect_eq(Reader::read_u64le_at(Bytes(eight, 4), 0), std::uint64_t{0});+    t.expect_eq(Reader::read_u64le_at(Bytes(eight, 8), 99), std::uint64_t{0});+}++void test_reader_sized_values(test::Context& t) {+    ByteWriter writer;+    writer.u8(1);+    writer.u16le(0x2345);+    writer.u32le(0x3456789a);+    writer.u64le(0x456789abcdef0123ull);+    writer.varint(300);+    writer.length_prefixed("payload");+    writer.id(make_id(7));+    const auto data = writer.take();++    Reader full(bytes_of(data));+    t.expect_eq(*full.u8(), 1);+    t.expect_eq(*full.u16le(), 0x2345);+    t.expect_eq(*full.u32le(), 0x3456789au);+    t.expect_eq(*full.u64le(), 0x456789abcdef0123ull);+    t.expect_eq(*full.varint(), 300u);+    t.expect_eq(to_string(*full.bytes(64)), "payload");+    t.expect_eq(std::memcmp(full.id()->data(), make_id(7).data(), ID_LEN), 0);+    t.expect(full.finish().has_value());++    for (std::size_t length = 0; length < data.size(); ++length) {+        Reader cut(bytes_of(data).first(length));+        (void)cut.u8();+        (void)cut.u16le();+        (void)cut.u32le();+        (void)cut.u64le();+        (void)cut.varint();+        (void)cut.bytes(64);+        (void)cut.id();+    }++    ByteWriter too_long;+    too_long.varint(9);+    too_long.raw("short");+    Reader limited(too_long.view());+    const auto limited_value = limited.bytes(8);+    t.expect(!limited_value.has_value());+    if (!limited_value)+        t.expect(limited_value.error().kind == ErrorKind::LimitExceeded);++    ByteWriter short_body;+    short_body.varint(9);+    short_body.raw("short");+    Reader truncated(short_body.view());+    const auto truncated_value = truncated.bytes(16);+    t.expect(!truncated_value.has_value());+    if (!truncated_value)+        t.expect(truncated_value.error().kind == ErrorKind::UnexpectedEnd);++    ByteWriter list;+    list.varint(1000);+    Reader list_reader(list.view());+    t.expect(!list_reader.list_len(1'000'000).has_value());++    Reader raw_empty(Bytes{});+    t.expect(raw_empty.raw(0).has_value());+    t.expect(!raw_empty.raw(1).has_value());+}++void test_reader_sig_and_time(test::Context& t) {+    ByteWriter writer;+    writer.sig(Reader::Sig{"Name", "mail@example.com", -1234, -90});+    writer.time_ms(Reader::TimeMs{1'700'000'000'123, 120});+    const auto data = writer.take();++    Reader reader(bytes_of(data));+    const auto sig = reader.sig(MAX_NAME_LEN, MAX_NAME_LEN);+    t.expect(sig.has_value());+    if (sig) {+        t.expect_eq(sig->name, "Name");+        t.expect_eq(sig->email, "mail@example.com");+        t.expect_eq(sig->seconds, -1234);+        t.expect_eq(sig->tz_min, -90);+    }+    const auto time = reader.time_ms();+    t.expect(time.has_value());+    if (time) {+        t.expect_eq(time->ms, 1'700'000'000'123);+        t.expect_eq(time->tz_min, 120);+    }+    t.expect(reader.finish().has_value());++    for (std::size_t length = 0; length < data.size(); ++length) {+        Reader cut(bytes_of(data).first(length));+        (void)cut.sig(MAX_NAME_LEN, MAX_NAME_LEN);+        (void)cut.time_ms();+    }+}++void test_identifiers(test::Context& t) {+    const std::string text = "hello";+    const Id id = text_id(text);+    const std::string hex = hex_encode(id);+    t.expect_eq(hex.size(), ID_LEN * 2);+    const auto parsed = parse_id(hex);+    t.expect(parsed.has_value());+    if (parsed)+        t.expect_eq(std::memcmp(parsed->data(), id.data(), ID_LEN), 0);+    t.expect(parse_id(hex.substr(0, 63)).has_value() == false);+    t.expect(!parse_id("not-hex").has_value());+    t.expect(!parse_id(std::string(64, 'z')).has_value());+    t.expect(parse_id(hex.substr(0, 62) + "AF").has_value());++    std::array<std::uint8_t, 1> out{};+    t.expect(!hex_decode("0000", MutBytes(out.data(), out.size())));+    t.expect(hex_decode("ff", MutBytes(out.data(), out.size())));+    t.expect_eq(out[0], static_cast<std::uint8_t>(0xff));++    ChangeId change{};+    for (std::size_t i = 0; i < change.size(); ++i)+        change[i] = static_cast<std::uint8_t>(i);+    const std::string encoded = base32_encode(change);+    t.expect(!encoded.empty());+    t.expect(base32_prefix_matches(encoded, encoded.substr(0, 4)));+    std::string upper = encoded.substr(0, 4);+    for (char& c : upper)+        if (c >= 'a' && c <= 'z')+            c = static_cast<char>(c - 32);+    t.expect(base32_prefix_matches(encoded, upper));+    t.expect(!base32_prefix_matches(encoded, "!!!!"));+    t.expect(!base32_prefix_matches(encoded, std::string(encoded.size() + 1, 'a')));++    const std::string empty_hash =+        "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";+    t.expect_eq(hex_encode(Bytes(blake3_hash(Bytes{}))), empty_hash);+    t.expect_eq(std::memcmp(object_id(TYPE_BLOB, bytes_of(text)).data(), id.data(), ID_LEN), 0);+    t.expect_ne(std::memcmp(object_id(TYPE_TREE, bytes_of(text)).data(), id.data(), ID_LEN), 0);+}++void test_byte_helpers(test::Context& t) {+    t.expect(equals(bytes_of("abc"), bytes_of("abc")));+    t.expect(!equals(bytes_of("abc"), bytes_of("abd")));+    t.expect(!equals(bytes_of("abc"), bytes_of("ab")));+    t.expect(compare(bytes_of("abc"), bytes_of("abd")) < 0);+    t.expect(compare(bytes_of("abc"), bytes_of("abc")) == 0);+    t.expect(compare(bytes_of("abc"), bytes_of("ab")) > 0);+    t.expect(ascii_iequals(bytes_of("AbC"), bytes_of("aBc")));+    t.expect(!ascii_iequals(bytes_of("AbC"), bytes_of("aBd")));+    t.expect(starts_with(bytes_of("abcdef"), bytes_of("abc")));+    t.expect(!starts_with(bytes_of("ab"), bytes_of("abc")));+    t.expect_eq(to_string(bytes_of("text")), "text");+    t.expect_eq(str_of(Bytes{}).size(), 0u);+    t.expect_eq(type_name(TYPE_BLOB), "blob");+    t.expect_eq(type_name(static_cast<std::uint8_t>(99)), "unknown");+    t.expect(type_valid(TYPE_CHUNK));+    t.expect(type_valid(TYPE_VIEW));+    t.expect(!type_valid(0));+    t.expect(!type_valid(static_cast<std::uint8_t>(TYPE_VIEW + 1)));+}++void test_file_helpers(test::Context& t) {+    const TempDir temp;+    const fs::path file = temp.path / "nested" / "file.txt";+    t.expect(ensure_directory(file.parent_path()));+    t.expect(write_file(file, bytes_of("content")));+    t.expect(path_exists(file));+    t.expect(path_is_file(file));+    t.expect(!path_is_dir(file));+    t.expect_eq(path_file_size(file).value_or(0), 7u);+    const auto read = read_file_opt(file);+    t.expect(read.has_value());+    if (read)+        t.expect_eq(to_string(bytes_of(*read)), "content");+    t.expect(!read_file_opt(file, 6).has_value());+    t.expect(read_file_opt(file, 7).has_value());+    t.expect(!read_file(temp.path / "missing").has_value());+    const auto range = read_file_range(file, 2, 3);+    t.expect(range.has_value());+    if (range)+        t.expect_eq(to_string(bytes_of(*range)), "nte");+    const auto beyond = read_file_range(file, 100, 3);+    t.expect(beyond.has_value());+    if (beyond)+        t.expect(beyond->empty());+    t.expect(write_atomic(file, bytes_of("replacement")));+    const auto replaced = read_file_opt(file);+    t.expect(replaced.has_value());+    if (replaced)+        t.expect_eq(to_string(bytes_of(*replaced)), "replacement");+    t.expect(remove_file(file));+    t.expect(!path_exists(file));+    t.expect(same_or_under(temp.path / "a" / "b", temp.path));+    t.expect(same_or_under(temp.path, temp.path));+    t.expect(!same_or_under(temp.path, temp.path / "a"));+    t.expect_eq(basename_string(file), "file.txt");+    t.expect(!write_file(temp.path, bytes_of("cannot replace directory")));+    t.expect(ensure_directory(temp.path / "nested"));+    t.expect(list_directory(temp.path / "missing").empty());++    const fs::path link = temp.path / "link";+    std::error_code ec;+    fs::create_symlink("nested/file.txt", link, ec);+    if (!ec) {+        t.expect(path_is_symlink(link));+        const auto target = path_read_symlink(link);+        t.expect(target.has_value());+        if (target)+            t.expect_eq(*target, "nested/file.txt");+        const auto info = stat_path(link);+        t.expect(info.has_value());+        if (info)+            t.expect_eq(info->kind, 3);+    }+    t.expect(remove_tree(temp.path / "missing-tree"));+}++} // namespace++test::Suite core_suite() {+    return {"unit-core",+            {+                {"varint", test_varint},+                {"reader_integers", test_reader_integers},+                {"reader_sized_values", test_reader_sized_values},+                {"reader_sig_and_time", test_reader_sig_and_time},+                {"identifiers", test_identifiers},+                {"byte_helpers", test_byte_helpers},+                {"file_helpers", test_file_helpers},+            }};+}++} // namespace vn::unit--- /dev/null+++ b/xveins/tests/unit/main.cpp@@ -0,0 +1,34 @@+#include "test_support.h"++#include "unit/suites.h"++#include <iostream>+#include <string>+#include <string_view>+#include <vector>++int main(int argc, char** argv) {+    const std::vector<vn::test::Suite> suites = {+        vn::unit::core_suite(),   vn::unit::object_suite(),  vn::unit::store_suite(),+        vn::unit::worktree_suite(), vn::unit::protocol_suite(),+    };++    std::string suite;+    for (int i = 1; i < argc; ++i) {+        const std::string_view arg = argv[i];+        if (arg == "--suite" && i + 1 < argc) {+            suite = argv[++i];+        } else if (arg == "--list") {+            for (const vn::test::Suite& item : suites)+                std::cout << item.name << "\n";+            return 0;+        } else {+            std::cerr << "unknown argument: " << arg << "\n";+            return 1;+        }+    }+    // Keep the historical alias that ran every unit suite.+    if (suite == "unit")+        suite.clear();+    return vn::test::run_tests(suites, suite);+}--- /dev/null+++ b/xveins/tests/unit/object_tests.cpp@@ -0,0 +1,366 @@+#include "test_support.h"++#include "core/common.h"+#include "object/object.h"+#include "unit/unit_helpers.h"++#include <algorithm>+#include <cstring>+#include <functional>+#include <string>+#include <vector>++namespace vn::unit {+namespace {++Commit make_commit() {+    Commit commit;+    commit.version = 1;+    commit.parents = {make_id(1)};+    commit.root_tree = make_id(2);+    for (std::size_t i = 0; i < commit.change_id.size(); ++i)+        commit.change_id[i] = static_cast<std::uint8_t>(i + 3);+    commit.author = Sig{"Author", "author@example.com", 1'700'000'000, 0};+    commit.committer = Sig{"Committer", "committer@example.com", 1'700'000'001, -120};+    commit.message = "commit message";+    commit.renames_state = RENAMES_RECORDED;+    commit.renames = {Rename{0, 1, "old.txt", "new.txt"}};+    commit.extra = {KeyValue{"encoding", "UTF-8"}};+    return commit;+}++View make_view() {+    const Id a = make_id(10);+    const Id b = make_id(20);+    View view;+    view.heads = a < b ? std::vector<Id>{a, b} : std::vector<Id>{b, a};+    Bookmark bookmark;+    bookmark.name = "master";+    bookmark.targets.adds = {view.heads.front()};+    view.bookmarks = {bookmark};+    view.tags = {TagRef{"v1", view.heads.back()}};+    view.remote_refs = {RemoteRef{"origin", "master", view.heads.front()}};+    view.working_copies = {WorkspaceRef{"default", view.heads.back()}};+    return view;+}++Conflict make_conflict() {+    Conflict conflict;+    conflict.adds = {+        ConflictValue{KIND_FILE, text_id("one")},+        ConflictValue{KIND_FILE, text_id("two")},+    };+    conflict.removes = {ConflictValue{KIND_FILE, text_id("three")}};+    return conflict;+}++Operation make_operation() {+    Operation op;+    op.parents = {make_id(1), make_id(2)};+    op.view = make_id(3);+    op.start = Reader::TimeMs{1'700'000'000'123, 0};+    op.end = Reader::TimeMs{1'700'000'000'456, 0};+    op.hostname = "host";+    op.username = "user";+    op.description = "describe";+    op.tags = {KeyValue{"kind", "test"}};+    return op;+}++template <typename Decode>+void expect_all_prefixes_rejected(test::Context& t, const std::vector<std::uint8_t>& body,+                                  Decode decode) {+    for (std::size_t length = 0; length < body.size(); ++length) {+        const auto result = decode(bytes_of(body).first(length));+        t.expect(!result.has_value());+    }+}++template <typename Decode>+void exercise_mutations(const std::vector<std::uint8_t>& body, Decode decode) {+    for (std::size_t i = 0; i < body.size(); ++i) {+        for (const std::uint8_t mask : {std::uint8_t{0x01}, std::uint8_t{0x80},+                                        std::uint8_t{0xff}}) {+            auto copy = body;+            copy[i] = static_cast<std::uint8_t>(copy[i] ^ mask);+            (void)decode(bytes_of(copy));+        }+    }+}++void test_blob_roundtrip(test::Context& t) {+    const std::string small = "small blob";+    const auto encoded = encode_inline_blob(bytes_of(small));+    t.expect(encoded.has_value());+    if (!encoded)+        return;+    const auto decoded = decode_blob(bytes_of(*encoded));+    t.expect(decoded.has_value());+    if (decoded) {+        t.expect(decoded->form == BlobForm::Inline);+        t.expect_eq(to_string(bytes_of(decoded->data)), small);+    }+    expect_all_prefixes_rejected(t, *encoded, [](Bytes bytes) { return decode_blob(bytes); });+    exercise_mutations(*encoded, [](Bytes bytes) { return decode_blob(bytes); });++    const std::string large(200'000, 'x');+    const BlobBuild build = build_blob(bytes_of(large));+    t.expect(!build.objects.empty());+    t.expect(build.root != Id{});+    const auto root = decode_blob(bytes_of(build.objects.back().body));+    t.expect(root.has_value());+    if (root)+        t.expect(root->form != BlobForm::Inline);+    expect_all_prefixes_rejected(t, build.objects.back().body,+                                 [](Bytes bytes) { return decode_blob(bytes); });+    exercise_mutations(build.objects.back().body, [](Bytes bytes) { return decode_blob(bytes); });++    t.expect_eq(fastcdc_next(bytes_of(std::string(1024, 'a'))), 1024u);+    t.expect_eq(fastcdc_next(Bytes{}), 0u);+    const std::size_t chunk = fastcdc_next(bytes_of(large));+    t.expect(chunk >= 16384);+    t.expect(chunk <= 262144);+}++void test_blob_invalid_values(test::Context& t) {+    const std::uint8_t bad_form[] = {3};+    t.expect(!decode_blob(Bytes(bad_form, 1)).has_value());++    ByteWriter empty_leaf;+    empty_leaf.u8(static_cast<std::uint8_t>(BlobForm::Leaf));+    empty_leaf.varint(0);+    t.expect(!decode_blob(empty_leaf.view()).has_value());++    ByteWriter oversized_chunk;+    oversized_chunk.u8(static_cast<std::uint8_t>(BlobForm::Leaf));+    oversized_chunk.varint(1);+    oversized_chunk.id(make_id(1));+    oversized_chunk.varint(MAX_CHUNK_LEN + 1);+    t.expect(!decode_blob(oversized_chunk.view()).has_value());++    ByteWriter zero_chunk;+    zero_chunk.u8(static_cast<std::uint8_t>(BlobForm::Leaf));+    zero_chunk.varint(1);+    zero_chunk.id(make_id(1));+    zero_chunk.varint(0);+    t.expect(!decode_blob(zero_chunk.view()).has_value());++    ByteWriter overflowing_total;+    overflowing_total.u8(static_cast<std::uint8_t>(BlobForm::Interior));+    overflowing_total.varint(2);+    overflowing_total.id(make_id(1));+    overflowing_total.varint(0xffffffffffffffffull);+    overflowing_total.id(make_id(2));+    overflowing_total.varint(1);+    t.expect(!decode_blob(overflowing_total.view()).has_value());+}++void test_tree_roundtrip(test::Context& t) {+    const Id first = text_id("first");+    const Id second = text_id("second");+    const std::vector<TreeEntry> entries = {+        TreeEntry{"a.txt", KIND_FILE, first},+        TreeEntry{"b.txt", KIND_EXECUTABLE, second},+        TreeEntry{"dir", KIND_SUBTREE, first},+    };+    const auto body = encode_tree(entries);+    t.expect(body.has_value());+    if (body) {+        const auto decoded = decode_tree(bytes_of(*body));+        t.expect(decoded.has_value());+        if (decoded) {+            t.expect_eq(decoded->entries.size(), entries.size());+            if (decoded->entries.size() == entries.size()) {+                for (std::size_t i = 0; i < entries.size(); ++i) {+                    t.expect_eq(decoded->entries[i].name, entries[i].name);+                    t.expect_eq(decoded->entries[i].kind, entries[i].kind);+                    t.expect_eq(std::memcmp(decoded->entries[i].target.data(),+                                            entries[i].target.data(), ID_LEN),+                                0);+                }+            }+        }+        expect_all_prefixes_rejected(t, *body, [](Bytes bytes) { return decode_tree(bytes); });+        exercise_mutations(*body, [](Bytes bytes) { return decode_tree(bytes); });+    }++    const std::vector<TreeEntry> unsorted = {+        TreeEntry{"b.txt", KIND_FILE, first},+        TreeEntry{"a.txt", KIND_FILE, second},+    };+    const auto rejected = encode_tree(unsorted);+    t.expect(!rejected.has_value());+    if (!rejected)+        t.expect(rejected.error().kind == ErrorKind::Unsorted);++    const std::vector<TreeEntry> duplicate = {+        TreeEntry{"a.txt", KIND_FILE, first},+        TreeEntry{"a.txt", KIND_FILE, second},+    };+    t.expect(!encode_tree(duplicate).has_value());+    t.expect(!encode_tree({TreeEntry{"a/b", KIND_FILE, first}}).has_value());+    t.expect(!encode_tree({TreeEntry{".veins", KIND_FILE, first}}).has_value());+    t.expect(!encode_tree({TreeEntry{"", KIND_FILE, first}}).has_value());+    t.expect(!encode_tree({TreeEntry{"a", static_cast<std::uint8_t>(200), first}}).has_value());++    ByteWriter huge_count;+    huge_count.varint(1'000'000);+    t.expect(!decode_tree(huge_count.view()).has_value());+}++void test_commit_roundtrip(test::Context& t) {+    const Commit commit = make_commit();+    const auto body = encode_commit(commit);+    const auto decoded = decode_commit(bytes_of(body));+    t.expect(decoded.has_value());+    if (!decoded)+        return;+    t.expect_eq(decoded->version, commit.version);+    t.expect_eq(decoded->parents.size(), commit.parents.size());+    t.expect_eq(decoded->message, commit.message);+    t.expect_eq(decoded->author.name, commit.author.name);+    t.expect_eq(decoded->author.email, commit.author.email);+    t.expect_eq(decoded->author.seconds, commit.author.seconds);+    t.expect_eq(decoded->committer.tz_min, commit.committer.tz_min);+    t.expect_eq(decoded->renames.size(), 1u);+    t.expect_eq(decoded->extra.size(), 1u);+    t.expect_eq(std::memcmp(decoded->root_tree.data(), commit.root_tree.data(), ID_LEN), 0);++    expect_all_prefixes_rejected(t, body, [](Bytes bytes) { return decode_commit(bytes); });+    exercise_mutations(body, [](Bytes bytes) { return decode_commit(bytes); });++    auto wrong_version = body;+    wrong_version[0] = 2;+    const auto rejected = decode_commit(bytes_of(wrong_version));+    t.expect(!rejected.has_value());+    if (!rejected)+        t.expect(rejected.error().kind == ErrorKind::UnsupportedVersion);++    auto trailing = body;+    trailing.push_back(0);+    t.expect(!decode_commit(bytes_of(trailing)).has_value());++    Commit invalid_state = commit;+    invalid_state.renames_state = 2;+    t.expect(!decode_commit(bytes_of(encode_commit(invalid_state))).has_value());++    ByteWriter huge_parents;+    huge_parents.u8(1);+    huge_parents.varint(1'000'000);+    t.expect(!decode_commit(huge_parents.view()).has_value());+}++void test_conflict_roundtrip(test::Context& t) {+    const Conflict conflict = make_conflict();+    const auto body = encode_conflict(conflict);+    const auto decoded = decode_conflict(bytes_of(body));+    t.expect(decoded.has_value());+    if (decoded) {+        t.expect_eq(decoded->adds.size(), 2u);+        t.expect_eq(decoded->removes.size(), 1u);+        t.expect_eq(decoded->adds[0].kind, KIND_FILE);+    }+    expect_all_prefixes_rejected(t, body, [](Bytes bytes) { return decode_conflict(bytes); });+    exercise_mutations(body, [](Bytes bytes) { return decode_conflict(bytes); });++    Conflict invalid;+    invalid.adds = {+        ConflictValue{KIND_FILE, text_id("same")},+        ConflictValue{KIND_FILE, text_id("same")},+    };+    invalid.removes = {ConflictValue{KIND_FILE, text_id("other")}};+    t.expect(!decode_conflict(bytes_of(encode_conflict(invalid))).has_value());++    Conflict no_removes;+    no_removes.adds = {ConflictValue{KIND_FILE, text_id("only")}};+    t.expect(!decode_conflict(bytes_of(encode_conflict(no_removes))).has_value());++    Conflict too_many;+    for (int i = 0; i < 100; ++i)+        too_many.adds.push_back(ConflictValue{KIND_FILE, text_id("a" + std::to_string(i))});+    for (int i = 0; i < 99; ++i)+        too_many.removes.push_back(ConflictValue{KIND_FILE, text_id("r" + std::to_string(i))});+    t.expect(!decode_conflict(bytes_of(encode_conflict(too_many))).has_value());+}++void test_view_roundtrip(test::Context& t) {+    const View view = make_view();+    const auto body = encode_view(view);+    const auto decoded = decode_view(bytes_of(body));+    t.expect(decoded.has_value());+    if (!decoded)+        return;+    t.expect_eq(decoded->heads.size(), 2u);+    t.expect_eq(decoded->bookmarks.size(), 1u);+    t.expect_eq(decoded->bookmarks[0].name, "master");+    t.expect_eq(decoded->tags.size(), 1u);+    t.expect_eq(decoded->remote_refs.size(), 1u);+    t.expect_eq(decoded->working_copies.size(), 1u);++    expect_all_prefixes_rejected(t, body, [](Bytes bytes) { return decode_view(bytes); });+    exercise_mutations(body, [](Bytes bytes) { return decode_view(bytes); });++    View invalid = view;+    invalid.bookmarks[0].targets.adds.clear();+    t.expect(!decode_view(bytes_of(encode_view(invalid))).has_value());++    View duplicate_heads = view;+    duplicate_heads.heads.push_back(duplicate_heads.heads.front());+    t.expect(!decode_view(bytes_of(encode_view(duplicate_heads))).has_value());++    View empty_head_list;+    t.expect(decode_view(bytes_of(encode_view(empty_head_list))).has_value());++    ByteWriter huge_heads;+    huge_heads.varint(1'000'000);+    t.expect(!decode_view(huge_heads.view()).has_value());+}++void test_operation_roundtrip(test::Context& t) {+    const Operation op = make_operation();+    const auto body = encode_operation(op);+    const auto decoded = decode_operation(bytes_of(body));+    t.expect(decoded.has_value());+    if (!decoded)+        return;+    t.expect_eq(decoded->parents.size(), 2u);+    t.expect_eq(decoded->start.ms, op.start.ms);+    t.expect_eq(decoded->end.ms, op.end.ms);+    t.expect_eq(decoded->description, op.description);+    t.expect_eq(decoded->tags.size(), 1u);++    expect_all_prefixes_rejected(t, body, [](Bytes bytes) { return decode_operation(bytes); });+    exercise_mutations(body, [](Bytes bytes) { return decode_operation(bytes); });++    Operation empty_key = op;+    empty_key.tags = {KeyValue{"", "value"}};+    t.expect(!decode_operation(bytes_of(encode_operation(empty_key))).has_value());++    ByteWriter huge_tags;+    huge_tags.varint(0);+    huge_tags.id(make_id(1));+    huge_tags.time_ms(Reader::TimeMs{0, 0});+    huge_tags.time_ms(Reader::TimeMs{0, 0});+    huge_tags.length_prefixed("host");+    huge_tags.length_prefixed("user");+    huge_tags.length_prefixed("description");+    huge_tags.varint(1'000'000);+    t.expect(!decode_operation(huge_tags.view()).has_value());+}++} // namespace++test::Suite object_suite() {+    return {"unit-object",+            {+                {"blob_roundtrip", test_blob_roundtrip},+                {"blob_invalid_values", test_blob_invalid_values},+                {"tree_roundtrip", test_tree_roundtrip},+                {"commit_roundtrip", test_commit_roundtrip},+                {"conflict_roundtrip", test_conflict_roundtrip},+                {"view_roundtrip", test_view_roundtrip},+                {"operation_roundtrip", test_operation_roundtrip},+            }};+}++} // namespace vn::unit--- /dev/null+++ b/xveins/tests/unit/protocol_tests.cpp@@ -0,0 +1,365 @@+#include "test_support.h"++#include "core/common.h"+#include "git/git_internal.h"+#include "protocol/protocol.h"+#include "protocol/wire.h"+#include "unit/unit_helpers.h"++#include <array>+#include <cstring>+#include <string>+#include <vector>++namespace vn::unit {+namespace {++template <typename Decode>+void expect_all_prefixes_rejected(test::Context& t, const std::vector<std::uint8_t>& body,+                                  Decode decode) {+    for (std::size_t length = 0; length < body.size(); ++length) {+        const auto result = decode(bytes_of(body).first(length));+        t.expect(!result.has_value());+    }+}++template <typename Decode>+void exercise_mutations(const std::vector<std::uint8_t>& body, Decode decode) {+    for (std::size_t i = 0; i < body.size(); ++i) {+        for (const std::uint8_t mask : {std::uint8_t{0x01}, std::uint8_t{0xff}}) {+            auto copy = body;+            copy[i] = static_cast<std::uint8_t>(copy[i] ^ mask);+            (void)decode(bytes_of(copy));+        }+    }+}++void test_protocol_roundtrips(test::Context& t) {+    proto::Hello hello;+    hello.min_version = 1;+    hello.max_version = 2;+    hello.capabilities = {"zstd", "auth"};+    hello.repo = "repo";+    hello.client_nonce = "nonce";+    auto hello_bytes = proto::encode_hello(hello);+    const auto decoded_hello = proto::decode_hello(bytes_of(hello_bytes));+    t.expect(decoded_hello.has_value());+    if (decoded_hello) {+        t.expect_eq(decoded_hello->max_version, 2);+        t.expect_eq(decoded_hello->capabilities.size(), 2u);+        t.expect_eq(decoded_hello->repo, "repo");+        t.expect_eq(decoded_hello->client_nonce, "nonce");+    }+    expect_all_prefixes_rejected(t, hello_bytes,+                                 [](Bytes bytes) { return proto::decode_hello(bytes); });+    exercise_mutations(hello_bytes, [](Bytes bytes) { return proto::decode_hello(bytes); });++    proto::HelloOk hello_ok;+    hello_ok.version = 1;+    hello_ok.capabilities = {"auth"};+    hello_ok.server_nonce = "server";+    hello_ok.auth_required = 1;+    auto hello_ok_bytes = proto::encode_hello_ok(hello_ok);+    const auto decoded_hello_ok = proto::decode_hello_ok(bytes_of(hello_ok_bytes));+    t.expect(decoded_hello_ok.has_value());+    if (decoded_hello_ok) {+        t.expect_eq(decoded_hello_ok->version, 1);+        t.expect_eq(decoded_hello_ok->capabilities.size(), 1u);+        t.expect_eq(decoded_hello_ok->auth_required, 1);+    }+    expect_all_prefixes_rejected(t, hello_ok_bytes,+                                 [](Bytes bytes) { return proto::decode_hello_ok(bytes); });+    exercise_mutations(hello_ok_bytes, [](Bytes bytes) { return proto::decode_hello_ok(bytes); });++    proto::Auth auth;+    auth.public_key = "key";+    auth.signature = "signature";+    auto auth_bytes = proto::encode_auth(auth);+    const auto decoded_auth = proto::decode_auth(bytes_of(auth_bytes));+    t.expect(decoded_auth.has_value());+    if (decoded_auth)+        t.expect_eq(decoded_auth->public_key, "key");+    expect_all_prefixes_rejected(t, auth_bytes,+                                 [](Bytes bytes) { return proto::decode_auth(bytes); });+    exercise_mutations(auth_bytes, [](Bytes bytes) { return proto::decode_auth(bytes); });++    proto::AuthOk auth_ok;+    auth_ok.role = 2;+    auth_ok.fingerprint = "fingerprint";+    auto auth_ok_bytes = proto::encode_auth_ok(auth_ok);+    const auto decoded_auth_ok = proto::decode_auth_ok(bytes_of(auth_ok_bytes));+    t.expect(decoded_auth_ok.has_value());+    if (decoded_auth_ok)+        t.expect_eq(decoded_auth_ok->role, 2);+    expect_all_prefixes_rejected(t, auth_ok_bytes,+                                 [](Bytes bytes) { return proto::decode_auth_ok(bytes); });+    exercise_mutations(auth_ok_bytes, [](Bytes bytes) { return proto::decode_auth_ok(bytes); });++    std::vector<proto::RefInfo> refs = {+        proto::RefInfo{"refs/heads/master", make_id(1), "change", 0},+        proto::RefInfo{"refs/tags/v1", make_id(2), "tag", 1},+    };+    auto refs_bytes = proto::encode_refs(refs);+    const auto decoded_refs = proto::decode_refs(bytes_of(refs_bytes));+    t.expect(decoded_refs.has_value());+    if (decoded_refs)+        t.expect_eq(decoded_refs->size(), 2u);+    expect_all_prefixes_rejected(t, refs_bytes,+                                 [](Bytes bytes) { return proto::decode_refs(bytes); });+    exercise_mutations(refs_bytes, [](Bytes bytes) { return proto::decode_refs(bytes); });++    const std::vector<Id> ids = {make_id(1), make_id(2)};+    auto ids_bytes = proto::encode_ids(ids);+    const auto decoded_ids = proto::decode_ids(bytes_of(ids_bytes), 10);+    t.expect(decoded_ids.has_value());+    if (decoded_ids)+        t.expect_eq(decoded_ids->size(), 2u);+    expect_all_prefixes_rejected(t, ids_bytes,+                                 [](Bytes bytes) { return proto::decode_ids(bytes, 10); });+    exercise_mutations(ids_bytes, [](Bytes bytes) { return proto::decode_ids(bytes, 10); });++    auto negotiate_bytes = proto::encode_negotiate({ids[0]}, {ids[1]});+    const auto decoded_negotiate = proto::decode_negotiate(bytes_of(negotiate_bytes));+    t.expect(decoded_negotiate.has_value());+    if (decoded_negotiate) {+        t.expect_eq(decoded_negotiate->wants.size(), 1u);+        t.expect_eq(decoded_negotiate->haves.size(), 1u);+    }+    expect_all_prefixes_rejected(t, negotiate_bytes,+                                 [](Bytes bytes) { return proto::decode_negotiate(bytes); });+    exercise_mutations(negotiate_bytes, [](Bytes bytes) { return proto::decode_negotiate(bytes); });++    auto negotiate_ok_bytes = proto::encode_negotiate_ok({1, 0, 1}, 1);+    const auto decoded_negotiate_ok = proto::decode_negotiate_ok(bytes_of(negotiate_ok_bytes));+    t.expect(decoded_negotiate_ok.has_value());+    if (decoded_negotiate_ok)+        t.expect_eq(decoded_negotiate_ok->size(), 3u);+    expect_all_prefixes_rejected(t, negotiate_ok_bytes, [](Bytes bytes) {+        return proto::decode_negotiate_ok(bytes);+    });+    exercise_mutations(negotiate_ok_bytes, [](Bytes bytes) {+        return proto::decode_negotiate_ok(bytes);+    });++    auto bitmap_bytes = proto::encode_bitmap({1, 0, 1, 1});+    const auto decoded_bitmap = proto::decode_bitmap(bytes_of(bitmap_bytes));+    t.expect(decoded_bitmap.has_value());+    if (decoded_bitmap)+        t.expect_eq(decoded_bitmap->size(), 4u);+    expect_all_prefixes_rejected(t, bitmap_bytes,+                                 [](Bytes bytes) { return proto::decode_bitmap(bytes); });+    exercise_mutations(bitmap_bytes, [](Bytes bytes) { return proto::decode_bitmap(bytes); });++    std::vector<proto::UpdateRef> updates = {+        proto::UpdateRef{"refs/heads/master", std::nullopt, ids[0]},+        proto::UpdateRef{"refs/tags/v1", ids[1], std::nullopt},+    };+    auto updates_bytes = proto::encode_update_refs(updates);+    const auto decoded_updates = proto::decode_update_refs(bytes_of(updates_bytes));+    t.expect(decoded_updates.has_value());+    if (decoded_updates)+        t.expect_eq(decoded_updates->size(), 2u);+    expect_all_prefixes_rejected(t, updates_bytes,+                                 [](Bytes bytes) { return proto::decode_update_refs(bytes); });+    exercise_mutations(updates_bytes,+                       [](Bytes bytes) { return proto::decode_update_refs(bytes); });++    t.expect_eq(proto::role_name(2), "write");+    t.expect_eq(proto::role_name(1), "read");+    t.expect_eq(proto::role_name(0), "anonymous");+    const std::string message = proto::auth_message(1, "repo", bytes_of("server"),+                                                    bytes_of("client"), bytes_of("binding"));+    t.expect(!message.empty());+}++void test_protocol_limits(test::Context& t) {+    ByteWriter huge_ids;+    huge_ids.varint(1'000'000);+    t.expect(!proto::decode_ids(huge_ids.view(), 1'000'000).has_value());+    t.expect(!proto::decode_negotiate(huge_ids.view()).has_value());+    t.expect(!proto::decode_refs(huge_ids.view()).has_value());+    t.expect(!proto::decode_bitmap(huge_ids.view()).has_value());+    t.expect(!proto::decode_update_refs(huge_ids.view()).has_value());++    ByteWriter invalid_control;+    invalid_control.varint(0);+    t.expect(proto::decode_ids(invalid_control.view(), 1).has_value());+}++void test_wire_records(test::Context& t) {+    const Id id = make_id(3);+    const std::string body = "record body";+    const auto encoded = wire::make_record(id, TYPE_BLOB, bytes_of(body));+    const auto record = wire::parse_record(bytes_of(encoded));+    t.expect(record.has_value());+    if (record) {+        t.expect_eq(std::memcmp(record->id.data(), id.data(), ID_LEN), 0);+        t.expect_eq(record->kind, TYPE_BLOB);+        t.expect_eq(to_string(bytes_of(record->body)), body);+    }+    expect_all_prefixes_rejected(t, encoded,+                                 [](Bytes bytes) { return wire::parse_record(bytes); });+    exercise_mutations(encoded, [](Bytes bytes) { return wire::parse_record(bytes); });++    ByteWriter claimed_huge;+    claimed_huge.raw(Bytes(id.data(), id.size()));+    claimed_huge.u8(TYPE_BLOB);+    claimed_huge.u8(0);+    claimed_huge.varint(64u * 1024u * 1024u);+    claimed_huge.varint(0);+    t.expect(!wire::parse_record(claimed_huge.view()).has_value());++    t.expect_eq(wire::read_error(Bytes{}), wire::ERR_INTERNAL);+    const std::uint8_t error_bytes[] = {wire::ERR_NOT_FOUND, 0};+    t.expect_eq(wire::read_error(Bytes(error_bytes, 1)), wire::ERR_NOT_FOUND);+    t.expect(wire::error_message(Bytes{}).empty());+    t.expect_eq(wire::error_code_name(wire::ERR_NOT_FOUND), "object not found");+    t.expect_eq(wire::error_code_name(250), "unknown server error");+}++void test_url_parsing(test::Context& t) {+    auto file = proto::parse_url("file:///tmp/repo");+    t.expect(file.has_value());+    if (file) {+        t.expect(!file->tls);+        t.expect(!file->ssh);+        t.expect_eq(file->path, "/tmp/repo");+    }+    auto ssh = proto::parse_url("ssh://git@example.com:2222/repo.git");+    t.expect(ssh.has_value());+    if (ssh) {+        t.expect(ssh->ssh);+        t.expect_eq(ssh->host, "example.com");+        t.expect_eq(ssh->port, 2222);+        t.expect_eq(ssh->path, "repo.git");+    }+    auto tls = proto::parse_url("veins://example.com/repo");+    t.expect(tls.has_value());+    if (tls) {+        t.expect(tls->tls);+        t.expect_eq(tls->host, "example.com");+        t.expect_eq(tls->port, 7419);+        t.expect_eq(tls->path, "repo");+    }+    auto port = proto::parse_url("veins://example.com:1/repo");+    t.expect(port.has_value());+    if (port)+        t.expect_eq(port->port, 1);+    t.expect(!proto::parse_url("").has_value());+    t.expect(!proto::parse_url("http://example.com/repo").has_value());+    t.expect(!proto::parse_url("veins://example.com").has_value());+    t.expect(!proto::parse_url("ssh://example.com").has_value());+    t.expect_eq(proto::url_repo_name("veins://example.com/repo"), "repo");+    t.expect(proto::url_repo_name("file:///tmp/repo").empty());+    t.expect(proto::url_repo_name("not a url").empty());+}++void test_git_parsers(test::Context& t) {+    const auto hello_oid = git::object_hash(git::KIND_BLOB, bytes_of("hello"));+    t.expect(hello_oid.has_value());+    if (hello_oid)+        t.expect_eq(git::oid_hex(*hello_oid), "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0");+    t.expect(!git::object_hash(99, bytes_of("x")).has_value());+    t.expect(git::oid_from_hex(std::string(40, '0')).has_value());+    t.expect(!git::oid_from_hex("xyz").has_value());++    const auto sig = git::parse_sig("Name <mail@example.com> 1234567890 +0530");+    t.expect(sig.has_value());+    if (sig) {+        t.expect_eq(sig->name, "Name");+        t.expect_eq(sig->email, "mail@example.com");+        t.expect_eq(sig->seconds, 1234567890);+        t.expect_eq(sig->tz_min, 330);+    }+    const auto negative = git::parse_sig("Name <mail@example.com> -12 -0130");+    t.expect(negative.has_value());+    if (negative)+        t.expect_eq(negative->tz_min, -90);+    t.expect(!git::parse_sig("Name <mail@example.com> 1 +000").has_value());+    t.expect(!git::parse_sig("Name <mail@example.com> nope +0000").has_value());+    t.expect(!git::parse_sig("Name mail@example.com 1 +0000").has_value());+    t.expect(!git::parse_sig("Name <mail@example.com> 999999999999999999999999 +0000")+                 .has_value());++    git::ParsedCommit commit;+    const auto tree_oid = git::oid_from_hex(std::string(40, '1'));+    const auto parent_oid = git::oid_from_hex(std::string(40, '2'));+    t.expect(tree_oid.has_value() && parent_oid.has_value());+    if (!tree_oid || !parent_oid)+        return;+    commit.tree = *tree_oid;+    commit.parents = {*parent_oid};+    commit.author = Sig{"Author", "author@example.com", 1, 0};+    commit.committer = Sig{"Committer", "committer@example.com", 2, -60};+    commit.message = "message\n";+    commit.extras = {KeyValue{"encoding", "UTF-8"}};+    const auto commit_body = git::serialize_commit(commit);+    const auto parsed_commit = git::parse_commit(bytes_of(commit_body));+    t.expect(parsed_commit.has_value());+    if (parsed_commit) {+        t.expect_eq(parsed_commit->parents.size(), 1u);+        t.expect_eq(parsed_commit->message, commit.message);+        t.expect_eq(parsed_commit->extras.size(), 1u);+        t.expect(parsed_commit->canonical);+    }+    for (std::size_t length = 0; length < commit_body.size(); ++length)+        (void)git::parse_commit(bytes_of(commit_body).first(length));+    exercise_mutations(commit_body,+                       [](Bytes bytes) { return git::parse_commit(bytes); });++    std::vector<std::uint8_t> tree_body;+    const std::string mode = "100644";+    tree_body.insert(tree_body.end(), mode.begin(), mode.end());+    tree_body.push_back(' ');+    const std::string name = "a.txt";+    tree_body.insert(tree_body.end(), name.begin(), name.end());+    tree_body.push_back(0);+    const auto blob_oid = git::oid_from_hex(std::string(40, '3'));+    t.expect(blob_oid.has_value());+    if (blob_oid)+        tree_body.insert(tree_body.end(), blob_oid->begin(), blob_oid->end());+    const auto parsed_tree = git::parse_tree(bytes_of(tree_body));+    t.expect(parsed_tree.has_value());+    if (parsed_tree) {+        t.expect_eq(parsed_tree->entries.size(), 1u);+        t.expect(parsed_tree->canonical);+    }+    for (std::size_t length = 0; length < tree_body.size(); ++length)+        (void)git::parse_tree(bytes_of(tree_body).first(length));+    exercise_mutations(tree_body, [](Bytes bytes) { return git::parse_tree(bytes); });++    const std::string tag_text = "object " + git::oid_hex(*tree_oid) ++                                 "\ntype commit\n\nmessage\n";+    const auto parsed_tag = git::parse_tag(bytes_of(tag_text));+    t.expect(parsed_tag.has_value());+    if (parsed_tag) {+        t.expect_eq(git::oid_hex(parsed_tag->target), git::oid_hex(*tree_oid));+        t.expect_eq(parsed_tag->target_kind, git::KIND_COMMIT);+    }+    exercise_mutations(bytes_from(tag_text), [](Bytes bytes) { return git::parse_tag(bytes); });++    t.expect_eq(git::mode_for_kind(KIND_FILE), "100644");+    t.expect_eq(git::mode_for_kind(KIND_EXECUTABLE), "100755");+    t.expect_eq(git::mode_for_kind(KIND_SYMLINK), "120000");+    t.expect_eq(git::mode_for_kind(KIND_SUBTREE), "40000");+    t.expect_eq(git::mode_for_kind(KIND_SUBMODULE), "160000");+    t.expect_eq(git::mode_kind("100755"), KIND_EXECUTABLE);+    t.expect_eq(git::mode_kind("40000"), KIND_SUBTREE);+    t.expect_eq(git::mode_kind("040000"), KIND_SUBTREE);+    t.expect_eq(git::mode_kind("nonsense"), KIND_FILE);+}++} // namespace++test::Suite protocol_suite() {+    return {"unit-protocol",+            {+                {"protocol_roundtrips", test_protocol_roundtrips},+                {"protocol_limits", test_protocol_limits},+                {"wire_records", test_wire_records},+                {"url_parsing", test_url_parsing},+                {"git_parsers", test_git_parsers},+            }};+}++} // namespace vn::unit--- /dev/null+++ b/xveins/tests/unit/store_tests.cpp@@ -0,0 +1,235 @@+#include "test_support.h"++#include "core/common.h"+#include "object/object.h"+#include "store/store.h"+#include "unit/unit_helpers.h"++#include <algorithm>+#include <cstring>+#include <string>+#include <vector>++namespace vn::unit {+namespace {++std::vector<RawObject> sample_objects() {+    std::vector<RawObject> objects;+    const auto tree_body = encode_tree({TreeEntry{"a.txt", KIND_FILE, text_id("a")}});+    if (tree_body)+        objects.push_back(+            RawObject{TYPE_TREE, *tree_body, object_id(TYPE_TREE, bytes_of(*tree_body))});++    const std::string blob = "packed blob data";+    objects.push_back(RawObject{TYPE_BLOB, bytes_from(blob), text_id(blob)});++    const std::string large(200'000, 'q');+    const BlobBuild build = build_blob(bytes_of(large));+    for (const auto& object : build.objects) {+        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));+        objects.push_back(RawObject{object.type, object.body, id});+    }+    return objects;+}++void test_pack_roundtrip(test::Context& t) {+    const auto objects = sample_objects();+    const PackOutput output = encode_pack(objects);+    t.expect_eq(output.count, objects.size());+    const auto pack = decode_pack(output.pack);+    t.expect(pack.has_value());+    const auto index =+        decode_index(output.index, pack ? std::optional(pack->trailer) : std::nullopt);+    t.expect(index.has_value());+    if (!pack || !index)+        return;+    t.expect_eq(pack->records.size(), objects.size());+    t.expect_eq(index->ids.size(), objects.size());+    for (std::size_t i = 0; i < pack->records.size(); ++i) {+        const auto data = pack->get(i);+        t.expect(data.has_value());+        if (data)+            t.expect_eq(data->size(), pack->records[i].raw_len);+        t.expect(index->find(pack->records[i].id).has_value());+    }+    t.expect(!decode_index(output.index, std::array<std::uint8_t, 32>{}).has_value());+}++void test_pack_corruption(test::Context& t) {+    (void)t;+    const PackOutput output = encode_pack(sample_objects());+    const std::size_t body_size = output.pack.size() - 32;++    for (std::size_t length = 0; length <= body_size; ++length) {+        auto copy = output.pack;+        copy.resize(length);+        fix_blake3_trailer(copy);+        if (auto decoded = decode_pack(copy)) {+            for (std::size_t i = 0; i < decoded->records.size(); ++i)+                (void)decoded->get(i);+        }+    }++    for (std::size_t i = 0; i < body_size; ++i) {+        for (const std::uint8_t mask : {std::uint8_t{0x01}, std::uint8_t{0xff}}) {+            auto copy = output.pack;+            copy[i] = static_cast<std::uint8_t>(copy[i] ^ mask);+            fix_blake3_trailer(copy);+            if (auto decoded = decode_pack(copy)) {+                for (std::size_t record = 0; record < decoded->records.size(); ++record)+                    (void)decoded->get(record);+            }+        }+    }++    std::vector<std::uint8_t> garbage(200);+    for (std::size_t i = 0; i < garbage.size(); ++i)+        garbage[i] = static_cast<std::uint8_t>(i * 37);+    fix_blake3_trailer(garbage);+    (void)decode_pack(garbage);+}++void test_index_corruption(test::Context& t) {+    const PackOutput output = encode_pack(sample_objects());+    const auto pack = decode_pack(output.pack);+    t.expect(pack.has_value());+    if (!pack)+        return;++    std::vector<RecordMeta> records;+    for (const auto& record : pack->records)+        records.push_back(RecordMeta{record.id, record.record_off, record.type, record.raw_len});+    std::sort(records.begin(), records.end(), [](const RecordMeta& a, const RecordMeta& b) {+        return std::memcmp(a.id.data(), b.id.data(), ID_LEN) < 0;+    });+    const auto index_bytes = encode_index(records, pack->trailer);+    t.expect(decode_index(index_bytes).has_value());++    const std::size_t body_size = index_bytes.size() - 32;+    for (std::size_t length = 0; length <= body_size; ++length) {+        auto copy = index_bytes;+        copy.resize(length);+        fix_blake3_trailer(copy);+        if (auto decoded = decode_index(copy)) {+            for (const auto& id : decoded->ids)+                (void)decoded->find(id);+        }+    }++    for (std::size_t i = 0; i < body_size; ++i) {+        auto copy = index_bytes;+        copy[i] = static_cast<std::uint8_t>(copy[i] ^ 0xff);+        fix_blake3_trailer(copy);+        if (auto decoded = decode_index(copy)) {+            for (const auto& id : decoded->ids)+                (void)decoded->find(id);+        }+    }+}++void test_order_log_nodes(test::Context& t) {+    t.expect(order_log_nodes({}).empty());++    const LogOrderNode a{make_id(1), 100, {}};+    const LogOrderNode b{make_id(2), 100, {a.id}};+    auto order = order_log_nodes({a, b});+    t.expect_eq(order.size(), 2u);+    if (order.size() == 2) {+        t.expect_eq(order[0], 1u);+        t.expect_eq(order[1], 0u);+    }++    const LogOrderNode c{make_id(3), 100, {b.id}};+    order = order_log_nodes({a, b, c});+    t.expect_eq(order.size(), 3u);+    if (order.size() == 3) {+        t.expect_eq(order[0], 2u);+        t.expect_eq(order[1], 1u);+        t.expect_eq(order[2], 0u);+    }++    const LogOrderNode older_child{make_id(4), 1, {a.id}};+    order = order_log_nodes({a, older_child});+    t.expect_eq(order.size(), 2u);+    if (order.size() == 2) {+        t.expect_eq(order[0], 1u);+        t.expect_eq(order[1], 0u);+    }++    const LogOrderNode newer{make_id(5), 200, {}};+    const LogOrderNode middle{make_id(6), 150, {}};+    order = order_log_nodes({a, newer, middle});+    t.expect_eq(order.size(), 3u);+    if (order.size() == 3) {+        t.expect_eq(order[0], 1u);+        t.expect_eq(order[1], 2u);+        t.expect_eq(order[2], 0u);+    }++    const LogOrderNode merge{make_id(7), 100, {a.id, newer.id}};+    order = order_log_nodes({a, newer, merge});+    t.expect_eq(order.size(), 3u);+    if (order.size() == 3)+        t.expect_eq(order[0], 2u);++    const LogOrderNode orphan{make_id(8), 50, {make_id(99)}};+    order = order_log_nodes({orphan});+    t.expect_eq(order.size(), 1u);++    const LogOrderNode cycle_a{make_id(9), 10, {make_id(10)}};+    const LogOrderNode cycle_b{make_id(10), 10, {make_id(9)}};+    order = order_log_nodes({cycle_a, cycle_b});+    t.expect_eq(order.size(), 2u);+}++void test_repository_roundtrip(test::Context& t) {+    const TempDir temp;+    const fs::path repo = temp.path / "repo";+    const auto initialized = init_repo(repo);+    t.expect(initialized.has_value());+    if (!initialized)+        return;+    t.expect(path_is_file(repo / ".veins" / "format"));+    t.expect(discover_repo(repo).has_value());++    fs::create_directories(repo / "nested");+    t.expect(discover_repo(repo / "nested").has_value());+    t.expect(!discover_repo(temp.path).has_value());++    Store store = Store::open_all(repo);+    t.expect(!current_view(repo, store).has_value());+    t.expect(!store.read_body(make_id(1), TYPE_COMMIT).has_value());+    t.expect_eq(read_heads(repo).size(), 0u);++    auto tx = Txn::begin(repo, store);+    t.expect(tx.has_value());+    if (!tx)+        return;+    t.expect(tx->view().heads.empty());+    const auto status = tx->finish("unit transaction");+    t.expect(status.has_value());+    if (!status)+        return;++    Store refreshed = Store::open_all(repo);+    t.expect_eq(read_heads(repo).size(), 1u);+    const auto view = current_view(repo, refreshed);+    t.expect(view.has_value());+    if (view)+        t.expect(view->heads.empty());+}++} // namespace++test::Suite store_suite() {+    return {"unit-store",+            {+                {"pack_roundtrip", test_pack_roundtrip},+                {"pack_corruption", test_pack_corruption},+                {"index_corruption", test_index_corruption},+                {"order_log_nodes", test_order_log_nodes},+                {"repository_roundtrip", test_repository_roundtrip},+            }};+}++} // namespace vn::unit--- /dev/null+++ b/xveins/tests/unit/suites.h@@ -0,0 +1,13 @@+#pragma once++#include "test_support.h"++namespace vn::unit {++test::Suite core_suite();+test::Suite object_suite();+test::Suite store_suite();+test::Suite worktree_suite();+test::Suite protocol_suite();++} // namespace vn::unit--- /dev/null+++ b/xveins/tests/unit/unit_helpers.h@@ -0,0 +1,52 @@+#pragma once++#include "test_support.h"++#include "core/common.h"+#include "object/object.h"++#include <cstdint>+#include <string>+#include <string_view>+#include <vector>++namespace vn::unit {++inline Id make_id(std::uint8_t seed) {+    Id id{};+    for (std::size_t i = 0; i < id.size(); ++i)+        id[i] = static_cast<std::uint8_t>(seed + i);+    return id;+}++inline Id text_id(std::string_view text) {+    return object_id(TYPE_BLOB, bytes_of(text));+}++inline std::vector<std::uint8_t> bytes_from(std::string_view text) {+    return std::vector<std::uint8_t>(text.begin(), text.end());+}++struct TempDir {+    fs::path path;++    TempDir() {+        path = fs::temp_directory_path() / ("vn-unit-" + std::to_string(random_u64()));+        fs::create_directories(path);+    }++    ~TempDir() {+        std::error_code ec;+        fs::remove_all(path, ec);+    }+};++inline void fix_blake3_trailer(std::vector<std::uint8_t>& data) {+    if (data.size() < 33)+        return;+    data.resize(data.size() - 32);+    const auto digest = blake3_hash(bytes_of(data));+    data.insert(data.end(), digest.begin(), digest.end());+}++} // namespace vn::unit--- /dev/null+++ b/xveins/tests/unit/worktree_tests.cpp@@ -0,0 +1,218 @@+#include "test_support.h"++#include "core/common.h"+#include "unit/unit_helpers.h"+#include "worktree/attributes.h"+#include "worktree/pathspec.h"++#include <string>+#include <vector>++namespace vn::unit {+namespace {++void test_pathspecs(test::Context& t) {+    t.expect(pathspec_has_glob("src/*.cpp"));+    t.expect(pathspec_has_glob("a?.txt"));+    t.expect(!pathspec_has_glob("src/file.cpp"));++    const fs::path root = "/tmp/vn-pathspec/repo";+    const auto relative = pathspec_normalize(root, "sub", "./a/../b.txt");+    t.expect(relative.has_value());+    if (relative)+        t.expect_eq(*relative, "sub/b.txt");++    t.expect(!pathspec_normalize(root, "", "../outside").has_value());+    t.expect(!pathspec_normalize(root, "", "").has_value());+    const auto absolute = pathspec_normalize(root, "", "/tmp/vn-pathspec/repo/a/./b");+    t.expect(absolute.has_value());+    if (absolute)+        t.expect_eq(*absolute, "a/b");+    t.expect(!pathspec_normalize(root, "", "/tmp/vn-pathspec/other/a").has_value());+    t.expect(!pathspec_normalize(root, "", "/tmp/vn-pathspec/repo").has_value());++    const auto collapsed = pathspec_normalize(root, "", "a//b///c");+    t.expect(collapsed.has_value());+    if (collapsed)+        t.expect_eq(*collapsed, "a/b/c");++    const auto trailing = pathspec_normalize(root, "", "a/b/");+    t.expect(trailing.has_value());+    if (trailing)+        t.expect_eq(*trailing, "a/b");++    t.expect(!pathspec_normalize(root, "a", "../../b").has_value());+    const auto up = pathspec_normalize(root, "a/b", "../c");+    t.expect(up.has_value());+    if (up)+        t.expect_eq(*up, "a/c");+}++void test_ignore_rules(test::Context& t) {+    t.expect_eq(glob_match("*.tmp", "file.tmp"), true);+    t.expect_eq(glob_match("*.tmp", "file.txt"), false);+    t.expect_eq(glob_match("a?c", "abc"), true);+    t.expect_eq(glob_match("a?c", "a/c"), false);+    t.expect_eq(glob_match("src/**/x", "src/a/b/x"), true);+    t.expect_eq(glob_match("*", "a/b"), false);+    t.expect_eq(glob_match("**/Testing/Temporary/*", "xveins/tests/Testing/Temporary/CTest.log"),+                true);+    t.expect_eq(glob_match("*/Testing/Temporary/*", "xveins/tests/Testing/Temporary/CTest.log"),+                false);+    t.expect_eq(glob_match("", ""), true);+    t.expect_eq(glob_match("", "x"), false);+    t.expect_eq(glob_match("abc", "abc"), true);+    t.expect_eq(glob_match("abc", "abcd"), false);++    const TempDir temp;+    t.expect(+        write_file(temp.path / ".vnexclude", bytes_of("*.tmp\nbuild/\n**/Testing/Temporary/*\n")));+    t.expect(ignore_path_ignored(temp.path, "note.tmp"));+    t.expect(ignore_path_ignored(temp.path, "build/out.bin"));+    t.expect(ignore_path_ignored(temp.path, "xveins/tests/Testing/Temporary/CTest.log"));+    t.expect(!ignore_path_ignored(temp.path, "note.txt"));++    IgnoreRules rules = ignore_empty();+    rules.items.push_back(IgnoreRule{"*.log", false, false, false, false, ""});+    rules.items.push_back(IgnoreRule{"keep.log", true, false, false, false, ""});+    t.expect(ignore_ignored(rules, "debug.log", false));+    t.expect(!ignore_ignored(rules, "keep.log", false));++    t.expect(valid_name("file.txt"));+    t.expect(!valid_name("dir/file"));+    t.expect(!valid_name(".veins"));+    t.expect(!valid_name(".."));+    t.expect(!valid_name(""));+    t.expect(!valid_name(std::string(1, '\0')));+    t.expect(valid_path("a/b/c"));+    t.expect(!valid_path("/a"));+    t.expect(!valid_path("a//b"));+    t.expect(!valid_path("a/../b"));+    t.expect(!valid_path(""));+}++void test_glob_hostile_patterns(test::Context& t) {+    // Regression: the recursive matcher exhausted the stack on these inputs.+    std::string pattern;+    pattern.reserve(40'000);+    for (int i = 0; i < 20'000; ++i)+        pattern += "a*";+    const std::string text(50'000, 'a');+    (void)glob_match(pattern, text);++    const std::string stars(100'000, '*');+    const std::string letters(100'000, 'a');+    t.expect_eq(glob_match(stars, letters), true);++    const std::string double_stars = "**/" + std::string(50'000, '*');+    (void)glob_match(double_stars, letters);++    const std::string long_literal(60'000, 'z');+    t.expect_eq(glob_match(long_literal, long_literal), true);+    t.expect_eq(glob_match(long_literal, long_literal + "x"), false);++    IgnoreRules rules = ignore_empty();+    rules.items.push_back(IgnoreRule{stars, false, false, false, false, ""});+    (void)ignore_ignored(rules, "some/deep/path.txt", false);+}++void test_attributes(test::Context& t) {+    const TempDir temp;+    const std::string rules_text = "*.c txt eol:lf\n"+                                   "*.cmd txt eol:crlf\n"+                                   "*.ssa gen\n"+                                   "**/generated/* gen\n"+                                   "*.bin gen bin\n"+                                   "special.bin -gen\n";+    t.expect(write_file(temp.path / ".vnattribs", bytes_of(rules_text)));+    const AttributeRules rules = AttributeRules::load(temp.path);++    const auto source = rules.lookup("src/main.c");+    t.expect(source.text == AttributeText::Text);+    t.expect(source.eol == AttributeEol::Lf);+    t.expect(!source.generated);++    const auto script = rules.lookup("scripts/build.cmd");+    t.expect(script.text == AttributeText::Text);+    t.expect(script.eol == AttributeEol::Crlf);++    t.expect(rules.lookup("build/out.ssa").generated);+    t.expect(rules.lookup("pkg/generated/table.h").generated);++    const auto binary = rules.lookup("assets/blob.bin");+    t.expect(binary.generated);+    t.expect(binary.text == AttributeText::Binary);++    const auto overridden = rules.lookup("special.bin");+    t.expect(!overridden.generated);+    t.expect(overridden.text == AttributeText::Binary);++    const auto plain = rules.lookup("notes.txt");+    t.expect(plain.text == AttributeText::Auto);+    t.expect(plain.eol == AttributeEol::None);+    t.expect(!plain.generated);++    const auto lf = normalize_eol(bytes_of("a\r\nb\rc\nd"), AttributeEol::Lf);+    t.expect_eq(to_string(bytes_of(lf)), "a\nb\nc\nd");+    const auto crlf = normalize_eol(bytes_of("a\nb\rc\r\n"), AttributeEol::Crlf);+    t.expect_eq(to_string(bytes_of(crlf)), "a\r\nb\r\nc\r\n");+    const auto cr = normalize_eol(bytes_of("a\nb\r\nc\r"), AttributeEol::Cr);+    t.expect_eq(to_string(bytes_of(cr)), "a\rb\rc\r");+    const auto untouched = normalize_eol(bytes_of("a\r\nb"), AttributeEol::None);+    t.expect_eq(to_string(bytes_of(untouched)), "a\r\nb");+    t.expect(normalize_eol(Bytes{}, AttributeEol::Lf).empty());+}++void test_attributes_edges(test::Context& t) {+    const TempDir temp;+    const std::string rules_text = "# leading comment\r\n"+                                   "\r\n"+                                   "*.c gen\r\n"+                                   "*.c -gen\r\n"+                                   "*.h txt\r\n"+                                   "*.h -bin\r\n"+                                   "*.log eol:crlf\r\n"+                                   "*.log -eol\r\n"+                                   "*.mac eol:cr\r\n"+                                   "src/*.c gen\r\n"+                                   "*.dat unknown-token bin\r\n";+    t.expect(write_file(temp.path / ".vnattribs", bytes_of(rules_text)));+    const AttributeRules rules = AttributeRules::load(temp.path);++    t.expect(!rules.lookup("a.c").generated);+    t.expect(rules.lookup("deep/a.c").generated == false);+    t.expect(rules.lookup("a.h").text == AttributeText::Auto);+    t.expect(rules.lookup("a.log").eol == AttributeEol::None);+    t.expect(rules.lookup("a.mac").eol == AttributeEol::Cr);+    t.expect(rules.lookup("src/main.c").generated);+    t.expect(!rules.lookup("nested/src/main.c").generated);+    t.expect(rules.lookup("assets/blob.dat").text == AttributeText::Binary);++    const TempDir empty;+    const AttributeRules none = AttributeRules::load(empty.path);+    const auto plain = none.lookup("anything");+    t.expect(!plain.generated);+    t.expect(plain.text == AttributeText::Auto);+    t.expect(plain.eol == AttributeEol::None);++    const TempDir malformed;+    t.expect(write_file(malformed.path / ".vnattribs",+                        bytes_of(std::string("   \n# comment\n\n\t\n*\n"))));+    const AttributeRules malformed_rules = AttributeRules::load(malformed.path);+    (void)malformed_rules.lookup("file");+}++} // namespace++test::Suite worktree_suite() {+    return {"unit-worktree",+            {+                {"pathspecs", test_pathspecs},+                {"ignore_rules", test_ignore_rules},+                {"glob_hostile_patterns", test_glob_hostile_patterns},+                {"attributes", test_attributes},+                {"attributes_edges", test_attributes_edges},+            }};+}++} // namespace vn::unit--- a/xveins/tests/unit_tests.cpp+++ /dev/null@@ -1,568 +0,0 @@-#include "test_support.h"--#include "core/common.h"-#include "object/object.h"-#include "store/store.h"-#include "worktree/attributes.h"-#include "worktree/pathspec.h"--#include <algorithm>-#include <cstring>-#include <iostream>-#include <string>-#include <vector>--using namespace vn;--namespace {--Id make_id(std::uint8_t seed) {-    Id id{};-    for (std::size_t i = 0; i < id.size(); ++i)-        id[i] = static_cast<std::uint8_t>(seed + i);-    return id;-}--Id text_id(std::string_view text) {-    return object_id(TYPE_BLOB, bytes_of(text));-}--std::vector<std::uint8_t> bytes_from(std::string_view text) {-    return std::vector<std::uint8_t>(text.begin(), text.end());-}--struct TempDir {-    fs::path path;--    TempDir() {-        path = fs::temp_directory_path() / ("vn-unit-" + std::to_string(random_u64()));-        fs::create_directories(path);-    }--    ~TempDir() {-        std::error_code ec;-        fs::remove_all(path, ec);-    }-};--void test_varint(test::Context& t) {-    const std::vector<std::uint64_t> values = {-        0, 1, 2, 127, 128, 255, 256, 300, 16384, 1'000'000, 0xffffffffull,-    };-    for (std::uint64_t value : values) {-        ByteWriter writer;-        writer.varint(value);-        Reader reader(writer.view());-        const auto decoded = reader.varint();-        t.expect(decoded.has_value());-        if (decoded)-            t.expect_eq(*decoded, value);-        t.expect(reader.finish().has_value());-    }--    const std::uint8_t non_minimal[] = {0x80, 0x00};-    Reader reader(Bytes(non_minimal, sizeof(non_minimal)));-    const auto decoded = reader.varint();-    t.expect(!decoded.has_value());-    if (!decoded)-        t.expect(decoded.error().kind == ErrorKind::NonMinimalVarint);--    const std::uint8_t truncated[] = {0x80};-    Reader truncated_reader(Bytes(truncated, sizeof(truncated)));-    t.expect(!truncated_reader.varint().has_value());-}--void test_identifiers(test::Context& t) {-    const std::string text = "hello";-    const Id id = text_id(text);-    const std::string hex = hex_encode(id);-    t.expect_eq(hex.size(), ID_LEN * 2);-    const auto parsed = parse_id(hex);-    t.expect(parsed.has_value());-    if (parsed)-        t.expect_eq(std::memcmp(parsed->data(), id.data(), ID_LEN), 0);-    t.expect(!parse_id("not-hex").has_value());--    ChangeId change{};-    for (std::size_t i = 0; i < change.size(); ++i)-        change[i] = static_cast<std::uint8_t>(i);-    const std::string encoded = base32_encode(change);-    t.expect(!encoded.empty());-    t.expect(base32_prefix_matches(encoded, encoded.substr(0, 4)));-    t.expect(!base32_prefix_matches(encoded, "!!!!"));--    const std::string empty_hash =-        "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";-    t.expect_eq(hex_encode(Bytes(blake3_hash(Bytes{}))), empty_hash);-    t.expect_eq(std::memcmp(object_id(TYPE_BLOB, bytes_of(text)).data(), id.data(), ID_LEN), 0);-    t.expect_ne(std::memcmp(object_id(TYPE_TREE, bytes_of(text)).data(), id.data(), ID_LEN), 0);-}--void test_blob_roundtrip(test::Context& t) {-    const std::string small = "small blob";-    const auto encoded = encode_inline_blob(bytes_of(small));-    t.expect(encoded.has_value());-    if (!encoded)-        return;-    const auto decoded = decode_blob(bytes_of(*encoded));-    t.expect(decoded.has_value());-    if (decoded) {-        t.expect(decoded->form == BlobForm::Inline);-        t.expect_eq(to_string(bytes_of(decoded->data)), small);-    }--    const std::string large(200'000, 'x');-    const BlobBuild build = build_blob(bytes_of(large));-    t.expect(!build.objects.empty());-    const auto root = decode_blob(bytes_of(build.objects.back().body));-    t.expect(root.has_value());-    if (root)-        t.expect(root->form != BlobForm::Inline);--    t.expect_eq(fastcdc_next(bytes_of(std::string(1024, 'a'))), 1024u);-    const std::size_t chunk = fastcdc_next(bytes_of(large));-    t.expect(chunk >= 16384);-    t.expect(chunk <= 262144);-}--void test_tree_roundtrip(test::Context& t) {-    const Id first = text_id("first");-    const Id second = text_id("second");-    const std::vector<TreeEntry> entries = {-        TreeEntry{"a.txt", KIND_FILE, first},-        TreeEntry{"b.txt", KIND_EXECUTABLE, second},-        TreeEntry{"dir", KIND_SUBTREE, first},-    };-    const auto body = encode_tree(entries);-    t.expect(body.has_value());-    if (body) {-        const auto decoded = decode_tree(bytes_of(*body));-        t.expect(decoded.has_value());-        if (decoded) {-            t.expect_eq(decoded->entries.size(), entries.size());-            if (decoded->entries.size() == entries.size()) {-                for (std::size_t i = 0; i < entries.size(); ++i) {-                    t.expect_eq(decoded->entries[i].name, entries[i].name);-                    t.expect_eq(decoded->entries[i].kind, entries[i].kind);-                    t.expect_eq(std::memcmp(decoded->entries[i].target.data(),-                                            entries[i].target.data(), ID_LEN),-                                0);-                }-            }-        }-    }--    const std::vector<TreeEntry> unsorted = {-        TreeEntry{"b.txt", KIND_FILE, first},-        TreeEntry{"a.txt", KIND_FILE, second},-    };-    const auto rejected = encode_tree(unsorted);-    t.expect(!rejected.has_value());-    if (!rejected)-        t.expect(rejected.error().kind == ErrorKind::Unsorted);--    const std::vector<TreeEntry> duplicate = {-        TreeEntry{"a.txt", KIND_FILE, first},-        TreeEntry{"a.txt", KIND_FILE, second},-    };-    t.expect(!encode_tree(duplicate).has_value());-    t.expect(!encode_tree({TreeEntry{"a/b", KIND_FILE, first}}).has_value());-    t.expect(!encode_tree({TreeEntry{".veins", KIND_FILE, first}}).has_value());-}--Commit make_commit() {-    Commit commit;-    commit.version = 1;-    commit.parents = {make_id(1)};-    commit.root_tree = make_id(2);-    for (std::size_t i = 0; i < commit.change_id.size(); ++i)-        commit.change_id[i] = static_cast<std::uint8_t>(i + 3);-    commit.author = Sig{"Author", "author@example.com", 1'700'000'000, 0};-    commit.committer = Sig{"Committer", "committer@example.com", 1'700'000'001, -120};-    commit.message = "commit message";-    commit.renames_state = RENAMES_RECORDED;-    commit.renames = {Rename{0, 1, "old.txt", "new.txt"}};-    commit.extra = {KeyValue{"encoding", "UTF-8"}};-    return commit;-}--void test_commit_roundtrip(test::Context& t) {-    const Commit commit = make_commit();-    const auto body = encode_commit(commit);-    const auto decoded = decode_commit(bytes_of(body));-    t.expect(decoded.has_value());-    if (!decoded)-        return;-    t.expect_eq(decoded->version, commit.version);-    t.expect_eq(decoded->parents.size(), commit.parents.size());-    t.expect_eq(decoded->message, commit.message);-    t.expect_eq(decoded->author.name, commit.author.name);-    t.expect_eq(decoded->author.email, commit.author.email);-    t.expect_eq(decoded->author.seconds, commit.author.seconds);-    t.expect_eq(decoded->committer.tz_min, commit.committer.tz_min);-    t.expect_eq(decoded->renames.size(), 1u);-    t.expect_eq(decoded->extra.size(), 1u);-    t.expect_eq(std::memcmp(decoded->root_tree.data(), commit.root_tree.data(), ID_LEN), 0);--    auto wrong_version = body;-    wrong_version[0] = 2;-    const auto rejected = decode_commit(bytes_of(wrong_version));-    t.expect(!rejected.has_value());-    if (!rejected)-        t.expect(rejected.error().kind == ErrorKind::UnsupportedVersion);--    auto trailing = body;-    trailing.push_back(0);-    t.expect(!decode_commit(bytes_of(trailing)).has_value());-}--void test_conflict_roundtrip(test::Context& t) {-    Conflict conflict;-    conflict.adds = {-        ConflictValue{KIND_FILE, text_id("one")},-        ConflictValue{KIND_FILE, text_id("two")},-    };-    conflict.removes = {ConflictValue{KIND_FILE, text_id("three")}};-    const auto body = encode_conflict(conflict);-    const auto decoded = decode_conflict(bytes_of(body));-    t.expect(decoded.has_value());-    if (decoded) {-        t.expect_eq(decoded->adds.size(), 2u);-        t.expect_eq(decoded->removes.size(), 1u);-        t.expect_eq(decoded->adds[0].kind, KIND_FILE);-    }--    Conflict invalid;-    invalid.adds = {-        ConflictValue{KIND_FILE, text_id("same")},-        ConflictValue{KIND_FILE, text_id("same")},-    };-    invalid.removes = {ConflictValue{KIND_FILE, text_id("other")}};-    t.expect(!decode_conflict(bytes_of(encode_conflict(invalid))).has_value());--    Conflict no_removes;-    no_removes.adds = {ConflictValue{KIND_FILE, text_id("only")}};-    t.expect(!decode_conflict(bytes_of(encode_conflict(no_removes))).has_value());-}--View make_view() {-    const Id a = make_id(10);-    const Id b = make_id(20);-    View view;-    view.heads = a < b ? std::vector<Id>{a, b} : std::vector<Id>{b, a};-    Bookmark bookmark;-    bookmark.name = "master";-    bookmark.targets.adds = {view.heads.front()};-    view.bookmarks = {bookmark};-    view.tags = {TagRef{"v1", view.heads.back()}};-    view.remote_refs = {RemoteRef{"origin", "master", view.heads.front()}};-    view.working_copies = {WorkspaceRef{"default", view.heads.back()}};-    return view;-}--void test_view_roundtrip(test::Context& t) {-    const View view = make_view();-    const auto decoded = decode_view(bytes_of(encode_view(view)));-    t.expect(decoded.has_value());-    if (!decoded)-        return;-    t.expect_eq(decoded->heads.size(), 2u);-    t.expect_eq(decoded->bookmarks.size(), 1u);-    t.expect_eq(decoded->bookmarks[0].name, "master");-    t.expect_eq(decoded->tags.size(), 1u);-    t.expect_eq(decoded->remote_refs.size(), 1u);-    t.expect_eq(decoded->working_copies.size(), 1u);--    View invalid = view;-    invalid.bookmarks[0].targets.adds.clear();-    t.expect(!decode_view(bytes_of(encode_view(invalid))).has_value());-}--void test_operation_roundtrip(test::Context& t) {-    Operation op;-    op.parents = {make_id(1), make_id(2)};-    op.view = make_id(3);-    op.start = Reader::TimeMs{1'700'000'000'123, 0};-    op.end = Reader::TimeMs{1'700'000'000'456, 0};-    op.hostname = "host";-    op.username = "user";-    op.description = "describe";-    op.tags = {KeyValue{"kind", "test"}};-    const auto decoded = decode_operation(bytes_of(encode_operation(op)));-    t.expect(decoded.has_value());-    if (!decoded)-        return;-    t.expect_eq(decoded->parents.size(), 2u);-    t.expect_eq(decoded->start.ms, op.start.ms);-    t.expect_eq(decoded->end.ms, op.end.ms);-    t.expect_eq(decoded->description, op.description);-    t.expect_eq(decoded->tags.size(), 1u);-}--void test_pack_roundtrip(test::Context& t) {-    const auto tree_body = encode_tree({TreeEntry{"a.txt", KIND_FILE, text_id("a")}});-    t.expect(tree_body.has_value());-    if (!tree_body)-        return;-    std::vector<RawObject> objects;-    objects.push_back(RawObject{TYPE_TREE, *tree_body, object_id(TYPE_TREE, bytes_of(*tree_body))});-    const std::string blob = "packed blob data";-    objects.push_back(RawObject{TYPE_BLOB, bytes_from(blob), text_id(blob)});--    const PackOutput output = encode_pack(objects);-    t.expect_eq(output.count, 2u);-    const auto pack = decode_pack(output.pack);-    t.expect(pack.has_value());-    const auto index =-        decode_index(output.index, pack ? std::optional(pack->trailer) : std::nullopt);-    t.expect(index.has_value());-    if (!pack || !index)-        return;-    t.expect_eq(pack->records.size(), 2u);-    t.expect_eq(index->ids.size(), 2u);-    for (std::size_t i = 0; i < pack->records.size(); ++i) {-        const auto data = pack->get(i);-        t.expect(data.has_value());-        if (data)-            t.expect_eq(data->size(), pack->records[i].raw_len);-        t.expect(index->find(pack->records[i].id).has_value());-    }-    t.expect(!decode_index(output.index, std::array<std::uint8_t, 32>{}).has_value());-}--void test_order_log_nodes(test::Context& t) {-    t.expect(order_log_nodes({}).empty());--    const LogOrderNode a{make_id(1), 100, {}};-    const LogOrderNode b{make_id(2), 100, {a.id}};-    auto order = order_log_nodes({a, b});-    t.expect_eq(order.size(), 2u);-    if (order.size() == 2) {-        t.expect_eq(order[0], 1u);-        t.expect_eq(order[1], 0u);-    }--    const LogOrderNode c{make_id(3), 100, {b.id}};-    order = order_log_nodes({a, b, c});-    t.expect_eq(order.size(), 3u);-    if (order.size() == 3) {-        t.expect_eq(order[0], 2u);-        t.expect_eq(order[1], 1u);-        t.expect_eq(order[2], 0u);-    }--    const LogOrderNode older_child{make_id(4), 1, {a.id}};-    order = order_log_nodes({a, older_child});-    t.expect_eq(order.size(), 2u);-    if (order.size() == 2) {-        t.expect_eq(order[0], 1u);-        t.expect_eq(order[1], 0u);-    }--    const LogOrderNode newer{make_id(5), 200, {}};-    const LogOrderNode middle{make_id(6), 150, {}};-    order = order_log_nodes({a, newer, middle});-    t.expect_eq(order.size(), 3u);-    if (order.size() == 3) {-        t.expect_eq(order[0], 1u);-        t.expect_eq(order[1], 2u);-        t.expect_eq(order[2], 0u);-    }--    const LogOrderNode merge{make_id(7), 100, {a.id, newer.id}};-    order = order_log_nodes({a, newer, merge});-    t.expect_eq(order.size(), 3u);-    if (order.size() == 3)-        t.expect_eq(order[0], 2u);--    const LogOrderNode orphan{make_id(8), 50, {make_id(99)}};-    order = order_log_nodes({orphan});-    t.expect_eq(order.size(), 1u);--    const LogOrderNode cycle_a{make_id(9), 10, {make_id(10)}};-    const LogOrderNode cycle_b{make_id(10), 10, {make_id(9)}};-    order = order_log_nodes({cycle_a, cycle_b});-    t.expect_eq(order.size(), 2u);-}--void test_pathspecs(test::Context& t) {-    t.expect(pathspec_has_glob("src/*.cpp"));-    t.expect(pathspec_has_glob("a?.txt"));-    t.expect(!pathspec_has_glob("src/file.cpp"));--    const fs::path root = "/tmp/vn-pathspec/repo";-    const auto relative = pathspec_normalize(root, "sub", "./a/../b.txt");-    t.expect(relative.has_value());-    if (relative)-        t.expect_eq(*relative, "sub/b.txt");--    t.expect(!pathspec_normalize(root, "", "../outside").has_value());-    const auto absolute = pathspec_normalize(root, "", "/tmp/vn-pathspec/repo/a/./b");-    t.expect(absolute.has_value());-    if (absolute)-        t.expect_eq(*absolute, "a/b");-    t.expect(!pathspec_normalize(root, "", "/tmp/vn-pathspec/other/a").has_value());-}--void test_ignore_rules(test::Context& t) {-    t.expect_eq(glob_match("*.tmp", "file.tmp"), true);-    t.expect_eq(glob_match("*.tmp", "file.txt"), false);-    t.expect_eq(glob_match("a?c", "abc"), true);-    t.expect_eq(glob_match("src/**/x", "src/a/b/x"), true);-    t.expect_eq(glob_match("*", "a/b"), false);-    t.expect_eq(glob_match("**/Testing/Temporary/*", "xveins/tests/Testing/Temporary/CTest.log"),-                true);-    t.expect_eq(glob_match("*/Testing/Temporary/*", "xveins/tests/Testing/Temporary/CTest.log"),-                false);--    const TempDir temp;-    t.expect(-        write_file(temp.path / ".vnexclude", bytes_of("*.tmp\nbuild/\n**/Testing/Temporary/*\n")));-    t.expect(ignore_path_ignored(temp.path, "note.tmp"));-    t.expect(ignore_path_ignored(temp.path, "build/out.bin"));-    t.expect(ignore_path_ignored(temp.path, "xveins/tests/Testing/Temporary/CTest.log"));-    t.expect(!ignore_path_ignored(temp.path, "note.txt"));--    IgnoreRules rules = ignore_empty();-    rules.items.push_back(IgnoreRule{"*.log", false, false, false, false, ""});-    rules.items.push_back(IgnoreRule{"keep.log", true, false, false, false, ""});-    t.expect(ignore_ignored(rules, "debug.log", false));-    t.expect(!ignore_ignored(rules, "keep.log", false));--    t.expect(valid_name("file.txt"));-    t.expect(!valid_name("dir/file"));-    t.expect(!valid_name(".veins"));-    t.expect(!valid_name(".."));-    t.expect(valid_path("a/b/c"));-    t.expect(!valid_path("/a"));-    t.expect(!valid_path("a//b"));-    t.expect(!valid_path("a/../b"));-}--void test_attributes(test::Context& t) {-    const TempDir temp;-    const std::string rules_text = "*.c txt eol:lf\n"-                                   "*.cmd txt eol:crlf\n"-                                   "*.ssa gen\n"-                                   "**/generated/* gen\n"-                                   "*.bin gen bin\n"-                                   "special.bin -gen\n";-    t.expect(write_file(temp.path / ".vnattribs", bytes_of(rules_text)));-    const AttributeRules rules = AttributeRules::load(temp.path);--    const auto source = rules.lookup("src/main.c");-    t.expect(source.text == AttributeText::Text);-    t.expect(source.eol == AttributeEol::Lf);-    t.expect(!source.generated);--    const auto script = rules.lookup("scripts/build.cmd");-    t.expect(script.text == AttributeText::Text);-    t.expect(script.eol == AttributeEol::Crlf);--    t.expect(rules.lookup("build/out.ssa").generated);-    t.expect(rules.lookup("pkg/generated/table.h").generated);--    const auto binary = rules.lookup("assets/blob.bin");-    t.expect(binary.generated);-    t.expect(binary.text == AttributeText::Binary);--    const auto overridden = rules.lookup("special.bin");-    t.expect(!overridden.generated);-    t.expect(overridden.text == AttributeText::Binary);--    const auto plain = rules.lookup("notes.txt");-    t.expect(plain.text == AttributeText::Auto);-    t.expect(plain.eol == AttributeEol::None);-    t.expect(!plain.generated);--    const auto lf = normalize_eol(bytes_of("a\r\nb\rc\nd"), AttributeEol::Lf);-    t.expect_eq(to_string(bytes_of(lf)), "a\nb\nc\nd");-    const auto crlf = normalize_eol(bytes_of("a\nb\rc\r\n"), AttributeEol::Crlf);-    t.expect_eq(to_string(bytes_of(crlf)), "a\r\nb\r\nc\r\n");-    const auto cr = normalize_eol(bytes_of("a\nb\r\nc\r"), AttributeEol::Cr);-    t.expect_eq(to_string(bytes_of(cr)), "a\rb\rc\r");-}--void test_attributes_edges(test::Context& t) {-    const TempDir temp;-    const std::string rules_text = "# leading comment\r\n"-                                   "\r\n"-                                   "*.c gen\r\n"-                                   "*.c -gen\r\n"-                                   "*.h txt\r\n"-                                   "*.h -bin\r\n"-                                   "*.log eol:crlf\r\n"-                                   "*.log -eol\r\n"-                                   "*.mac eol:cr\r\n"-                                   "src/*.c gen\r\n"-                                   "*.dat unknown-token bin\r\n";-    t.expect(write_file(temp.path / ".vnattribs", bytes_of(rules_text)));-    const AttributeRules rules = AttributeRules::load(temp.path);--    t.expect(!rules.lookup("a.c").generated);-    t.expect(rules.lookup("deep/a.c").generated == false);-    t.expect(rules.lookup("a.h").text == AttributeText::Auto);-    t.expect(rules.lookup("a.log").eol == AttributeEol::None);-    t.expect(rules.lookup("a.mac").eol == AttributeEol::Cr);-    t.expect(rules.lookup("src/main.c").generated);-    t.expect(!rules.lookup("nested/src/main.c").generated);-    t.expect(rules.lookup("assets/blob.dat").text == AttributeText::Binary);--    const TempDir empty;-    const AttributeRules none = AttributeRules::load(empty.path);-    const auto plain = none.lookup("anything");-    t.expect(!plain.generated);-    t.expect(plain.text == AttributeText::Auto);-    t.expect(plain.eol == AttributeEol::None);-}--void test_file_helpers(test::Context& t) {-    const TempDir temp;-    const fs::path file = temp.path / "nested" / "file.txt";-    t.expect(ensure_directory(file.parent_path()));-    t.expect(write_file(file, bytes_of("content")));-    t.expect(path_exists(file));-    t.expect(path_is_file(file));-    t.expect(!path_is_dir(file));-    t.expect_eq(path_file_size(file).value_or(0), 7u);-    const auto read = read_file_opt(file);-    t.expect(read.has_value());-    if (read)-        t.expect_eq(to_string(bytes_of(*read)), "content");-    t.expect(write_atomic(file, bytes_of("replacement")));-    const auto replaced = read_file_opt(file);-    t.expect(replaced.has_value());-    if (replaced)-        t.expect_eq(to_string(bytes_of(*replaced)), "replacement");-    t.expect(remove_file(file));-    t.expect(!path_exists(file));-    t.expect(same_or_under(temp.path / "a" / "b", temp.path));-    t.expect(!same_or_under(temp.path, temp.path / "a"));-    t.expect_eq(basename_string(file), "file.txt");-}--} // namespace--int main() {-    const std::vector<test::Suite> suites = {-        {"unit",-         {-             {"varint", test_varint},-             {"identifiers", test_identifiers},-             {"blob_roundtrip", test_blob_roundtrip},-             {"tree_roundtrip", test_tree_roundtrip},-             {"commit_roundtrip", test_commit_roundtrip},-             {"conflict_roundtrip", test_conflict_roundtrip},-             {"view_roundtrip", test_view_roundtrip},-             {"operation_roundtrip", test_operation_roundtrip},-             {"pack_roundtrip", test_pack_roundtrip},-             {"order_log_nodes", test_order_log_nodes},-             {"pathspecs", test_pathspecs},-             {"ignore_rules", test_ignore_rules},-             {"attributes", test_attributes},-             {"attributes_edges", test_attributes_edges},-             {"file_helpers", test_file_helpers},-         }},-    };-    return test::run_tests(suites);-}