navid/veins / commit

1cc615afac9c

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

parents: 39ca2c868b17

Browse files at this commit · Download source

all: add docs, unit tests, diff improvements, topological sort
--- a/.vnexclude+++ b/.vnexclude@@ -1,2 +1,4 @@+**/Testing/Temporary/*+*.pyc .vscode .DS_Store--- a/xveins/BENCH.md+++ b/xveins/BENCH.md@@ -4,9 +4,9 @@  ### Environment -| Binary | Version |-|:---|:---|-| Baseline | `veins v0.0.1 (veins-store 1)` |+| Binary    | Version                        |+| :-------- | :----------------------------- |+| Baseline  | `veins v0.0.1 (veins-store 1)` | | Optimized | `veins v0.0.1 (veins-store 1)` |  ```@@ -29,15 +29,15 @@  ### Results -| Metric | Baseline | Optimized | Speedup |-|:---|---:|---:|---:|-| Commit total [s] | 1.2404 (1.2176-1.2505) | 1.0918 (1.0794-1.1877) | 1.14x |-| Status [ms] | 49.6 (49.4-50.2) | 14.4 (14.0-15.1) | 3.44x |-| Log [ms] | 50.6 (50.1-51.7) | 13.3 (13.3-14.1) | 3.79x |-| Log -l 5 [ms] | 50.4 (49.9-51.6) | 13.2 (13.0-14.6) | 3.81x |-| Checkout total [s] | 0.3880 (0.3791-0.4098) | 0.1667 (0.1650-0.1754) | 2.33x |-| Checkout mean [ms] | 48.5 (47.4-51.2) | 20.8 (20.6-21.9) | 2.33x |-| Store size [MiB] | 43.01 (43.01-43.31) | 42.92 (42.92-42.92) | 1.00x smaller |+| Metric             |               Baseline |              Optimized |       Speedup |+| :----------------- | ---------------------: | ---------------------: | ------------: |+| Commit total [s]   | 1.2404 (1.2176-1.2505) | 1.0918 (1.0794-1.1877) |         1.14x |+| Status [ms]        |       49.6 (49.4-50.2) |       14.4 (14.0-15.1) |         3.44x |+| Log [ms]           |       50.6 (50.1-51.7) |       13.3 (13.3-14.1) |         3.79x |+| Log -l 5 [ms]      |       50.4 (49.9-51.6) |       13.2 (13.0-14.6) |         3.81x |+| Checkout total [s] | 0.3880 (0.3791-0.4098) | 0.1667 (0.1650-0.1754) |         2.33x |+| Checkout mean [ms] |       48.5 (47.4-51.2) |       20.8 (20.6-21.9) |         2.33x |+| Store size [MiB]   |    43.01 (43.01-43.31) |    42.92 (42.92-42.92) | 1.00x smaller |  Each cell is the median with the observed min-max range in parentheses. A speedup above 1 means the optimized binary was faster.@@ -45,12 +45,12 @@ ### Repeats  | Repeat | Baseline status [ms] | Optimized status [ms] | Baseline log [ms] | Optimized log [ms] | Baseline checkout [ms] | Optimized checkout [ms] |-|:---|---:|---:|---:|---:|---:|---:|-| 1 | 50.2 | 15.1 | 51.7 | 14.1 | 51.2 | 21.9 |-| 2 | 49.6 | 14.0 | 50.5 | 13.6 | 49.2 | 20.7 |-| 3 | 49.4 | 14.2 | 51.0 | 13.3 | 48.5 | 20.9 |-| 4 | 50.1 | 14.5 | 50.6 | 13.3 | 47.4 | 20.6 |-| 5 | 49.6 | 14.4 | 50.1 | 13.3 | 48.2 | 20.8 |+| :----- | -------------------: | --------------------: | ----------------: | -----------------: | ---------------------: | ----------------------: |+| 1      |                 50.2 |                  15.1 |              51.7 |               14.1 |                   51.2 |                    21.9 |+| 2      |                 49.6 |                  14.0 |              50.5 |               13.6 |                   49.2 |                    20.7 |+| 3      |                 49.4 |                  14.2 |              51.0 |               13.3 |                   48.5 |                    20.9 |+| 4      |                 50.1 |                  14.5 |              50.6 |               13.3 |                   47.4 |                    20.6 |+| 5      |                 49.6 |                  14.4 |              50.1 |               13.3 |                   48.2 |                    20.8 |  ### Notes --- a/xveins/CMakeLists.txt+++ b/xveins/CMakeLists.txt@@ -123,8 +123,7 @@     FetchContent_MakeAvailable(blake3) endif() -add_executable(vn-    src/main.cpp+set(VN_CORE_SOURCES     src/common.cpp     src/object.cpp     src/store.cpp@@ -150,30 +149,42 @@     src/cfg.cpp ) -target_include_directories(vn PRIVATE src)-target_link_libraries(vn PRIVATE-    BLAKE3::blake3-    ${VN_ZSTD_TARGET}-    OpenSSL::SSL-    OpenSSL::Crypto-    ZLIB::ZLIB-    Threads::Threads-)-if(WIN32)-    target_link_libraries(vn PRIVATE bcrypt ws2_32 crypt32)-endif()-target_compile_definitions(vn PRIVATE VN_VERSION="0.0.1")+check_cxx_compiler_flag(-Wconversion VN_HAS_WCONVERSION) -if(MSVC)-    target_compile_options(vn PRIVATE /W4 /permissive- /EHsc /Zc:__cplusplus)-    target_compile_definitions(vn PRIVATE _CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN)-else()-    target_compile_options(vn PRIVATE -Wall -Wextra -Wpedantic)-    check_cxx_compiler_flag(-Wconversion VN_HAS_WCONVERSION)-    if(VN_HAS_WCONVERSION)-        target_compile_options(vn PRIVATE -Wconversion -Wsign-conversion)+function(vn_configure_target target)+    target_include_directories(${target} PRIVATE src)+    target_link_libraries(${target} PRIVATE+        BLAKE3::blake3+        ${VN_ZSTD_TARGET}+        OpenSSL::SSL+        OpenSSL::Crypto+        ZLIB::ZLIB+        Threads::Threads+    )+    if(WIN32)+        target_link_libraries(${target} PRIVATE bcrypt ws2_32 crypt32)     endif()-endif()+    target_compile_definitions(${target} PRIVATE VN_VERSION="0.0.1")++    if(MSVC)+        target_compile_options(${target} PRIVATE /W4 /permissive- /EHsc /Zc:__cplusplus)+        target_compile_definitions(${target} PRIVATE+            _CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN+        )+    else()+        target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic)+        if(VN_HAS_WCONVERSION)+            target_compile_options(${target} PRIVATE -Wconversion -Wsign-conversion)+        endif()+    endif()+endfunction()++add_library(vn_core STATIC ${VN_CORE_SOURCES})+vn_configure_target(vn_core)++add_executable(vn src/main.cpp)+vn_configure_target(vn)+target_link_libraries(vn PRIVATE vn_core)  set_target_properties(vn PROPERTIES     RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"@@ -180,7 +191,29 @@     OUTPUT_NAME "vn" ) -enable_testing()-add_test(NAME vn-self-test COMMAND vn self-test)+include(CTest)+if(BUILD_TESTING)+    add_executable(vn-unit-tests tests/unit_tests.cpp)+    vn_configure_target(vn-unit-tests)+    target_link_libraries(vn-unit-tests PRIVATE vn_core)+    add_test(NAME vn-unit-tests COMMAND vn-unit-tests)++    add_executable(vn-integration-tests tests/integration_tests.cpp)+    vn_configure_target(vn-integration-tests)+    target_link_libraries(vn-integration-tests PRIVATE vn_core)++    add_test(NAME vn-self-test COMMAND vn self-test)++    set(VN_INTEGRATION_SUITES+        core worktree history refs config merge rebase git protocol errors+    )+    foreach(suite IN LISTS VN_INTEGRATION_SUITES)+        add_test(+            NAME "vn-integration-${suite}"+            COMMAND vn-integration-tests --suite ${suite}+        )+        set_tests_properties("vn-integration-${suite}" PROPERTIES TIMEOUT 180)+    endforeach()+endif()  install(TARGETS vn RUNTIME DESTINATION bin)--- a/xveins/bench/optim_bench.py+++ b/xveins/bench/optim_bench.py@@ -120,7 +120,9 @@     for _ in range(inner_runs):         status_runs.append(timed([str(binary), "status"], repo))         log_runs.append(timed([str(binary), "log", "-no-col-titles"], repo))-        limited_runs.append(timed([str(binary), "log", "-l", "5", "-no-col-titles"], repo))+        limited_runs.append(+            timed([str(binary), "log", "-l", "5", "-no-col-titles"], repo)+        )      log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()     targets = []@@ -297,7 +299,11 @@             opt_med = statistics.median(opt_values)             if key == "store_bytes":                 ratio = base_med / opt_med-                ratio_text = f"{ratio:.2f}x smaller" if ratio >= 1 else f"{1 / ratio:.2f}x larger"+                ratio_text = (+                    f"{ratio:.2f}x smaller"+                    if ratio >= 1+                    else f"{1 / ratio:.2f}x larger"+                )             else:                 ratio = base_med / opt_med                 ratio_text = f"{ratio:.2f}x"--- a/xveins/src/cli.cpp+++ b/xveins/src/cli.cpp@@ -4,6 +4,7 @@ #include "local_commands.h" #include "merge.h" #include "net_commands.h"+#include "pathspec.h" #include "promisor.h" #include "store.h" #include "worktree.h"@@ -13,6 +14,7 @@ #include <iostream> #include <map> #include <set>+#include <sstream>  namespace vn { @@ -438,8 +440,19 @@ }  void render_diff(Store& store, std::optional<Id> old_tree, std::optional<Id> new_tree,-                 bool announce_no_diff) {-    const auto changes = compare_trees(store, old_tree, new_tree);+                 bool announce_no_diff, std::string_view path_filter = {}) {+    auto changes = compare_trees(store, old_tree, new_tree);+    if (!path_filter.empty()) {+        changes.erase(std::remove_if(changes.begin(), changes.end(),+                                     [&](const TreeChange& change) {+                                         return change.path != path_filter &&+                                                !(change.path.size() > path_filter.size() &&+                                                  change.path.compare(0, path_filter.size(),+                                                                      path_filter) == 0 &&+                                                  change.path[path_filter.size()] == '/');+                                     }),+                      changes.end());+    }     for (const auto& change : changes) {         if (change.new_kind == KIND_CONFLICT) {             std::cout << "Conflict: " << change.path << "\n";@@ -721,6 +734,7 @@      struct Rec {         Id id{};+        std::vector<Id> parents;         std::string change;         std::int64_t seconds = 0;         std::string message;@@ -737,6 +751,7 @@             continue;         Rec rec;         rec.id = id;+        rec.parents = loaded->commit.parents;         rec.change = base32_encode(loaded->commit.change_id);         rec.seconds = loaded->commit.committer.seconds;         rec.message = first_line(loaded->commit.message);@@ -750,8 +765,16 @@                 stack.push_back(parent);         }     }-    std::stable_sort(recs.begin(), recs.end(),-                     [](const Rec& a, const Rec& b) { return a.seconds > b.seconds; });+    std::vector<LogOrderNode> nodes;+    nodes.reserve(recs.size());+    for (const auto& rec : recs)+        nodes.push_back(LogOrderNode{rec.id, rec.seconds, rec.parents});+    const auto order = order_log_nodes(nodes);+    std::vector<Rec> ordered;+    ordered.reserve(recs.size());+    for (std::size_t index : order)+        ordered.push_back(std::move(recs[index]));+    recs = std::move(ordered);      if (limit) {         if (first) {@@ -1077,12 +1100,16 @@ }  int run_diff(const std::vector<std::string>& args) {-    std::vector<std::string> revs;+    std::vector<std::string> flag_revs;+    std::vector<std::string> operands;+    bool all = false;     bool end_flags = false;     for (std::size_t i = 2; i < args.size(); ++i) {         const std::string& arg = args[i];         if (!end_flags && arg == "--") {             end_flags = true;+        } else if (!end_flags && (arg == "-a" || arg == "-all" || arg == "--all")) {+            all = true;         } else if (!end_flags && (arg == "-r" || arg == "-rev")) {             if (i + 1 >= args.size()) {                 error_prefix();@@ -1089,13 +1116,13 @@                 std::cout << arg << " requires a revision\n";                 return 1;             }-            revs.push_back(args[++i]);+            flag_revs.push_back(args[++i]);         } else if (!end_flags && is_flag(arg)) {             error_prefix();             std::cout << "unknown flag: " << arg << "\n";             return 1;         } else {-            revs.push_back(arg);+            operands.push_back(arg);         }     }     const auto root = open_repo();@@ -1111,6 +1138,52 @@         std::cout << "no operation state\n";         return 1;     }++    std::vector<std::string> revs = flag_revs;+    std::optional<std::string> path_filter;+    if (!operands.empty()) {+        if (!revs.empty()) {+            if (operands.size() > 1) {+                error_prefix();+                std::cout << "too many arguments\n";+                return 1;+            }+            path_filter = operands.front();+        } else if (operands.size() >= 2) {+            if (operands.size() > 2) {+                error_prefix();+                std::cout << "too many revisions\n";+                return 1;+            }+            revs.push_back(operands[0]);+            revs.push_back(operands[1]);+        } else if (resolve_revision(store, *view, operands.front())) {+            revs.push_back(operands.front());+        } else {+            path_filter = operands.front();+        }+    }+    if (revs.size() > 2) {+        error_prefix();+        std::cout << "too many revisions\n";+        return 1;+    }+    if (path_filter) {+        const auto cwd_rel = cwd_relative(*root);+        if (!cwd_rel) {+            error_prefix();+            std::cout << "cannot determine current directory\n";+            return 1;+        }+        auto normalized = pathspec_normalize(*root, *cwd_rel, *path_filter);+        if (!normalized || normalized->empty()) {+            error_prefix();+            std::cout << "path is outside the repository: " << *path_filter << "\n";+            return 1;+        }+        path_filter = std::move(*normalized);+    }+     std::optional<Id> old_tree;     std::optional<Id> new_tree;     bool failed = false;@@ -1129,7 +1202,7 @@             return std::nullopt;         return parent->commit.root_tree;     };-    if (revs.size() >= 2) {+    if (revs.size() == 2) {         auto a = resolve_revision(store, *view, revs[0]);         auto b = resolve_revision(store, *view, revs[1]);         if (!a || !b)@@ -1158,7 +1231,17 @@         std::cout << "unknown revision\n";         return 1;     }-    render_diff(store, old_tree, new_tree, true);++    const std::string_view filter =+        path_filter ? std::string_view(*path_filter) : std::string_view{};+    std::ostringstream rendered;+    auto* old_out = std::cout.rdbuf(rendered.rdbuf());+    render_diff(store, old_tree, new_tree, true, filter);+    std::cout.rdbuf(old_out);+    if (!all && stdout_is_terminal())+        (void)run_pager(*root, rendered.str());+    else+        std::cout << rendered.str();     return 0; } @@ -2033,7 +2116,7 @@     std::cout << "  log          show commit history\n";     std::cout << "  show         show a commit and its diff\n";     std::cout << "  hash         print the commit hash for a revision\n";-    std::cout << "  diff         show a unified diff\n";+    std::cout << "  diff         show a unified diff, paged on a terminal\n";     std::cout << "  merge        create a merge commit; never fails\n";     std::cout << "  rebase       rewrite changes onto a new parent\n";     std::cout << "  xs           list conflicted paths\n";@@ -2128,8 +2211,11 @@ }  void show_diff() {-    std::cout << "usage: vn diff [-rev <rev>] [<rev> <rev>]\n\n";-    std::cout << "show a unified diff\n";+    std::cout << "usage: vn diff [-a] [-rev <rev>] [<rev> <rev>] [<path>]\n\n";+    std::cout << "show a unified diff, paged when stdout is a terminal\n\n";+    std::cout << "options:\n";+    std::cout << "  -a, -all                  print the whole diff at once\n";+    std::cout << "  -rev <rev>                compare a revision with its parent\n"; }  void show_new() {--- a/xveins/src/common.cpp+++ b/xveins/src/common.cpp@@ -1603,7 +1603,62 @@     return _isatty(_fileno(stdin)) != 0; #else     return ::isatty(STDIN_FILENO) != 0;+#endif+}++bool stdout_is_terminal() {+#if defined(_WIN32)+    return _isatty(_fileno(stdout)) != 0;+#else+    return ::isatty(STDOUT_FILENO) != 0;+#endif+}++std::string pager_command(const fs::path& repo_root) {+    if (auto value = user_config_value("pager")) {+        if (!value->empty())+            return *value;+    }+    if (auto value = user_config_value("core.pager")) {+        if (!value->empty())+            return *value;+    }+    if (auto value = repo_config_value(repo_root, "pager")) {+        if (!value->empty())+            return *value;+    }+    if (const char* value = std::getenv("VN_PAGER")) {+        if (value[0] != '\0')+            return value;+    }+    if (const char* value = std::getenv("PAGER")) {+        if (value[0] != '\0')+            return value;+    }+#if defined(_WIN32)+    return "more";+#else+    return "less -R"; #endif+}++bool run_pager(const fs::path& repo_root, std::string_view text) {+    if (!stdout_is_terminal()) {+        std::cout << text;+        return true;+    }+    const fs::path file =+        fs::temp_directory_path() / ("vn-pager-" + std::to_string(random_u64()) + ".txt");+    if (!write_file(file, bytes_of(text))) {+        std::cout << text;+        return false;+    }+    const std::string command = pager_command(repo_root) + " " + shell_quote_arg(path_to_bytes(file));+    const bool ok = std::system(command.c_str()) == 0;+    (void)remove_file(file);+    if (!ok)+        std::cout << text;+    return ok; }  std::optional<std::string> current_bookmark_name(const fs::path& repo_root) {--- a/xveins/src/common.h+++ b/xveins/src/common.h@@ -445,6 +445,9 @@ bool run_editor(const fs::path& repo_root, const std::vector<std::string>& paths,                 const std::optional<fs::path>& message_file = std::nullopt); bool stdin_is_terminal();+bool stdout_is_terminal();+std::string pager_command(const fs::path& repo_root);+bool run_pager(const fs::path& repo_root, std::string_view text);  std::optional<std::string> current_bookmark_name(const fs::path& repo_root); bool set_current_bookmark(const fs::path& repo_root, std::string_view name);--- a/xveins/src/object.h+++ b/xveins/src/object.h@@ -203,6 +203,12 @@ struct LoadedCommit {     Commit commit;     std::vector<std::uint8_t> body;+};++struct LogOrderNode {+    Id id{};+    std::int64_t seconds = 0;+    std::vector<Id> parents; };  std::optional<LoadedCommit> load_commit(Store& store, const Id& id);@@ -210,6 +216,7 @@ std::vector<Id> collect_commits(Store& store, std::span<const Id> start); std::vector<Id> all_commits(Store& store, const View& view); std::vector<Id> view_roots(const View& view);+std::vector<std::size_t> order_log_nodes(const std::vector<LogOrderNode>& nodes); std::optional<Id> resolve_revision(Store& store, const View& view, std::string_view rev); std::optional<Id> working_copy_id(const View& view); --- a/xveins/src/protocol.cpp+++ b/xveins/src/protocol.cpp@@ -14,9 +14,6 @@ namespace {  std::string connect_error;-std::string& connect_error_slot() {-    return connect_error;-}  void put_u16_be(ByteWriter& writer, std::uint16_t value) {     writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));--- a/xveins/src/store.cpp+++ b/xveins/src/store.cpp@@ -7,7 +7,9 @@ #include <cstring> #include <iostream> #include <limits>+#include <queue> #include <thread>+#include <unordered_map> #include <unordered_set>  #include <zstd.h>@@ -1280,6 +1282,67 @@     return out; } +// Orders log nodes newest-first while keeping every child before its parents.+std::vector<std::size_t> order_log_nodes(const std::vector<LogOrderNode>& nodes) {+    std::unordered_map<Id, std::size_t, IdHash, IdEq> index;+    index.reserve(nodes.size());+    for (std::size_t i = 0; i < nodes.size(); ++i)+        index.emplace(nodes[i].id, i);++    std::vector<std::size_t> unemitted_children(nodes.size(), 0);+    for (const auto& node : nodes) {+        for (const auto& parent : node.parents) {+            const auto found = index.find(parent);+            if (found != index.end())+                ++unemitted_children[found->second];+        }+    }++    struct Ready {+        std::int64_t seconds = 0;+        std::size_t index = 0;+    };+    struct ReadyAfter {+        bool operator()(const Ready& a, const Ready& b) const {+            if (a.seconds != b.seconds)+                return a.seconds < b.seconds;+            return a.index > b.index;+        }+    };+    std::priority_queue<Ready, std::vector<Ready>, ReadyAfter> ready;+    for (std::size_t i = 0; i < nodes.size(); ++i) {+        if (unemitted_children[i] == 0)+            ready.push(Ready{nodes[i].seconds, i});+    }++    std::vector<std::size_t> order;+    order.reserve(nodes.size());+    std::vector<bool> emitted(nodes.size(), false);+    while (!ready.empty()) {+        const Ready next = ready.top();+        ready.pop();+        if (emitted[next.index])+            continue;+        emitted[next.index] = true;+        order.push_back(next.index);+        for (const auto& parent : nodes[next.index].parents) {+            const auto found = index.find(parent);+            if (found == index.end())+                continue;+            std::size_t& count = unemitted_children[found->second];+            if (count > 0)+                --count;+            if (count == 0)+                ready.push(Ready{nodes[found->second].seconds, found->second});+        }+    }+    for (std::size_t i = 0; i < nodes.size(); ++i) {+        if (!emitted[i])+            order.push_back(i);+    }+    return order;+}+ std::vector<Id> view_roots(const View& view) {     std::vector<Id> out;     auto add = [&](const Id& id) {--- /dev/null+++ b/xveins/tests/integration_tests.cpp@@ -0,0 +1,1267 @@+#include "test_support.h"++#include "cli.h"+#include "common.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"));+    t.expect_contains(f.vn({"version"}).out, "veins");+    const std::string help_text = f.vn({"help"}).out;+    t.expect_contains(help_text, "subcommands:");+    t.expect_contains(f.vn({"help", "log"}).out, "vn log");+    t.expect_contains(f.vn({"help", "go"}).out, "aliases: commit");+}++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_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 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_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");++    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({"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");+    t.expect_contains(f.vn({"show", one}).out, "one");+}++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_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";+    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);+    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({"whoami", "origin"}, clone_a).out, "role: write");++    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:");+}++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},+             {"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},+             {"editor", worktree_editor},+         }},+        {"history",+         {+             {"log_is_topological", history_log_is_topological},+             {"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},+             {"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/test_support.h@@ -0,0 +1,135 @@+#pragma once++#include <iostream>+#include <source_location>+#include <sstream>+#include <stdexcept>+#include <string>+#include <string_view>+#include <type_traits>+#include <vector>++namespace vn::test {++class Failure : public std::runtime_error {+public:+    using std::runtime_error::runtime_error;+};++inline std::string location_text(const std::source_location& location) {+    std::ostringstream out;+    out << location.file_name() << ":" << location.line();+    return out.str();+}++template <typename T> std::string display(const T& value) {+    if constexpr (std::is_enum_v<T>) {+        std::ostringstream out;+        out << static_cast<long long>(value);+        return out.str();+    } else if constexpr (std::is_same_v<T, bool>) {+        return value ? "true" : "false";+    } else {+        std::ostringstream out;+        out << value;+        return out.str();+    }+}++struct Context {+    [[noreturn]] void+    fail(std::string message,+         const std::source_location& location = std::source_location::current()) const {+        throw Failure(location_text(location) + ": " + std::move(message));+    }++    void expect(bool condition,+                const std::source_location& location = std::source_location::current()) const {+        if (!condition)+            fail("expected condition to be true", location);+    }++    template <typename A, typename B>+    void expect_eq(const A& actual, const B& expected,+                   const std::source_location& location = std::source_location::current()) const {+        if (!(actual == expected))+            fail("expected " + display(actual) + " == " + display(expected), location);+    }++    template <typename A, typename B>+    void expect_ne(const A& actual, const B& expected,+                   const std::source_location& location = std::source_location::current()) const {+        if (actual == expected)+            fail("expected " + display(actual) + " != " + display(expected), location);+    }++    void+    expect_contains(std::string_view text, std::string_view needle,+                    const std::source_location& location = std::source_location::current()) const {+        if (text.find(needle) == std::string_view::npos)+            fail("expected text to contain \"" + std::string(needle) + "\", got:\n" ++                     std::string(text),+                 location);+    }++    void expect_not_contains(+        std::string_view text, std::string_view needle,+        const std::source_location& location = std::source_location::current()) const {+        if (text.find(needle) != std::string_view::npos)+            fail("expected text not to contain \"" + std::string(needle) + "\", got:\n" ++                     std::string(text),+                 location);+    }++    void expect_starts_with(+        std::string_view text, std::string_view prefix,+        const std::source_location& location = std::source_location::current()) const {+        if (!text.starts_with(prefix))+            fail("expected text to start with \"" + std::string(prefix) + "\", got:\n" ++                     std::string(text),+                 location);+    }+};++struct TestCase {+    std::string name;+    void (*run)(Context&) = nullptr;+};++struct Suite {+    std::string name;+    std::vector<TestCase> tests;+};++inline int run_tests(const std::vector<Suite>& suites, std::string_view only = {}) {+    int failures = 0;+    int count = 0;+    for (const Suite& suite : suites) {+        if (!only.empty() && suite.name != only)+            continue;+        for (const TestCase& test : suite.tests) {+            ++count;+            Context context;+            try {+                test.run(context);+                std::cout << "[ok] " << suite.name << "." << test.name << "\n";+            } catch (const Failure& failure) {+                ++failures;+                std::cerr << "[FAIL] " << suite.name << "." << test.name << ": " << failure.what()+                          << "\n";+            } catch (const std::exception& error) {+                ++failures;+                std::cerr << "[FAIL] " << suite.name << "." << test.name+                          << ": unexpected exception: " << error.what() << "\n";+            }+        }+    }+    if (count == 0) {+        std::cerr << "no tests selected\n";+        return 1;+    }+    std::cout << count - failures << "/" << count << " tests passed\n";+    return failures == 0 ? 0 : 1;+}++} // namespace vn::test--- /dev/null+++ b/xveins/tests/unit_tests.cpp@@ -0,0 +1,488 @@+#include "test_support.h"++#include "common.h"+#include "object.h"+#include "pathspec.h"+#include "store.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_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},+             {"file_helpers", test_file_helpers},+         }},+    };+    return test::run_tests(suites);+}