navid/veins / commit
8f27ca4e7bfe
Navid M <navidmomtahen@gmail.com> · 2026-11-27
parents: 77ac733614a6
Browse files at this commit · Download source
--- /dev/null+++ b/veins-cpprewrite/.gitignore@@ -0,0 +1,2 @@+/build*/+/.cache/--- /dev/null+++ b/veins-cpprewrite/CMakeLists.txt@@ -0,0 +1,111 @@+cmake_minimum_required(VERSION 3.25)++project(veins_cpp+ VERSION 0.0.1+ DESCRIPTION "C++ implementation of the veins version control system"+ LANGUAGES C CXX+)++set(CMAKE_CXX_STANDARD 23)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+set(CMAKE_CXX_EXTENSIONS OFF)+set(CMAKE_C_STANDARD 11)+set(CMAKE_C_STANDARD_REQUIRED ON)++if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)+ set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)+endif()++include(FetchContent)+include(CheckCXXCompilerFlag)++find_package(Threads REQUIRED)++# ---------------------------------------------------------------------------+# zstd: prefer an installed package, otherwise fetch a pinned release.+# ---------------------------------------------------------------------------+find_package(zstd CONFIG QUIET)+if(TARGET zstd::libzstd_static)+ set(VN_ZSTD_TARGET zstd::libzstd_static)+elseif(TARGET zstd::libzstd_shared)+ set(VN_ZSTD_TARGET zstd::libzstd_shared)+elseif(TARGET libzstd_static)+ set(VN_ZSTD_TARGET libzstd_static)+elseif(TARGET libzstd)+ set(VN_ZSTD_TARGET libzstd)+else()+ set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)+ set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "" FORCE)+ set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE)+ set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE)+ set(ZSTD_BUILD_STATIC ON CACHE BOOL "" FORCE)+ set(ZSTD_LEGACY_SUPPORT OFF CACHE BOOL "" FORCE)+ set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE)+ FetchContent_Declare(+ zstd+ GIT_REPOSITORY https://github.com/facebook/zstd.git+ GIT_TAG v1.5.6+ GIT_SHALLOW TRUE+ )+ FetchContent_MakeAvailable(zstd)+ if(TARGET libzstd_static)+ set(VN_ZSTD_TARGET libzstd_static)+ else()+ set(VN_ZSTD_TARGET libzstd)+ endif()+endif()++# ---------------------------------------------------------------------------+# BLAKE3: use an installed config when present, otherwise fetch the C sources.+# ---------------------------------------------------------------------------+find_package(blake3 CONFIG QUIET)+if(TARGET blake3 AND NOT TARGET BLAKE3::blake3)+ add_library(BLAKE3::blake3 ALIAS blake3)+endif()+if(NOT TARGET BLAKE3::blake3)+ FetchContent_Declare(+ blake3+ GIT_REPOSITORY https://github.com/BLAKE3-team/BLAKE3.git+ GIT_TAG 1.5.5+ GIT_SHALLOW TRUE+ SOURCE_SUBDIR c+ )+ FetchContent_MakeAvailable(blake3)+endif()++add_executable(vn+ src/main.cpp+ src/common.cpp+ src/object.cpp+ src/store.cpp+ src/worktree.cpp+ src/cli.cpp+)++target_include_directories(vn PRIVATE src)+target_link_libraries(vn PRIVATE BLAKE3::blake3 ${VN_ZSTD_TARGET} Threads::Threads)+if(WIN32)+ target_link_libraries(vn PRIVATE bcrypt)+endif()+target_compile_definitions(vn PRIVATE VN_VERSION="0.0.1")++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)+ endif()+endif()++set_target_properties(vn PROPERTIES+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"+ OUTPUT_NAME "vn"+)++enable_testing()+add_test(NAME vn-self-test COMMAND vn self-test)++install(TARGETS vn RUNTIME DESTINATION bin)--- /dev/null+++ b/veins-cpprewrite/bench/bench.py@@ -0,0 +1,190 @@+#!/usr/bin/env python3+"""Compare the C++ and Spectre veins binaries on a synthetic edit workload."""++from __future__ import annotations++import argparse+import os+import random+import re+import shutil+import statistics+import subprocess+import sys+import tempfile+import time+from pathlib import Path++HEX12 = re.compile(r"\b[0-9a-f]{12}\b")+++def command_prefix() -> list[str]:+ try:+ subprocess.run(+ ["taskset", "-c", "0", "true"],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=True,+ )+ return ["taskset", "-c", "0"]+ except Exception:+ return []+++PREFIX: list[str] = []+++def run(cmd: list[str], cwd: Path) -> str:+ env = os.environ.copy()+ env["LC_ALL"] = "C"+ env["NO_COLOR"] = "1"+ result = subprocess.run(+ [str(part) for part in PREFIX + cmd],+ cwd=str(cwd),+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ check=True,+ text=True,+ )+ return result.stdout+++def timed(cmd: list[str], cwd: Path) -> float:+ start = time.perf_counter()+ run(cmd, cwd)+ return time.perf_counter() - start+++def make_base(root: Path, lines: int, small_files: int) -> None:+ root.mkdir(parents=True)+ (root / "generated.c").write_text(+ "".join(f"int value_{i} = {i * 3 + 7};\n" for i in range(lines)),+ encoding="utf-8",+ )+ for i in range(small_files):+ (root / f"module_{i:03d}.c").write_text(+ f"// module {i}\nint module_{i}(void) {{ return {i}; }}\n", encoding="utf-8"+ )+ (root / "sub").mkdir()+ (root / "sub" / "nested.txt").write_text("nested\n" * 200, encoding="utf-8")+++def mutate(root: Path, revision: int) -> None:+ path = root / "generated.c"+ lines = path.read_text(encoding="utf-8").splitlines(keepends=True)+ rng = random.Random(revision)+ for _ in range(max(1, len(lines) // 100)):+ index = rng.randrange(len(lines))+ lines[index] = f"int changed_{revision}_{index} = {revision};\n"+ path.write_text("".join(lines), encoding="utf-8")+ for i in range(3):+ (root / f"module_{i:03d}.c").write_text(+ f"// module {i}, revision {revision}\n"+ f"int module_{i}(void) {{ return {revision * 1000 + i}; }}\n",+ encoding="utf-8",+ )+++def tree_bytes(root: Path) -> int:+ return sum(path.stat().st_size for path in root.rglob("*") if path.is_file())+++def bench_one(+ binary: Path, work: Path, label: str, revisions: int, checkouts: int+) -> tuple[float, float, int]:+ repo = work / label+ shutil.copytree(work / "base", repo)+ run([str(binary), "init"], repo)+ (repo / ".veins" / "config").write_text(+ "user.name = Bench\nuser.email = bench@example.com\n", encoding="utf-8"+ )+ mutate(repo, 0)+ run([str(binary), "go", "-m", "warmup"], repo)++ commit_time = 0.0+ for revision in range(1, revisions + 1):+ mutate(repo, revision)+ commit_time += timed([str(binary), "go", "-m", f"revision {revision}"], repo)++ log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()+ ids = [match.group(0) for line in log_lines if (match := HEX12.search(line))]+ targets = ids[: max(1, checkouts)]+ checkout_time = 0.0+ for i in range(checkouts):+ target = targets[min(i, len(targets) - 1)]+ checkout_time += timed([str(binary), "co", target], repo)+ return commit_time, checkout_time, tree_bytes(repo / ".veins")+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--spectre",+ type=Path,+ default=Path(__file__).resolve().parents[2] / "veins" / "vn",+ )+ parser.add_argument(+ "--cpp", type=Path, default=Path(__file__).resolve().parents[1] / "build" / "vn"+ )+ parser.add_argument("--revisions", type=int, default=20)+ parser.add_argument("--checkouts", type=int, default=8)+ parser.add_argument("--repeats", type=int, default=3)+ parser.add_argument("--large-lines", type=int, default=120000)+ parser.add_argument("--small-files", type=int, default=40)+ parser.add_argument("--no-pin", action="store_true")+ args = parser.parse_args()++ global PREFIX+ PREFIX = [] if args.no_pin else command_prefix()++ if not args.spectre.exists():+ print(f"missing Spectre binary: {args.spectre}", file=sys.stderr)+ return 2+ if not args.cpp.exists():+ print(f"missing C++ binary: {args.cpp}", file=sys.stderr)+ return 2++ work = Path(tempfile.mkdtemp(prefix="veins-bench-"))+ try:+ make_base(work / "base", args.large_lines, args.small_files)+ size = tree_bytes(work / "base")+ print(+ f"workload: {size / (1024 * 1024):.2f} MiB, "+ f"{args.revisions} revisions, {args.checkouts} checkouts, "+ f"{args.repeats} repeats, cpu pinning={'no' if args.no_pin else 'yes'}"+ )+ rows: dict[str, list[tuple[float, float, int]]] = {"spectre": [], "cpp": []}+ for repeat in range(args.repeats):+ print(f"repeat {repeat + 1}/{args.repeats}")+ for label, binary in (("spectre", args.spectre), ("cpp", args.cpp)):+ commit, checkout, store = bench_one(+ binary, work, f"{label}-{repeat}", args.revisions, args.checkouts+ )+ rows[label].append((commit, checkout, store))+ print(+ f" {label}: commit {commit:.3f}s checkout {checkout:.3f}s "+ f"store {store / (1024 * 1024):.2f} MiB"+ )++ def median(label: str, index: int) -> float:+ return statistics.median(row[index] for row in rows[label])++ spectre_commit = median("spectre", 0)+ cpp_commit = median("cpp", 0)+ spectre_checkout = median("spectre", 1)+ cpp_checkout = median("cpp", 1)+ print()+ print(f"commit speedup C++/Spectre: {spectre_commit / cpp_commit:.2f}x")+ print(f"checkout speedup C++/Spectre: {spectre_checkout / cpp_checkout:.2f}x")+ print(+ f"store size ratio C++/Spectre: "+ f"{median('cpp', 2) / median('spectre', 2):.2f}x"+ )+ return 0+ finally:+ shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+ raise SystemExit(main())--- /dev/null+++ b/veins-cpprewrite/src/cli.cpp@@ -0,0 +1,2178 @@+#include "cli.h"++#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <cstring>+#include <iostream>+#include <map>+#include <set>++namespace vn {++namespace {++bool is_flag(std::string_view arg) {+ return !arg.empty() && arg.front() == '-';+}++std::optional<fs::path> open_repo() {+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return std::nullopt;+ }+ return root;+}++std::string join_args(const std::vector<std::string> &parts) {+ std::string out;+ for (std::size_t i = 0; i < parts.size(); ++i) {+ if (i != 0)+ out.push_back(' ');+ out += parts[i];+ }+ return out;+}++bool message_is_blank(const std::vector<std::string> &parts) {+ for (const auto &part : parts) {+ for (char c : part) {+ if (c != ' ' && c != '\t' && c != '\n' && c != '\r')+ return false;+ }+ }+ return true;+}++Result<std::vector<std::string>>+parse_message(const std::vector<std::string> &args, std::size_t start) {+ std::vector<std::string> parts;+ bool end_flags = false;+ for (std::size_t i = start; i < args.size(); ++i) {+ const std::string &arg = args[i];+ if (!end_flags && arg == "--") {+ end_flags = true;+ } else if (!end_flags && (arg == "-m" || arg == "-message")) {+ if (i + 1 < args.size()) {+ parts.push_back(args[++i]);+ } else {+ error_prefix();+ std::cout << arg << " requires a message\n";+ return fail_usage("missing message");+ }+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return fail_usage("unknown flag");+ } else {+ parts.push_back(arg);+ }+ }+ return parts;+}++void print_cell(std::string_view text, std::size_t width, Color color,+ bool dim) {+ if (dim) {+ print_styled(text, color, true, false);+ } else if (color == Color::Default) {+ std::cout << text;+ } else {+ print_colored(text, color, false, false);+ }+ for (std::size_t i = text.size(); i < width; ++i)+ std::cout << ' ';+}++void print_gap() { std::cout << " "; }++std::string first_line(const std::string &message) {+ const std::size_t newline = message.find('\n');+ return newline == std::string::npos ? message : message.substr(0, newline);+}++std::string short_hex(const Id &id) { return hex_encode(id).substr(0, 12); }++std::string short_change_id(const std::vector<std::string> &ids,+ std::size_t index) {+ const std::string &target = ids[index];+ std::size_t len = std::min<std::size_t>(4, target.size());+ while (len < target.size()) {+ const std::string_view prefix(target.data(), len);+ bool unique = true;+ for (std::size_t j = 0; j < ids.size(); ++j) {+ if (j == index)+ continue;+ if (ids[j] == target)+ continue;+ if (ids[j].starts_with(prefix)) {+ unique = false;+ break;+ }+ }+ if (unique)+ break;+ ++len;+ }+ return target.substr(0, len);+}++// ---------------------------------------------------------------------------+// Diff rendering+// ---------------------------------------------------------------------------++struct DiffOp {+ char tag = ' ';+ std::size_t ai = 0;+ std::size_t bi = 0;+};++std::vector<std::string> split_lines(Bytes data) {+ std::vector<std::string> out;+ std::size_t start = 0;+ for (std::size_t i = 0; i < data.size(); ++i) {+ if (data[i] == '\n') {+ out.emplace_back(reinterpret_cast<const char *>(data.data() + start),+ i - start);+ start = i + 1;+ }+ }+ if (start < data.size()) {+ out.emplace_back(reinterpret_cast<const char *>(data.data() + start),+ data.size() - start);+ } else if (!data.empty() && data.back() == '\n') {+ // A trailing newline does not introduce an extra empty line.+ } else if (data.empty()) {+ // No lines.+ }+ return out;+}++std::vector<DiffOp> build_ops_lcs(const std::vector<std::string> &a,+ const std::vector<std::string> &b) {+ const std::size_t n = a.size();+ const std::size_t m = b.size();+ const std::size_t cols = m + 1;+ std::vector<std::uint32_t> dp((n + 1) * cols, 0);+ for (std::size_t i = 1; i <= n; ++i) {+ for (std::size_t j = 1; j <= m; ++j) {+ if (a[i - 1] == b[j - 1])+ dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;+ else+ dp[i * cols + j] =+ std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);+ }+ }+ std::vector<DiffOp> ops;+ std::size_t i = n;+ std::size_t j = m;+ while (i > 0 || j > 0) {+ if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) {+ ops.push_back(DiffOp{' ', i - 1, j - 1});+ --i;+ --j;+ } else if (j > 0 &&+ (i == 0 || dp[i * cols + (j - 1)] >= dp[(i - 1) * cols + j])) {+ ops.push_back(DiffOp{'+', 0, j - 1});+ --j;+ } else {+ ops.push_back(DiffOp{'-', i - 1, 0});+ --i;+ }+ }+ std::reverse(ops.begin(), ops.end());+ return ops;+}++std::vector<DiffOp> build_ops_myers(const std::vector<std::string> &a,+ const std::vector<std::string> &b) {+ const int n = static_cast<int>(a.size());+ const int m = static_cast<int>(b.size());+ const int max_d = n + m;+ const int offset = max_d;+ std::vector<int> v(static_cast<std::size_t>(2 * max_d + 1), 0);+ std::vector<std::vector<int>> trace;+ constexpr std::size_t trace_cap = 64u * 1024u * 1024u;+ int found_d = -1;+ for (int d = 0; d <= max_d; ++d) {+ if (static_cast<std::size_t>(trace.size() + 1) * v.size() * sizeof(int) >+ trace_cap)+ return {};+ trace.push_back(v);+ for (int k = -d; k <= d; k += 2) {+ int x = 0;+ if (k == -d ||+ (k != d && v[static_cast<std::size_t>(offset + k - 1)] <+ v[static_cast<std::size_t>(offset + k + 1)]))+ x = v[static_cast<std::size_t>(offset + k + 1)];+ else+ x = v[static_cast<std::size_t>(offset + k - 1)] + 1;+ int y = x - k;+ while (x < n && y < m &&+ a[static_cast<std::size_t>(x)] == b[static_cast<std::size_t>(y)]) {+ ++x;+ ++y;+ }+ v[static_cast<std::size_t>(offset + k)] = x;+ if (x >= n && y >= m) {+ found_d = d;+ break;+ }+ }+ if (found_d >= 0)+ break;+ }+ if (found_d < 0)+ return {};+ std::vector<DiffOp> ops;+ int x = n;+ int y = m;+ for (int d = found_d; d >= 0; --d) {+ const auto &prev = trace[static_cast<std::size_t>(d)];+ const int k = x - y;+ int prev_k = 0;+ if (k == -d ||+ (k != d && prev[static_cast<std::size_t>(offset + k - 1)] <+ prev[static_cast<std::size_t>(offset + k + 1)]))+ prev_k = k + 1;+ else+ prev_k = k - 1;+ const int prev_x = prev[static_cast<std::size_t>(offset + prev_k)];+ const int prev_y = prev_x - prev_k;+ while (x > prev_x && y > prev_y) {+ ops.push_back(DiffOp{' ', static_cast<std::size_t>(x - 1),+ static_cast<std::size_t>(y - 1)});+ --x;+ --y;+ }+ if (d > 0) {+ if (x == prev_x) {+ ops.push_back(DiffOp{'+', 0, static_cast<std::size_t>(y - 1)});+ --y;+ } else {+ ops.push_back(DiffOp{'-', static_cast<std::size_t>(x - 1), 0});+ --x;+ }+ }+ }+ std::reverse(ops.begin(), ops.end());+ return ops;+}++std::vector<DiffOp> build_ops_fallback(const std::vector<std::string> &a,+ const std::vector<std::string> &b) {+ std::size_t prefix = 0;+ while (prefix < a.size() && prefix < b.size() && a[prefix] == b[prefix])+ ++prefix;+ std::size_t suffix = 0;+ while (suffix < a.size() - prefix && suffix < b.size() - prefix &&+ a[a.size() - 1 - suffix] == b[b.size() - 1 - suffix])+ ++suffix;+ std::vector<DiffOp> ops;+ for (std::size_t i = 0; i < prefix; ++i)+ ops.push_back(DiffOp{' ', i, i});+ for (std::size_t i = prefix; i < a.size() - suffix; ++i)+ ops.push_back(DiffOp{'-', i, 0});+ for (std::size_t j = prefix; j < b.size() - suffix; ++j)+ ops.push_back(DiffOp{'+', 0, j});+ for (std::size_t k = 0; k < suffix; ++k) {+ const std::size_t i = a.size() - suffix + k;+ const std::size_t j = b.size() - suffix + k;+ ops.push_back(DiffOp{' ', i, j});+ }+ return ops;+}++std::vector<DiffOp> build_ops(const std::vector<std::string> &a,+ const std::vector<std::string> &b) {+ const std::size_t n = a.size();+ const std::size_t m = b.size();+ if (n == 0 && m == 0)+ return {};+ if (n != 0 && m != 0 && n <= 2048 && m <= 2048)+ return build_ops_lcs(a, b);+ if (n != 0 && m != 0 && n * m <= 4'000'000)+ return build_ops_lcs(a, b);+ auto myers = build_ops_myers(a, b);+ if (!myers.empty())+ return myers;+ return build_ops_fallback(a, b);+}++void render_unified(const std::vector<std::string> &a,+ const std::vector<std::string> &b) {+ const auto ops = build_ops(a, b);+ std::vector<std::size_t> changes;+ for (std::size_t i = 0; i < ops.size(); ++i) {+ if (ops[i].tag != ' ')+ changes.push_back(i);+ }+ constexpr std::size_t context = 3;+ std::size_t pos = 0;+ std::size_t old_seen = 0;+ std::size_t new_seen = 0;+ std::size_t ci = 0;+ while (ci < changes.size()) {+ const std::size_t first = changes[ci];+ std::size_t start = first > context ? first - context : 0;+ std::size_t last = first;+ ++ci;+ while (ci < changes.size() && changes[ci] <= last + context * 2) {+ last = changes[ci];+ ++ci;+ }+ std::size_t end = std::min(last + context + 1, ops.size());+ while (pos < start) {+ const auto &op = ops[pos];+ if (op.tag == ' ') {+ ++old_seen;+ ++new_seen;+ } else if (op.tag == '-') {+ ++old_seen;+ } else {+ ++new_seen;+ }+ ++pos;+ }+ std::size_t old_count = 0;+ std::size_t new_count = 0;+ for (std::size_t e = start; e < end; ++e) {+ if (ops[e].tag == ' ') {+ ++old_count;+ ++new_count;+ } else if (ops[e].tag == '-') {+ ++old_count;+ } else {+ ++new_count;+ }+ }+ const std::size_t old_start = old_seen + (old_count > 0 ? 1 : 0);+ const std::size_t new_start = new_seen + (new_count > 0 ? 1 : 0);+ std::cout << "@@ -" << old_start << "," << old_count << " +" << new_start+ << "," << new_count << " @@\n";+ while (pos < end) {+ const auto &op = ops[pos];+ if (op.tag == ' ') {+ std::cout << " " << a[op.ai] << "\n";+ ++old_seen;+ ++new_seen;+ } else if (op.tag == '-') {+ print_colored("-", Color::Red, false, false);+ print_colored(a[op.ai], Color::Red, false, false);+ std::cout << "\n";+ ++old_seen;+ } else {+ print_colored("+", Color::Green, false, false);+ print_colored(b[op.bi], Color::Green, false, false);+ std::cout << "\n";+ ++new_seen;+ }+ ++pos;+ }+ }+}++bool contains_nul(Bytes data) {+ const std::size_t limit = std::min<std::size_t>(data.size(), 8192);+ for (std::size_t i = 0; i < limit; ++i) {+ if (data[i] == 0)+ return true;+ }+ return false;+}++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);+ for (const auto &change : changes) {+ if (change.new_kind == KIND_CONFLICT) {+ std::cout << "Conflict: " << change.path << "\n";+ continue;+ }+ std::vector<std::uint8_t> old_data;+ std::vector<std::uint8_t> new_data;+ if (change.old_kind != KIND_MISSING && change.old_id) {+ if (auto data = read_blob(store, *change.old_id))+ old_data = std::move(*data);+ }+ if (change.new_kind != KIND_MISSING && change.new_id) {+ if (auto data = read_blob(store, *change.new_id))+ new_data = std::move(*data);+ }+ if (contains_nul(bytes_of(old_data)) || contains_nul(bytes_of(new_data))) {+ std::cout << "Binary files a/" << change.path << " and b/" << change.path+ << " differ\n";+ continue;+ }+ print_colored("--- ", Color::Red, false, false);+ if (change.old_kind == KIND_MISSING) {+ print_colored("/dev/null", Color::Red, false, false);+ } else {+ print_colored("a/", Color::Red, false, false);+ print_colored(change.path, Color::Red, false, false);+ }+ std::cout << "\n";+ print_colored("+++ ", Color::Green, false, false);+ if (change.new_kind == KIND_MISSING) {+ print_colored("/dev/null", Color::Green, false, false);+ } else {+ print_colored("b/", Color::Green, false, false);+ print_colored(change.path, Color::Green, false, false);+ }+ std::cout << "\n";+ const auto a = split_lines(bytes_of(old_data));+ const auto b = split_lines(bytes_of(new_data));+ render_unified(a, b);+ }+ if (announce_no_diff && changes.empty()) {+ info_prefix();+ std::cout << "no diff to show\n";+ }+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++int run_init(const std::vector<std::string> &args) {+ std::string path = ".";+ std::optional<std::string> source;+ 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.rfind("-git-import:", 0) == 0) {+ source = arg.substr(12);+ if (source->empty()) {+ error_prefix();+ std::cout << "-git-import: requires a path\n";+ return 1;+ }+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ path = arg;+ }+ }+ const auto initialized = init_repo(path_from_bytes(path));+ if (!initialized) {+ error_prefix();+ std::cout << "init failed with code " << initialized.error().offset << "\n";+ return 1;+ }+ info_prefix();+ std::cout << "initialized veins repository at " << path_display(*initialized)+ << "\n";+ if (source) {+ error_prefix();+ std::cout << "cannot prepare git mirror from " << *source << " (code 1)\n";+ return 1;+ }+ return 0;+}++int run_status() {+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto view = current_view(*root, store);+ if (!view) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ const auto wc = working_copy_id(*view);+ if (!wc) {+ info_prefix();+ std::cout << "working copy clean\n";+ return 0;+ }+ std::optional<Id> old_tree;+ std::optional<Id> new_tree;+ auto wc_body = store.read_body(*wc, TYPE_COMMIT);+ if (!wc_body) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ auto wc_commit = decode_commit(bytes_of(*wc_body));+ if (!wc_commit) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ new_tree = wc_commit->root_tree;+ if (!wc_commit->parents.empty()) {+ auto parent_body = store.read_body(wc_commit->parents.front(), TYPE_COMMIT);+ if (parent_body) {+ auto parent_commit = decode_commit(bytes_of(*parent_body));+ if (parent_commit)+ old_tree = parent_commit->root_tree;+ }+ }+ const auto changes = compare_trees(store, old_tree, new_tree);+ std::size_t conflicts = 0;+ for (const auto &change : changes) {+ if (change.old_kind == KIND_MISSING) {+ print_colored("A", Color::BrightGreen, false, false);+ std::cout << " " << change.path << "\n";+ } else if (change.new_kind == KIND_MISSING) {+ print_colored("D", Color::Red, false, false);+ std::cout << " " << change.path << "\n";+ } else if (change.new_kind == KIND_CONFLICT) {+ print_colored("C", Color::BrightRed, false, false);+ std::cout << " " << change.path << "\n";+ ++conflicts;+ } else {+ print_colored("M", Color::Cyan, false, false);+ std::cout << " " << change.path << "\n";+ }+ }+ if (changes.empty()) {+ info_prefix();+ std::cout << "working copy clean\n";+ }+ if (conflicts > 0)+ std::cout << conflicts << " conflict(s)\n";++ const std::vector<Id> start{*wc};+ const auto ancestry = collect_commits(store, start);+ std::size_t conflicted_commits = 0;+ for (const auto &id : ancestry) {+ auto loaded = load_commit(store, id);+ if (loaded && tree_conflicted(store, loaded->commit.root_tree))+ ++conflicted_commits;+ }+ if (conflicted_commits > 0)+ std::cout << conflicted_commits << " conflicted commit(s) in ancestry\n";+ return 0;+}++int run_log(const std::vector<std::string> &args) {+ std::string rev;+ bool col_titles = true;+ 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 == "-r" || arg == "-rev")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a revision\n";+ return 1;+ }+ rev = args[++i];+ } else if (!end_flags && arg == "-no-col-titles") {+ col_titles = false;+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ rev = arg;+ }+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto view = current_view(*root, store);+ if (!view) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ const auto wc = working_copy_id(*view);+ std::vector<Id> ids;+ if (rev.empty() || rev == "all()") {+ const auto roots = view_roots(*view);+ ids = collect_commits(store, roots);+ } else if (auto one = resolve_revision(store, *view, rev)) {+ const std::vector<Id> start{*one};+ ids = collect_commits(store, start);+ }++ struct Rec {+ Id id{};+ std::string change;+ std::int64_t seconds = 0;+ std::string message;+ std::string author;+ bool conflicted = false;+ bool has_changes = false;+ };+ std::vector<Rec> recs;+ for (const auto &id : ids) {+ auto loaded = load_commit(store, id);+ if (!loaded)+ continue;+ Rec rec;+ rec.id = id;+ rec.change = base32_encode(loaded->commit.change_id);+ rec.seconds = loaded->commit.committer.seconds;+ rec.message = first_line(loaded->commit.message);+ rec.author = loaded->commit.author.name;+ rec.conflicted = tree_conflicted(store, loaded->commit.root_tree);+ if (wc && std::memcmp(wc->data(), id.data(), ID_LEN) == 0)+ rec.has_changes = has_changes(store, *loaded);+ recs.push_back(std::move(rec));+ }+ std::stable_sort(recs.begin(), recs.end(), [](const Rec &a, const Rec &b) {+ return a.seconds > b.seconds;+ });++ std::vector<std::string> change_ids;+ for (const auto &rec : recs)+ change_ids.push_back(rec.change);+ std::size_t w_commit = 12;+ std::size_t w_change = 6;+ std::size_t w_date = 19;+ std::size_t w_author = 6;+ for (std::size_t i = 0; i < recs.size(); ++i) {+ const auto cid = short_change_id(change_ids, i);+ w_change = std::max(w_change, cid.size());+ w_author = std::max(w_author, recs[i].author.size());+ }+ if (col_titles) {+ print_cell("", 1, Color::Default, false);+ std::cout << " ";+ print_cell("Commit", w_commit, Color::Default, false);+ print_gap();+ print_cell("Change", w_change, Color::Default, false);+ print_gap();+ print_cell("Date", w_date, Color::Default, false);+ print_gap();+ print_cell("Author", w_author, Color::Default, false);+ print_gap();+ std::cout << "Message\n";+ }+ for (std::size_t i = 0; i < recs.size(); ++i) {+ const auto &rec = recs[i];+ const bool is_wc =+ wc && std::memcmp(wc->data(), rec.id.data(), ID_LEN) == 0;+ std::string marker = is_wc ? "@" : " ";+ Color marker_color = Color::Default;+ if (is_wc)+ marker_color = rec.has_changes ? Color::BrightCyan : Color::Red;+ const auto cid = short_change_id(change_ids, i);+ const auto stamp = format_utc(rec.seconds);+ print_cell(marker, 1, marker_color, false);+ std::cout << " ";+ print_cell(short_hex(rec.id), w_commit, Color::Red, false);+ print_gap();+ print_cell(cid, w_change, Color::Red, false);+ print_gap();+ print_cell(stamp, w_date, Color::Cyan, true);+ print_gap();+ print_cell(rec.author, w_author, Color::Cyan, false);+ print_gap();+ if (!rec.message.empty())+ print_colored(rec.message, Color::Green, false, false);+ else+ print_colored("<unset>", Color::BrightBlack, false, false);+ for (const auto &name : bookmark_names(*view, rec.id))+ std::cout << " [" << name << "]";+ for (const auto &name : tag_names(*view, rec.id))+ std::cout << " <" << name << ">";+ if (rec.conflicted)+ std::cout << " (conflicted)";+ bool divergent = false;+ for (std::size_t j = 0; j < recs.size(); ++j) {+ if (j != i && recs[j].change == rec.change) {+ divergent = true;+ break;+ }+ }+ if (divergent)+ std::cout << " (divergent)";+ std::cout << "\n";+ }+ return 0;+}++int run_show(const std::vector<std::string> &args) {+ std::string rev;+ bool col_titles = true;+ 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 == "-r" || arg == "-rev")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a revision\n";+ return 1;+ }+ rev = args[++i];+ } else if (!end_flags && arg == "-no-col-titles") {+ col_titles = false;+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ rev = arg;+ }+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto view = current_view(*root, store);+ if (!view) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ auto target = resolve_revision(store, *view, rev);+ if (!target) {+ error_prefix();+ if (rev.empty())+ std::cout << "no working-copy commit\n";+ else+ std::cout << "unknown revision: " << rev << "\n";+ return 1;+ }+ auto loaded = load_commit(store, *target);+ if (!loaded) {+ error_prefix();+ std::cout << "cannot read commit\n";+ return 1;+ }+ if (col_titles) {+ std::cout << "commit " << hex_encode(*target) << "\n";+ std::cout << "change " << base32_encode(loaded->commit.change_id) << "\n";+ std::cout << "author " << loaded->commit.author.name << " <"+ << loaded->commit.author.email << ">\n";+ std::cout << "date " << format_utc(loaded->commit.committer.seconds)+ << "\n";+ std::cout << "parents ";+ if (loaded->commit.parents.empty()) {+ std::cout << "<none>";+ } else {+ for (std::size_t i = 0; i < loaded->commit.parents.size(); ++i) {+ if (i != 0)+ std::cout << " ";+ std::cout << short_hex(loaded->commit.parents[i]);+ }+ }+ std::cout << "\n";+ const auto names = bookmark_names(*view, *target);+ if (!names.empty()) {+ std::cout << "bookmarks";+ for (const auto &name : names)+ std::cout << " [" << name << "]";+ std::cout << "\n";+ }+ std::cout << "\n";+ if (!loaded->commit.message.empty())+ std::cout << loaded->commit.message << "\n";+ else+ std::cout << "<unset>\n";+ std::cout << "\n";+ }+ std::optional<Id> old_tree;+ if (!loaded->commit.parents.empty()) {+ auto parent = load_commit(store, loaded->commit.parents.front());+ if (parent)+ old_tree = parent->commit.root_tree;+ }+ render_diff(store, old_tree, loaded->commit.root_tree, false);+ return 0;+}++int run_hash(const std::vector<std::string> &args) {+ std::string rev;+ bool short_hash = 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 == "-short") {+ short_hash = true;+ } else if (!end_flags && arg == "-long") {+ short_hash = false;+ } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a revision\n";+ return 1;+ }+ rev = args[++i];+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ rev = arg;+ }+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto view = current_view(*root, store);+ if (!view) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ auto target = resolve_revision(store, *view, rev);+ if (!target) {+ error_prefix();+ if (rev.empty())+ std::cout << "no working-copy commit\n";+ else+ std::cout << "unknown revision: " << rev << "\n";+ return 1;+ }+ const auto hex = hex_encode(*target);+ std::cout << hex.substr(0, short_hash ? 12 : 64) << "\n";+ return 0;+}++bool print_tree(const fs::path &root, Store &store, const Id &tree_id,+ const std::string &prefix, std::size_t depth) {+ if (depth > 4096)+ return false;+ auto body = store.read_body(tree_id, TYPE_TREE);+ if (!body)+ return false;+ auto tree = decode_tree(bytes_of(*body));+ if (!tree)+ return false;+ for (std::size_t i = 0; i < tree->entries.size(); ++i) {+ const auto &entry = tree->entries[i];+ const bool last = i + 1 == tree->entries.size();+ std::cout << prefix << (last ? "`-- " : "|-- ") << entry.name << "\n";+ if (entry.kind == KIND_SUBTREE) {+ if (!print_tree(root, store, entry.target,+ prefix + (last ? " " : "| "), depth + 1))+ return false;+ }+ }+ return true;+}++int run_ls(const std::vector<std::string> &args) {+ std::string rev;+ bool plain = 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 == "-plain" || arg == "-p")) {+ plain = true;+ } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a revision\n";+ return 1;+ }+ rev = args[++i];+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ rev = arg;+ }+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto view = current_view(*root, store);+ if (!view) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ auto target = resolve_revision(store, *view, rev);+ if (!target) {+ error_prefix();+ if (rev.empty())+ std::cout << "no working-copy commit\n";+ else+ std::cout << "unknown revision: " << rev << "\n";+ return 1;+ }+ auto loaded = load_commit(store, *target);+ if (!loaded) {+ error_prefix();+ std::cout << "cannot read commit\n";+ return 1;+ }+ bool good = true;+ if (plain) {+ auto entries = flatten_tree_checked(store, loaded->commit.root_tree);+ if (!entries) {+ good = false;+ } else {+ for (const auto &entry : *entries)+ std::cout << entry.path << "\n";+ }+ } else {+ std::cout << ".\n";+ good = print_tree(*root, store, loaded->commit.root_tree, "", 0);+ }+ if (!good) {+ error_prefix();+ std::cout << "cannot read tree\n";+ return 1;+ }+ return 0;+}++int run_diff(const std::vector<std::string> &args) {+ std::vector<std::string> revs;+ 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 == "-r" || arg == "-rev")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a revision\n";+ return 1;+ }+ 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);+ }+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto view = current_view(*root, store);+ if (!view) {+ error_prefix();+ std::cout << "no operation state\n";+ return 1;+ }+ std::optional<Id> old_tree;+ std::optional<Id> new_tree;+ bool failed = false;+ auto tree_of = [&](const Id &id) -> std::optional<Id> {+ auto loaded = load_commit(store, id);+ if (!loaded)+ return std::nullopt;+ return loaded->commit.root_tree;+ };+ auto parent_tree_of = [&](const Id &id) -> std::optional<Id> {+ auto loaded = load_commit(store, id);+ if (!loaded || loaded->commit.parents.empty())+ return std::nullopt;+ auto parent = load_commit(store, loaded->commit.parents.front());+ if (!parent)+ return std::nullopt;+ return parent->commit.root_tree;+ };+ if (revs.size() >= 2) {+ auto a = resolve_revision(store, *view, revs[0]);+ auto b = resolve_revision(store, *view, revs[1]);+ if (!a || !b)+ failed = true;+ else {+ old_tree = tree_of(*a);+ new_tree = tree_of(*b);+ }+ } else if (revs.size() == 1) {+ auto a = resolve_revision(store, *view, revs[0]);+ if (!a)+ failed = true;+ else {+ old_tree = parent_tree_of(*a);+ new_tree = tree_of(*a);+ }+ } else {+ const auto wc = working_copy_id(*view);+ if (wc) {+ old_tree = parent_tree_of(*wc);+ new_tree = tree_of(*wc);+ }+ }+ if (failed) {+ error_prefix();+ std::cout << "unknown revision\n";+ return 1;+ }+ render_diff(store, old_tree, new_tree, true);+ return 0;+}++int run_new(const std::vector<std::string> &args) {+ std::vector<std::string> revs;+ 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 && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ revs.push_back(arg);+ }+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto tx = Txn::begin(*root, store);+ if (!tx) {+ error_prefix();+ std::cout << "cannot load repository state\n";+ return 1;+ }+ const auto wc = working_copy_id(tx->view());+ std::optional<Id> old_root;+ std::vector<Id> parents;+ std::optional<Id> root_tree;+ if (revs.empty()) {+ if (!wc) {+ error_prefix();+ std::cout << "no working-copy commit\n";+ return 1;+ }+ auto loaded = load_commit(store, *wc);+ if (!loaded) {+ error_prefix();+ std::cout << "cannot read working-copy commit\n";+ return 1;+ }+ parents.push_back(*wc);+ root_tree = loaded->commit.root_tree;+ old_root = root_tree;+ } else {+ for (std::size_t i = 0; i < revs.size(); ++i) {+ auto resolved = resolve_revision(store, tx->view(), revs[i]);+ if (!resolved) {+ error_prefix();+ std::cout << "unknown revision\n";+ return 1;+ }+ parents.push_back(*resolved);+ if (i == 0) {+ auto loaded = load_commit(store, *resolved);+ if (!loaded) {+ error_prefix();+ std::cout << "unknown revision\n";+ return 1;+ }+ root_tree = loaded->commit.root_tree;+ }+ }+ if (wc) {+ auto old_loaded = load_commit(store, *wc);+ if (old_loaded)+ old_root = old_loaded->commit.root_tree;+ }+ }+ const Sig sig = identity_signature(*root);+ Commit commit;+ commit.version = 1;+ commit.parents = parents;+ commit.root_tree = *root_tree;+ commit.change_id = random_change_id();+ commit.author = sig;+ commit.committer = sig;+ commit.message = "";+ commit.renames_state = RENAMES_RECORDED;+ const auto encoded = encode_commit(commit);+ const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+ if (wc)+ remove_head(tx->view(), *wc);+ set_workspace(tx->view(), new_id);+ rebuild_heads(tx->view());+ const auto status = tx->finish("new");+ if (!status)+ return 1;+ store.refresh(*root);+ (void)mark_native(*root, new_id);+ if (!revs.empty()) {+ const int materialized =+ checkout_materialize_commit(*root, store, old_root, *root_tree);+ if (materialized != 0)+ return materialized;+ }+ return 0;+}++int describe_impl(const fs::path &root, Store &store,+ const std::vector<std::string> &parts, bool require_changes) {+ const int snap = snapshot_run(root, store);+ if (snap != 0)+ return snap;+ auto tx = Txn::begin(root, store);+ if (!tx) {+ error_prefix();+ std::cout << "cannot load repository state\n";+ return 1;+ }+ const auto wc = working_copy_id(tx->view());+ if (!wc) {+ error_prefix();+ std::cout << "no working-copy commit\n";+ return 1;+ }+ auto loaded = load_commit(store, *wc);+ if (!loaded) {+ error_prefix();+ std::cout << "cannot read working-copy commit\n";+ return 1;+ }+ const std::string message = join_args(parts);+ const bool changed = has_changes(store, *loaded);+ const bool same_message = message == loaded->commit.message;+ if (!changed && (require_changes || same_message)) {+ if (require_changes) {+ info_prefix();+ std::cout << "nothing to commit, working copy clean\n";+ return 2;+ }+ return 0;+ }+ const Sig sig = identity_signature(root);+ Commit commit = loaded->commit;+ commit.committer = sig;+ commit.message = message;+ const auto encoded = encode_commit(commit);+ const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+ remove_head(tx->view(), *wc);+ move_bookmarks(tx->view(), *wc, new_id);+ set_workspace(tx->view(), new_id);+ rebuild_heads(tx->view());+ const auto status = tx->finish("describe");+ if (!status)+ return 1;+ store.refresh(root);+ (void)mark_native(root, new_id);+ return 0;+}++int run_describe(const std::vector<std::string> &args) {+ auto parsed = parse_message(args, 2);+ if (!parsed)+ return 1;+ const auto root = open_repo();+ if (!root)+ return 1;+ Store store = Store::open_all(*root);+ return describe_impl(*root, store, *parsed, false);+}++int run_commit(const std::vector<std::string> &args) {+ auto parsed = parse_message(args, 2);+ if (!parsed)+ return 1;+ if (message_is_blank(*parsed)) {+ error_prefix();+ std::cout << "commit requires a non-empty message (-message)\n";+ return 1;+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ Store store = Store::open_all(*root);+ const int described = describe_impl(*root, store, *parsed, true);+ if (described == 2)+ return 0;+ if (described != 0)+ return described;++ auto tx = Txn::begin(*root, store);+ if (!tx) {+ error_prefix();+ std::cout << "cannot load repository state\n";+ return 1;+ }+ const auto wc = working_copy_id(tx->view());+ if (!wc) {+ error_prefix();+ std::cout << "no working-copy commit\n";+ return 1;+ }+ auto loaded = load_commit(store, *wc);+ if (!loaded) {+ error_prefix();+ std::cout << "cannot read working-copy commit\n";+ return 1;+ }+ const Sig sig = identity_signature(*root);+ Commit commit;+ commit.version = 1;+ commit.parents = {*wc};+ commit.root_tree = loaded->commit.root_tree;+ commit.change_id = random_change_id();+ commit.author = sig;+ commit.committer = sig;+ commit.message = "";+ commit.renames_state = RENAMES_RECORDED;+ const auto encoded = encode_commit(commit);+ const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+ remove_head(tx->view(), *wc);+ set_workspace(tx->view(), new_id);+ rebuild_heads(tx->view());+ const auto status = tx->finish("new");+ if (!status)+ return 1;+ (void)mark_native(*root, new_id);+ return 0;+}++std::optional<Id> mapped_id(const std::vector<Id> &old_ids,+ const std::vector<Id> &new_ids, const Id &id) {+ for (std::size_t i = 0; i < old_ids.size(); ++i) {+ if (std::memcmp(old_ids[i].data(), id.data(), ID_LEN) == 0)+ return new_ids[i];+ }+ return std::nullopt;+}++void remap_ids(const std::vector<Id> &old_ids, const std::vector<Id> &new_ids,+ std::vector<std::optional<Id>> &ids) {+ for (auto &id : ids) {+ if (!id)+ continue;+ if (auto mapped = mapped_id(old_ids, new_ids, *id))+ id = *mapped;+ }+}++int run_amend(const std::vector<std::string> &args) {+ std::string rev;+ std::vector<std::string> parts;+ 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 == "-m" || arg == "-message")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a message\n";+ return 1;+ }+ parts.push_back(args[++i]);+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (rev.empty()) {+ rev = arg;+ } else {+ parts.push_back(arg);+ }+ }+ if (rev.empty()) {+ error_prefix();+ std::cout << "amend requires a revision\n";+ return 1;+ }+ if (message_is_blank(parts)) {+ error_prefix();+ std::cout << "amend requires a non-empty message (-message)\n";+ return 1;+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ auto tx = Txn::begin(*root, store);+ if (!tx) {+ error_prefix();+ std::cout << "cannot load repository state\n";+ return 1;+ }+ auto target = resolve_revision(store, tx->view(), rev);+ if (!target) {+ error_prefix();+ std::cout << "unknown revision\n";+ return 1;+ }+ std::vector<Id> pushed_roots;+ for (const auto &ref : tx->view().remote_refs)+ pushed_roots.push_back(ref.target);+ if (!pushed_roots.empty() &&+ contains_id(collect_commits(store, pushed_roots), *target)) {+ error_prefix();+ std::cout << "cannot amend a revision that has been pushed\n";+ return 1;+ }+ auto target_loaded = load_commit(store, *target);+ if (!target_loaded) {+ error_prefix();+ std::cout << "cannot read revision\n";+ return 1;+ }+ const std::string message = join_args(parts);+ if (target_loaded->commit.message == message) {+ info_prefix();+ std::cout << "message unchanged\n";+ return 0;+ }+ auto remaining = all_commits(store, tx->view());+ std::vector<Id> old_ids;+ std::vector<Id> new_ids;+ const Sig sig = identity_signature(*root);+ bool target_rewritten = false;+ bool failed = false;+ while (!remaining.empty() && !failed) {+ std::optional<std::size_t> ready;+ for (std::size_t i = 0; i < remaining.size(); ++i) {+ bool is_ready =+ std::memcmp(remaining[i].data(), target->data(), ID_LEN) == 0;+ if (!is_ready) {+ auto loaded = load_commit(store, remaining[i]);+ if (loaded) {+ for (const auto &parent : loaded->commit.parents) {+ if (contains_id(old_ids, parent)) {+ is_ready = true;+ break;+ }+ }+ }+ }+ if (is_ready) {+ ready = i;+ break;+ }+ }+ if (!ready)+ break;+ const Id chosen = remaining[*ready];+ auto loaded = load_commit(store, chosen);+ if (!loaded) {+ failed = true;+ break;+ }+ std::vector<Id> new_parents;+ for (const auto &parent : loaded->commit.parents) {+ if (auto mapped = mapped_id(old_ids, new_ids, parent))+ new_parents.push_back(*mapped);+ else+ new_parents.push_back(parent);+ }+ Commit commit = loaded->commit;+ commit.parents = new_parents;+ commit.committer = sig;+ if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)+ commit.message = message;+ const auto encoded = encode_commit(commit);+ const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+ old_ids.push_back(chosen);+ new_ids.push_back(new_id);+ if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)+ target_rewritten = true;+ remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(*ready));+ }+ if (failed || !target_rewritten) {+ error_prefix();+ std::cout << "cannot amend revision\n";+ return 1;+ }+ for (auto &bookmark : tx->view().bookmarks) {+ remap_ids(old_ids, new_ids, bookmark.targets.adds);+ remap_ids(old_ids, new_ids, bookmark.targets.removes);+ }+ for (auto &tag : tx->view().tags) {+ if (auto mapped = mapped_id(old_ids, new_ids, tag.target))+ tag.target = *mapped;+ }+ for (auto &workspace : tx->view().working_copies) {+ if (auto mapped = mapped_id(old_ids, new_ids, workspace.target))+ workspace.target = *mapped;+ }+ for (auto &ref : tx->view().remote_refs) {+ if (auto mapped = mapped_id(old_ids, new_ids, ref.target))+ ref.target = *mapped;+ }+ rebuild_heads(tx->view());+ const auto status = tx->finish("amend " + rev);+ if (!status)+ return 1;+ for (const auto &id : new_ids)+ (void)mark_native(*root, id);+ return 0;+}++int run_checkout(const std::vector<std::string> &args) {+ std::string rev;+ 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 && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (rev.empty()) {+ rev = arg;+ }+ }+ const auto root = open_repo();+ if (!root)+ return 1;+ return checkout_run(*root, rev);+}++int run_fsck(const std::vector<std::string> &args) {+ std::string path = ".";+ bool verbose = 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 == "-v" || arg == "-verbose")) {+ verbose = true;+ } else if (!end_flags && is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ path = arg;+ }+ }+ const auto root = discover_repo(path_from_bytes(path));+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository: " << path << "\n";+ return 1;+ }+ return fsck_repository(*root, verbose);+}++int run_self_test() {+ auto fail = [](std::string_view why) {+ error_prefix();+ std::cout << "self-test: failed: " << why << "\n";+ return 1;+ };+ const auto empty_hash = blake3_hash(Bytes{});+ const std::string expected_empty =+ "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";+ if (hex_encode(Bytes(empty_hash.data(), empty_hash.size())) != expected_empty)+ return fail("blake3 vector");+ const auto &gear = fastcdc_gear();+ if (gear[0] != 0xf8447b379cdadcd5ull || gear[1] != 0xbe63d125aec8ca6dull)+ return fail("fastcdc gear table");++ BlobBuild build = build_blob(bytes_of(std::string("hello world")));+ if (!build.objects.empty()) {+ auto body = build.objects.back().body;+ auto decoded = decode_blob(bytes_of(body));+ if (!decoded || decoded->form != BlobForm::Inline)+ return fail("blob round trip");+ }+ Tree tree;+ tree.entries.push_back(TreeEntry{"a.txt", KIND_FILE, build.root});+ auto tree_body = encode_tree(tree.entries);+ if (!tree_body)+ return fail("tree encode");+ auto decoded_tree = decode_tree(bytes_of(*tree_body));+ if (!decoded_tree || decoded_tree->entries.size() != 1)+ return fail("tree round trip");++ std::vector<RawObject> objects;+ objects.push_back(RawObject{TYPE_TREE, *tree_body,+ object_id(TYPE_TREE, bytes_of(*tree_body))});+ PackOutput pack = encode_pack(objects);+ auto decoded_pack = decode_pack(pack.pack);+ if (!decoded_pack)+ return fail("pack decode");+ auto decoded_index = decode_index(pack.index, decoded_pack->trailer);+ if (!decoded_index)+ return fail("index decode");+ if (decoded_index->ids.size() != 1)+ return fail("index count");++ info_prefix();+ std::cout << "self-test: ok\n";+ return 0;+}++// ---------------------------------------------------------------------------+// inf+// ---------------------------------------------------------------------------++struct ExtStat {+ std::string ext;+ std::uint64_t files = 0;+ std::uint64_t lines = 0;+ std::uint64_t bytes = 0;+};++struct AuthorStat {+ std::string name;+ std::uint64_t commits = 0;+};++std::uint64_t percent(std::uint64_t num, std::uint64_t total) {+ if (total == 0)+ return 0;+ return (num * 100 + total / 2) / total;+}++void print_percent(std::uint64_t pct) {+ if (pct < 10)+ std::cout << " " << pct;+ else if (pct < 100)+ std::cout << " " << pct;+ else+ std::cout << pct;+}++Color color_for(std::size_t i) {+ static const Color colors[] = {Color::BrightCyan, Color::BrightGreen,+ Color::BrightYellow, Color::BrightMagenta,+ Color::BrightBlue, Color::BrightRed,+ Color::Cyan, Color::Green};+ return colors[i % 8];+}++void print_bar(std::uint64_t num, std::uint64_t total, Color color) {+ std::uint64_t filled = 0;+ if (total > 0 && num > 0) {+ filled = (num * 24 + total / 2) / total;+ if (filled == 0)+ filled = 1;+ if (filled > 24)+ filled = 24;+ }+ for (std::uint64_t i = 0; i < filled; ++i)+ print_colored("\xe2\x96\x88", color, false, false);+ for (std::uint64_t i = filled; i < 24; ++i)+ print_colored("\xe2\x96\x91", Color::BrightBlack, false, false);+}++void print_left(std::string_view text, std::size_t width, Color color,+ bool dim) {+ if (dim)+ print_styled(text, color, true, false);+ else if (color == Color::Default)+ std::cout << text;+ else+ print_colored(text, color, false, false);+ for (std::size_t i = text.size(); i < width; ++i)+ std::cout << ' ';+}++void row_value(std::string_view label, std::string_view value) {+ print_left(label, 14, Color::Default, true);+ std::cout << value << "\n";+}++void row_number(std::string_view label, std::uint64_t value) {+ print_left(label, 14, Color::Default, true);+ std::cout << value << "\n";+}++std::string ext_of(std::string_view path) {+ std::size_t base_start = 0;+ for (std::size_t i = 0; i < path.size(); ++i) {+ if (path[i] == '/')+ base_start = i + 1;+ }+ std::optional<std::size_t> dot;+ for (std::size_t i = base_start; i < path.size(); ++i) {+ if (path[i] == '.')+ dot = i;+ }+ if (!dot || *dot <= base_start || *dot + 1 >= path.size())+ return "(none)";+ std::string out(path.substr(*dot));+ for (char &c : out) {+ if (c >= 'A' && c <= 'Z')+ c = static_cast<char>(c + 32);+ }+ return out;+}++bool looks_binary(Bytes data) {+ const std::size_t limit = std::min<std::size_t>(data.size(), 8192);+ for (std::size_t i = 0; i < limit; ++i)+ if (data[i] == 0)+ return true;+ return false;+}++std::uint64_t count_nonblank(Bytes data) {+ std::uint64_t count = 0;+ std::size_t i = 0;+ while (i < data.size()) {+ std::size_t end = i;+ while (end < data.size() && data[end] != '\n')+ ++end;+ bool blank = true;+ for (std::size_t j = i; j < end; ++j) {+ if (data[j] != ' ' && data[j] != '\t' && data[j] != '\r') {+ blank = false;+ break;+ }+ }+ if (!blank)+ ++count;+ i = end >= data.size() ? data.size() : end + 1;+ }+ return count;+}++void add_ext_stat(std::vector<ExtStat> &stats, std::string_view path,+ std::uint64_t lines, std::uint64_t size) {+ const std::string ext = ext_of(path);+ for (auto &stat : stats) {+ if (stat.ext == ext) {+ ++stat.files;+ stat.lines += lines;+ stat.bytes += size;+ return;+ }+ }+ stats.push_back(ExtStat{ext, 1, lines, size});+}++std::uint64_t dir_size(const fs::path &path, std::size_t depth) {+ if (depth > 64)+ return 0;+ std::uint64_t total = 0;+ std::error_code ec;+ fs::recursive_directory_iterator it(path, ec);+ if (ec)+ return 0;+ for (const auto &entry : it) {+ if (entry.is_regular_file(ec)) {+ const auto size = entry.file_size(ec);+ if (!ec)+ total += size;+ }+ }+ return total;+}++void print_size(std::uint64_t n) {+ if (n >= 1073741824) {+ std::cout << n / 1073741824 << "." << ((n % 1073741824) * 10) / 1073741824+ << " GiB\n";+ } else if (n >= 1048576) {+ std::cout << n / 1048576 << "." << ((n % 1048576) * 10) / 1048576+ << " MiB\n";+ } else if (n >= 1024) {+ std::cout << n / 1024 << "." << ((n % 1024) * 10) / 1024 << " KiB\n";+ } else {+ std::cout << n << " B\n";+ }+}++void show_date(std::string_view label, std::int64_t seconds) {+ const std::string stamp = format_utc(seconds);+ print_left(label, 14, Color::Default, true);+ std::cout << stamp.substr(0, 10) << "\n";+}++int run_inf() {+ const auto root = open_repo();+ if (!root)+ return 1;+ Store store = Store::open_all(*root);+ auto view_opt = current_view(*root, store);+ View view = view_opt ? *view_opt : empty_view();+ const auto wc = working_copy_id(view);+ std::optional<Id> wc_tree;+ if (wc) {+ auto loaded = load_commit(store, *wc);+ if (loaded)+ wc_tree = loaded->commit.root_tree;+ }++ std::vector<ExtStat> exts;+ std::vector<AuthorStat> authors;+ std::uint64_t total_files = 0;+ std::uint64_t total_lines = 0;+ if (wc_tree) {+ for (const auto &entry : flatten_tree(store, *wc_tree)) {+ if (entry.kind != KIND_FILE && entry.kind != KIND_EXECUTABLE)+ continue;+ ++total_files;+ auto data = read_blob(store, entry.target);+ if (!data) {+ add_ext_stat(exts, entry.path, 0, 0);+ continue;+ }+ const std::uint64_t size = data->size();+ std::uint64_t lines = 0;+ if (!looks_binary(bytes_of(*data)))+ lines = count_nonblank(bytes_of(*data));+ total_lines += lines;+ add_ext_stat(exts, entry.path, lines, size);+ }+ }++ std::uint64_t commits = 0;+ bool has_time = false;+ std::int64_t created = 0;+ std::int64_t last = 0;+ const auto roots = view_roots(view);+ for (const auto &id : collect_commits(store, roots)) {+ auto loaded = load_commit(store, id);+ if (!loaded)+ continue;+ ++commits;+ const auto secs = loaded->commit.committer.seconds;+ if (!has_time) {+ created = secs;+ last = secs;+ has_time = true;+ } else {+ created = std::min(created, secs);+ last = std::max(last, secs);+ }+ std::string name = loaded->commit.author.name;+ if (name.empty())+ name = "(unknown)";+ bool found = false;+ for (auto &author : authors) {+ if (author.name == name) {+ ++author.commits;+ found = true;+ break;+ }+ }+ if (!found)+ authors.push_back(AuthorStat{name, 1});+ }++ std::cout << "\n";+ print_bold("Repository overview", Color::BrightCyan, false);+ std::cout << "\n\n";+ row_value("Project", basename_string(*root));+ print_left("HEAD", 14, Color::Default, true);+ if (wc)+ std::cout << short_hex(*wc) << "\n";+ else+ std::cout << "<none>\n";+ row_number("Changes", commits);+ row_number("Bookmarks", view.bookmarks.size());+ row_number("Tags", view.tags.size());+ row_number("Files", total_files);+ row_number("Lines", total_lines);+ row_number("Authors", authors.size());+ if (has_time) {+ show_date("Created", created);+ show_date("Last change", last);+ }+ print_left("Size", 14, Color::Default, true);+ print_size(dir_size(veins_dir(*root), 0));+ std::cout << "\n";++ print_bold("Languages", Color::BrightCyan, false);+ std::cout << "\n\n";+ if (exts.empty()) {+ std::cout << " no tracked files\n";+ } else {+ std::stable_sort(exts.begin(), exts.end(),+ [](const ExtStat &a, const ExtStat &b) {+ if (a.lines != b.lines)+ return a.lines > b.lines;+ return compare(bytes_of(a.ext), bytes_of(b.ext)) < 0;+ });+ std::size_t w_ext = 6;+ for (const auto &ext : exts)+ w_ext = std::max(w_ext, ext.ext.size());+ for (std::size_t i = 0; i < exts.size(); ++i) {+ const auto &ext = exts[i];+ print_left(ext.ext, w_ext, Color::Default, false);+ std::cout << " ";+ print_bar(ext.lines, total_lines, color_for(i));+ std::cout << " ";+ print_percent(percent(ext.lines, total_lines));+ std::cout << "% " << ext.lines << " lines " << ext.files << " files\n";+ }+ }+ std::cout << "\n";++ print_bold("Authors", Color::BrightCyan, false);+ std::cout << "\n\n";+ if (authors.empty()) {+ std::cout << " no commits\n";+ } else {+ std::stable_sort(authors.begin(), authors.end(),+ [](const AuthorStat &a, const AuthorStat &b) {+ if (a.commits != b.commits)+ return a.commits > b.commits;+ return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+ });+ std::size_t w_name = 6;+ for (const auto &author : authors)+ w_name = std::max(w_name, author.name.size());+ for (std::size_t i = 0; i < authors.size(); ++i) {+ const auto &author = authors[i];+ print_left(author.name, w_name, Color::Cyan, false);+ std::cout << " ";+ print_bar(author.commits, commits, color_for(i));+ std::cout << " ";+ print_percent(percent(author.commits, commits));+ std::cout << "% " << author.commits << " commits\n";+ }+ }+ std::cout << "\n";+ return 0;+}++// ---------------------------------------------------------------------------+// Help+// ---------------------------------------------------------------------------++void usage() {+ std::cout << "veins is a tool for managing source code\n";+ std::cout << "\n";+ std::cout << "subcommands:\n";+ std::cout << " init create a repository\n";+ std::cout << " git import from or export to git\n";+ std::cout << " remote manage native remotes\n";+ std::cout << " clone clone a repository over the native protocol\n";+ std::cout << " fetch fetch from a native remote\n";+ std::cout << " push push a bookmark to a native remote\n";+ std::cout << " serve run the native server over stdio or TLS\n";+ std::cout << " key manage local Ed25519 keys\n";+ std::cout << " auth remember keys for hosts and set a default\n";+ std::cout << " access manage a served repository's access file\n";+ std::cout << " whoami report the role granted by a server\n";+ std::cout << " co write a revision into the working directory; "+ "alias: checkout\n";+ std::cout << " stat show working-copy changes; alias: status\n";+ std::cout << " ls list tracked files\n";+ std::cout << " inf show a repository breakdown\n";+ 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 << " 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";+ std::cout << " resolve resolve a conflicted path\n";+ std::cout << " new start a new change\n";+ std::cout << " bmk manage named branch pointers\n";+ std::cout+ << " rm untrack paths, keeping files on disk by default\n";+ std::cout << " mv move a tracked file and record the rename\n";+ std::cout << " ex add paths or globs to .vnexclude\n";+ std::cout << " desc set the working-copy commit message; alias: "+ "describe\n";+ std::cout+ << " go describe and start a new change; alias: commit\n";+ std::cout+ << " amend rewrite a revision's message and its descendants\n";+ std::cout << " undo restore the previous operation view\n";+ std::cout << " op operation log commands\n";+ std::cout << " fsck verify repository integrity\n";+ std::cout << " self-test run the format self-tests\n";+ std::cout << " version print version information\n";+ std::cout << " bench-import compare lazy import metadata; requires git\n";+ std::cout << " help show help for a command\n";+ std::cout << "\n";+ std::cout << "run 'vn help <command>' for details\n";+}++void show_init() {+ std::cout << "usage: vn init [path] [-git-import:<gitdir>]\n\n";+ std::cout << "create a veins repository, optionally importing an existing "+ "git repository\n\n";+ std::cout << "arguments:\n";+ std::cout+ << " [path] directory to create (default: .)\n\n";+ std::cout << "options:\n";+ std::cout << " -git-import:<gitdir> import from <gitdir> (a directory "+ "containing .git)\n";+}++void show_status() {+ std::cout << "usage: vn stat\n\n";+ std::cout << "show working-copy changes relative to the parent commit\n\n";+ std::cout << "aliases: status\n";+}++void show_ls() {+ std::cout << "usage: vn ls [rev] [-plain]\n\n";+ std::cout << "list tracked files as an ASCII tree\n\n";+ std::cout << "arguments:\n";+ std::cout << " [rev] revision to list (default: @)\n\n";+ std::cout << "options:\n";+ std::cout << " -rev <rev> revision to list\n";+ std::cout << " -plain, -p print one tracked path per line\n";+}++void show_inf() {+ std::cout << "usage: vn inf\n\n";+ std::cout << "show a repository overview with a language breakdown by file "+ "extension,\n";+ std::cout+ << "line-of-code shares, author commit shares, and repository metadata\n";+}++void show_log() {+ std::cout << "usage: vn log [-rev <revset>] [-no-col-titles]\n\n";+ std::cout << "show commit history, newest first\n\n";+ std::cout << "options:\n";+ std::cout << " -rev <revset> show only the given revision set\n";+ std::cout << " -no-col-titles omit column titles\n";+}++void show_show() {+ std::cout << "usage: vn show [rev] [-no-col-titles]\n\n";+ std::cout+ << "show a commit's metadata and its diff against its first parent\n\n";+ std::cout << "arguments:\n";+ std::cout << " [rev] revision to show (default: @)\n\n";+ std::cout << "options:\n";+ std::cout << " -no-col-titles omit the metadata labels\n";+}++void show_hash() {+ std::cout << "usage: vn hash [rev] [-short|-long]\n\n";+ std::cout << "print the commit hash for a revision\n\n";+ std::cout << "arguments:\n";+ std::cout << " [rev] revision to hash (default: @)\n\n";+ std::cout << "options:\n";+ std::cout << " -rev <rev> revision to hash\n";+ std::cout << " -short print the 12-character abbreviated "+ "hash\n";+ std::cout << " -long print the full 64-character hash "+ "(default)\n";+}++void show_diff() {+ std::cout << "usage: vn diff [-rev <rev>] [<rev> <rev>]\n\n";+ std::cout << "show a unified diff\n";+}++void show_new() {+ std::cout << "usage: vn new [<rev>...]\n\n";+ std::cout+ << "start a new empty change on top of the working copy or a revision\n";+}++void show_describe() {+ std::cout << "usage: vn desc [-message <message>] [<message>]\n\n";+ std::cout << "set the working-copy commit message\n\n";+ std::cout << "aliases: describe\n";+}++void show_commit() {+ std::cout << "usage: vn go -message <message>\n\n";+ std::cout << "set the message and start a new change\n\n";+ std::cout << "a non-empty commit message is required\n\n";+ std::cout << "aliases: commit\n";+}++void show_amend() {+ std::cout << "usage: vn amend <rev> -m <message>\n\n";+ std::cout << "rewrite a revision's message and update its descendants\n\n";+ std::cout << "options:\n";+ std::cout << " -m, -message <message> new commit message\n\n";+ std::cout << "revisions reachable from a remote ref cannot be amended\n";+}++void show_checkout() {+ std::cout << "usage: vn co [rev]\n\n";+ std::cout << "write a revision into the working directory\n\n";+ std::cout << "aliases: checkout\n\n";+ std::cout << "arguments:\n";+ std::cout << " [rev] revision to check out\n";+}++void show_fsck() {+ std::cout << "usage: vn fsck [path] [-verbose]\n\n";+ std::cout << "verify pack, index, object, and operation-log integrity\n\n";+ std::cout << "arguments:\n";+ std::cout+ << " [path] repository to check (default: .)\n\n";+ std::cout << "options:\n";+ std::cout << " -v, -verbose print verbose output\n";+}++void show_selftest() {+ std::cout << "usage: vn self-test\n\n";+ std::cout << "run the format self-tests\n";+}++void show_version() {+ std::cout << "usage: vn version\n\n";+ std::cout << "print version information\n";+}++void show_help() {+ std::cout << "usage: vn help [command]\n\n";+ std::cout << "show help for the program or a command\n\n";+ std::cout << "arguments:\n";+ std::cout << " [command] command to describe\n";+}++void show_unimplemented(std::string_view command) {+ std::cout << "usage: vn " << command << "\n\n";+ std::cout << "this command is planned for a later stage of the C++ rewrite\n";+ std::cout << "and is not available in the current local-core build\n";+}++int run_help(const std::vector<std::string> &args) {+ if (args.size() <= 2) {+ usage();+ return 0;+ }+ const std::string &cmd = args[2];+ if (cmd == "init")+ show_init();+ else if (cmd == "stat" || cmd == "status")+ show_status();+ else if (cmd == "ls")+ show_ls();+ else if (cmd == "inf")+ show_inf();+ else if (cmd == "log")+ show_log();+ else if (cmd == "show")+ show_show();+ else if (cmd == "hash")+ show_hash();+ else if (cmd == "diff")+ show_diff();+ else if (cmd == "new")+ show_new();+ else if (cmd == "desc" || cmd == "describe")+ show_describe();+ else if (cmd == "go" || cmd == "commit")+ show_commit();+ else if (cmd == "amend")+ show_amend();+ else if (cmd == "co" || cmd == "checkout")+ show_checkout();+ else if (cmd == "fsck")+ show_fsck();+ else if (cmd == "self-test")+ show_selftest();+ else if (cmd == "version")+ show_version();+ else if (cmd == "help")+ show_help();+ else if (cmd == "git" || cmd == "remote" || cmd == "clone" ||+ cmd == "fetch" || cmd == "push" || cmd == "serve" || cmd == "key" ||+ cmd == "auth" || cmd == "access" || cmd == "whoami" ||+ cmd == "merge" || cmd == "rebase" || cmd == "xs" ||+ cmd == "resolve" || cmd == "bmk" || cmd == "rm" || cmd == "mv" ||+ cmd == "ex" || cmd == "undo" || cmd == "op" || cmd == "bench-import")+ show_unimplemented(cmd);+ else {+ usage();+ error_prefix();+ std::cout << "unknown command: " << cmd << "\n";+ return 1;+ }+ return 0;+}++} // namespace++int cli_run(const std::vector<std::string> &args) {+ if (args.size() < 2) {+ usage();+ return 1;+ }+ const std::string &cmd = args[1];+ if (cmd == "init")+ return run_init(args);+ if (cmd == "stat" || cmd == "status")+ return run_status();+ if (cmd == "ls")+ return run_ls(args);+ if (cmd == "inf")+ return run_inf();+ if (cmd == "log")+ return run_log(args);+ if (cmd == "show")+ return run_show(args);+ if (cmd == "hash")+ return run_hash(args);+ if (cmd == "diff")+ return run_diff(args);+ if (cmd == "new")+ return run_new(args);+ if (cmd == "desc" || cmd == "describe")+ return run_describe(args);+ if (cmd == "go" || cmd == "commit")+ return run_commit(args);+ if (cmd == "amend")+ return run_amend(args);+ if (cmd == "co" || cmd == "checkout")+ return run_checkout(args);+ if (cmd == "fsck")+ return run_fsck(args);+ if (cmd == "self-test")+ return run_self_test();+ if (cmd == "version" || cmd == "-version") {+ std::cout << "veins v" << VN_VERSION << " (veins-store 1)\n";+ return 0;+ }+ if (cmd == "help" || cmd == "-help" || cmd == "-h")+ return run_help(args);++ if (cmd == "git" || cmd == "remote" || cmd == "clone" || cmd == "fetch" ||+ cmd == "push" || cmd == "serve" || cmd == "key" || cmd == "auth" ||+ cmd == "access" || cmd == "whoami" || cmd == "merge" || cmd == "rebase" ||+ cmd == "xs" || cmd == "resolve" || cmd == "bmk" || cmd == "rm" ||+ cmd == "mv" || cmd == "ex" || cmd == "undo" || cmd == "op" ||+ cmd == "bench-import") {+ error_prefix();+ std::cout << "command '" << cmd << "' is not available in this stage\n";+ return 1;+ }+ usage();+ error_prefix();+ std::cout << "unknown command: " << cmd << "\n";+ return 1;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/cli.h@@ -0,0 +1,10 @@+#pragma once++#include <string>+#include <vector>++namespace vn {++int cli_run(const std::vector<std::string> &args);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/common.cpp@@ -0,0 +1,1622 @@+#include "common.h"++#include <algorithm>+#include <cerrno>+#include <cstdlib>+#include <ctime>+#include <fstream>+#include <iostream>+#include <random>+#include <sstream>+#include <thread>++#if defined(_WIN32)+#include <bcrypt.h>+#include <fcntl.h>+#include <io.h>+#include <windows.h>+#else+#include <dirent.h>+#include <fcntl.h>+#include <sys/random.h>+#include <sys/stat.h>+#include <sys/types.h>+#include <unistd.h>+#if defined(__linux__)+#include <sched.h>+#endif+#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \+ defined(__NetBSD__) || defined(__DragonFly__)+#include <stdlib.h>+#endif+#endif++namespace vn {++std::string_view error_kind_name(ErrorKind kind) {+ switch (kind) {+ case ErrorKind::None:+ return "none";+ case ErrorKind::UnexpectedEnd:+ return "unexpected end of input";+ case ErrorKind::VarintOverflow:+ return "varint overflow";+ case ErrorKind::NonMinimalVarint:+ return "non-minimal varint";+ case ErrorKind::InvalidValue:+ return "invalid value";+ case ErrorKind::LimitExceeded:+ return "format limit exceeded";+ case ErrorKind::InvalidName:+ return "invalid name";+ case ErrorKind::Duplicate:+ return "duplicate entry";+ case ErrorKind::Unsorted:+ return "entries are not sorted";+ case ErrorKind::TrailingBytes:+ return "trailing bytes";+ case ErrorKind::UnsupportedVersion:+ return "unsupported format version";+ case ErrorKind::InvalidMagic:+ return "bad file magic";+ case ErrorKind::HashMismatch:+ return "hash mismatch";+ case ErrorKind::Corrupt:+ return "corrupt data";+ case ErrorKind::Io:+ return "I/O error";+ case ErrorKind::Usage:+ return "usage error";+ }+ return "unknown error";+}++Error Error::decode(ErrorKind kind, std::size_t offset) {+ return Error{kind, offset, std::string(error_kind_name(kind))};+}+Error Error::io(std::string message) {+ return Error{ErrorKind::Io, 0, std::move(message)};+}+Error Error::usage(std::string message) {+ return Error{ErrorKind::Usage, 0, std::move(message)};+}++// ---------------------------------------------------------------------------+// Hex / base32+// ---------------------------------------------------------------------------++static char hex_digit(std::uint8_t v) {+ return static_cast<char>(v < 10 ? '0' + v : 'a' + (v - 10));+}++std::string hex_encode(Bytes data) {+ std::string out(data.size() * 2, '0');+ for (std::size_t i = 0; i < data.size(); ++i) {+ out[i * 2] = hex_digit(static_cast<std::uint8_t>(data[i] >> 4));+ out[i * 2 + 1] = hex_digit(static_cast<std::uint8_t>(data[i] & 15));+ }+ return out;+}++std::string hex_encode(const Id &id) {+ return hex_encode(Bytes(id.data(), id.size()));+}++static int hex_value(char c) {+ if (c >= '0' && c <= '9')+ return c - '0';+ if (c >= 'a' && c <= 'f')+ return c - 'a' + 10;+ if (c >= 'A' && c <= 'F')+ return c - 'A' + 10;+ return -1;+}++bool hex_decode(std::string_view text, MutBytes out) {+ if (text.size() != out.size() * 2)+ return false;+ for (std::size_t i = 0; i < out.size(); ++i) {+ const int hi = hex_value(text[i * 2]);+ const int lo = hex_value(text[i * 2 + 1]);+ if (hi < 0 || lo < 0)+ return false;+ out[i] = static_cast<std::uint8_t>((hi << 4) | lo);+ }+ return true;+}++std::optional<Id> parse_id(std::string_view hex) {+ if (hex.size() != ID_LEN * 2)+ return std::nullopt;+ Id id{};+ if (!hex_decode(hex, MutBytes(id.data(), id.size())))+ return std::nullopt;+ return id;+}++std::string base32_encode(const ChangeId &id) {+ static constexpr char alphabet[] = "abcdefghijklmnopqrstuvwxyz234567";+ std::string out;+ out.reserve(26);+ std::uint64_t buffer = 0;+ std::size_t bits = 0;+ for (std::uint8_t c : id) {+ buffer = (buffer << 8) | c;+ bits += 8;+ while (bits >= 5) {+ const std::size_t shift = bits - 5;+ const std::size_t index = (buffer >> shift) & 31u;+ out.push_back(alphabet[index]);+ bits = shift;+ }+ if (bits == 0) {+ buffer = 0;+ } else {+ buffer &= (std::uint64_t{1} << bits) - 1;+ }+ }+ if (bits > 0) {+ out.push_back(alphabet[(buffer << (5 - bits)) & 31u]);+ }+ return out;+}++bool base32_prefix_matches(std::string_view full, std::string_view prefix) {+ if (prefix.empty() || prefix.size() > full.size())+ return false;+ for (std::size_t i = 0; i < prefix.size(); ++i) {+ char c = prefix[i];+ if (c >= 'A' && c <= 'Z')+ c = static_cast<char>(c + 32);+ if (full[i] != c)+ return false;+ }+ return true;+}++// ---------------------------------------------------------------------------+// Hashing and randomness+// ---------------------------------------------------------------------------++std::array<std::uint8_t, 32> blake3_hash(Bytes data) {+ std::array<std::uint8_t, 32> out{};+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ if (!data.empty())+ blake3_hasher_update(&hasher, data.data(), data.size());+ blake3_hasher_finalize(&hasher, out.data(), out.size());+ return out;+}++Id object_id(std::uint8_t type_byte, Bytes body) {+ static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n',+ 's', '/', '1', 0};+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ blake3_hasher_update(&hasher, prefix, sizeof(prefix));+ blake3_hasher_update(&hasher, &type_byte, 1);+ if (!body.empty())+ blake3_hasher_update(&hasher, body.data(), body.size());+ Id out{};+ blake3_hasher_finalize(&hasher, out.data(), out.size());+ return out;+}++static void os_random_bytes(MutBytes out) {+#if defined(_WIN32)+ if (BCryptGenRandom(nullptr, out.data(), static_cast<ULONG>(out.size()),+ BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0) {+ return;+ }+#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \+ defined(__NetBSD__) || defined(__DragonFly__)+ arc4random_buf(out.data(), out.size());+ return;+#else+ std::size_t done = 0;+ while (done < out.size()) {+ const ssize_t n = ::getrandom(out.data() + done, out.size() - done, 0);+ if (n > 0) {+ done += static_cast<std::size_t>(n);+ continue;+ }+ if (n < 0 && errno == EINTR)+ continue;+ break;+ }+ if (done == out.size())+ return;+#endif+ std::random_device rd;+ for (std::size_t i = 0; i < out.size(); ++i) {+ out[i] = static_cast<std::uint8_t>(rd());+ }+}++std::array<std::uint8_t, 16> random_change_id() {+ std::array<std::uint8_t, 16> out{};+ os_random_bytes(MutBytes(out.data(), out.size()));+ return out;+}++std::uint64_t random_u64() {+ std::uint64_t value = 0;+ os_random_bytes(+ MutBytes(reinterpret_cast<std::uint8_t *>(&value), sizeof(value)));+ return value;+}++// ---------------------------------------------------------------------------+// Reader / writer+// ---------------------------------------------------------------------------++Result<std::uint8_t> Reader::u8() {+ if (pos_ >= data_.size())+ return fail(ErrorKind::UnexpectedEnd, pos_);+ return data_[pos_++];+}++Result<std::uint16_t> Reader::u16le() {+ if (remaining() < 2)+ return fail(ErrorKind::UnexpectedEnd, pos_);+ const auto v = static_cast<std::uint16_t>(+ static_cast<std::uint16_t>(data_[pos_]) |+ static_cast<std::uint16_t>(static_cast<std::uint16_t>(data_[pos_ + 1])+ << 8));+ pos_ += 2;+ return v;+}++Result<std::uint32_t> Reader::u32le() {+ if (remaining() < 4)+ return fail(ErrorKind::UnexpectedEnd, pos_);+ std::uint32_t v = 0;+ for (std::size_t i = 0; i < 4; ++i) {+ v |= static_cast<std::uint32_t>(data_[pos_ + i]) << (i * 8);+ }+ pos_ += 4;+ return v;+}++Result<std::uint64_t> Reader::u64le() {+ if (remaining() < 8)+ return fail(ErrorKind::UnexpectedEnd, pos_);+ std::uint64_t v = 0;+ for (int i = 0; i < 8; ++i) {+ v |= static_cast<std::uint64_t>(data_[pos_ + static_cast<std::size_t>(i)])+ << (i * 8);+ }+ pos_ += 8;+ return v;+}++Result<std::int16_t> Reader::i16le() {+ const auto v = u16le();+ if (!v)+ return unexpected(v.error());+ return static_cast<std::int16_t>(*v);+}++Result<std::int64_t> Reader::i64le() {+ const auto v = u64le();+ if (!v)+ return unexpected(v.error());+ return static_cast<std::int64_t>(*v);+}++Result<std::uint64_t> Reader::varint() {+ const std::size_t start = pos_;+ std::uint64_t value = 0;+ unsigned shift = 0;+ for (unsigned i = 0; i < 10; ++i) {+ const auto b = u8();+ if (!b)+ return unexpected(b.error());+ const std::uint64_t low = static_cast<std::uint64_t>(*b & 127u);+ if (shift == 63 && low > 1)+ return fail(ErrorKind::VarintOverflow, start);+ value |= low << shift;+ if ((*b & 128u) == 0) {+ if (i > 0 && low == 0)+ return fail(ErrorKind::NonMinimalVarint, start);+ return value;+ }+ shift += 7;+ }+ return fail(ErrorKind::VarintOverflow, start);+}++Result<Bytes> Reader::raw(std::size_t n) {+ if (n > remaining())+ return fail(ErrorKind::UnexpectedEnd, pos_);+ const Bytes out = data_.subspan(pos_, n);+ pos_ += n;+ return out;+}++Result<Bytes> Reader::bytes(std::size_t max_len) {+ const std::size_t at = pos_;+ const auto n = varint();+ if (!n)+ return unexpected(n.error());+ if (*n > max_len)+ return fail(ErrorKind::LimitExceeded, at);+ if (*n > remaining())+ return fail(ErrorKind::UnexpectedEnd, at);+ return raw(static_cast<std::size_t>(*n));+}++Result<std::string> Reader::string_bytes(std::size_t max_len) {+ const auto b = bytes(max_len);+ if (!b)+ return unexpected(b.error());+ return std::string(str_of(*b));+}++Result<std::size_t> Reader::list_len(std::size_t max) {+ const std::size_t at = pos_;+ const auto n = varint();+ if (!n)+ return unexpected(n.error());+ if (*n > max)+ return fail(ErrorKind::LimitExceeded, at);+ return static_cast<std::size_t>(*n);+}++Result<Id> Reader::id() {+ const auto b = raw(ID_LEN);+ if (!b)+ return unexpected(b.error());+ Id out{};+ std::memcpy(out.data(), b->data(), ID_LEN);+ return out;+}++Result<std::optional<Id>> Reader::opt_id() {+ const std::size_t at = pos_;+ const auto tag = u8();+ if (!tag)+ return unexpected(tag.error());+ if (*tag == 0)+ return std::optional<Id>{};+ if (*tag != 1)+ return fail(ErrorKind::InvalidValue, at);+ const auto value = id();+ if (!value)+ return unexpected(value.error());+ return std::optional<Id>(*value);+}++Result<void> Reader::finish() {+ if (pos_ != data_.size())+ return fail(ErrorKind::TrailingBytes, pos_);+ return {};+}++Result<Reader::Sig> Reader::sig(std::size_t max_name, std::size_t max_email) {+ Sig out;+ const auto name = string_bytes(max_name);+ if (!name)+ return unexpected(name.error());+ const auto email = string_bytes(max_email);+ if (!email)+ return unexpected(email.error());+ const auto secs = i64le();+ if (!secs)+ return unexpected(secs.error());+ const auto tz = i16le();+ if (!tz)+ return unexpected(tz.error());+ out.name = *name;+ out.email = *email;+ out.seconds = *secs;+ out.tz_min = *tz;+ return out;+}++Result<Reader::TimeMs> Reader::time_ms() {+ TimeMs out;+ const auto ms = i64le();+ if (!ms)+ return unexpected(ms.error());+ const auto tz = i16le();+ if (!tz)+ return unexpected(tz.error());+ out.ms = *ms;+ out.tz_min = *tz;+ return out;+}++std::uint64_t Reader::read_u64le_at(Bytes data, std::size_t off) {+ 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);+ return v;+}++void ByteWriter::u8(std::uint8_t v) { buf_.push_back(v); }++void ByteWriter::u16le(std::uint16_t v) {+ buf_.push_back(static_cast<std::uint8_t>(v & 255u));+ buf_.push_back(static_cast<std::uint8_t>((v >> 8) & 255u));+}++void ByteWriter::u32le(std::uint32_t v) {+ for (int i = 0; i < 4; ++i)+ buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));+}++void ByteWriter::u64le(std::uint64_t v) {+ for (int i = 0; i < 8; ++i)+ buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));+}++void ByteWriter::i16le(std::int16_t v) { u16le(static_cast<std::uint16_t>(v)); }+void ByteWriter::i64le(std::int64_t v) { u64le(static_cast<std::uint64_t>(v)); }++void ByteWriter::varint(std::uint64_t v) {+ for (;;) {+ const std::uint8_t low = static_cast<std::uint8_t>(v & 127u);+ v >>= 7;+ if (v == 0) {+ buf_.push_back(low);+ return;+ }+ buf_.push_back(static_cast<std::uint8_t>(low | 128u));+ }+}++void ByteWriter::raw(Bytes data) {+ if (!data.empty()) {+ buf_.insert(buf_.end(), data.begin(), data.end());+ }+}++void ByteWriter::length_prefixed(std::string_view s) {+ length_prefixed(bytes_of(s));+}+void ByteWriter::length_prefixed(Bytes b) {+ varint(b.size());+ raw(b);+}++void ByteWriter::id(const Id &id) { raw(Bytes(id.data(), id.size())); }++void ByteWriter::opt_id(const std::optional<Id> &id) {+ if (!id) {+ u8(0);+ return;+ }+ u8(1);+ this->id(*id);+}++void ByteWriter::sig(const Reader::Sig &s) {+ length_prefixed(s.name);+ length_prefixed(s.email);+ i64le(s.seconds);+ i16le(s.tz_min);+}++void ByteWriter::time_ms(const Reader::TimeMs &t) {+ i64le(t.ms);+ i16le(t.tz_min);+}++// ---------------------------------------------------------------------------+// Time / terminal+// ---------------------------------------------------------------------------++std::size_t available_cpu_count() {+#if defined(_WIN32)+ const DWORD count = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);+ return count == 0 ? 1 : static_cast<std::size_t>(count);+#elif defined(__linux__)+ cpu_set_t set;+ CPU_ZERO(&set);+ if (sched_getaffinity(0, sizeof(set), &set) == 0) {+ const auto *bytes = reinterpret_cast<const unsigned char *>(&set);+ std::size_t count = 0;+ for (std::size_t i = 0; i < sizeof(set); ++i) {+ unsigned char value = bytes[i];+ while (value != 0) {+ count += value & 1u;+ value >>= 1;+ }+ }+ if (count != 0)+ return count;+ }+ const long n = sysconf(_SC_NPROCESSORS_ONLN);+ return n > 0 ? static_cast<std::size_t>(n) : 1;+#else+ const long n = sysconf(_SC_NPROCESSORS_ONLN);+ return n > 0 ? static_cast<std::size_t>(n) : 1;+#endif+}++std::int64_t unix_now_seconds() {+ return std::chrono::duration_cast<std::chrono::seconds>(+ std::chrono::system_clock::now().time_since_epoch())+ .count();+}++std::int64_t unix_now_millis() {+ return std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::system_clock::now().time_since_epoch())+ .count();+}++static std::int64_t floor_div(std::int64_t a, std::int64_t b) {+ std::int64_t q = a / b;+ const std::int64_t r = a % b;+ if (r != 0 && ((r < 0) != (b < 0)))+ --q;+ return q;+}++static void append_pad(std::string &out, std::int64_t value, int width) {+ if (value < 0)+ value = 0;+ std::string digits;+ do {+ digits.push_back(static_cast<char>('0' + (value % 10)));+ value /= 10;+ } while (value > 0);+ for (int i = static_cast<int>(digits.size()); i < width; ++i)+ out.push_back('0');+ for (auto it = digits.rbegin(); it != digits.rend(); ++it)+ out.push_back(*it);+}++std::string format_utc(std::int64_t seconds) {+ const std::int64_t days = floor_div(seconds, 86400);+ const std::int64_t rem = seconds - days * 86400;+ const std::int64_t hour = rem / 3600;+ const std::int64_t minute = (rem % 3600) / 60;+ const std::int64_t second = rem % 60;++ const std::int64_t z = days + 719468;+ const std::int64_t era = floor_div(z, 146097);+ const std::int64_t doe = z - era * 146097;+ const std::int64_t yoe =+ (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+ const std::int64_t y0 = yoe + era * 400;+ const std::int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ const std::int64_t mp = (5 * doy + 2) / 153;+ const std::int64_t d = doy - (153 * mp + 2) / 5 + 1;+ const std::int64_t m0 = mp + 3;+ const std::int64_t m = mp >= 10 ? mp - 9 : m0;+ const std::int64_t y = m <= 2 ? y0 + 1 : y0;++ std::string out;+ out.reserve(19);+ append_pad(out, y, 4);+ out.push_back('-');+ append_pad(out, m, 2);+ out.push_back('-');+ append_pad(out, d, 2);+ out.push_back(' ');+ append_pad(out, hour, 2);+ out.push_back(':');+ append_pad(out, minute, 2);+ out.push_back(':');+ append_pad(out, second, 2);+ return out;+}++static bool g_colors = false;+static bool g_colors_checked = false;++bool colors_enabled() {+ if (g_colors_checked)+ return g_colors;+ g_colors_checked = true;+ if (std::getenv("NO_COLOR") != nullptr)+ return false;+#if defined(_WIN32)+ const bool tty = _isatty(_fileno(stdout)) != 0;+ bool ansi = false;+ if (tty) {+ HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);+ DWORD mode = 0;+ if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {+ ansi = SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;+ }+ }+ if (!ansi)+ return false;+#else+ const bool tty = ::isatty(STDOUT_FILENO) != 0;+#endif+ const char *forced = std::getenv("FORCE_COLOR");+ if (forced != nullptr && *forced != '\0' && std::strcmp(forced, "0") != 0) {+ g_colors = true;+ return true;+ }+ if (!tty)+ return false;+ const char *term = std::getenv("TERM");+ if (term != nullptr && std::strcmp(term, "dumb") == 0)+ return false;+ g_colors = true;+ return true;+}++static std::string_view color_code(Color c) {+ switch (c) {+ case Color::Default:+ return "\x1b[39m";+ case Color::Black:+ return "\x1b[30m";+ case Color::Red:+ return "\x1b[31m";+ case Color::Green:+ return "\x1b[32m";+ case Color::Yellow:+ return "\x1b[33m";+ case Color::Blue:+ return "\x1b[34m";+ case Color::Magenta:+ return "\x1b[35m";+ case Color::Cyan:+ return "\x1b[36m";+ case Color::BrightBlack:+ return "\x1b[90m";+ case Color::BrightRed:+ return "\x1b[91m";+ case Color::BrightGreen:+ return "\x1b[92m";+ case Color::BrightYellow:+ return "\x1b[93m";+ case Color::BrightBlue:+ return "\x1b[94m";+ case Color::BrightMagenta:+ return "\x1b[95m";+ case Color::BrightCyan:+ return "\x1b[96m";+ case Color::BrightWhite:+ return "\x1b[97m";+ }+ return "\x1b[39m";+}++void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr) {+ (void)to_stderr;+ auto &stream = std::cout;+ if (!colors_enabled()) {+ stream << text;+ return;+ }+ if (dim)+ stream << "\x1b[2m";+ if (fg != Color::Default)+ stream << color_code(fg);+ stream << text;+ stream << "\x1b[0m";+}++void print_colored(std::string_view text, Color color, bool dim,+ bool to_stderr) {+ print_styled(text, color, dim, to_stderr);+}++void print_bold(std::string_view text, Color fg, bool to_stderr) {+ (void)to_stderr;+ auto &stream = std::cout;+ if (!colors_enabled()) {+ stream << text;+ return;+ }+ stream << "\x1b[1m";+ if (fg != Color::Default)+ stream << color_code(fg);+ stream << text << "\x1b[0m";+}++void error_prefix() {+ print_bold("error", Color::Red, false);+ std::cout << ": ";+}+void warning_prefix() {+ print_bold("warning", Color::Yellow, false);+ std::cout << ": ";+}+void info_prefix() {+ print_styled("info", Color::Cyan, false, false);+ std::cout << ": ";+}++// ---------------------------------------------------------------------------+// Filesystem+// ---------------------------------------------------------------------------++fs::path path_from_bytes(std::string_view bytes) {+#if defined(_WIN32)+ std::u8string u;+ u.reserve(bytes.size());+ for (char c : bytes)+ u.push_back(static_cast<char8_t>(c));+ return fs::path(u);+#else+ return fs::path(std::string(bytes));+#endif+}++std::string path_to_bytes(const fs::path &p) {+#if defined(_WIN32)+ const std::u8string u = p.u8string();+ return std::string(reinterpret_cast<const char *>(u.data()), u.size());+#else+ return p.native();+#endif+}++std::string path_display(const fs::path &p) { return path_to_bytes(p); }++bool path_exists(const fs::path &p) {+ std::error_code ec;+ return fs::exists(p, ec);+}++bool path_is_dir(const fs::path &p) {+ std::error_code ec;+ return fs::is_directory(p, ec);+}++bool path_is_file(const fs::path &p) {+ std::error_code ec;+ return fs::is_regular_file(p, ec);+}++bool path_is_symlink(const fs::path &p) {+ std::error_code ec;+ return fs::is_symlink(fs::symlink_status(p, ec));+}++std::optional<std::uint64_t> path_file_size(const fs::path &p) {+ std::error_code ec;+ const auto n = fs::file_size(p, ec);+ if (ec)+ return std::nullopt;+ return static_cast<std::uint64_t>(n);+}++std::string basename_string(const fs::path &p) {+ return path_to_bytes(p.filename());+}++std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path &p) {+#if defined(_WIN32)+ std::ifstream in(p, std::ios::binary);+ if (!in)+ return std::nullopt;+ in.seekg(0, std::ios::end);+ const std::streamoff n = in.tellg();+ if (n < 0)+ return std::nullopt;+ in.seekg(0, std::ios::beg);+ std::vector<std::uint8_t> data(static_cast<std::size_t>(n));+ if (n > 0 && !in.read(reinterpret_cast<char *>(data.data()), n)) {+ return std::nullopt;+ }+ return data;+#else+ const int fd = ::open(p.c_str(), O_RDONLY);+ if (fd < 0)+ return std::nullopt;+ struct stat st {};+ if (::fstat(fd, &st) != 0 || st.st_size < 0) {+ ::close(fd);+ return std::nullopt;+ }+ std::vector<std::uint8_t> data(static_cast<std::size_t>(st.st_size));+ std::size_t done = 0;+ while (done < data.size()) {+ const ssize_t n = ::read(fd, data.data() + done, data.size() - done);+ if (n > 0) {+ done += static_cast<std::size_t>(n);+ } else if (n < 0 && errno == EINTR) {+ continue;+ } else {+ ::close(fd);+ return std::nullopt;+ }+ }+ ::close(fd);+ return data;+#endif+}++Result<std::vector<std::uint8_t>> read_file(const fs::path &p) {+ auto data = read_file_opt(p);+ if (!data)+ return fail_io("cannot read " + path_display(p));+ return *data;+}++static bool sync_file_path(const fs::path &p) {+#if defined(_WIN32)+ const int fd = _wopen(p.c_str(), _O_RDWR | _O_BINARY);+ if (fd < 0)+ return false;+ const bool ok = _commit(fd) == 0;+ _close(fd);+ return ok;+#else+ const int fd = ::open(p.c_str(), O_RDONLY);+ if (fd < 0)+ return false;+ const bool ok = ::fsync(fd) == 0;+ ::close(fd);+ return ok;+#endif+}++static void sync_parent_directory(const fs::path &p) {+#if defined(_WIN32)+ (void)p;+#else+ const fs::path parent = p.parent_path();+ if (parent.empty())+ return;+#if defined(__linux__)+ const int fd = ::open(parent.c_str(), O_RDONLY | O_DIRECTORY);+#else+ const int fd = ::open(parent.c_str(), O_RDONLY);+#endif+ if (fd >= 0) {+ (void)::fsync(fd);+ ::close(fd);+ }+#endif+}++static bool replace_file(const fs::path &from, const fs::path &to) {+#if defined(_WIN32)+ return MoveFileExW(from.c_str(), to.c_str(),+ MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;+#else+ return std::rename(from.c_str(), to.c_str()) == 0;+#endif+}++bool write_file(const fs::path &p, Bytes data) {+ std::error_code ec;+ if (!p.parent_path().empty())+ fs::create_directories(p.parent_path(), ec);+#if defined(_WIN32)+ std::ofstream out(p, std::ios::binary | std::ios::trunc);+ if (!out)+ return false;+ if (!data.empty()) {+ out.write(reinterpret_cast<const char *>(data.data()),+ static_cast<std::streamsize>(data.size()));+ }+ out.flush();+ return static_cast<bool>(out);+#else+ const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);+ if (fd < 0)+ return false;+ std::size_t done = 0;+ while (done < data.size()) {+ const ssize_t n = ::write(fd, data.data() + done, data.size() - done);+ if (n > 0) {+ done += static_cast<std::size_t>(n);+ } else if (n < 0 && errno == EINTR) {+ continue;+ } else {+ ::close(fd);+ return false;+ }+ }+ if (::close(fd) != 0)+ return false;+ return true;+#endif+}++bool append_file(const fs::path &p, Bytes data) {+ std::error_code ec;+ if (!p.parent_path().empty())+ fs::create_directories(p.parent_path(), ec);+#if defined(_WIN32)+ std::ofstream out(p, std::ios::binary | std::ios::app);+ if (!out)+ return false;+ if (!data.empty()) {+ out.write(reinterpret_cast<const char *>(data.data()),+ static_cast<std::streamsize>(data.size()));+ }+ out.flush();+ return static_cast<bool>(out);+#else+ const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);+ if (fd < 0)+ return false;+ std::size_t done = 0;+ while (done < data.size()) {+ const ssize_t n = ::write(fd, data.data() + done, data.size() - done);+ if (n > 0) {+ done += static_cast<std::size_t>(n);+ } else if (n < 0 && errno == EINTR) {+ continue;+ } else {+ ::close(fd);+ return false;+ }+ }+ if (::close(fd) != 0)+ return false;+ return true;+#endif+}++bool write_atomic(const fs::path &tmp_path, const fs::path &final_path,+ Bytes data) {+ std::error_code ec;+ if (!tmp_path.parent_path().empty())+ fs::create_directories(tmp_path.parent_path(), ec);+ if (!final_path.parent_path().empty())+ fs::create_directories(final_path.parent_path(), ec);+ if (!write_file(tmp_path, data))+ return false;+ if (!sync_file_path(tmp_path)) {+ remove_file(tmp_path);+ return false;+ }+ if (!replace_file(tmp_path, final_path)) {+ remove_file(tmp_path);+ return false;+ }+ sync_parent_directory(final_path);+ return true;+}++bool write_atomic(const fs::path &final_path, Bytes data) {+ const fs::path dir = final_path.parent_path();+ const std::string name = basename_string(final_path);+ const std::string tmp_name =+ "." + name + ".tmp." ++ std::to_string(static_cast<unsigned long>(random_u64()));+ return write_atomic(dir / tmp_name, final_path, data);+}++bool ensure_directory(const fs::path &p) {+ std::error_code ec;+ fs::create_directories(p, ec);+ return !ec;+}++bool remove_file(const fs::path &p) {+ std::error_code ec;+ return fs::remove(p, ec);+}++bool remove_tree(const fs::path &p) {+ std::error_code ec;+ fs::remove_all(p, ec);+ return !ec;+}++std::vector<std::string> list_directory(const fs::path &p) {+ std::vector<std::string> out;+#if defined(_WIN32)+ std::error_code ec;+ fs::directory_iterator it(p, ec);+ if (ec)+ return out;+ for (const auto &entry : it)+ out.push_back(path_to_bytes(entry.path().filename()));+#else+ DIR *dir = ::opendir(p.c_str());+ if (dir == nullptr)+ return out;+ while (dirent *entry = ::readdir(dir)) {+ const char *name = entry->d_name;+ if (std::strcmp(name, ".") == 0 || std::strcmp(name, "..") == 0)+ continue;+ out.emplace_back(name);+ }+ ::closedir(dir);+#endif+ return out;+}++bool same_or_under(const fs::path &child, const fs::path &parent) {+ std::error_code ec;+ const fs::path c = fs::weakly_canonical(child, ec);+ if (ec)+ return false;+ const fs::path p = fs::weakly_canonical(parent, ec);+ if (ec)+ return false;+ auto ci = c.begin();+ auto pi = p.begin();+ for (; pi != p.end(); ++pi, ++ci) {+ if (ci == c.end() || *ci != *pi)+ return false;+ }+ return true;+}++std::optional<std::string> path_read_symlink(const fs::path &p) {+ std::error_code ec;+ const fs::path target = fs::read_symlink(p, ec);+ if (ec)+ return std::nullopt;+ return path_to_bytes(target);+}++#if defined(_WIN32)+static std::optional<std::uint64_t> mtime_from_file_time(const fs::path &p) {+ std::error_code ec;+ const auto ft = fs::last_write_time(p, ec);+ if (ec)+ return std::nullopt;+ // Convert the filesystem clock value to Unix nanoseconds without assuming+ // a particular epoch offset: compare against a known reference point.+ const auto now_file = fs::file_time_type::clock::now();+ const auto now_sys = std::chrono::system_clock::now();+ const auto delta =+ std::chrono::duration_cast<std::chrono::nanoseconds>(ft - now_file);+ const auto sys = now_sys + delta;+ return static_cast<std::uint64_t>(+ std::chrono::duration_cast<std::chrono::nanoseconds>(+ sys.time_since_epoch())+ .count());+}+#endif++std::optional<StatInfo> stat_path(const fs::path &p) {+#if defined(_WIN32)+ std::error_code ec;+ const auto status = fs::symlink_status(p, ec);+ if (ec || status.type() == fs::file_type::not_found)+ return std::nullopt;+ StatInfo info;+ if (fs::is_symlink(status)) {+ info.kind = 3;+ } else if (fs::is_directory(status)) {+ info.kind = 2;+ } else if (fs::is_regular_file(status)) {+ info.kind = 1;+ } else {+ return std::nullopt;+ }+ if (info.kind == 1) {+ info.size = path_file_size(p).value_or(0);+ }+ info.mtime_ns = mtime_from_file_time(p).value_or(0);+ return info;+#else+ struct stat st {};+ if (::lstat(p.c_str(), &st) != 0)+ return std::nullopt;+ StatInfo info;+ if (S_ISLNK(st.st_mode)) {+ info.kind = 3;+ } else if (S_ISDIR(st.st_mode)) {+ info.kind = 2;+ } else if (S_ISREG(st.st_mode)) {+ info.kind = 1;+ } else {+ return std::nullopt;+ }+ info.executable = (st.st_mode & 0111) != 0;+ info.size = static_cast<std::uint64_t>(st.st_size);+ info.inode = static_cast<std::uint64_t>(st.st_ino);+#if defined(__APPLE__)+ info.mtime_ns =+ static_cast<std::uint64_t>(st.st_mtimespec.tv_sec) * 1'000'000'000ull ++ static_cast<std::uint64_t>(st.st_mtimespec.tv_nsec);+#else+ info.mtime_ns =+ static_cast<std::uint64_t>(st.st_mtim.tv_sec) * 1'000'000'000ull ++ static_cast<std::uint64_t>(st.st_mtim.tv_nsec);+#endif+ return info;+#endif+}++std::optional<std::uint64_t> file_mtime_ns(const fs::path &p) {+ const auto info = stat_path(p);+ if (!info)+ return std::nullopt;+ return info->mtime_ns;+}++std::optional<std::uint64_t> file_inode(const fs::path &p) {+ const auto info = stat_path(p);+ if (!info)+ return std::nullopt;+ return info->inode;+}++bool is_executable(const fs::path &p) {+ const auto info = stat_path(p);+ return info && info->executable;+}++// ---------------------------------------------------------------------------+// Configuration+// ---------------------------------------------------------------------------++static std::string_view trim_view(std::string_view s) {+ std::size_t start = 0;+ std::size_t end = s.size();+ while (start < end) {+ const char c = s[start];+ if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+ break;+ ++start;+ }+ while (end > start) {+ const char c = s[end - 1];+ if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+ break;+ --end;+ }+ return s.substr(start, end - start);+}++static std::string trim_copy(std::string_view s) {+ return std::string(trim_view(s));+}++std::optional<std::string> repo_config_value(const fs::path &repo_root,+ std::string_view key) {+ const auto data = read_file_opt(repo_root / ".veins" / "config");+ if (!data)+ return std::nullopt;+ std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ std::size_t start = 0;+ while (start <= text.size()) {+ std::size_t end = text.find('\n', start);+ if (end == std::string_view::npos)+ end = text.size();+ const std::string_view line = trim_view(text.substr(start, end - start));+ if (!line.empty() && line.front() != '#') {+ const std::size_t eq = line.find('=');+ if (eq != std::string_view::npos) {+ const std::string_view k = trim_view(line.substr(0, eq));+ if (k == key)+ return trim_copy(line.substr(eq + 1));+ }+ }+ if (end == text.size())+ break;+ start = end + 1;+ }+ return std::nullopt;+}++static std::string strip_comment(std::string_view v) {+ const std::size_t hash = v.find('#');+ if (hash != std::string_view::npos)+ v = v.substr(0, hash);+ return trim_copy(v);+}++bool repo_config_bool(const fs::path &repo_root, std::string_view key,+ bool fallback) {+ const auto v = repo_config_value(repo_root, key);+ if (!v)+ return fallback;+ const std::string value = strip_comment(*v);+ return value == "true" || value == "1" || value == "yes" || value == "on";+}++bool repo_config_set(const fs::path &repo_root, std::string_view key,+ std::string_view value) {+ const fs::path path = repo_root / ".veins" / "config";+ const auto data = read_file_opt(path);+ std::string out;+ if (data) {+ std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ std::size_t start = 0;+ while (start <= text.size()) {+ std::size_t end = text.find('\n', start);+ if (end == std::string_view::npos)+ end = text.size();+ const std::string_view line = text.substr(start, end - start);+ const std::string_view t = trim_view(line);+ const std::size_t eq = t.find('=');+ const bool is_key =+ eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;+ if (!is_key) {+ out.append(line);+ if (end < text.size())+ out.push_back('\n');+ }+ if (end == text.size())+ break;+ start = end + 1;+ }+ }+ out.append(key);+ out.append(" = ");+ out.append(value);+ out.push_back('\n');+ return write_file(path, bytes_of(out));+}++bool repo_config_remove(const fs::path &repo_root, std::string_view key) {+ const fs::path path = repo_root / ".veins" / "config";+ const auto data = read_file_opt(path);+ std::string out;+ if (data) {+ std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ std::size_t start = 0;+ while (start <= text.size()) {+ std::size_t end = text.find('\n', start);+ if (end == std::string_view::npos)+ end = text.size();+ const std::string_view line = text.substr(start, end - start);+ const std::string_view t = trim_view(line);+ const std::size_t eq = t.find('=');+ const bool is_key =+ eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;+ if (!is_key) {+ out.append(line);+ if (end < text.size())+ out.push_back('\n');+ }+ if (end == text.size())+ break;+ start = end + 1;+ }+ }+ return write_file(path, bytes_of(out));+}++static fs::path user_config_path() {+#if defined(_WIN32)+ const char *home = std::getenv("USERPROFILE");+#else+ const char *home = std::getenv("HOME");+#endif+ if (home == nullptr || *home == '\0')+ return {};+ return path_from_bytes(home) / ".local" / "config" / "veins" / "veins.toml";+}++static std::optional<std::string> unquote_toml(std::string_view raw) {+ raw = trim_view(raw);+ if (raw.size() >= 2) {+ if ((raw.front() == '\'' && raw.back() == '\'') ||+ (raw.front() == '"' && raw.back() == '"')) {+ const char quote = raw.front();+ std::string out;+ for (std::size_t i = 1; i + 1 < raw.size(); ++i) {+ const char c = raw[i];+ if (quote == '"' && c == '\\' && i + 2 < raw.size()) {+ const char next = raw[i + 1];+ if (next == '"')+ out.push_back('"');+ else if (next == '\\')+ out.push_back('\\');+ else if (next == 'n')+ out.push_back('\n');+ else if (next == 'r')+ out.push_back('\r');+ else if (next == 't')+ out.push_back('\t');+ else {+ out.push_back('\\');+ out.push_back(next);+ }+ ++i;+ } else {+ out.push_back(c);+ }+ }+ return out;+ }+ }+ if (raw.empty())+ return std::nullopt;+ return std::string(raw);+}++static std::optional<std::string> user_config_value(bool want_name) {+ const fs::path path = user_config_path();+ if (path.empty())+ return std::nullopt;+ const auto data = read_file_opt(path);+ if (!data)+ return std::nullopt;+ std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ bool in_user = false;+ std::size_t start = 0;+ while (start <= text.size()) {+ std::size_t end = text.find('\n', start);+ if (end == std::string_view::npos)+ end = text.size();+ const std::string_view line = trim_view(text.substr(start, end - start));+ if (!line.empty() && line.front() != '#') {+ if (line.front() == '[') {+ const std::size_t close = line.find(']');+ if (close != std::string_view::npos) {+ in_user = trim_view(line.substr(1, close - 1)) == "user";+ }+ } else {+ const std::size_t eq = line.find('=');+ if (eq != std::string_view::npos) {+ const std::string_view key = trim_view(line.substr(0, eq));+ const bool matches =+ (in_user && key == (want_name ? "name" : "email")) ||+ (!in_user && key == (want_name ? "user.name" : "user.email"));+ if (matches) {+ std::string_view value = line.substr(eq + 1);+ std::string value_copy = strip_comment(value);+ auto decoded = unquote_toml(value_copy);+ if (decoded && !decoded->empty())+ return decoded;+ }+ }+ }+ }+ if (end == text.size())+ break;+ start = end + 1;+ }+ return std::nullopt;+}++std::optional<std::string> user_config_author_name() {+ return user_config_value(true);+}+std::optional<std::string> user_config_author_email() {+ return user_config_value(false);+}++static std::optional<std::string> env_value(const char *name) {+ const char *v = std::getenv(name);+ if (v == nullptr)+ return std::nullopt;+ return std::string(v);+}++static std::string first_config(const fs::path &repo_root, std::string_view key,+ bool want_name, const char *env1,+ const char *env2) {+ if (auto v = repo_config_value(repo_root, key))+ return *v;+ auto user =+ want_name ? user_config_author_name() : user_config_author_email();+ if (user)+ return *user;+ if (auto v = env_value(env1))+ return *v;+ if (auto v = env_value(env2))+ return *v;+ return "unknown";+}++Sig identity_signature(const fs::path &repo_root) {+ Sig sig;+ sig.name =+ first_config(repo_root, "user.name", true, "GIT_AUTHOR_NAME", "USER");+ sig.email =+ first_config(repo_root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL");+#if defined(_WIN32)+ if (sig.name == "unknown") {+ if (auto v = env_value("USERNAME"))+ sig.name = *v;+ }+#endif+ sig.seconds = unix_now_seconds();+ sig.tz_min = 0;+ return sig;+}++// ---------------------------------------------------------------------------+// Ignore rules+// ---------------------------------------------------------------------------++IgnoreRules ignore_empty() { return {}; }++static std::optional<std::string_view> relative_to(std::string_view base,+ std::string_view path) {+ if (base.empty())+ return path;+ if (path.size() <= base.size())+ return std::nullopt;+ if (path.substr(0, base.size()) != base)+ return std::nullopt;+ if (path[base.size()] != '/')+ return std::nullopt;+ return path.substr(base.size() + 1);+}++static void add_ignore_line(IgnoreRules &rules, std::string_view base,+ std::string_view input) {+ std::string_view line = trim_view(input);+ if (line.empty() || line.front() == '#')+ return;+ bool negated = false;+ std::size_t start = 0;+ if (line.front() == '!') {+ negated = true;+ start = 1;+ }+ if (start >= line.size())+ return;+ std::size_t end = line.size();+ bool dir_only = false;+ if (line[end - 1] == '/') {+ dir_only = true;+ --end;+ }+ if (start >= end)+ return;+ bool anchored = false;+ if (line[start] == '/') {+ anchored = true;+ ++start;+ }+ if (start >= end)+ return;+ const std::string_view pattern = line.substr(start, end - start);+ const bool has_slash = pattern.find('/') != std::string_view::npos;+ rules.items.push_back(IgnoreRule{std::string(pattern), negated, dir_only,+ anchored, has_slash, std::string(base)});+}++void ignore_load_file(IgnoreRules &rules, const fs::path &repo_root,+ std::string_view base, std::string_view name) {+ const fs::path dir =+ base.empty() ? repo_root : repo_root / path_from_bytes(base);+ const auto data = read_file_opt(dir / path_from_bytes(name));+ if (!data)+ return;+ std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ std::size_t start = 0;+ while (start <= text.size()) {+ std::size_t end = text.find('\n', start);+ if (end == std::string_view::npos)+ end = text.size();+ add_ignore_line(rules, base, text.substr(start, end - start));+ if (end == text.size())+ break;+ start = end + 1;+ }+}++void ignore_load_root(IgnoreRules &rules, const fs::path &repo_root) {+ ignore_load_file(rules, repo_root, "", ".vnexclude");+ ignore_load_file(rules, repo_root, "", ".gitignore");+}++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] == '/') {+ ++j;+ continue;+ }+ ++j;+ while (j < text.size() && text[j] != '/')+ ++j;+ }+ return false;+ }+ std::size_t j = ti;+ for (;;) {+ if (glob_here(pattern, next, text, j))+ return true;+ if (j >= text.size())+ break;+ ++j;+ }+ return false;+ }+ std::size_t j = ti;+ for (;;) {+ if (glob_here(pattern, pi + 1, text, j))+ return true;+ if (j >= text.size() || text[j] == '/')+ break;+ ++j;+ }+ return false;+ }+ 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);+}++bool glob_match(std::string_view pattern, std::string_view text) {+ return glob_here(pattern, 0, text, 0);+}++static bool rule_matches(const IgnoreRule &rule, std::string_view path,+ bool is_dir) {+ const auto rel_opt = relative_to(rule.base, path);+ if (!rel_opt)+ return false;+ const std::string_view rel = *rel_opt;+ if (rel.empty())+ return false;+ if (rule.dir_only && !is_dir)+ return false;+ if (!rule.has_slash && !rule.anchored) {+ std::size_t start = 0;+ for (;;) {+ std::size_t end = rel.find('/', start);+ if (end == std::string_view::npos)+ end = rel.size();+ if (glob_here(rule.pattern, 0, rel.substr(start, end - start), 0))+ return true;+ if (end >= rel.size())+ break;+ start = end + 1;+ }+ return false;+ }+ return glob_here(rule.pattern, 0, rel, 0);+}++bool ignore_ignored(const IgnoreRules &rules, std::string_view path,+ bool is_dir) {+ bool ignored = false;+ for (const auto &rule : rules.items) {+ if (rule_matches(rule, path, is_dir))+ ignored = !rule.negated;+ }+ return ignored;+}++bool ignore_path_ignored(const fs::path &repo_root, std::string_view path) {+ IgnoreRules rules = ignore_empty();+ ignore_load_root(rules, repo_root);+ for (std::size_t i = 0; i < path.size(); ++i) {+ if (path[i] == '/') {+ const std::string_view base = path.substr(0, i);+ ignore_load_file(rules, repo_root, base, ".vnexclude");+ ignore_load_file(rules, repo_root, base, ".gitignore");+ }+ }+ bool result = false;+ for (std::size_t j = 0; j < path.size(); ++j) {+ if (path[j] == '/') {+ if (ignore_ignored(rules, path.substr(0, j), true)) {+ result = true;+ break;+ }+ }+ }+ if (!result)+ result = ignore_ignored(rules, path, false);+ return result;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/common.h@@ -0,0 +1,414 @@+#pragma once++#include <array>+#include <chrono>+#include <cstdint>+#include <cstdio>+#include <cstring>+#include <filesystem>+#include <optional>+#include <span>+#include <string>+#include <string_view>+#include <system_error>+#include <variant>+#include <vector>++#if __has_include(<expected>)+#include <expected>+#endif++#include <blake3.h>++namespace vn {++namespace fs = std::filesystem;++using Bytes = std::span<const std::uint8_t>;+using MutBytes = std::span<std::uint8_t>;+using Id = std::array<std::uint8_t, 32>;+using ChangeId = std::array<std::uint8_t, 16>;++constexpr std::size_t ID_LEN = 32;+constexpr std::size_t CHANGE_ID_LEN = 16;+constexpr std::size_t MAX_NAME_LEN = 4096;+constexpr std::size_t MAX_PATH_LEN = 65536;+constexpr std::size_t MAX_MESSAGE_LEN = 16u * 1024u * 1024u;+constexpr std::size_t MAX_OBJECT_BODY = 64u * 1024u * 1024u;+constexpr std::size_t MAX_CHUNK_LEN = 256u * 1024u;+constexpr std::size_t MAX_MANIFEST_ENTRIES = 1024;+constexpr std::size_t MAX_TREE_ENTRIES = 1'000'000;+constexpr std::size_t MAX_CONFLICT_TERMS = 64;+constexpr std::size_t INLINE_THRESHOLD = 16u * 1024u;++enum class ErrorKind {+ None,+ UnexpectedEnd,+ VarintOverflow,+ NonMinimalVarint,+ InvalidValue,+ LimitExceeded,+ InvalidName,+ Duplicate,+ Unsorted,+ TrailingBytes,+ UnsupportedVersion,+ InvalidMagic,+ HashMismatch,+ Corrupt,+ Io,+ Usage,+};++std::string_view error_kind_name(ErrorKind kind);++struct Error {+ ErrorKind kind = ErrorKind::None;+ std::size_t offset = 0;+ std::string message;++ Error() = default;+ Error(ErrorKind k, std::size_t off, std::string msg)+ : kind(k), offset(off), message(std::move(msg)) {}++ static Error decode(ErrorKind kind, std::size_t offset);+ static Error io(std::string message);+ static Error usage(std::string message);+};++#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L+template <typename T> using Result = std::expected<T, Error>;+template <typename E> using Unexpected = std::unexpected<E>;+#else+template <typename E> struct Unexpected {+ E err;+ explicit Unexpected(E value) : err(std::move(value)) {}+};++template <typename T, typename E> class Expected {+public:+ Expected(T &&value) : data_(std::in_place_index<0>, std::move(value)) {}+ Expected(const T &value) : data_(std::in_place_index<0>, value) {}+ Expected(Unexpected<E> value)+ : data_(std::in_place_index<1>, std::move(value.err)) {}++ [[nodiscard]] bool has_value() const { return data_.index() == 0; }+ explicit operator bool() const { return has_value(); }+ T &operator*() { return std::get<0>(data_); }+ const T &operator*() const { return std::get<0>(data_); }+ T *operator->() { return &std::get<0>(data_); }+ const T *operator->() const { return &std::get<0>(data_); }+ T &value() { return std::get<0>(data_); }+ const T &value() const { return std::get<0>(data_); }+ E &error() { return std::get<1>(data_); }+ const E &error() const { return std::get<1>(data_); }++private:+ std::variant<T, E> data_;+};++template <typename E> class Expected<void, E> {+public:+ Expected() = default;+ Expected(Unexpected<E> value) : error_(std::move(value.err)) {}+ [[nodiscard]] bool has_value() const { return !error_.has_value(); }+ explicit operator bool() const { return has_value(); }+ E &error() { return *error_; }+ const E &error() const { return *error_; }++private:+ std::optional<E> error_;+};++template <typename T> using Result = Expected<T, Error>;+#endif++using Status = Result<void>;++inline Unexpected<Error> unexpected(Error error) {+ return Unexpected<Error>(std::move(error));+}+inline Status ok() { return {}; }+inline Unexpected<Error> fail(ErrorKind kind, std::size_t offset = 0) {+ return unexpected(Error::decode(kind, offset));+}+inline Unexpected<Error> fail_io(std::string message) {+ return unexpected(Error::io(std::move(message)));+}+inline Unexpected<Error> fail_usage(std::string message) {+ return unexpected(Error::usage(std::move(message)));+}++// ---------------------------------------------------------------------------+// Byte and string helpers+// ---------------------------------------------------------------------------++inline Bytes bytes_of(std::string_view s) {+ return Bytes(reinterpret_cast<const std::uint8_t *>(s.data()), s.size());+}+inline Bytes bytes_of(const std::vector<std::uint8_t> &v) {+ return Bytes(v.data(), v.size());+}+inline std::string_view str_of(Bytes b) {+ return std::string_view(reinterpret_cast<const char *>(b.data()), b.size());+}+inline std::string to_string(Bytes b) { return std::string(str_of(b)); }+inline bool equals(Bytes a, Bytes b) {+ return a.size() == b.size() &&+ (a.empty() || std::memcmp(a.data(), b.data(), a.size()) == 0);+}+inline int compare(Bytes a, Bytes b) {+ const std::size_t n = std::min(a.size(), b.size());+ if (n != 0) {+ const int c = std::memcmp(a.data(), b.data(), n);+ if (c != 0)+ return c < 0 ? -1 : 1;+ }+ if (a.size() < b.size())+ return -1;+ if (a.size() > b.size())+ return 1;+ return 0;+}+inline bool ascii_iequals(Bytes a, Bytes b) {+ if (a.size() != b.size())+ return false;+ for (std::size_t i = 0; i < a.size(); ++i) {+ auto lower = [](std::uint8_t c) -> std::uint8_t {+ return (c >= 'A' && c <= 'Z') ? static_cast<std::uint8_t>(c + 32) : c;+ };+ if (lower(a[i]) != lower(b[i]))+ return false;+ }+ return true;+}+inline bool starts_with(Bytes value, Bytes prefix) {+ return value.size() >= prefix.size() &&+ equals(value.first(prefix.size()), prefix);+}++std::string hex_encode(Bytes data);+std::string hex_encode(const Id &id);+bool hex_decode(std::string_view text, MutBytes out);+std::optional<Id> parse_id(std::string_view hex);+std::string base32_encode(const ChangeId &id);+bool base32_prefix_matches(std::string_view full, std::string_view prefix);++// ---------------------------------------------------------------------------+// Hashing and random bytes+// ---------------------------------------------------------------------------++std::array<std::uint8_t, 32> blake3_hash(Bytes data);+Id object_id(std::uint8_t type_byte, Bytes body);+std::array<std::uint8_t, 16> random_change_id();+std::uint64_t random_u64();++// ---------------------------------------------------------------------------+// Binary reader / writer+// ---------------------------------------------------------------------------++class Reader {+public:+ explicit Reader(Bytes data) : data_(data) {}++ [[nodiscard]] std::size_t offset() const { return pos_; }+ [[nodiscard]] std::size_t remaining() const { return data_.size() - pos_; }+ [[nodiscard]] bool at_end() const { return pos_ >= data_.size(); }++ Result<std::uint8_t> u8();+ Result<std::uint16_t> u16le();+ Result<std::uint32_t> u32le();+ Result<std::uint64_t> u64le();+ Result<std::int16_t> i16le();+ Result<std::int64_t> i64le();+ Result<std::uint64_t> varint();+ Result<Bytes> raw(std::size_t n);+ Result<Bytes> bytes(std::size_t max_len);+ Result<std::string> string_bytes(std::size_t max_len);+ Result<std::size_t> list_len(std::size_t max);+ Result<Id> id();+ Result<std::optional<Id>> opt_id();+ Result<void> finish();++ struct Sig {+ std::string name;+ std::string email;+ std::int64_t seconds = 0;+ std::int16_t tz_min = 0;+ };+ struct TimeMs {+ std::int64_t ms = 0;+ std::int16_t tz_min = 0;+ };++ Result<Sig> sig(std::size_t max_name, std::size_t max_email);+ Result<TimeMs> time_ms();++ static std::uint64_t read_u64le_at(Bytes data, std::size_t off);++private:+ Bytes data_;+ std::size_t pos_ = 0;+};++class ByteWriter {+public:+ explicit ByteWriter(std::size_t reserve = 64) { buf_.reserve(reserve); }++ void u8(std::uint8_t v);+ void u16le(std::uint16_t v);+ void u32le(std::uint32_t v);+ void u64le(std::uint64_t v);+ void i16le(std::int16_t v);+ void i64le(std::int64_t v);+ void varint(std::uint64_t v);+ void raw(Bytes data);+ void raw(std::string_view s) { raw(bytes_of(s)); }+ void bytes(std::string_view s) { raw(s); }+ void length_prefixed(std::string_view s);+ void length_prefixed(Bytes b);+ void id(const Id &id);+ void opt_id(const std::optional<Id> &id);+ void sig(const Reader::Sig &s);+ void time_ms(const Reader::TimeMs &t);++ [[nodiscard]] Bytes view() const { return Bytes(buf_.data(), buf_.size()); }+ [[nodiscard]] const std::vector<std::uint8_t> &data() const { return buf_; }+ [[nodiscard]] std::vector<std::uint8_t> take() { return std::move(buf_); }+ [[nodiscard]] std::size_t size() const { return buf_.size(); }+ void clear() { buf_.clear(); }+ void append(Bytes b) { raw(b); }+ void reserve(std::size_t n) { buf_.reserve(n); }++private:+ std::vector<std::uint8_t> buf_;+};++// ---------------------------------------------------------------------------+// Dates, terminal output+// ---------------------------------------------------------------------------++std::string format_utc(std::int64_t seconds);+std::int64_t unix_now_seconds();+std::int64_t unix_now_millis();+std::size_t available_cpu_count();++enum class Color {+ Default,+ Black,+ Red,+ Green,+ Yellow,+ Blue,+ Magenta,+ Cyan,+ BrightBlack,+ BrightRed,+ BrightGreen,+ BrightYellow,+ BrightBlue,+ BrightMagenta,+ BrightCyan,+ BrightWhite,+};++bool colors_enabled();+void print_colored(std::string_view text, Color color, bool dim = false,+ bool to_stderr = false);+void print_styled(std::string_view text, Color fg, bool dim,+ bool to_stderr = false);+void print_bold(std::string_view text, Color fg, bool to_stderr = false);+void error_prefix();+void warning_prefix();+void info_prefix();++// ---------------------------------------------------------------------------+// Filesystem helpers+// ---------------------------------------------------------------------------++fs::path path_from_bytes(std::string_view bytes);+std::string path_to_bytes(const fs::path &p);+std::string path_display(const fs::path &p);++Result<std::vector<std::uint8_t>> read_file(const fs::path &p);+std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path &p);+bool write_file(const fs::path &p, Bytes data);+bool append_file(const fs::path &p, Bytes data);+bool write_atomic(const fs::path &final_path, Bytes data);+bool write_atomic(const fs::path &tmp_path, const fs::path &final_path,+ Bytes data);+bool ensure_directory(const fs::path &p);+bool remove_file(const fs::path &p);+bool remove_tree(const fs::path &p);+bool path_exists(const fs::path &p);+bool path_is_dir(const fs::path &p);+bool path_is_file(const fs::path &p);+bool path_is_symlink(const fs::path &p);+std::optional<std::uint64_t> path_file_size(const fs::path &p);+std::optional<std::uint64_t> file_mtime_ns(const fs::path &p);+std::optional<std::uint64_t> file_inode(const fs::path &p);+bool is_executable(const fs::path &p);+std::optional<std::string> path_read_symlink(const fs::path &p);+std::vector<std::string> list_directory(const fs::path &p);+bool same_or_under(const fs::path &child, const fs::path &parent);+std::string basename_string(const fs::path &p);++struct StatInfo {+ std::uint8_t kind = 0; // 0 missing, 1 file, 2 directory, 3 symlink+ bool executable = false;+ std::uint64_t size = 0;+ std::uint64_t mtime_ns = 0;+ std::uint64_t inode = 0;+};+std::optional<StatInfo> stat_path(const fs::path &p);++// ---------------------------------------------------------------------------+// Configuration and identity+// ---------------------------------------------------------------------------++std::optional<std::string> repo_config_value(const fs::path &repo_root,+ std::string_view key);+bool repo_config_set(const fs::path &repo_root, std::string_view key,+ std::string_view value);+bool repo_config_remove(const fs::path &repo_root, std::string_view key);+bool repo_config_bool(const fs::path &repo_root, std::string_view key,+ bool fallback);++struct Sig {+ std::string name;+ std::string email;+ std::int64_t seconds = 0;+ std::int16_t tz_min = 0;+};++Sig identity_signature(const fs::path &repo_root);+std::optional<std::string> user_config_author_name();+std::optional<std::string> user_config_author_email();++// ---------------------------------------------------------------------------+// Ignore rules+// ---------------------------------------------------------------------------++struct IgnoreRule {+ std::string pattern;+ bool negated = false;+ bool dir_only = false;+ bool anchored = false;+ bool has_slash = false;+ std::string base;+};++struct IgnoreRules {+ std::vector<IgnoreRule> items;+};++IgnoreRules ignore_empty();+void ignore_load_file(IgnoreRules &rules, const fs::path &repo_root,+ std::string_view base, std::string_view name);+void ignore_load_root(IgnoreRules &rules, const fs::path &repo_root);+bool ignore_ignored(const IgnoreRules &rules, std::string_view path,+ bool is_dir);+bool ignore_path_ignored(const fs::path &repo_root, std::string_view path);+bool glob_match(std::string_view pattern, std::string_view text);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/main.cpp@@ -0,0 +1,22 @@+#include "cli.h"++#include <exception>+#include <iostream>+#include <string>+#include <vector>++int main(int argc, char **argv) {+ 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]);+ try {+ return vn::cli_run(args);+ } catch (const std::exception &e) {+ std::cout << "error: " << e.what() << "\n";+ return 1;+ } catch (...) {+ std::cout << "error: unexpected failure\n";+ return 1;+ }+}--- /dev/null+++ b/veins-cpprewrite/src/object.cpp@@ -0,0 +1,1026 @@+#include "object.h"++#include <algorithm>+#include <cstring>++namespace vn {++std::string_view type_name(std::uint8_t type) {+ switch (type) {+ case TYPE_CHUNK:+ return "chunk";+ case TYPE_BLOB:+ return "blob";+ case TYPE_TREE:+ return "tree";+ case TYPE_COMMIT:+ return "commit";+ case TYPE_CONFLICT:+ return "conflict";+ case TYPE_OPERATION:+ return "operation";+ case TYPE_VIEW:+ return "view";+ default:+ return "unknown";+ }+}++bool type_valid(std::uint8_t type) {+ return type >= TYPE_CHUNK && type <= TYPE_VIEW;+}++// ---------------------------------------------------------------------------+// Names+// ---------------------------------------------------------------------------++static bool is_dot_name(std::string_view s) { return s == "." || s == ".."; }++bool valid_name(std::string_view name) {+ if (name.empty() || name.size() > MAX_NAME_LEN)+ return false;+ for (char c : name) {+ if (c == '\0' || c == '/')+ return false;+ }+ if (is_dot_name(name))+ return false;+ if (ascii_iequals(bytes_of(name), bytes_of(".veins")))+ return false;+ return true;+}++static bool valid_component(std::string_view component) {+ if (component.empty() || component.size() > MAX_NAME_LEN)+ return false;+ if (is_dot_name(component))+ return false;+ for (char c : component) {+ if (c == '\0' || c == '/')+ return false;+ }+ return true;+}++bool valid_path(std::string_view path) {+ if (path.empty() || path.size() > MAX_PATH_LEN)+ return false;+ if (path.front() == '/')+ return false;+ std::size_t start = 0;+ for (std::size_t i = 0; i <= path.size(); ++i) {+ const bool at_end = i == path.size();+ const bool sep = !at_end && path[i] == '/';+ if (at_end || sep) {+ if (!valid_component(path.substr(start, i - start)))+ return false;+ start = i + 1;+ }+ }+ return true;+}++// ---------------------------------------------------------------------------+// FastCDC+// ---------------------------------------------------------------------------++static std::array<std::uint64_t, 256> make_gear_table() {+ static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '/', 'f',+ 'a', 's', 't', 'c', 'd', 'c', '/',+ 'g', 'e', 'a', 'r', '/', 'v', '1'};+ std::array<std::uint64_t, 256> table{};+ for (std::size_t i = 0; i < table.size(); ++i) {+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ blake3_hasher_update(&hasher, prefix, sizeof(prefix));+ const auto byte = static_cast<std::uint8_t>(i);+ blake3_hasher_update(&hasher, &byte, 1);+ std::array<std::uint8_t, 32> digest{};+ blake3_hasher_finalize(&hasher, digest.data(), digest.size());+ std::uint64_t value = 0;+ for (int j = 0; j < 8; ++j)+ value |= static_cast<std::uint64_t>(digest[static_cast<std::size_t>(j)])+ << (j * 8);+ table[i] = value;+ }+ return table;+}++const std::array<std::uint64_t, 256> &fastcdc_gear() {+ static const auto table = make_gear_table();+ return table;+}++std::size_t fastcdc_next(Bytes data) {+ constexpr std::size_t min_size = 16384;+ constexpr std::size_t avg_size = 65536;+ constexpr std::size_t max_size = 262144;+ constexpr std::uint64_t mask_s = 0x3ffffull;+ constexpr std::uint64_t mask_l = 0x3fffull;+ const std::size_t len = data.size();+ if (len <= min_size)+ return len;+ const std::size_t limit = std::min(len, max_size);+ const std::size_t normal = std::min(avg_size, limit);+ const auto &gear = fastcdc_gear();+ std::uint64_t fp = 0;+ for (std::size_t i = min_size; i < normal; ++i) {+ fp = (fp >> 1) + gear[data[i]];+ if ((fp & mask_s) == 0)+ return i + 1;+ }+ for (std::size_t i = normal; i < limit; ++i) {+ fp = (fp >> 1) + gear[data[i]];+ if ((fp & mask_l) == 0)+ return i + 1;+ }+ return limit;+}++// ---------------------------------------------------------------------------+// Blobs+// ---------------------------------------------------------------------------++Result<std::vector<std::uint8_t>> encode_inline_blob(Bytes data) {+ ByteWriter w(data.size() + 8);+ w.u8(static_cast<std::uint8_t>(BlobForm::Inline));+ w.varint(data.size());+ w.raw(data);+ return w.take();+}++Result<Blob> decode_blob(Bytes body) {+ Reader r(body);+ const auto form = r.u8();+ if (!form)+ return unexpected(form.error());+ if (*form > 2)+ return fail(ErrorKind::InvalidValue, 0);+ Blob blob;+ blob.form = static_cast<BlobForm>(*form);+ if (blob.form == BlobForm::Inline) {+ const auto data = r.bytes(INLINE_THRESHOLD);+ if (!data)+ return unexpected(data.error());+ blob.data.assign(data->begin(), data->end());+ const auto fin = r.finish();+ if (!fin)+ return unexpected(fin.error());+ return blob;+ }+ const auto count = r.list_len(MAX_MANIFEST_ENTRIES);+ if (!count)+ return unexpected(count.error());+ if (*count == 0)+ return fail(ErrorKind::InvalidValue, 1);+ std::uint64_t total = 0;+ blob.entries.reserve(*count);+ for (std::size_t i = 0; i < *count; ++i) {+ const std::size_t at = r.offset();+ const auto cid = r.id();+ if (!cid)+ return unexpected(cid.error());+ const auto length = r.varint();+ if (!length)+ return unexpected(length.error());+ if (*length == 0)+ return fail(ErrorKind::InvalidValue, at);+ if (blob.form == BlobForm::Leaf && *length > MAX_CHUNK_LEN)+ return fail(ErrorKind::LimitExceeded, at);+ const std::uint64_t next = total + *length;+ if (next < total)+ return fail(ErrorKind::InvalidValue, at);+ total = next;+ blob.entries.push_back(BlobEntry{*cid, *length});+ }+ const auto fin = r.finish();+ if (!fin)+ return unexpected(fin.error());+ return blob;+}++struct NodeRef {+ Id id{};+ std::uint64_t length = 0;+};++struct Group {+ std::size_t start = 0;+ std::size_t count = 0;+};++static bool manifest_cut_after(const Id &id, std::size_t current_len) {+ if (current_len >= MAX_MANIFEST_ENTRIES)+ return true;+ if (current_len < 16)+ return false;+ return id[0] == 0;+}++BlobBuild build_blob(Bytes data) {+ BlobBuild build;+ if (data.size() <= INLINE_THRESHOLD) {+ auto body = encode_inline_blob(data);+ if (!body)+ return build;+ build.root = object_id(TYPE_BLOB, bytes_of(*body));+ RawObject object{TYPE_BLOB, std::move(*body), std::nullopt};+ object.id = build.root;+ build.objects.push_back(std::move(object));+ return build;+ }++ std::vector<NodeRef> level;+ std::size_t off = 0;+ while (off < data.size()) {+ const std::size_t n = fastcdc_next(data.subspan(off));+ const Bytes chunk = data.subspan(off, n);+ const Id cid = object_id(TYPE_CHUNK, chunk);+ RawObject object{TYPE_CHUNK,+ std::vector<std::uint8_t>(chunk.begin(), chunk.end()),+ std::nullopt};+ object.id = cid;+ build.objects.push_back(std::move(object));+ level.push_back(NodeRef{cid, static_cast<std::uint64_t>(n)});+ off += n;+ }++ bool leaf_level = true;+ for (;;) {+ std::vector<Group> groups;+ std::size_t start = 0;+ for (std::size_t i = 0; i < level.size(); ++i) {+ const std::size_t current = i - start + 1;+ if (manifest_cut_after(level[i].id, current) || i + 1 == level.size()) {+ groups.push_back(Group{start, current});+ start = i + 1;+ }+ }++ std::vector<NodeRef> next;+ for (const Group &group : groups) {+ ByteWriter w(group.count * 40 + 8);+ w.u8(static_cast<std::uint8_t>(leaf_level ? BlobForm::Leaf+ : BlobForm::Interior));+ w.varint(group.count);+ std::uint64_t total = 0;+ for (std::size_t i = 0; i < group.count; ++i) {+ const NodeRef &node = level[group.start + i];+ w.id(node.id);+ w.varint(node.length);+ total += node.length;+ }+ auto body = w.take();+ const Id node_id = object_id(TYPE_BLOB, bytes_of(body));+ RawObject object{TYPE_BLOB, std::move(body), std::nullopt};+ object.id = node_id;+ build.objects.push_back(std::move(object));+ next.push_back(NodeRef{node_id, total});+ }++ if (next.size() == 1) {+ build.root = next.front().id;+ break;+ }+ level = std::move(next);+ leaf_level = false;+ }+ return build;+}++// ---------------------------------------------------------------------------+// Trees+// ---------------------------------------------------------------------------++static bool valid_tree_kind(std::uint8_t kind) {+ return kind >= KIND_FILE && kind <= KIND_CONFLICT;+}++static bool valid_submodule_target(const Id &id) {+ for (std::size_t i = 20; i < ID_LEN; ++i) {+ if (id[i] != 0)+ return false;+ }+ return true;+}++Result<Tree> decode_tree(Bytes body) {+ Reader r(body);+ const auto count = r.list_len(MAX_TREE_ENTRIES);+ if (!count)+ return unexpected(count.error());+ Tree tree;+ tree.entries.reserve(*count);+ std::optional<std::string> prev;+ for (std::size_t i = 0; i < *count; ++i) {+ const std::size_t at = r.offset();+ auto name = r.string_bytes(MAX_NAME_LEN);+ if (!name)+ return unexpected(name.error());+ if (!valid_name(*name))+ return fail(ErrorKind::InvalidName, at);+ if (prev) {+ const int c = compare(bytes_of(*prev), bytes_of(*name));+ if (c == 0)+ return fail(ErrorKind::Duplicate, at);+ if (c > 0)+ return fail(ErrorKind::Unsorted, at);+ }+ const auto kind = r.u8();+ if (!kind)+ return unexpected(kind.error());+ if (!valid_tree_kind(*kind))+ return fail(ErrorKind::InvalidValue, at);+ const auto target = r.id();+ if (!target)+ return unexpected(target.error());+ if (*kind == KIND_SUBMODULE && !valid_submodule_target(*target))+ return fail(ErrorKind::InvalidValue, at);+ tree.entries.push_back(TreeEntry{std::move(*name), *kind, *target});+ prev = tree.entries.back().name;+ }+ const auto fin = r.finish();+ if (!fin)+ return unexpected(fin.error());+ tree.body.assign(body.begin(), body.end());+ return tree;+}++Result<std::vector<std::uint8_t>>+encode_tree(const std::vector<TreeEntry> &entries) {+ ByteWriter w(entries.size() * 48 + 8);+ w.varint(entries.size());+ std::optional<std::string> prev;+ for (std::size_t i = 0; i < entries.size(); ++i) {+ const auto &e = entries[i];+ if (!valid_name(e.name))+ return fail(ErrorKind::InvalidName, i);+ if (prev && compare(bytes_of(*prev), bytes_of(e.name)) >= 0)+ return fail(ErrorKind::Unsorted, i);+ if (!valid_tree_kind(e.kind))+ return fail(ErrorKind::InvalidValue, i);+ w.length_prefixed(e.name);+ w.u8(e.kind);+ w.id(e.target);+ prev = e.name;+ }+ return w.take();+}++// ---------------------------------------------------------------------------+// Commits+// ---------------------------------------------------------------------------++static Result<std::vector<Id>> read_parents(Reader &r) {+ const auto n = r.list_len(1024);+ if (!n)+ return unexpected(n.error());+ std::vector<Id> out;+ out.reserve(*n);+ for (std::size_t i = 0; i < *n; ++i) {+ const auto id = r.id();+ if (!id)+ return unexpected(id.error());+ out.push_back(*id);+ }+ return out;+}++static Result<std::vector<Rename>>+read_renames(Reader &r, std::size_t parent_count, std::uint8_t state) {+ const auto n = r.list_len(1'000'000);+ if (!n)+ return unexpected(n.error());+ std::vector<Rename> out;+ if (state == RENAMES_UNKNOWN) {+ if (*n != 0)+ return fail(ErrorKind::InvalidValue, r.offset());+ return out;+ }+ out.reserve(*n);+ std::uint64_t prev_parent = 0;+ std::string prev_path;+ bool have_prev = false;+ for (std::size_t i = 0; i < *n; ++i) {+ const std::size_t at = r.offset();+ const auto parent = r.varint();+ if (!parent)+ return unexpected(parent.error());+ const auto kind = r.u8();+ if (!kind)+ return unexpected(kind.error());+ auto from = r.string_bytes(MAX_PATH_LEN);+ if (!from)+ return unexpected(from.error());+ auto to = r.string_bytes(MAX_PATH_LEN);+ if (!to)+ return unexpected(to.error());+ if (*parent >= parent_count)+ return fail(ErrorKind::InvalidValue, at);+ if (*kind > 1)+ return fail(ErrorKind::InvalidValue, at);+ if (!valid_path(*from) || !valid_path(*to))+ return fail(ErrorKind::InvalidName, at);+ if (have_prev) {+ if (*parent < prev_parent)+ return fail(ErrorKind::Unsorted, at);+ if (*parent == prev_parent &&+ compare(bytes_of(prev_path), bytes_of(*to)) >= 0)+ return fail(ErrorKind::Unsorted, at);+ }+ out.push_back(Rename{*parent, *kind, std::move(*from), std::move(*to)});+ prev_parent = *parent;+ prev_path = out.back().to_path;+ have_prev = true;+ }+ return out;+}++static Result<std::vector<KeyValue>> read_extra(Reader &r) {+ const auto n = r.list_len(1024);+ if (!n)+ return unexpected(n.error());+ std::vector<KeyValue> out;+ out.reserve(*n);+ for (std::size_t i = 0; i < *n; ++i) {+ const std::size_t at = r.offset();+ auto key = r.string_bytes(MAX_NAME_LEN);+ if (!key)+ return unexpected(key.error());+ auto value = r.string_bytes(MAX_MESSAGE_LEN);+ if (!value)+ return unexpected(value.error());+ if (key->empty())+ return fail(ErrorKind::InvalidValue, at);+ out.push_back(KeyValue{std::move(*key), std::move(*value)});+ }+ return out;+}++Result<Commit> decode_commit(Bytes body) {+ Reader r(body);+ const auto version = r.u8();+ if (!version)+ return unexpected(version.error());+ if (*version != 1)+ return fail(ErrorKind::UnsupportedVersion, 0);+ Commit commit;+ commit.version = *version;+ auto parents = read_parents(r);+ if (!parents)+ return unexpected(parents.error());+ commit.parents = std::move(*parents);+ const auto root = r.id();+ if (!root)+ return unexpected(root.error());+ commit.root_tree = *root;+ const auto change = r.raw(CHANGE_ID_LEN);+ if (!change)+ return unexpected(change.error());+ std::memcpy(commit.change_id.data(), change->data(), CHANGE_ID_LEN);+ auto author = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);+ if (!author)+ return unexpected(author.error());+ commit.author =+ Sig{author->name, author->email, author->seconds, author->tz_min};+ auto committer = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);+ if (!committer)+ return unexpected(committer.error());+ commit.committer = Sig{committer->name, committer->email, committer->seconds,+ committer->tz_min};+ auto message = r.string_bytes(MAX_MESSAGE_LEN);+ if (!message)+ return unexpected(message.error());+ commit.message = std::move(*message);+ const auto state = r.u8();+ if (!state)+ return unexpected(state.error());+ if (*state > 1)+ return fail(ErrorKind::InvalidValue, r.offset() - 1);+ commit.renames_state = *state;+ auto renames = read_renames(r, commit.parents.size(), commit.renames_state);+ if (!renames)+ return unexpected(renames.error());+ commit.renames = std::move(*renames);+ auto extra = read_extra(r);+ if (!extra)+ return unexpected(extra.error());+ commit.extra = std::move(*extra);+ const auto fin = r.finish();+ if (!fin)+ return unexpected(fin.error());+ return commit;+}++std::vector<std::uint8_t> encode_commit(const Commit &commit) {+ ByteWriter w(256);+ w.u8(commit.version);+ w.varint(commit.parents.size());+ for (const auto &p : commit.parents)+ w.id(p);+ w.id(commit.root_tree);+ w.raw(Bytes(commit.change_id.data(), commit.change_id.size()));+ w.sig(Reader::Sig{commit.author.name, commit.author.email,+ commit.author.seconds, commit.author.tz_min});+ w.sig(Reader::Sig{commit.committer.name, commit.committer.email,+ commit.committer.seconds, commit.committer.tz_min});+ w.length_prefixed(commit.message);+ w.u8(commit.renames_state);+ w.varint(commit.renames.size());+ for (const auto &r : commit.renames) {+ w.varint(r.parent_index);+ w.u8(r.kind);+ w.length_prefixed(r.from_path);+ w.length_prefixed(r.to_path);+ }+ w.varint(commit.extra.size());+ for (const auto &kv : commit.extra) {+ w.length_prefixed(kv.key);+ w.length_prefixed(kv.value);+ }+ return w.take();+}++// ---------------------------------------------------------------------------+// Conflicts+// ---------------------------------------------------------------------------++static bool conflict_kind_valid(std::uint8_t kind) {+ return kind == 0 || (kind >= KIND_FILE && kind <= KIND_CONFLICT);+}++static Result<ConflictValue> read_conflict_value(Reader &r) {+ const std::size_t at = r.offset();+ const auto kind = r.u8();+ if (!kind)+ return unexpected(kind.error());+ if (!conflict_kind_valid(*kind))+ return fail(ErrorKind::InvalidValue, at);+ if (*kind == 0)+ return ConflictValue{0, std::nullopt};+ const auto target = r.id();+ if (!target)+ return unexpected(target.error());+ return ConflictValue{*kind, *target};+}++static Result<std::vector<ConflictValue>> read_conflict_values(Reader &r) {+ const auto n = r.list_len(MAX_CONFLICT_TERMS);+ if (!n)+ return unexpected(n.error());+ std::vector<ConflictValue> out;+ out.reserve(*n);+ for (std::size_t i = 0; i < *n; ++i) {+ auto value = read_conflict_value(r);+ if (!value)+ return unexpected(value.error());+ out.push_back(*value);+ }+ return out;+}++static bool conflict_value_equal(const ConflictValue &a,+ const ConflictValue &b) {+ if (a.kind != b.kind)+ return false;+ if (a.kind == 0)+ return true;+ return a.target == b.target;+}++Result<Conflict> decode_conflict(Bytes body) {+ Reader r(body);+ Conflict conflict;+ auto adds = read_conflict_values(r);+ if (!adds)+ return unexpected(adds.error());+ conflict.adds = std::move(*adds);+ auto removes = read_conflict_values(r);+ if (!removes)+ return unexpected(removes.error());+ conflict.removes = std::move(*removes);+ const std::size_t at = r.offset();+ const auto fin = r.finish();+ if (!fin)+ return unexpected(fin.error());+ if (conflict.removes.empty())+ return fail(ErrorKind::InvalidValue, at);+ if (conflict.adds.size() != conflict.removes.size() + 1)+ return fail(ErrorKind::InvalidValue, at);+ if (conflict.adds.size() + conflict.removes.size() > MAX_CONFLICT_TERMS)+ return fail(ErrorKind::LimitExceeded, at);+ for (const auto &a : conflict.adds) {+ for (const auto &rem : conflict.removes) {+ if (conflict_value_equal(a, rem))+ return fail(ErrorKind::InvalidValue, at);+ }+ }+ bool all_same = true;+ for (std::size_t i = 1; i < conflict.adds.size(); ++i) {+ if (!conflict_value_equal(conflict.adds[0], conflict.adds[i])) {+ all_same = false;+ break;+ }+ }+ if (all_same)+ return fail(ErrorKind::InvalidValue, at);+ return conflict;+}++std::vector<std::uint8_t> encode_conflict(const Conflict &conflict) {+ ByteWriter w((conflict.adds.size() + conflict.removes.size()) * 40 + 16);+ w.varint(conflict.adds.size());+ for (const auto &v : conflict.adds) {+ w.u8(v.kind);+ if (v.kind != 0 && v.target)+ w.id(*v.target);+ }+ w.varint(conflict.removes.size());+ for (const auto &v : conflict.removes) {+ w.u8(v.kind);+ if (v.kind != 0 && v.target)+ w.id(*v.target);+ }+ return w.take();+}++// ---------------------------------------------------------------------------+// Views+// ---------------------------------------------------------------------------++static bool view_name_valid(std::string_view name) {+ if (name.empty() || name.size() > MAX_NAME_LEN)+ return false;+ return name.find('\0') == std::string_view::npos;+}++static Result<std::vector<Id>> read_view_heads(Reader &r) {+ const auto n = r.list_len(1'000'000);+ if (!n)+ return unexpected(n.error());+ std::vector<Id> out;+ out.reserve(*n);+ std::optional<Id> prev;+ for (std::size_t i = 0; i < *n; ++i) {+ const std::size_t at = r.offset();+ const auto id = r.id();+ if (!id)+ return unexpected(id.error());+ if (prev) {+ const int c = std::memcmp(prev->data(), id->data(), ID_LEN);+ if (c == 0)+ return fail(ErrorKind::Duplicate, at);+ if (c > 0)+ return fail(ErrorKind::Unsorted, at);+ }+ out.push_back(*id);+ prev = *id;+ }+ return out;+}++static Result<std::vector<std::optional<Id>>>+read_opt_id_list(Reader &r, std::size_t max) {+ const auto n = r.list_len(max);+ if (!n)+ return unexpected(n.error());+ std::vector<std::optional<Id>> out;+ out.reserve(*n);+ for (std::size_t i = 0; i < *n; ++i) {+ const auto id = r.opt_id();+ if (!id)+ return unexpected(id.error());+ out.push_back(*id);+ }+ return out;+}++static bool opt_id_contains(const std::vector<std::optional<Id>> &ids,+ const std::optional<Id> &id) {+ for (const auto &x : ids) {+ if (x.has_value() == id.has_value()) {+ if (!x || std::memcmp(x->data(), id->data(), ID_LEN) == 0)+ return true;+ }+ }+ return false;+}++static Result<TargetSet> read_target_set(Reader &r) {+ const std::size_t at = r.offset();+ TargetSet set;+ auto adds = read_opt_id_list(r, 64);+ if (!adds)+ return unexpected(adds.error());+ set.adds = std::move(*adds);+ auto removes = read_opt_id_list(r, 64);+ if (!removes)+ return unexpected(removes.error());+ set.removes = std::move(*removes);+ if (set.adds.empty())+ return fail(ErrorKind::InvalidValue, at);+ if (set.adds.size() != set.removes.size() + 1)+ return fail(ErrorKind::InvalidValue, at);+ if (set.adds.size() + set.removes.size() > MAX_CONFLICT_TERMS)+ return fail(ErrorKind::LimitExceeded, at);+ for (const auto &a : set.adds) {+ if (opt_id_contains(set.removes, a))+ return fail(ErrorKind::InvalidValue, at);+ }+ bool all_same = true;+ for (std::size_t i = 1; i < set.adds.size(); ++i) {+ const bool same =+ set.adds[0].has_value() == set.adds[i].has_value() &&+ (!set.adds[0] ||+ std::memcmp(set.adds[0]->data(), set.adds[i]->data(), ID_LEN) == 0);+ if (!same) {+ all_same = false;+ break;+ }+ }+ if (all_same && set.adds.size() > 1)+ return fail(ErrorKind::InvalidValue, at);+ return set;+}++static Result<std::vector<Bookmark>> read_bookmarks(Reader &r) {+ const auto n = r.list_len(1'000'000);+ if (!n)+ return unexpected(n.error());+ std::vector<Bookmark> out;+ out.reserve(*n);+ std::optional<std::string> prev;+ for (std::size_t i = 0; i < *n; ++i) {+ const std::size_t at = r.offset();+ auto name = r.string_bytes(MAX_NAME_LEN);+ if (!name)+ return unexpected(name.error());+ if (!view_name_valid(*name))+ return fail(ErrorKind::InvalidName, at);+ if (prev) {+ const int c = compare(bytes_of(*prev), bytes_of(*name));+ if (c == 0)+ return fail(ErrorKind::Duplicate, at);+ if (c > 0)+ return fail(ErrorKind::Unsorted, at);+ }+ auto targets = read_target_set(r);+ if (!targets)+ return unexpected(targets.error());+ out.push_back(Bookmark{std::move(*name), std::move(*targets)});+ prev = out.back().name;+ }+ return out;+}++static Result<std::vector<TagRef>> read_tags(Reader &r) {+ const auto n = r.list_len(1'000'000);+ if (!n)+ return unexpected(n.error());+ std::vector<TagRef> out;+ out.reserve(*n);+ std::optional<std::string> prev;+ for (std::size_t i = 0; i < *n; ++i) {+ const std::size_t at = r.offset();+ auto name = r.string_bytes(MAX_NAME_LEN);+ if (!name)+ return unexpected(name.error());+ if (!view_name_valid(*name))+ return fail(ErrorKind::InvalidName, at);+ if (prev) {+ const int c = compare(bytes_of(*prev), bytes_of(*name));+ if (c == 0)+ return fail(ErrorKind::Duplicate, at);+ if (c > 0)+ return fail(ErrorKind::Unsorted, at);+ }+ const auto id = r.id();+ if (!id)+ return unexpected(id.error());+ out.push_back(TagRef{std::move(*name), *id});+ prev = out.back().name;+ }+ return out;+}++static Result<std::vector<RemoteRef>> read_remote_refs(Reader &r) {+ const auto n = r.list_len(1'000'000);+ if (!n)+ return unexpected(n.error());+ std::vector<RemoteRef> out;+ out.reserve(*n);+ std::optional<std::pair<std::string, std::string>> prev;+ for (std::size_t i = 0; i < *n; ++i) {+ const std::size_t at = r.offset();+ auto remote = r.string_bytes(MAX_NAME_LEN);+ if (!remote)+ return unexpected(remote.error());+ auto name = r.string_bytes(MAX_NAME_LEN);+ if (!name)+ return unexpected(name.error());+ if (!view_name_valid(*remote) || !view_name_valid(*name))+ return fail(ErrorKind::InvalidName, at);+ if (prev) {+ const int c1 = compare(bytes_of(prev->first), bytes_of(*remote));+ const int c2 =+ c1 != 0 ? 0 : compare(bytes_of(prev->second), bytes_of(*name));+ if (c1 == 0 && c2 == 0)+ return fail(ErrorKind::Duplicate, at);+ if (c1 > 0 || (c1 == 0 && c2 > 0))+ return fail(ErrorKind::Unsorted, at);+ }+ const auto id = r.id();+ if (!id)+ return unexpected(id.error());+ out.push_back(RemoteRef{std::move(*remote), std::move(*name), *id});+ prev = std::make_pair(out.back().remote, out.back().name);+ }+ return out;+}++static Result<std::vector<WorkspaceRef>> read_workspaces(Reader &r) {+ const auto n = r.list_len(1'000'000);+ if (!n)+ return unexpected(n.error());+ std::vector<WorkspaceRef> out;+ out.reserve(*n);+ std::optional<std::string> prev;+ for (std::size_t i = 0; i < *n; ++i) {+ const std::size_t at = r.offset();+ auto workspace = r.string_bytes(MAX_NAME_LEN);+ if (!workspace)+ return unexpected(workspace.error());+ if (!view_name_valid(*workspace))+ return fail(ErrorKind::InvalidName, at);+ if (prev) {+ const int c = compare(bytes_of(*prev), bytes_of(*workspace));+ if (c == 0)+ return fail(ErrorKind::Duplicate, at);+ if (c > 0)+ return fail(ErrorKind::Unsorted, at);+ }+ const auto id = r.id();+ if (!id)+ return unexpected(id.error());+ out.push_back(WorkspaceRef{std::move(*workspace), *id});+ prev = out.back().workspace;+ }+ return out;+}++Result<View> decode_view(Bytes body) {+ Reader r(body);+ View view;+ auto heads = read_view_heads(r);+ if (!heads)+ return unexpected(heads.error());+ view.heads = std::move(*heads);+ auto bookmarks = read_bookmarks(r);+ if (!bookmarks)+ return unexpected(bookmarks.error());+ view.bookmarks = std::move(*bookmarks);+ auto tags = read_tags(r);+ if (!tags)+ return unexpected(tags.error());+ view.tags = std::move(*tags);+ auto remote_refs = read_remote_refs(r);+ if (!remote_refs)+ return unexpected(remote_refs.error());+ view.remote_refs = std::move(*remote_refs);+ auto workspaces = read_workspaces(r);+ if (!workspaces)+ return unexpected(workspaces.error());+ view.working_copies = std::move(*workspaces);+ const auto fin = r.finish();+ if (!fin)+ return unexpected(fin.error());+ return view;+}++static void put_target_set(ByteWriter &w, const TargetSet &set) {+ w.varint(set.adds.size());+ for (const auto &id : set.adds)+ w.opt_id(id);+ w.varint(set.removes.size());+ for (const auto &id : set.removes)+ w.opt_id(id);+}++std::vector<std::uint8_t> encode_view(const View &view) {+ ByteWriter w(256);+ w.varint(view.heads.size());+ for (const auto &id : view.heads)+ w.id(id);+ w.varint(view.bookmarks.size());+ for (const auto &bookmark : view.bookmarks) {+ w.length_prefixed(bookmark.name);+ put_target_set(w, bookmark.targets);+ }+ w.varint(view.tags.size());+ for (const auto &tag : view.tags) {+ w.length_prefixed(tag.name);+ w.id(tag.target);+ }+ w.varint(view.remote_refs.size());+ for (const auto &ref : view.remote_refs) {+ w.length_prefixed(ref.remote);+ w.length_prefixed(ref.name);+ w.id(ref.target);+ }+ w.varint(view.working_copies.size());+ for (const auto &workspace : view.working_copies) {+ w.length_prefixed(workspace.workspace);+ w.id(workspace.target);+ }+ return w.take();+}++// ---------------------------------------------------------------------------+// Operations+// ---------------------------------------------------------------------------++Result<Operation> decode_operation(Bytes body) {+ Reader r(body);+ Operation op;+ const auto parent_count = r.list_len(1024);+ if (!parent_count)+ return unexpected(parent_count.error());+ op.parents.reserve(*parent_count);+ for (std::size_t i = 0; i < *parent_count; ++i) {+ const auto id = r.id();+ if (!id)+ return unexpected(id.error());+ op.parents.push_back(*id);+ }+ const auto view = r.id();+ if (!view)+ return unexpected(view.error());+ op.view = *view;+ auto start = r.time_ms();+ if (!start)+ return unexpected(start.error());+ op.start = *start;+ auto end = r.time_ms();+ if (!end)+ return unexpected(end.error());+ op.end = *end;+ auto hostname = r.string_bytes(MAX_NAME_LEN);+ if (!hostname)+ return unexpected(hostname.error());+ op.hostname = std::move(*hostname);+ auto username = r.string_bytes(MAX_NAME_LEN);+ if (!username)+ return unexpected(username.error());+ op.username = std::move(*username);+ auto description = r.string_bytes(MAX_MESSAGE_LEN);+ if (!description)+ return unexpected(description.error());+ op.description = std::move(*description);+ const auto tag_count = r.list_len(1024);+ if (!tag_count)+ return unexpected(tag_count.error());+ op.tags.reserve(*tag_count);+ for (std::size_t i = 0; i < *tag_count; ++i) {+ const std::size_t at = r.offset();+ auto key = r.string_bytes(MAX_NAME_LEN);+ if (!key)+ return unexpected(key.error());+ auto value = r.string_bytes(MAX_MESSAGE_LEN);+ if (!value)+ return unexpected(value.error());+ if (key->empty())+ return fail(ErrorKind::InvalidValue, at);+ op.tags.push_back(KeyValue{std::move(*key), std::move(*value)});+ }+ const auto fin = r.finish();+ if (!fin)+ return unexpected(fin.error());+ return op;+}++std::vector<std::uint8_t> encode_operation(const Operation &op) {+ ByteWriter w(256);+ w.varint(op.parents.size());+ for (const auto &p : op.parents)+ w.id(p);+ w.id(op.view);+ w.time_ms(op.start);+ w.time_ms(op.end);+ w.length_prefixed(op.hostname);+ w.length_prefixed(op.username);+ w.length_prefixed(op.description);+ w.varint(op.tags.size());+ for (const auto &kv : op.tags) {+ w.length_prefixed(kv.key);+ w.length_prefixed(kv.value);+ }+ return w.take();+}++bool is_lazy_blob(const Id &id) {+ static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '-',+ 'g', 'i', 't', 'o', 'i', 'd'};+ return std::memcmp(id.data(), prefix, sizeof(prefix)) == 0;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/object.h@@ -0,0 +1,251 @@+#pragma once++#include "common.h"++#include <optional>+#include <string>+#include <vector>++namespace vn {++class Store;++constexpr std::uint8_t TYPE_CHUNK = 1;+constexpr std::uint8_t TYPE_BLOB = 2;+constexpr std::uint8_t TYPE_TREE = 3;+constexpr std::uint8_t TYPE_COMMIT = 4;+constexpr std::uint8_t TYPE_CONFLICT = 5;+constexpr std::uint8_t TYPE_OPERATION = 6;+constexpr std::uint8_t TYPE_VIEW = 7;++std::string_view type_name(std::uint8_t type);+bool type_valid(std::uint8_t type);++struct RawObject {+ std::uint8_t type = 0;+ std::vector<std::uint8_t> body;+ std::optional<Id> id;+};++struct KeyValue {+ std::string key;+ std::string value;+};++// ---------------------------------------------------------------------------+// Names+// ---------------------------------------------------------------------------++bool valid_name(std::string_view name);+bool valid_path(std::string_view path);++// ---------------------------------------------------------------------------+// Blobs+// ---------------------------------------------------------------------------++enum class BlobForm : std::uint8_t { Inline = 0, Leaf = 1, Interior = 2 };++struct BlobEntry {+ Id id{};+ std::uint64_t length = 0;+};++struct Blob {+ BlobForm form = BlobForm::Inline;+ std::vector<std::uint8_t> data;+ std::vector<BlobEntry> entries;+};++Result<Blob> decode_blob(Bytes body);+Result<std::vector<std::uint8_t>> encode_inline_blob(Bytes data);++std::size_t fastcdc_next(Bytes data);+const std::array<std::uint64_t, 256> &fastcdc_gear();++struct BlobBuild {+ Id root{};+ std::vector<RawObject> objects;+};++BlobBuild build_blob(Bytes data);++// ---------------------------------------------------------------------------+// Trees+// ---------------------------------------------------------------------------++constexpr std::uint8_t KIND_FILE = 1;+constexpr std::uint8_t KIND_EXECUTABLE = 2;+constexpr std::uint8_t KIND_SYMLINK = 3;+constexpr std::uint8_t KIND_SUBTREE = 4;+constexpr std::uint8_t KIND_SUBMODULE = 5;+constexpr std::uint8_t KIND_CONFLICT = 6;+constexpr std::uint8_t KIND_MISSING = 0;++struct TreeEntry {+ std::string name;+ std::uint8_t kind = 0;+ Id target{};+};++struct Tree {+ std::vector<TreeEntry> entries;+ std::vector<std::uint8_t> body;+};++Result<Tree> decode_tree(Bytes body);+Result<std::vector<std::uint8_t>>+encode_tree(const std::vector<TreeEntry> &entries);++// ---------------------------------------------------------------------------+// Commits+// ---------------------------------------------------------------------------++constexpr std::uint8_t RENAMES_UNKNOWN = 0;+constexpr std::uint8_t RENAMES_RECORDED = 1;++struct Rename {+ std::uint64_t parent_index = 0;+ std::uint8_t kind = 0;+ std::string from_path;+ std::string to_path;+};++struct Commit {+ std::uint8_t version = 1;+ std::vector<Id> parents;+ Id root_tree{};+ ChangeId change_id{};+ Sig author;+ Sig committer;+ std::string message;+ std::uint8_t renames_state = RENAMES_RECORDED;+ std::vector<Rename> renames;+ std::vector<KeyValue> extra;+};++Result<Commit> decode_commit(Bytes body);+std::vector<std::uint8_t> encode_commit(const Commit &commit);++// ---------------------------------------------------------------------------+// Conflicts+// ---------------------------------------------------------------------------++struct ConflictValue {+ std::uint8_t kind = 0;+ std::optional<Id> target;+};++struct Conflict {+ std::vector<ConflictValue> adds;+ std::vector<ConflictValue> removes;+};++Result<Conflict> decode_conflict(Bytes body);+std::vector<std::uint8_t> encode_conflict(const Conflict &conflict);++// ---------------------------------------------------------------------------+// Operations and views+// ---------------------------------------------------------------------------++struct TargetSet {+ std::vector<std::optional<Id>> adds;+ std::vector<std::optional<Id>> removes;+};++struct Bookmark {+ std::string name;+ TargetSet targets;+};++struct TagRef {+ std::string name;+ Id target{};+};++struct RemoteRef {+ std::string remote;+ std::string name;+ Id target{};+};++struct WorkspaceRef {+ std::string workspace;+ Id target{};+};++struct View {+ std::vector<Id> heads;+ std::vector<Bookmark> bookmarks;+ std::vector<TagRef> tags;+ std::vector<RemoteRef> remote_refs;+ std::vector<WorkspaceRef> working_copies;+};++struct Operation {+ std::vector<Id> parents;+ Id view{};+ Reader::TimeMs start;+ Reader::TimeMs end;+ std::string hostname;+ std::string username;+ std::string description;+ std::vector<KeyValue> tags;+};++Result<View> decode_view(Bytes body);+std::vector<std::uint8_t> encode_view(const View &view);+Result<Operation> decode_operation(Bytes body);+std::vector<std::uint8_t> encode_operation(const Operation &op);++// ---------------------------------------------------------------------------+// Graph, tree walking, and content+// ---------------------------------------------------------------------------++struct LoadedCommit {+ Commit commit;+ std::vector<std::uint8_t> body;+};++std::optional<LoadedCommit> load_commit(Store &store, const Id &id);+bool has_changes(Store &store, const LoadedCommit &loaded);+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::optional<Id> resolve_revision(Store &store, const View &view,+ std::string_view rev);+std::optional<Id> working_copy_id(const View &view);++bool contains_id(const std::vector<Id> &ids, const Id &id);+bool target_contains(const std::vector<std::optional<Id>> &ids, const Id &id);++struct FlatEntry {+ std::string path;+ std::uint8_t kind = 0;+ Id target{};+};++std::vector<FlatEntry> flatten_tree(Store &store, const Id &tree_id);+Result<std::vector<FlatEntry>> flatten_tree_checked(Store &store,+ const Id &tree_id);+std::vector<FlatEntry> flatten_or_empty(Store &store,+ std::optional<Id> tree_id);+const FlatEntry *find_flat(const std::vector<FlatEntry> &entries,+ std::string_view path);+int find_tree_name(const Tree &tree, std::string_view name);+bool tree_conflicted(Store &store, const Id &tree_id);++struct TreeChange {+ std::string path;+ std::uint8_t old_kind = KIND_MISSING;+ std::uint8_t new_kind = KIND_MISSING;+ std::optional<Id> old_id;+ std::optional<Id> new_id;+};++std::vector<TreeChange> compare_trees(Store &store, std::optional<Id> old_tree,+ std::optional<Id> new_tree);++std::optional<std::vector<std::uint8_t>> read_blob(Store &store, const Id &id);+bool is_lazy_blob(const Id &id);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/store.cpp@@ -0,0 +1,1924 @@+#include "store.h"++#include <algorithm>+#include <atomic>+#include <cstring>+#include <iostream>+#include <thread>+#include <unordered_set>++#include <zstd.h>++namespace vn {++// ---------------------------------------------------------------------------+// Layout+// ---------------------------------------------------------------------------++fs::path veins_dir(const fs::path &root) { return root / ".veins"; }+fs::path packs_dir(const fs::path &root) {+ return veins_dir(root) / "store" / "packs";+}+fs::path tmp_dir(const fs::path &root) {+ return veins_dir(root) / "store" / "tmp";+}+fs::path op_heads_dir(const fs::path &root) {+ return veins_dir(root) / "op-heads";+}+fs::path git_dir(const fs::path &root) { return veins_dir(root) / "git"; }+fs::path git_map_dir(const fs::path &root) {+ return veins_dir(root) / "git-map";+}+fs::path working_copy_dir(const fs::path &root) {+ return veins_dir(root) / "working-copy";+}+fs::path resolutions_dir(const fs::path &root) {+ return veins_dir(root) / "resolutions";+}+fs::path config_path(const fs::path &root) {+ return veins_dir(root) / "config";+}+fs::path format_path(const fs::path &root) {+ return veins_dir(root) / "format";+}++std::optional<fs::path> discover_repo(const fs::path &start) {+ std::error_code ec;+ fs::path current = fs::absolute(start, ec);+ if (ec)+ return std::nullopt;+ current = fs::weakly_canonical(current, ec);+ if (ec)+ return std::nullopt;+ for (;;) {+ if (path_is_file(current / ".veins" / "format"))+ return current;+ const fs::path parent = current.parent_path();+ if (parent == current || parent.empty())+ return std::nullopt;+ current = parent;+ }+}++static bool migrate_dir(const fs::path &from, const fs::path &to) {+ if (path_is_dir(from) && !path_is_dir(to)) {+ std::error_code ec;+ fs::rename(from, to, ec);+ return !ec;+ }+ return true;+}++static bool ensure_layout(const fs::path &root) {+ if (!migrate_dir(veins_dir(root) / "op_heads", op_heads_dir(root)))+ return false;+ if (!migrate_dir(veins_dir(root) / "working_copy", working_copy_dir(root)))+ return false;+ const fs::path dirs[] = {+ veins_dir(root), veins_dir(root) / "store",+ packs_dir(root), tmp_dir(root),+ op_heads_dir(root), git_map_dir(root),+ git_map_dir(root) / "raw", working_copy_dir(root),+ resolutions_dir(root),+ };+ for (const auto &dir : dirs) {+ if (!ensure_directory(dir))+ return false;+ }+ return true;+}++Result<fs::path> init_repo(const fs::path &path) {+ fs::path root = path.lexically_normal();+ if (root.empty())+ root = ".";+ if (!path_is_dir(root)) {+ if (!ensure_directory(root))+ return unexpected(Error{ErrorKind::Io, 4, "init failed"});+ }+ const fs::path format = format_path(root);+ const std::string_view expected = "veins-store 1";+ if (path_exists(format)) {+ auto data = read_file(format);+ if (!data)+ return unexpected(Error{ErrorKind::Io, 3, "init failed"});+ if (!equals(bytes_of(*data), bytes_of(expected)))+ return unexpected(Error{ErrorKind::InvalidValue, 2, "init failed"});+ }+ if (!ensure_layout(root))+ return unexpected(Error{ErrorKind::Io, 4, "init failed"});+ if (!path_exists(format)) {+ if (!write_file(format, bytes_of(expected)))+ return unexpected(Error{ErrorKind::Io, 11, "init failed"});+ }+ if (!path_exists(config_path(root))) {+ (void)write_file(config_path(root), Bytes{});+ }+ return root;+}++// ---------------------------------------------------------------------------+// Pack decoding+// ---------------------------------------------------------------------------++std::optional<std::size_t> Pack::find_by_offset(std::uint64_t offset) const {+ std::size_t lo = 0;+ std::size_t hi = records.size();+ while (lo < hi) {+ const std::size_t mid = lo + (hi - lo) / 2;+ const std::uint64_t cur = records[mid].record_off;+ if (cur == offset)+ return mid;+ if (cur < offset)+ lo = mid + 1;+ else+ hi = mid;+ }+ return std::nullopt;+}++Result<std::vector<std::uint8_t>> Pack::get(std::size_t record_index) const {+ if (record_index >= records.size())+ return fail(ErrorKind::Corrupt, 0);+ const PackRecord &rec = records[record_index];+ const auto raw_len = static_cast<std::size_t>(rec.raw_len);+ if (raw_len == 0)+ return std::vector<std::uint8_t>{};+ const auto off = static_cast<std::size_t>(rec.data_off);+ const auto stored_len = static_cast<std::size_t>(rec.stored_len);+ if (off > data.size() || stored_len > data.size() - off)+ return fail(ErrorKind::Corrupt, off);+ if (rec.compression == 0) {+ return std::vector<std::uint8_t>(+ data.begin() + static_cast<std::ptrdiff_t>(off),+ data.begin() + static_cast<std::ptrdiff_t>(off + stored_len));+ }+ std::vector<std::uint8_t> out(raw_len);+ const std::size_t n =+ ZSTD_decompress(out.data(), raw_len, data.data() + off, stored_len);+ if (ZSTD_isError(n) || n != raw_len)+ return fail(ErrorKind::Corrupt, off);+ return out;+}++static std::size_t pack_type_limit(std::uint8_t type) {+ return type == TYPE_CHUNK ? MAX_CHUNK_LEN : MAX_OBJECT_BODY;+}++Result<Pack> decode_pack(std::vector<std::uint8_t> data) {+ constexpr std::size_t header_len = 16;+ constexpr std::size_t record_min = 36;+ if (data.size() < header_len + 32)+ return fail(ErrorKind::UnexpectedEnd, 0);+ if (std::memcmp(data.data(), "VPK1", 4) != 0)+ return fail(ErrorKind::InvalidMagic, 0);+ Reader header(Bytes(data.data(), header_len));+ (void)header.raw(4);+ const auto version = header.u32le();+ if (!version)+ return unexpected(version.error());+ if (*version != 1)+ return fail(ErrorKind::UnsupportedVersion, 4);+ const auto count_u64 = header.u64le();+ if (!count_u64)+ return unexpected(count_u64.error());++ const std::size_t body_end = data.size() - 32;+ const auto digest = blake3_hash(Bytes(data.data(), body_end));+ if (!equals(Bytes(digest.data(), digest.size()),+ Bytes(data.data() + body_end, 32)))+ return fail(ErrorKind::HashMismatch, body_end);++ if (*count_u64 > body_end / record_min)+ return fail(ErrorKind::LimitExceeded, 8);+ const std::size_t count = static_cast<std::size_t>(*count_u64);++ Reader r(Bytes(data.data(), body_end));+ (void)r.raw(header_len);+ Pack pack;+ pack.records.reserve(count);+ for (std::size_t i = 0; i < count; ++i) {+ PackRecord rec;+ rec.record_off = r.offset();+ const auto id = r.id();+ if (!id)+ return unexpected(id.error());+ rec.id = *id;+ const auto kind = r.u8();+ if (!kind)+ return unexpected(kind.error());+ if (!type_valid(*kind))+ return fail(ErrorKind::InvalidValue, r.offset() - 1);+ rec.type = *kind;+ const auto comp = r.u8();+ if (!comp)+ return unexpected(comp.error());+ if (*comp > 1)+ return fail(ErrorKind::InvalidValue, r.offset() - 1);+ rec.compression = *comp;+ const std::size_t at = r.offset();+ const auto raw_len = r.varint();+ if (!raw_len)+ return unexpected(raw_len.error());+ const auto stored_len = r.varint();+ if (!stored_len)+ return unexpected(stored_len.error());+ if (*raw_len == 0)+ return fail(ErrorKind::InvalidValue, at);+ if (*raw_len > pack_type_limit(rec.type))+ return fail(ErrorKind::LimitExceeded, at);+ if (rec.compression == 0 && *raw_len != *stored_len)+ return fail(ErrorKind::InvalidValue, at);+ if (*stored_len > r.remaining())+ return fail(ErrorKind::UnexpectedEnd, at);+ rec.raw_len = *raw_len;+ rec.stored_len = *stored_len;+ rec.data_off = r.offset();+ const auto body = r.raw(static_cast<std::size_t>(*stored_len));+ if (!body)+ return unexpected(body.error());+ pack.records.push_back(rec);+ }+ if (r.offset() != body_end)+ return fail(ErrorKind::TrailingBytes, r.offset());+ std::memcpy(pack.trailer.data(), data.data() + body_end, 32);+ pack.data = std::move(data);+ return pack;+}++// ---------------------------------------------------------------------------+// Index+// ---------------------------------------------------------------------------++std::optional<std::size_t> Index::find(const Id &id) const {+ std::size_t lo = 0;+ std::size_t hi = ids.size();+ while (lo < hi) {+ const std::size_t mid = lo + (hi - lo) / 2;+ const int c = std::memcmp(ids[mid].data(), id.data(), ID_LEN);+ if (c == 0)+ return mid;+ if (c < 0)+ lo = mid + 1;+ else+ hi = mid;+ }+ return std::nullopt;+}++Result<Index> decode_index(+ std::vector<std::uint8_t> data,+ const std::optional<std::array<std::uint8_t, 32>> &expected_pack_trailer) {+ constexpr std::size_t base = 1032 + 64;+ if (data.size() < base)+ return fail(ErrorKind::UnexpectedEnd, 0);+ if (std::memcmp(data.data(), "VIX1", 4) != 0)+ return fail(ErrorKind::InvalidMagic, 0);+ Reader r(Bytes(data.data(), data.size()));+ (void)r.raw(4);+ const auto version = r.u32le();+ if (!version)+ return unexpected(version.error());+ if (*version != 1)+ return fail(ErrorKind::UnsupportedVersion, 4);+ std::array<std::uint32_t, 256> fanout{};+ std::uint32_t prev = 0;+ for (std::size_t i = 0; i < 256; ++i) {+ const auto v = r.u32le();+ if (!v)+ return unexpected(v.error());+ if (*v < prev)+ return fail(ErrorKind::Unsorted, r.offset() - 4);+ prev = *v;+ fanout[i] = *v;+ }+ const std::size_t body = data.size() - base;+ if (body % 40 != 0)+ return fail(ErrorKind::TrailingBytes, base);+ const std::size_t count = body / 40;+ if (count != fanout[255])+ return fail(ErrorKind::Corrupt, 1032);++ Index index;+ index.ids.resize(count);+ index.offsets.resize(count);+ std::memcpy(index.ids.data(), data.data() + 1032, count * 32);+ std::memcpy(index.offsets.data(), data.data() + 1032 + count * 32, count * 8);+ std::memcpy(index.pack_trailer.data(),+ data.data() + 1032 + count * 32 + count * 8, 32);+ const std::size_t index_trailer_off = data.size() - 32;+ const auto digest = blake3_hash(Bytes(data.data(), index_trailer_off));+ if (!equals(Bytes(digest.data(), digest.size()),+ Bytes(data.data() + index_trailer_off, 32)))+ return fail(ErrorKind::HashMismatch, index_trailer_off);+ if (expected_pack_trailer &&+ !equals(Bytes(index.pack_trailer.data(), 32),+ Bytes(expected_pack_trailer->data(), 32)))+ return fail(ErrorKind::Corrupt, index_trailer_off);++ std::array<std::uint32_t, 256> counts{};+ for (std::size_t i = 0; i < count; ++i) {+ if (i > 0) {+ const int c =+ std::memcmp(index.ids[i - 1].data(), index.ids[i].data(), ID_LEN);+ if (c == 0)+ return fail(ErrorKind::Duplicate, 1032 + i * 32);+ if (c > 0)+ return fail(ErrorKind::Unsorted, 1032 + i * 32);+ }+ counts[index.ids[i][0]]++;+ }+ std::uint32_t running = 0;+ for (std::size_t i = 0; i < 256; ++i) {+ running += counts[i];+ if (fanout[i] != running)+ return fail(ErrorKind::Corrupt, 8 + i * 4);+ }+ return Result<Index>(std::move(index));+}++static void write_u64le(std::vector<std::uint8_t> &out, std::size_t off,+ std::uint64_t value) {+ for (int i = 0; i < 8; ++i)+ out[off + static_cast<std::size_t>(i)] =+ static_cast<std::uint8_t>((value >> (i * 8)) & 255u);+}++std::vector<std::uint8_t>+encode_index(const std::vector<RecordMeta> &records,+ const std::array<std::uint8_t, 32> &trailer) {+ std::array<std::uint32_t, 256> counts{};+ for (const auto &rec : records)+ counts[rec.id[0]]++;+ ByteWriter w(records.size() * 40 + 128);+ w.raw("VIX1");+ w.u32le(1);+ std::uint32_t running = 0;+ for (std::size_t i = 0; i < 256; ++i) {+ running += counts[i];+ w.u32le(running);+ }+ for (const auto &rec : records)+ w.id(rec.id);+ for (const auto &rec : records)+ w.u64le(rec.offset);+ w.raw(Bytes(trailer.data(), trailer.size()));+ auto bytes = w.take();+ const auto digest = blake3_hash(bytes_of(bytes));+ bytes.insert(bytes.end(), digest.begin(), digest.end());+ return bytes;+}++// ---------------------------------------------------------------------------+// Pack encoding+// ---------------------------------------------------------------------------++static std::vector<std::uint8_t> zstd_compress(Bytes data) {+ if (data.empty())+ return {};+ const std::size_t bound = ZSTD_compressBound(data.size());+ std::vector<std::uint8_t> out(bound);+ const std::size_t n =+ ZSTD_compress(out.data(), bound, data.data(), data.size(), 1);+ if (ZSTD_isError(n) || n >= data.size())+ return {};+ out.resize(n);+ return out;+}++PackOutput encode_pack(const std::vector<RawObject> &objects) {+ PackOutput output;+ std::set<Id> seen;+ struct Pending {+ const RawObject *object = nullptr;+ Id id{};+ std::uint8_t compression = 0;+ std::vector<std::uint8_t> compressed;+ };+ std::vector<Pending> pending;+ pending.reserve(objects.size());+ for (const auto &object : objects) {+ if (!type_valid(object.type))+ continue;+ const Id id =+ object.id ? *object.id : object_id(object.type, bytes_of(object.body));+ if (!seen.insert(id).second)+ continue;+ pending.push_back(Pending{&object, id, 0, {}});+ }++ auto compress_one = [](Pending &item) {+ if (item.object->body.size() < 64)+ return;+ item.compressed = zstd_compress(bytes_of(item.object->body));+ item.compression = item.compressed.empty() ? 0 : 1;+ };+ if (pending.size() > 1) {+ std::size_t workers = available_cpu_count();+ if (workers == 0)+ workers = 1;+ workers = std::min<std::size_t>(workers, pending.size());+ workers = std::min<std::size_t>(workers, 16);+ if (workers > 1) {+ std::atomic<std::size_t> next{0};+ std::vector<std::thread> threads;+ threads.reserve(workers);+ for (std::size_t w = 0; w < workers; ++w) {+ threads.emplace_back([&]() {+ for (;;) {+ const std::size_t index = next.fetch_add(1);+ if (index >= pending.size())+ return;+ compress_one(pending[index]);+ }+ });+ }+ for (auto &thread : threads)+ thread.join();+ } else {+ for (auto &item : pending)+ compress_one(item);+ }+ } else {+ for (auto &item : pending)+ compress_one(item);+ }++ std::vector<RecordMeta> metas;+ metas.reserve(pending.size());+ std::size_t estimate = 16;+ for (const auto &item : pending) {+ estimate += 32 + 2 + 20 ++ (item.compression == 1 ? item.compressed.size()+ : item.object->body.size());+ }+ ByteWriter w(estimate);+ w.raw("VPK1");+ w.u32le(1);+ w.u64le(0);+ for (const auto &item : pending) {+ const auto &object = *item.object;+ const std::uint64_t offset = w.size();+ const Bytes stored = item.compression == 1 ? bytes_of(item.compressed)+ : bytes_of(object.body);+ ByteWriter rec(64);+ rec.id(item.id);+ rec.u8(object.type);+ rec.u8(item.compression);+ rec.varint(object.body.size());+ rec.varint(stored.size());+ rec.raw(stored);+ w.raw(rec.view());+ metas.push_back(+ RecordMeta{item.id, offset, object.type, object.body.size()});+ }++ auto pack = w.take();+ write_u64le(pack, 8, static_cast<std::uint64_t>(metas.size()));+ const auto digest = blake3_hash(bytes_of(pack));+ pack.insert(pack.end(), digest.begin(), digest.end());+ std::array<std::uint8_t, 32> trailer{};+ std::memcpy(trailer.data(), digest.data(), 32);++ std::stable_sort(metas.begin(), metas.end(),+ [](const RecordMeta &a, const RecordMeta &b) {+ return std::memcmp(a.id.data(), b.id.data(), ID_LEN) < 0;+ });+ output.index = encode_index(metas, trailer);+ output.name = hex_encode(Bytes(trailer.data(), trailer.size()));+ output.count = metas.size();+ output.pack = std::move(pack);+ return output;+}++bool write_pack(const fs::path &root, const std::vector<RawObject> &objects) {+ PackOutput output = encode_pack(objects);+ if (output.count == 0)+ return true;+ const fs::path pfinal = packs_dir(root) / (output.name + ".vpack");+ const fs::path ifinal = packs_dir(root) / (output.name + ".vidx");+ const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack.tmp");+ const fs::path itmp = tmp_dir(root) / (output.name + ".vidx.tmp");+ if (!write_atomic(ptmp, pfinal, bytes_of(output.pack)))+ return false;+ if (!write_atomic(itmp, ifinal, bytes_of(output.index))) {+ (void)remove_file(pfinal);+ return false;+ }+ return true;+}++// ---------------------------------------------------------------------------+// Store+// ---------------------------------------------------------------------------++static bool handle_index(StoreHandle &handle) {+ if (handle.index)+ return true;+ std::string name = basename_string(handle.path);+ if (name.size() <= 6)+ return false;+ name.resize(name.size() - 6);+ const fs::path idx_path = handle.path.parent_path() / (name + ".vidx");+ auto data = read_file_opt(idx_path);+ if (!data)+ return false;+ auto decoded = decode_index(std::move(*data));+ if (!decoded)+ return false;+ if (name != hex_encode(Bytes(decoded->pack_trailer.data(), 32)))+ return false;+ handle.index = std::move(*decoded);+ return true;+}++bool Store::ensure_index(StoreHandle &handle) { return handle_index(handle); }++bool Store::ensure_pack(StoreHandle &handle) {+ if (handle.pack)+ return true;+ if (!ensure_index(handle))+ return false;+ auto data = read_file_opt(handle.path);+ if (!data)+ return false;+ auto decoded = decode_pack(std::move(*data));+ if (!decoded)+ return false;+ if (!equals(Bytes(decoded->trailer.data(), 32),+ Bytes(handle.index->pack_trailer.data(), 32)))+ return false;+ handle.pack = std::move(*decoded);+ return true;+}++static std::uint64_t handle_mtime(const fs::path &path) {+ const auto info = stat_path(path);+ return info ? info->mtime_ns : 0;+}++Store Store::open_all(const fs::path &root) {+ Store store;+ for (const auto &name : list_directory(packs_dir(root))) {+ if (name.size() <= 6)+ continue;+ if (name.compare(name.size() - 6, 6, ".vpack") != 0)+ continue;+ StoreHandle handle;+ handle.path = packs_dir(root) / path_from_bytes(name);+ handle.mtime_ns = handle_mtime(handle.path);+ store.handles_.push_back(std::move(handle));+ }+ std::stable_sort(store.handles_.begin(), store.handles_.end(),+ [](const StoreHandle &a, const StoreHandle &b) {+ return a.mtime_ns >= b.mtime_ns;+ });+ return store;+}++void Store::preload() {+ for (auto &handle : handles_) {+ (void)ensure_index(handle);+ (void)ensure_pack(handle);+ }+}++void Store::refresh(const fs::path &root) {+ for (const auto &name : list_directory(packs_dir(root))) {+ if (name.size() <= 6)+ continue;+ if (name.compare(name.size() - 6, 6, ".vpack") != 0)+ continue;+ const fs::path path = packs_dir(root) / path_from_bytes(name);+ bool found = false;+ for (const auto &handle : handles_) {+ if (handle.path == path) {+ found = true;+ break;+ }+ }+ if (!found) {+ StoreHandle handle;+ handle.path = path;+ handle.mtime_ns = handle_mtime(path);+ handles_.push_back(std::move(handle));+ }+ }+ std::stable_sort(handles_.begin(), handles_.end(),+ [](const StoreHandle &a, const StoreHandle &b) {+ return a.mtime_ns >= b.mtime_ns;+ });+}++std::optional<Loc> Store::find(const Id &id) {+ for (std::size_t i = 0; i < handles_.size(); ++i) {+ auto &handle = handles_[i];+ if (!ensure_index(handle))+ continue;+ const auto pos = handle.index->find(id);+ if (!pos)+ continue;+ const std::uint64_t offset = handle.index->offsets[*pos];+ if (!ensure_pack(handle))+ continue;+ const auto rec = handle.pack->find_by_offset(offset);+ if (!rec)+ continue;+ return Loc{i, *rec, handle.pack->records[*rec].type};+ }+ return std::nullopt;+}++Result<std::vector<std::uint8_t>> Store::get(const Loc &loc) {+ if (loc.pack_index >= handles_.size())+ return fail(ErrorKind::Corrupt, 0);+ auto &handle = handles_[loc.pack_index];+ if (!ensure_pack(handle))+ return fail(ErrorKind::Corrupt, 0);+ return handle.pack->get(loc.record_index);+}++std::optional<std::vector<std::uint8_t>>+Store::read_body(const Id &id, std::uint8_t expected) {+ const auto loc = find(id);+ if (!loc || loc->kind != expected)+ return std::nullopt;+ auto body = get(*loc);+ if (!body)+ return std::nullopt;+ const Id computed = object_id(expected, bytes_of(*body));+ if (std::memcmp(computed.data(), id.data(), ID_LEN) != 0)+ return std::nullopt;+ return std::move(*body);+}++std::optional<View> Store::read_view(const Id &id) {+ auto body = read_body(id, TYPE_VIEW);+ if (!body)+ return std::nullopt;+ auto view = decode_view(bytes_of(*body));+ if (!view)+ return std::nullopt;+ return std::move(*view);+}++std::optional<Operation> Store::read_operation(const Id &id) {+ auto body = read_body(id, TYPE_OPERATION);+ if (!body)+ return std::nullopt;+ auto op = decode_operation(bytes_of(*body));+ if (!op)+ return std::nullopt;+ return std::move(*op);+}++bool Store::has_promisor(const fs::path &root) const {+ auto data = read_file_opt(config_path(root));+ if (!data)+ return false;+ const std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ return text.find("promisor") != std::string_view::npos;+}++// ---------------------------------------------------------------------------+// Writer+// ---------------------------------------------------------------------------++Id Writer::add(std::uint8_t type, const std::vector<std::uint8_t> &body) {+ const Id id = object_id(type, bytes_of(body));+ if (!seen_.insert(id).second)+ return id;+ objects_.push_back(RawObject{type, body, id});+ if (type != TYPE_CHUNK || cache_chunks_)+ cache_.push_back(RawObject{type, body, id});+ return id;+}++Id Writer::add(std::uint8_t type, std::vector<std::uint8_t> &&body) {+ const Id id = object_id(type, bytes_of(body));+ if (!seen_.insert(id).second)+ return id;+ if (type != TYPE_CHUNK || cache_chunks_)+ cache_.push_back(RawObject{type, body, id});+ objects_.push_back(RawObject{type, std::move(body), id});+ return id;+}++Id Writer::add_known(std::uint8_t type, const Id &id,+ const std::vector<std::uint8_t> &body) {+ if (!seen_.insert(id).second)+ return id;+ objects_.push_back(RawObject{type, body, id});+ if (type != TYPE_CHUNK || cache_chunks_)+ cache_.push_back(RawObject{type, body, id});+ return id;+}++Id Writer::add_known(std::uint8_t type, const Id &id,+ std::vector<std::uint8_t> &&body) {+ if (!seen_.insert(id).second)+ return id;+ if (type != TYPE_CHUNK || cache_chunks_)+ cache_.push_back(RawObject{type, body, id});+ objects_.push_back(RawObject{type, std::move(body), id});+ return id;+}++std::optional<std::vector<std::uint8_t>>+Writer::find_cached(std::uint8_t type, const Id &id) const {+ for (const auto &object : cache_) {+ const Id candidate =+ object.id ? *object.id : object_id(type, bytes_of(object.body));+ if (object.type == type &&+ std::memcmp(candidate.data(), id.data(), ID_LEN) == 0)+ return object.body;+ }+ return std::nullopt;+}++bool Writer::finish(const fs::path &root) { return write_pack(root, objects_); }++// ---------------------------------------------------------------------------+// View helpers+// ---------------------------------------------------------------------------++static bool id_less(const Id &a, const Id &b) {+ return std::memcmp(a.data(), b.data(), ID_LEN) < 0;+}++static bool id_equal(const Id &a, const Id &b) {+ return std::memcmp(a.data(), b.data(), ID_LEN) == 0;+}++namespace {+struct IdHash {+ std::size_t operator()(const Id &id) const noexcept {+ std::size_t h = 1469598103934665603ull;+ for (auto b : id) {+ h ^= b;+ h *= 1099511628211ull;+ }+ return h;+ }+};+struct IdEq {+ bool operator()(const Id &a, const Id &b) const noexcept {+ return id_equal(a, b);+ }+};+} // namespace++bool contains_id(const std::vector<Id> &ids, const Id &id) {+ return std::find_if(ids.begin(), ids.end(), [&](const Id &x) {+ return id_equal(x, id);+ }) != ids.end();+}++bool target_contains(const std::vector<std::optional<Id>> &ids, const Id &id) {+ for (const auto &x : ids) {+ if (x && id_equal(*x, id))+ return true;+ }+ return false;+}++std::optional<Id> working_copy_id(const View &view) {+ for (const auto &workspace : view.working_copies) {+ if (workspace.workspace == "default")+ return workspace.target;+ }+ return std::nullopt;+}++void sort_ids(std::vector<Id> &ids) {+ std::stable_sort(ids.begin(), ids.end(), id_less);+}++void sort_view(View &view) {+ sort_ids(view.heads);+ std::stable_sort(view.bookmarks.begin(), view.bookmarks.end(),+ [](const Bookmark &a, const Bookmark &b) {+ return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+ });+ std::stable_sort(view.tags.begin(), view.tags.end(),+ [](const TagRef &a, const TagRef &b) {+ return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+ });+ std::stable_sort(view.remote_refs.begin(), view.remote_refs.end(),+ [](const RemoteRef &a, const RemoteRef &b) {+ const int c =+ compare(bytes_of(a.remote), bytes_of(b.remote));+ if (c != 0)+ return c < 0;+ return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+ });+ std::stable_sort(view.working_copies.begin(), view.working_copies.end(),+ [](const WorkspaceRef &a, const WorkspaceRef &b) {+ return compare(bytes_of(a.workspace),+ bytes_of(b.workspace)) < 0;+ });+}++void add_unique_head(View &view, const Id &id) {+ if (!contains_id(view.heads, id))+ view.heads.push_back(id);+}++void rebuild_heads(View &view) {+ view.heads.clear();+ for (const auto &bookmark : view.bookmarks) {+ for (const auto &id : bookmark.targets.adds) {+ if (id)+ add_unique_head(view, *id);+ }+ }+ for (const auto &tag : view.tags)+ add_unique_head(view, tag.target);+ for (const auto &workspace : view.working_copies)+ add_unique_head(view, workspace.target);+ sort_ids(view.heads);+}++void set_workspace(View &view, const Id &id) {+ for (auto &workspace : view.working_copies) {+ if (workspace.workspace == "default") {+ workspace.target = id;+ return;+ }+ }+ view.working_copies.push_back(WorkspaceRef{"default", id});+ std::stable_sort(view.working_copies.begin(), view.working_copies.end(),+ [](const WorkspaceRef &a, const WorkspaceRef &b) {+ return compare(bytes_of(a.workspace),+ bytes_of(b.workspace)) < 0;+ });+}++void remove_head(View &view, const Id &id) {+ view.heads.erase(std::remove_if(view.heads.begin(), view.heads.end(),+ [&](const Id &x) { return id_equal(x, id); }),+ view.heads.end());+}++void move_bookmarks(View &view, const Id &old_id, const Id &new_id) {+ if (id_equal(old_id, new_id))+ return;+ for (auto &bookmark : view.bookmarks) {+ if (target_contains(bookmark.targets.adds, old_id)) {+ bookmark.targets.adds = {new_id};+ bookmark.targets.removes.clear();+ }+ }+}++std::optional<std::size_t> find_bookmark(const View &view,+ std::string_view name) {+ for (std::size_t i = 0; i < view.bookmarks.size(); ++i) {+ if (view.bookmarks[i].name == name)+ return i;+ }+ return std::nullopt;+}++std::optional<std::size_t> find_tag(const View &view, std::string_view name) {+ for (std::size_t i = 0; i < view.tags.size(); ++i) {+ if (view.tags[i].name == name)+ return i;+ }+ return std::nullopt;+}++std::vector<std::string> bookmark_names(const View &view, const Id &id) {+ std::vector<std::string> out;+ for (const auto &bookmark : view.bookmarks) {+ if (target_contains(bookmark.targets.adds, id))+ out.push_back(bookmark.name);+ }+ return out;+}++std::vector<std::string> tag_names(const View &view, const Id &id) {+ std::vector<std::string> out;+ for (const auto &tag : view.tags) {+ if (id_equal(tag.target, id))+ out.push_back(tag.name);+ }+ return out;+}++View empty_view() { return {}; }++std::vector<Id> read_heads(const fs::path &root) {+ std::vector<Id> out;+ for (const auto &name : list_directory(op_heads_dir(root))) {+ if (name.size() != 64)+ continue;+ Id id{};+ if (!hex_decode(name, MutBytes(id.data(), id.size())))+ continue;+ out.push_back(id);+ }+ sort_ids(out);+ return out;+}++bool write_head(const fs::path &root, const Id &id) {+ const std::string name = hex_encode(id);+ const fs::path final_path = op_heads_dir(root) / name;+ const fs::path tmp_path = tmp_dir(root) / (name + ".tmp");+ return write_atomic(tmp_path, final_path, Bytes{});+}++bool delete_head(const fs::path &root, const Id &id) {+ return remove_file(op_heads_dir(root) / hex_encode(id));+}++std::optional<View> current_view(const fs::path &root, Store &store) {+ const auto heads = read_heads(root);+ if (heads.empty())+ return std::nullopt;+ auto op = store.read_operation(heads.front());+ if (!op)+ return std::nullopt;+ return store.read_view(op->view);+}++static std::optional<View> load_view_for_head(Store &store, const Id &id) {+ auto op = store.read_operation(id);+ if (!op)+ return std::nullopt;+ return store.read_view(op->view);+}++static void merge_view_into(View &dst, const View &src) {+ for (const auto &head : src.heads)+ add_unique_head(dst, head);+ for (const auto &bookmark : src.bookmarks) {+ const auto found = find_bookmark(dst, bookmark.name);+ if (!found) {+ dst.bookmarks.push_back(bookmark);+ continue;+ }+ auto &existing = dst.bookmarks[*found];+ std::optional<Id> a = existing.targets.adds.empty()+ ? std::optional<Id>{}+ : existing.targets.adds.front();+ std::optional<Id> b = bookmark.targets.adds.empty()+ ? std::optional<Id>{}+ : bookmark.targets.adds.front();+ const bool same =+ a.has_value() == b.has_value() && (!a || id_equal(*a, *b));+ if (!same || existing.targets.adds.size() != bookmark.targets.adds.size()) {+ existing.targets.adds = {a, b};+ existing.targets.removes = {std::nullopt};+ }+ }+ for (const auto &tag : src.tags) {+ if (!find_tag(dst, tag.name))+ dst.tags.push_back(tag);+ }+ for (const auto &workspace : src.working_copies) {+ bool found = false;+ for (const auto &existing : dst.working_copies) {+ if (existing.workspace == workspace.workspace) {+ found = true;+ break;+ }+ }+ if (!found)+ dst.working_copies.push_back(workspace);+ }+}++// ---------------------------------------------------------------------------+// Transactions+// ---------------------------------------------------------------------------++Result<Txn> Txn::begin(const fs::path &root, Store &store) {+ Txn tx;+ tx.root_ = root;+ tx.store_ = &store;+ const auto heads = read_heads(root);+ if (heads.empty()) {+ tx.view_ = empty_view();+ } else if (heads.size() == 1) {+ auto view = load_view_for_head(store, heads.front());+ if (!view)+ return fail_io("cannot load repository state");+ tx.view_ = std::move(*view);+ } else {+ auto base = load_view_for_head(store, heads.front());+ if (!base)+ return fail_io("cannot load repository state");+ for (std::size_t i = 1; i < heads.size(); ++i) {+ auto extra = load_view_for_head(store, heads[i]);+ if (extra)+ merge_view_into(*base, *extra);+ }+ add_unique_head(*base, heads.front());+ tx.view_ = std::move(*base);+ }+ std::stable_sort(tx.view_.bookmarks.begin(), tx.view_.bookmarks.end(),+ [](const Bookmark &a, const Bookmark &b) {+ return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+ });+ std::stable_sort(tx.view_.tags.begin(), tx.view_.tags.end(),+ [](const TagRef &a, const TagRef &b) {+ return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+ });+ std::stable_sort(+ tx.view_.working_copies.begin(), tx.view_.working_copies.end(),+ [](const WorkspaceRef &a, const WorkspaceRef &b) {+ return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;+ });+ tx.parents_ = heads;+ tx.start_ms_ = unix_now_millis();+ return Result<Txn>(std::move(tx));+}++static std::string host_name() {+ if (const char *v = std::getenv("HOSTNAME"); v && *v)+ return v;+ return "localhost";+}++static std::string user_name() {+ if (const char *v = std::getenv("USER"); v && *v)+ return v;+#if defined(_WIN32)+ if (const char *w = std::getenv("USERNAME"); w && *w)+ return w;+#endif+ return "unknown";+}++Status Txn::finish(std::string_view description) {+ sort_view(view_);+ const auto view_body = encode_view(view_);+ const Id view_id = writer_.add(TYPE_VIEW, view_body);+ const std::int64_t now = unix_now_millis();++ Operation op;+ op.parents = parents_;+ op.view = view_id;+ op.start = Reader::TimeMs{start_ms_, 0};+ op.end = Reader::TimeMs{now, 0};+ op.hostname = host_name();+ op.username = user_name();+ op.description = std::string(description);+ op.tags.push_back(KeyValue{"command", std::string(description)});+ const auto op_body = encode_operation(op);+ const Id op_id = writer_.add(TYPE_OPERATION, op_body);++ if (!writer_.finish(root_)) {+ error_prefix();+ std::cout << "failed to write object pack\n";+ return fail_io("failed to write object pack");+ }+ if (!write_head(root_, op_id))+ return fail_io("failed to write operation head");+ for (const auto &parent : parents_)+ (void)delete_head(root_, parent);+ return {};+}++// ---------------------------------------------------------------------------+// Native commit map+// ---------------------------------------------------------------------------++static fs::path native_path(const fs::path &root) {+ return git_map_dir(root) / "native";+}++bool mark_native(const fs::path &root, const Id &id) {+ const std::string line = hex_encode(id) + "\n";+ return append_file(native_path(root), bytes_of(line));+}++std::vector<Id> load_native(const fs::path &root) {+ std::vector<Id> out;+ auto data = read_file_opt(native_path(root));+ if (!data)+ return out;+ std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ std::size_t start = 0;+ while (start <= text.size()) {+ std::size_t end = text.find('\n', start);+ if (end == std::string_view::npos)+ end = text.size();+ if (end - start >= 64) {+ Id id{};+ if (hex_decode(text.substr(start, 64), MutBytes(id.data(), id.size())))+ out.push_back(id);+ }+ if (end == text.size())+ break;+ start = end + 1;+ }+ return out;+}++bool is_native(const std::vector<Id> &native, const Id &id) {+ return contains_id(native, id);+}++// ---------------------------------------------------------------------------+// Graph+// ---------------------------------------------------------------------------++std::optional<LoadedCommit> load_commit(Store &store, const Id &id) {+ auto body = store.read_body(id, TYPE_COMMIT);+ if (!body)+ return std::nullopt;+ auto commit = decode_commit(bytes_of(*body));+ if (!commit)+ return std::nullopt;+ return LoadedCommit{std::move(*commit), std::move(*body)};+}++bool has_changes(Store &store, const LoadedCommit &loaded) {+ if (!loaded.commit.parents.empty()) {+ auto parent = load_commit(store, loaded.commit.parents.front());+ if (!parent)+ return true;+ return !id_equal(parent->commit.root_tree, loaded.commit.root_tree);+ }+ const auto entries = flatten_tree(store, loaded.commit.root_tree);+ return !entries.empty();+}++std::vector<Id> collect_commits(Store &store, std::span<const Id> start) {+ std::vector<Id> out;+ std::vector<Id> stack;+ std::unordered_set<Id, IdHash, IdEq> seen;+ for (const auto &id : start) {+ if (seen.insert(id).second)+ stack.push_back(id);+ }+ while (!stack.empty()) {+ const Id id = stack.back();+ stack.pop_back();+ out.push_back(id);+ auto loaded = load_commit(store, id);+ if (!loaded)+ continue;+ for (const auto &parent : loaded->commit.parents) {+ if (seen.insert(parent).second)+ stack.push_back(parent);+ }+ }+ return out;+}++std::vector<Id> view_roots(const View &view) {+ std::vector<Id> out;+ auto add = [&](const Id &id) {+ if (!contains_id(out, id))+ out.push_back(id);+ };+ for (const auto &head : view.heads)+ add(head);+ for (const auto &bookmark : view.bookmarks) {+ for (const auto &id : bookmark.targets.adds) {+ if (id)+ add(*id);+ }+ }+ for (const auto &tag : view.tags)+ add(tag.target);+ for (const auto &workspace : view.working_copies)+ add(workspace.target);+ return out;+}++std::vector<Id> all_commits(Store &store, const View &view) {+ const auto roots = view_roots(view);+ return collect_commits(store, roots);+}++static std::optional<Id> bookmark_target(const View &view,+ std::string_view name) {+ for (const auto &bookmark : view.bookmarks) {+ if (bookmark.name == name) {+ if (bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front())+ return bookmark.targets.adds.front();+ return std::nullopt;+ }+ }+ return std::nullopt;+}++static std::optional<Id> tag_target(const View &view, std::string_view name) {+ for (const auto &tag : view.tags) {+ if (tag.name == name)+ return tag.target;+ }+ return std::nullopt;+}++static std::optional<Id> remote_target(const View &view,+ std::string_view text) {+ for (const auto &ref : view.remote_refs) {+ const std::string joined = ref.remote + "/" + ref.name;+ if (joined == text)+ return ref.target;+ }+ return std::nullopt;+}++static bool is_hex_char(char c) {+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||+ (c >= 'A' && c <= 'F');+}++static bool is_hex_prefix(std::string_view text) {+ if (text.size() < 4 || text.size() > 64)+ return false;+ for (char c : text) {+ if (!is_hex_char(c))+ return false;+ }+ return true;+}++std::optional<Id> resolve_revision(Store &store, const View &view,+ std::string_view rev) {+ if (rev.empty() || rev == "@")+ return working_copy_id(view);+ if (auto id = bookmark_target(view, rev))+ return id;+ if (auto id = tag_target(view, rev))+ return id;+ if (auto id = remote_target(view, rev))+ return id;++ const auto ids = all_commits(store, view);+ std::vector<Id> matches;+ if (is_hex_prefix(rev)) {+ for (const auto &id : ids) {+ const std::string full = hex_encode(id);+ if (base32_prefix_matches(full, rev))+ matches.push_back(id);+ }+ }+ if (matches.empty()) {+ for (const auto &id : ids) {+ auto loaded = load_commit(store, id);+ if (!loaded)+ continue;+ const std::string encoded = base32_encode(loaded->commit.change_id);+ if (base32_prefix_matches(encoded, rev))+ matches.push_back(id);+ }+ }+ if (matches.size() == 1)+ return matches.front();+ return std::nullopt;+}++// ---------------------------------------------------------------------------+// Tree walking+// ---------------------------------------------------------------------------++static void join_path(std::string &prefix, std::string_view name) {+ if (!prefix.empty())+ prefix.push_back('/');+ prefix.append(name);+}++static bool flatten_into(Store &store, const Id &tree_id, std::string &prefix,+ std::vector<FlatEntry> &out, std::size_t depth) {+ if (depth > 4096)+ return false;+ auto body = store.read_body(tree_id, TYPE_TREE);+ if (!body)+ return false;+ auto tree = decode_tree(bytes_of(*body));+ if (!tree)+ return false;+ for (const auto &entry : tree->entries) {+ const std::size_t old_size = prefix.size();+ join_path(prefix, entry.name);+ if (entry.kind == KIND_SUBTREE) {+ if (!flatten_into(store, entry.target, prefix, out, depth + 1)) {+ prefix.resize(old_size);+ return false;+ }+ prefix.resize(old_size);+ } else {+ out.push_back(FlatEntry{prefix, entry.kind, entry.target});+ prefix.resize(old_size);+ }+ }+ return true;+}++std::vector<FlatEntry> flatten_tree(Store &store, const Id &tree_id) {+ std::vector<FlatEntry> out;+ std::string prefix;+ (void)flatten_into(store, tree_id, prefix, out, 0);+ std::stable_sort(out.begin(), out.end(),+ [](const FlatEntry &a, const FlatEntry &b) {+ return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+ });+ return out;+}++Result<std::vector<FlatEntry>> flatten_tree_checked(Store &store,+ const Id &tree_id) {+ std::vector<FlatEntry> out;+ std::string prefix;+ if (!flatten_into(store, tree_id, prefix, out, 0))+ return fail(ErrorKind::Corrupt, 0);+ std::stable_sort(out.begin(), out.end(),+ [](const FlatEntry &a, const FlatEntry &b) {+ return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+ });+ return Result<std::vector<FlatEntry>>(std::move(out));+}++std::vector<FlatEntry> flatten_or_empty(Store &store,+ std::optional<Id> tree_id) {+ if (!tree_id)+ return {};+ return flatten_tree(store, *tree_id);+}++const FlatEntry *find_flat(const std::vector<FlatEntry> &entries,+ std::string_view path) {+ std::size_t lo = 0;+ std::size_t hi = entries.size();+ while (lo < hi) {+ const std::size_t mid = lo + (hi - lo) / 2;+ const int c = compare(bytes_of(entries[mid].path), bytes_of(path));+ if (c == 0)+ return &entries[mid];+ if (c < 0)+ lo = mid + 1;+ else+ hi = mid;+ }+ return nullptr;+}++int find_tree_name(const Tree &tree, std::string_view name) {+ std::size_t lo = 0;+ std::size_t hi = tree.entries.size();+ while (lo < hi) {+ const std::size_t mid = lo + (hi - lo) / 2;+ const int c = compare(bytes_of(tree.entries[mid].name), bytes_of(name));+ if (c == 0)+ return static_cast<int>(mid);+ if (c < 0)+ lo = mid + 1;+ else+ hi = mid;+ }+ return -1;+}++static bool conflicted_into(Store &store, const Id &tree_id,+ std::size_t depth) {+ if (depth > 4096)+ return true;+ auto body = store.read_body(tree_id, TYPE_TREE);+ if (!body)+ return true;+ auto tree = decode_tree(bytes_of(*body));+ if (!tree)+ return true;+ for (const auto &entry : tree->entries) {+ if (entry.kind == KIND_CONFLICT)+ return true;+ if (entry.kind == KIND_SUBTREE &&+ conflicted_into(store, entry.target, depth + 1))+ return true;+ }+ return false;+}++bool tree_conflicted(Store &store, const Id &tree_id) {+ return conflicted_into(store, tree_id, 0);+}++std::vector<TreeChange> compare_trees(Store &store, std::optional<Id> old_tree,+ std::optional<Id> new_tree) {+ const auto old_entries = flatten_or_empty(store, old_tree);+ const auto new_entries = flatten_or_empty(store, new_tree);+ std::vector<TreeChange> out;+ std::size_t i = 0;+ std::size_t j = 0;+ while (i < old_entries.size() || j < new_entries.size()) {+ int take = 0;+ if (i >= old_entries.size())+ take = 1;+ else if (j >= new_entries.size())+ take = -1;+ else+ take =+ compare(bytes_of(old_entries[i].path), bytes_of(new_entries[j].path));+ if (take < 0) {+ out.push_back(TreeChange{old_entries[i].path, old_entries[i].kind,+ KIND_MISSING, old_entries[i].target,+ std::nullopt});+ ++i;+ } else if (take > 0) {+ out.push_back(TreeChange{new_entries[j].path, KIND_MISSING,+ new_entries[j].kind, std::nullopt,+ new_entries[j].target});+ ++j;+ } else {+ const auto &o = old_entries[i];+ const auto &n = new_entries[j];+ const bool same = o.kind == n.kind && id_equal(o.target, n.target);+ if (!same)+ out.push_back(TreeChange{o.path, o.kind, n.kind, o.target, n.target});+ ++i;+ ++j;+ }+ }+ return out;+}++// ---------------------------------------------------------------------------+// Blob content+// ---------------------------------------------------------------------------++static bool append_blob_data(Store &store, const Id &id,+ std::vector<std::uint8_t> &out,+ std::size_t depth) {+ if (depth > 64)+ return false;+ if (is_lazy_blob(id))+ return false;+ auto body = store.read_body(id, TYPE_BLOB);+ if (!body)+ return false;+ auto blob = decode_blob(bytes_of(*body));+ if (!blob)+ return false;+ if (blob->form == BlobForm::Inline) {+ out.insert(out.end(), blob->data.begin(), blob->data.end());+ return true;+ }+ if (blob->form == BlobForm::Leaf) {+ for (const auto &entry : blob->entries) {+ auto chunk = store.read_body(entry.id, TYPE_CHUNK);+ if (!chunk)+ return false;+ out.insert(out.end(), chunk->begin(), chunk->end());+ }+ return true;+ }+ for (const auto &entry : blob->entries) {+ if (!append_blob_data(store, entry.id, out, depth + 1))+ return false;+ }+ return true;+}++std::optional<std::vector<std::uint8_t>> read_blob(Store &store, const Id &id) {+ std::vector<std::uint8_t> out;+ if (!append_blob_data(store, id, out, 0))+ return std::nullopt;+ return out;+}++// ---------------------------------------------------------------------------+// fsck+// ---------------------------------------------------------------------------++namespace {++struct FsckCtx {+ fs::path root;+ bool promisor = false;+ bool verbose = false;+ std::size_t errors = 0;+ std::size_t warnings = 0;+};++void fsck_report(FsckCtx &ctx, const fs::path &path, std::string_view text) {+ ++ctx.errors;+ error_prefix();+ std::cout << "fsck: " << path_display(path) << ": " << text << "\n";+}++void fsck_report_id(FsckCtx &ctx, const fs::path &path, std::string_view text,+ const Id &id) {+ ++ctx.errors;+ error_prefix();+ std::cout << "fsck: " << path_display(path) << ": " << text << " "+ << hex_encode(id) << "\n";+}++void fsck_warn(FsckCtx &ctx, const fs::path &path, std::string_view text) {+ ++ctx.warnings;+ if (ctx.verbose) {+ warning_prefix();+ std::cout << "fsck: " << path_display(path) << ": " << text << "\n";+ }+}++void fsck_report_decode(FsckCtx &ctx, const fs::path &path,+ std::string_view what, const Error &error) {+ ++ctx.errors;+ error_prefix();+ std::cout << "fsck: " << path_display(path) << ": invalid " << what+ << " at byte " << error.offset << ": "+ << error_kind_name(error.kind) << "\n";+}++bool check_format(FsckCtx &ctx) {+ const fs::path path = format_path(ctx.root);+ auto data = read_file_opt(path);+ if (!data) {+ fsck_report(ctx, ctx.root, "missing .veins/format");+ return false;+ }+ const std::string_view expected = "veins-store 1";+ bool ok = equals(bytes_of(*data), bytes_of(expected));+ if (!ok && data->size() == expected.size() + 1) {+ ok = equals(bytes_of(*data).first(expected.size()), bytes_of(expected)) &&+ (*data)[expected.size()] == '\n';+ }+ if (!ok) {+ fsck_report(ctx, ctx.root, "unsupported .veins/format");+ return false;+ }+ return true;+}++std::uint8_t expected_type_for_value(std::uint8_t kind) {+ if (kind == 1 || kind == 2 || kind == 3)+ return TYPE_BLOB;+ if (kind == 4)+ return TYPE_TREE;+ if (kind == 6)+ return TYPE_CONFLICT;+ return 0;+}++bool check_ref(FsckCtx &ctx, Store &store, const fs::path &path, const Id &id,+ std::uint8_t expected, std::string_view what) {+ if (expected == TYPE_BLOB && is_lazy_blob(id))+ return true;+ const auto loc = store.find(id);+ if (!loc) {+ const bool promised =+ ctx.promisor && (expected == TYPE_CHUNK || expected == TYPE_BLOB);+ if (promised)+ fsck_warn(ctx, path, "missing promised object");+ if (!promised) {+ ++ctx.errors;+ error_prefix();+ std::cout << "fsck: " << path_display(path) << ": missing " << what+ << " object " << hex_encode(id) << "\n";+ }+ return promised;+ }+ if (loc->kind != expected) {+ ++ctx.errors;+ error_prefix();+ std::cout << "fsck: " << path_display(path) << ": object has type "+ << type_name(loc->kind) << ", expected " << type_name(expected)+ << " " << hex_encode(id) << "\n";+ return false;+ }+ return true;+}++void check_blob_refs(FsckCtx &ctx, Store &store, const fs::path &path,+ const Blob &blob) {+ if (blob.form == BlobForm::Inline)+ return;+ const std::uint8_t expected =+ blob.form == BlobForm::Leaf ? TYPE_CHUNK : TYPE_BLOB;+ for (const auto &entry : blob.entries) {+ (void)check_ref(ctx, store, path, entry.id, expected, "blob");+ }+}++void check_tree_refs(FsckCtx &ctx, Store &store, const fs::path &path,+ const Tree &tree) {+ for (const auto &entry : tree.entries) {+ std::uint8_t expected = 0;+ if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||+ entry.kind == KIND_SYMLINK)+ expected = TYPE_BLOB;+ else if (entry.kind == KIND_SUBTREE)+ expected = TYPE_TREE;+ else if (entry.kind == KIND_CONFLICT)+ expected = TYPE_CONFLICT;+ if (expected != 0)+ (void)check_ref(ctx, store, path, entry.target, expected, "tree");+ }+}++void check_conflict_refs(FsckCtx &ctx, Store &store, const fs::path &path,+ const Conflict &conflict) {+ for (const auto &value : conflict.adds) {+ const std::uint8_t expected = expected_type_for_value(value.kind);+ if (expected != 0 && value.target)+ (void)check_ref(ctx, store, path, *value.target, expected, "conflict");+ }+ for (const auto &value : conflict.removes) {+ const std::uint8_t expected = expected_type_for_value(value.kind);+ if (expected != 0 && value.target)+ (void)check_ref(ctx, store, path, *value.target, expected, "conflict");+ }+}++void check_commit_refs(FsckCtx &ctx, Store &store, const fs::path &path,+ const Commit &commit) {+ for (const auto &parent : commit.parents)+ (void)check_ref(ctx, store, path, parent, TYPE_COMMIT, "parent commit");+ (void)check_ref(ctx, store, path, commit.root_tree, TYPE_TREE, "root tree");+}++void check_operation_refs(FsckCtx &ctx, Store &store, const fs::path &path,+ const Operation &op) {+ for (const auto &parent : op.parents)+ (void)check_ref(ctx, store, path, parent, TYPE_OPERATION,+ "parent operation");+ (void)check_ref(ctx, store, path, op.view, TYPE_VIEW, "view");+}++void check_view_refs(FsckCtx &ctx, Store &store, const fs::path &path,+ const View &view) {+ for (const auto &head : view.heads)+ (void)check_ref(ctx, store, path, head, TYPE_COMMIT, "head commit");+ for (const auto &bookmark : view.bookmarks) {+ for (const auto &id : bookmark.targets.adds) {+ if (id)+ (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");+ }+ for (const auto &id : bookmark.targets.removes) {+ if (id)+ (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");+ }+ }+ for (const auto &tag : view.tags)+ (void)check_ref(ctx, store, path, tag.target, TYPE_COMMIT, "tag");+ for (const auto &ref : view.remote_refs)+ (void)check_ref(ctx, store, path, ref.target, TYPE_COMMIT, "remote ref");+ for (const auto &workspace : view.working_copies)+ (void)check_ref(ctx, store, path, workspace.target, TYPE_COMMIT,+ "working copy");+}++void check_object(FsckCtx &ctx, Store &store, const fs::path &path,+ const Id &id, std::uint8_t kind, Bytes body) {+ const Id computed = object_id(kind, body);+ if (!id_equal(computed, id)) {+ fsck_report_id(ctx, path, "hash mismatch for", id);+ return;+ }+ switch (kind) {+ case TYPE_CHUNK:+ if (body.empty() || body.size() > MAX_CHUNK_LEN)+ fsck_report_id(ctx, path, "invalid chunk length for", id);+ return;+ case TYPE_BLOB: {+ auto blob = decode_blob(body);+ if (!blob) {+ fsck_report_decode(ctx, path, "blob", blob.error());+ return;+ }+ check_blob_refs(ctx, store, path, *blob);+ return;+ }+ case TYPE_TREE: {+ auto tree = decode_tree(body);+ if (!tree) {+ fsck_report_decode(ctx, path, "tree", tree.error());+ return;+ }+ check_tree_refs(ctx, store, path, *tree);+ return;+ }+ case TYPE_CONFLICT: {+ auto conflict = decode_conflict(body);+ if (!conflict) {+ fsck_report_decode(ctx, path, "conflict", conflict.error());+ return;+ }+ check_conflict_refs(ctx, store, path, *conflict);+ return;+ }+ case TYPE_COMMIT: {+ auto commit = decode_commit(body);+ if (!commit) {+ fsck_report_decode(ctx, path, "commit", commit.error());+ return;+ }+ check_commit_refs(ctx, store, path, *commit);+ return;+ }+ case TYPE_OPERATION: {+ auto op = decode_operation(body);+ if (!op) {+ fsck_report_decode(ctx, path, "operation", op.error());+ return;+ }+ check_operation_refs(ctx, store, path, *op);+ return;+ }+ case TYPE_VIEW: {+ auto view = decode_view(body);+ if (!view) {+ fsck_report_decode(ctx, path, "view", view.error());+ return;+ }+ check_view_refs(ctx, store, path, *view);+ return;+ }+ default:+ return;+ }+}++} // namespace++static void check_op_log(FsckCtx &ctx, Store &store) {+ const fs::path dir = op_heads_dir(ctx.root);+ if (!path_is_dir(dir)) {+ fsck_report(ctx, dir, "missing op-heads directory");+ return;+ }+ std::vector<Id> frontier;+ for (const auto &name : list_directory(dir)) {+ if (name.size() != 64) {+ fsck_report(ctx, dir, "op-heads entry is not a 64-character id");+ continue;+ }+ Id id{};+ if (!hex_decode(name, MutBytes(id.data(), id.size()))) {+ fsck_report(ctx, dir, "op-heads entry is not hexadecimal");+ continue;+ }+ frontier.push_back(id);+ }+ std::unordered_set<Id, IdHash, IdEq> seen;+ while (!frontier.empty()) {+ const Id id = frontier.back();+ frontier.pop_back();+ if (!seen.insert(id).second)+ continue;+ const auto loc = store.find(id);+ if (!loc) {+ fsck_report_id(ctx, dir, "operation head or parent is missing:", id);+ continue;+ }+ if (loc->kind != TYPE_OPERATION) {+ fsck_report_id(ctx, dir, "op-log entry is not an operation:", id);+ continue;+ }+ auto body = store.get(*loc);+ if (!body) {+ fsck_report_decode(ctx, dir, "operation", body.error());+ continue;+ }+ auto op = decode_operation(bytes_of(*body));+ if (!op) {+ fsck_report_decode(ctx, dir, "operation", op.error());+ continue;+ }+ for (const auto &parent : op->parents)+ frontier.push_back(parent);+ (void)check_ref(ctx, store, dir, op->view, TYPE_VIEW, "operation view");+ }+}++int fsck_repository(const fs::path &root, bool verbose) {+ FsckCtx ctx;+ ctx.root = root;+ ctx.verbose = verbose;+ std::vector<StoreHandle> handles;+ if (check_format(ctx)) {+ auto cfg = read_file_opt(config_path(root));+ if (cfg) {+ const std::string_view text(reinterpret_cast<const char *>(cfg->data()),+ cfg->size());+ ctx.promisor = text.find("promisor") != std::string_view::npos;+ }+ const fs::path dir = packs_dir(root);+ if (!path_is_dir(dir)) {+ fsck_report(ctx, dir, "missing store/packs directory");+ } else {+ const auto names = list_directory(dir);+ for (const auto &name : names) {+ if (name.size() > 5 && name.compare(name.size() - 5, 5, ".vidx") == 0) {+ std::string pack_name = name.substr(0, name.size() - 5) + ".vpack";+ const fs::path ppath = dir / path_from_bytes(pack_name);+ if (!path_is_file(ppath))+ fsck_report(ctx, ppath, "index has no pack");+ }+ }+ for (const auto &name : names) {+ if (name.size() <= 6 || name.compare(name.size() - 6, 6, ".vpack") != 0)+ continue;+ const fs::path ppath = dir / path_from_bytes(name);+ auto pdata = read_file_opt(ppath);+ if (!pdata) {+ fsck_report(ctx, ppath, "cannot read pack");+ continue;+ }+ auto pack = decode_pack(std::move(*pdata));+ if (!pack) {+ fsck_report_decode(ctx, ppath, "pack", pack.error());+ continue;+ }+ std::string base = name.substr(0, name.size() - 6);+ const fs::path ipath = dir / path_from_bytes(base + ".vidx");+ auto idata = read_file_opt(ipath);+ if (!idata) {+ fsck_report(ctx, ppath, "pack has no index");+ continue;+ }+ auto index = decode_index(std::move(*idata), pack->trailer);+ if (!index) {+ fsck_report_decode(ctx, ipath, "index", index.error());+ continue;+ }+ bool eligible = true;+ if (index->ids.size() != pack->records.size()) {+ fsck_report(ctx, ppath, "pack and index object counts differ");+ eligible = false;+ }+ if (eligible) {+ std::vector<bool> visited(pack->records.size(), false);+ for (std::size_t j = 0; j < index->ids.size(); ++j) {+ const auto rec = pack->find_by_offset(index->offsets[j]);+ if (!rec) {+ fsck_report_id(ctx, ppath, "index offset names no record for",+ index->ids[j]);+ eligible = false;+ continue;+ }+ if (!id_equal(pack->records[*rec].id, index->ids[j])) {+ fsck_report_id(ctx, ppath, "index id does not match record for",+ index->ids[j]);+ eligible = false;+ }+ if (visited[*rec]) {+ fsck_report_id(ctx, ppath, "record indexed more than once",+ index->ids[j]);+ eligible = false;+ }+ visited[*rec] = true;+ }+ for (std::size_t k = 0; k < pack->records.size(); ++k) {+ if (!visited[k]) {+ fsck_report_id(ctx, ppath, "record is not indexed",+ pack->records[k].id);+ eligible = false;+ }+ }+ }+ if (!eligible)+ continue;+ StoreHandle handle;+ handle.path = ppath;+ handle.index = std::move(*index);+ handle.pack = std::move(*pack);+ handles.push_back(std::move(handle));+ }+ }++ Store store;+ store.handles() = std::move(handles);+ for (auto &handle : store.handles()) {+ if (!handle.pack)+ continue;+ for (std::size_t j = 0; j < handle.pack->records.size(); ++j) {+ const auto &rec = handle.pack->records[j];+ auto body = handle.pack->get(j);+ if (!body) {+ fsck_report_decode(ctx, handle.path, "record", body.error());+ continue;+ }+ check_object(ctx, store, handle.path, rec.id, rec.type,+ bytes_of(*body));+ }+ }+ check_op_log(ctx, store);+ }++ if (ctx.warnings > 0 && ctx.verbose) {+ warning_prefix();+ std::cout << ctx.warnings << " warning(s)\n";+ }+ if (ctx.errors == 0) {+ info_prefix();+ std::cout << "fsck: clean\n";+ return 0;+ }+ error_prefix();+ std::cout << ctx.errors << " error(s)\n";+ return 1;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/store.h@@ -0,0 +1,233 @@+#pragma once++#include "object.h"++#include <memory>+#include <optional>+#include <set>+#include <string>+#include <vector>++namespace vn {++// ---------------------------------------------------------------------------+// Repository layout+// ---------------------------------------------------------------------------++fs::path veins_dir(const fs::path &root);+fs::path packs_dir(const fs::path &root);+fs::path tmp_dir(const fs::path &root);+fs::path op_heads_dir(const fs::path &root);+fs::path git_dir(const fs::path &root);+fs::path git_map_dir(const fs::path &root);+fs::path working_copy_dir(const fs::path &root);+fs::path resolutions_dir(const fs::path &root);+fs::path config_path(const fs::path &root);+fs::path format_path(const fs::path &root);++std::optional<fs::path> discover_repo(const fs::path &start);+Result<fs::path> init_repo(const fs::path &path);++// ---------------------------------------------------------------------------+// Pack and index files+// ---------------------------------------------------------------------------++struct PackRecord {+ Id id{};+ std::uint8_t type = 0;+ std::uint8_t compression = 0;+ std::uint64_t raw_len = 0;+ std::uint64_t stored_len = 0;+ std::uint64_t data_off = 0;+ std::uint64_t record_off = 0;+};++struct Pack {+ std::vector<std::uint8_t> data;+ std::vector<PackRecord> records;+ std::array<std::uint8_t, 32> trailer{};++ std::optional<std::size_t> find_by_offset(std::uint64_t offset) const;+ Result<std::vector<std::uint8_t>> get(std::size_t record_index) const;+};++Result<Pack> decode_pack(std::vector<std::uint8_t> data);++struct Index {+ std::vector<Id> ids;+ std::vector<std::uint64_t> offsets;+ std::array<std::uint8_t, 32> pack_trailer{};++ std::optional<std::size_t> find(const Id &id) const;+};++Result<Index> decode_index(std::vector<std::uint8_t> data,+ const std::optional<std::array<std::uint8_t, 32>>+ &expected_pack_trailer = std::nullopt);++struct RecordMeta {+ Id id{};+ std::uint64_t offset = 0;+ std::uint8_t type = 0;+ std::uint64_t raw_len = 0;+};++struct PackOutput {+ std::vector<std::uint8_t> pack;+ std::vector<std::uint8_t> index;+ std::string name;+ std::size_t count = 0;+};++PackOutput encode_pack(const std::vector<RawObject> &objects);+std::vector<std::uint8_t>+encode_index(const std::vector<RecordMeta> &records,+ const std::array<std::uint8_t, 32> &trailer);++bool write_pack(const fs::path &root, const std::vector<RawObject> &objects);++// ---------------------------------------------------------------------------+// Store+// ---------------------------------------------------------------------------++struct Loc {+ std::size_t pack_index = 0;+ std::size_t record_index = 0;+ std::uint8_t kind = 0;+};++struct StoreHandle {+ fs::path path;+ std::uint64_t mtime_ns = 0;+ std::optional<Index> index;+ std::optional<Pack> pack;+};++class Store {+public:+ Store() = default;+ Store(Store &&) noexcept = default;+ Store &operator=(Store &&) noexcept = default;+ Store(const Store &) = delete;+ Store &operator=(const Store &) = delete;++ static Store open_all(const fs::path &root);+ void refresh(const fs::path &root);++ std::optional<Loc> find(const Id &id);+ Result<std::vector<std::uint8_t>> get(const Loc &loc);+ std::optional<std::vector<std::uint8_t>> read_body(const Id &id,+ std::uint8_t expected);+ std::optional<View> read_view(const Id &id);+ std::optional<Operation> read_operation(const Id &id);+ bool has_promisor(const fs::path &root) const;++ std::vector<StoreHandle> &handles() { return handles_; }+ const std::vector<StoreHandle> &handles() const { return handles_; }+ void preload();++private:+ bool ensure_index(StoreHandle &handle);+ bool ensure_pack(StoreHandle &handle);+ std::vector<StoreHandle> handles_;+};++// ---------------------------------------------------------------------------+// Writer and transactions+// ---------------------------------------------------------------------------++class Writer {+public:+ Writer() = default;++ Id add(std::uint8_t type, const std::vector<std::uint8_t> &body);+ Id add(std::uint8_t type, std::vector<std::uint8_t> &&body);+ Id add_known(std::uint8_t type, const Id &id,+ const std::vector<std::uint8_t> &body);+ Id add_known(std::uint8_t type, const Id &id,+ std::vector<std::uint8_t> &&body);+ void enable_chunk_cache() { cache_chunks_ = true; }+ std::optional<std::vector<std::uint8_t>> find_cached(std::uint8_t type,+ const Id &id) const;++ bool finish(const fs::path &root);+ std::vector<RawObject> &objects() { return objects_; }++private:+ std::vector<RawObject> objects_;+ std::vector<RawObject> cache_;+ std::set<Id> seen_;+ bool cache_chunks_ = false;+};++class Txn {+public:+ static Result<Txn> begin(const fs::path &root, Store &store);+ ~Txn() = default;++ View &view() { return view_; }+ Writer &writer() { return writer_; }+ Store &store() { return *store_; }++ Id add_object(std::uint8_t type, const std::vector<std::uint8_t> &body) {+ return writer_.add(type, body);+ }+ Id add_object(std::uint8_t type, std::vector<std::uint8_t> &&body) {+ return writer_.add(type, std::move(body));+ }+ Id add_known(std::uint8_t type, const Id &id,+ const std::vector<std::uint8_t> &body) {+ return writer_.add_known(type, id, body);+ }+ Id add_known(std::uint8_t type, const Id &id,+ std::vector<std::uint8_t> &&body) {+ return writer_.add_known(type, id, std::move(body));+ }++ Status finish(std::string_view description);++private:+ Txn() = default;+ fs::path root_;+ Store *store_ = nullptr;+ View view_;+ std::vector<Id> parents_;+ std::int64_t start_ms_ = 0;+ Writer writer_;+};++// ---------------------------------------------------------------------------+// Operation state and view mutations+// ---------------------------------------------------------------------------++std::vector<Id> read_heads(const fs::path &root);+bool write_head(const fs::path &root, const Id &id);+bool delete_head(const fs::path &root, const Id &id);+View empty_view();+std::optional<View> current_view(const fs::path &root, Store &store);++void sort_view(View &view);+void sort_ids(std::vector<Id> &ids);+void rebuild_heads(View &view);+void set_workspace(View &view, const Id &id);+void remove_head(View &view, const Id &id);+void move_bookmarks(View &view, const Id &old_id, const Id &new_id);+void add_unique_head(View &view, const Id &id);++std::optional<std::size_t> find_bookmark(const View &view,+ std::string_view name);+std::optional<std::size_t> find_tag(const View &view, std::string_view name);+std::vector<std::string> bookmark_names(const View &view, const Id &id);+std::vector<std::string> tag_names(const View &view, const Id &id);++bool mark_native(const fs::path &root, const Id &id);+std::vector<Id> load_native(const fs::path &root);+bool is_native(const std::vector<Id> &native, const Id &id);++// ---------------------------------------------------------------------------+// fsck+// ---------------------------------------------------------------------------++int fsck_repository(const fs::path &root, bool verbose);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/worktree.cpp@@ -0,0 +1,954 @@+#include "worktree.h"++#include <algorithm>+#include <atomic>+#include <fstream>+#include <iostream>+#include <mutex>+#include <set>+#include <thread>++#if !defined(_WIN32)+#include <sys/stat.h>+#endif++namespace vn {++namespace {++struct CacheEntry {+ std::string path;+ std::uint64_t size = 0;+ std::uint64_t mtime_ns = 0;+ std::uint64_t inode = 0;+ std::uint8_t kind = 0;+ bool executable = false;+ Id target{};+};++struct Cache {+ std::vector<CacheEntry> entries;+ std::int64_t written_ms = 0;+};++std::string join_rel(std::string_view base, std::string_view name) {+ if (base.empty())+ return std::string(name);+ std::string out(base);+ out.push_back('/');+ out.append(name);+ return out;+}++bool name_ends_with(std::string_view name, std::string_view suffix) {+ return name.size() >= suffix.size() &&+ name.substr(name.size() - suffix.size()) == suffix;+}++std::optional<std::string> sidecar_base(std::string_view name) {+ if (name_ends_with(name, ".base") && name.size() > 5)+ return std::string(name.substr(0, name.size() - 5));+ if (name_ends_with(name, ".ours") && name.size() > 5)+ return std::string(name.substr(0, name.size() - 5));+ if (name_ends_with(name, ".theirs") && name.size() > 7)+ return std::string(name.substr(0, name.size() - 7));+ std::size_t digits = 0;+ while (digits < name.size() && name[name.size() - 1 - digits] >= '0' &&+ name[name.size() - 1 - digits] <= '9')+ ++digits;+ if (digits > 0) {+ const std::size_t stem_end = name.size() - digits;+ const std::string_view stem = name.substr(0, stem_end);+ if (stem_end > 5 && name_ends_with(stem, ".base"))+ return std::string(stem.substr(0, stem.size() - 5));+ if (stem_end > 7 && name_ends_with(stem, ".theirs"))+ return std::string(stem.substr(0, stem.size() - 7));+ }+ return std::nullopt;+}++bool is_meta_name(std::string_view name) {+ return name == ".veins" || name == ".git";+}++bool cache_matches(const CacheEntry &entry, const StatInfo &info,+ bool executable, std::int64_t now_ms,+ std::int64_t written_ms) {+ if (entry.size != info.size || entry.mtime_ns != info.mtime_ns ||+ entry.inode != info.inode)+ return false;+ if (entry.executable != executable || entry.kind != info.kind)+ return false;+ const std::int64_t now_ns = now_ms * 1'000'000;+ const std::int64_t written_ns = written_ms * 1'000'000;+ constexpr std::int64_t window = 2'000'000'000;+ if (static_cast<std::int64_t>(info.mtime_ns) >= written_ns - window)+ return false;+ if (now_ns - static_cast<std::int64_t>(info.mtime_ns) < window)+ return false;+ return true;+}++Cache load_cache(const fs::path &root) {+ Cache cache;+ auto data = read_file_opt(working_copy_dir(root) / "stat-cache");+ if (!data || data->size() < 13)+ return cache;+ if (std::memcmp(data->data(), "VST1", 4) != 0)+ return cache;+ Reader r(Bytes(data->data() + 4, data->size() - 4));+ const auto version = r.u8();+ if (!version || *version != 49)+ return cache;+ const auto written = r.u64le();+ if (!written)+ return cache;+ cache.written_ms = static_cast<std::int64_t>(*written);+ const auto count = r.varint();+ if (!count)+ return cache;+ for (std::uint64_t i = 0; i < *count; ++i) {+ auto path = r.string_bytes(65536);+ if (!path)+ break;+ const auto size = r.u64le();+ const auto mtime = r.u64le();+ const auto inode = r.u64le();+ const auto kind = r.u8();+ const auto executable = r.u8();+ const auto target = r.id();+ if (!size || !mtime || !inode || !kind || !executable || !target)+ break;+ cache.entries.push_back(CacheEntry{std::move(*path), *size, *mtime, *inode,+ *kind, *executable != 0, *target});+ }+ std::stable_sort(cache.entries.begin(), cache.entries.end(),+ [](const CacheEntry &a, const CacheEntry &b) {+ return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+ });+ return cache;+}++bool save_cache(const fs::path &root, const std::vector<CacheEntry> &entries,+ std::int64_t written_ms) {+ ByteWriter w(4096);+ w.raw("VST1");+ w.u8(49);+ w.u64le(static_cast<std::uint64_t>(written_ms));+ w.varint(entries.size());+ for (const auto &entry : entries) {+ w.length_prefixed(entry.path);+ w.u64le(entry.size);+ w.u64le(entry.mtime_ns);+ w.u64le(entry.inode);+ w.u8(entry.kind);+ w.u8(entry.executable ? 1 : 0);+ w.id(entry.target);+ }+ const fs::path final_path = working_copy_dir(root) / "stat-cache";+ const fs::path tmp_path = tmp_dir(root) / "stat-cache.tmp";+ return write_atomic(tmp_path, final_path, w.view());+}++const CacheEntry *cache_lookup(const Cache &cache, std::string_view path) {+ std::size_t lo = 0;+ std::size_t hi = cache.entries.size();+ while (lo < hi) {+ const std::size_t mid = lo + (hi - lo) / 2;+ const int c = compare(bytes_of(cache.entries[mid].path), bytes_of(path));+ if (c == 0)+ return &cache.entries[mid];+ if (c < 0)+ lo = mid + 1;+ else+ hi = mid;+ }+ return nullptr;+}++Id add_blob_data(Txn &txn, Bytes data) {+ BlobBuild build = build_blob(data);+ for (auto &object : build.objects) {+ const Id id =+ object.id ? *object.id : object_id(object.type, bytes_of(object.body));+ (void)txn.add_known(object.type, id, std::move(object.body));+ }+ return build.root;+}++struct BuildState {+ bool failed = false;+};++std::optional<Id> empty_tree_id(Txn &txn) {+ static const std::vector<TreeEntry> empty;+ auto body = encode_tree(empty);+ if (!body)+ return std::nullopt;+ return txn.add_object(TYPE_TREE, std::move(*body));+}++std::optional<Id>+build_dir(Txn &txn, const fs::path &root, std::string_view base,+ std::optional<Id> old_tree_id, const IgnoreRules &base_rules,+ const Cache &cache, std::vector<CacheEntry> &new_cache,+ std::int64_t now_ms, BuildState &state, std::size_t depth) {+ if (depth > 4096) {+ state.failed = true;+ return std::nullopt;+ }++ IgnoreRules local = base_rules;+ ignore_load_file(local, root, base, ".vnexclude");+ ignore_load_file(local, root, base, ".gitignore");++ std::optional<Tree> old_tree;+ if (old_tree_id) {+ auto body = txn.store().read_body(*old_tree_id, TYPE_TREE);+ if (!body) {+ state.failed = true;+ return std::nullopt;+ }+ auto decoded = decode_tree(bytes_of(*body));+ if (!decoded) {+ state.failed = true;+ return std::nullopt;+ }+ old_tree = std::move(*decoded);+ }++ const fs::path dir = base.empty() ? root : root / path_from_bytes(base);+ if (!path_is_dir(dir)) {+ state.failed = true;+ return std::nullopt;+ }++ auto names = list_directory(dir);+ std::stable_sort(names.begin(), names.end(),+ [](const std::string &a, const std::string &b) {+ return compare(bytes_of(a), bytes_of(b)) < 0;+ });++ std::vector<TreeEntry> entries;+ for (const auto &name : names) {+ if (is_meta_name(name))+ continue;+ if (old_tree) {+ if (auto base_name = sidecar_base(name)) {+ const int index = find_tree_name(*old_tree, *base_name);+ if (index >= 0 &&+ old_tree->entries[static_cast<std::size_t>(index)].kind ==+ KIND_CONFLICT)+ continue;+ }+ }++ const std::string rel = join_rel(base, name);+ const fs::path fs_path = dir / path_from_bytes(name);+ const auto info = stat_path(fs_path);+ if (!info)+ continue;+ const bool is_dir = info->kind == 2;+ const bool ignored = ignore_ignored(local, rel, is_dir);+ const int old_index = old_tree ? find_tree_name(*old_tree, name) : -1;+ if (old_index >= 0 &&+ old_tree->entries[static_cast<std::size_t>(old_index)].kind ==+ KIND_CONFLICT) {+ entries.push_back(TreeEntry{+ name, KIND_CONFLICT,+ old_tree->entries[static_cast<std::size_t>(old_index)].target});+ continue;+ }+ if (ignored && old_index < 0)+ continue;++ if (is_dir) {+ std::optional<Id> child_old;+ if (old_tree && old_index >= 0) {+ const auto &old_entry =+ old_tree->entries[static_cast<std::size_t>(old_index)];+ if (old_entry.kind == KIND_SUBTREE)+ child_old = old_entry.target;+ }+ auto child = build_dir(txn, root, rel, child_old, local, cache, new_cache,+ now_ms, state, depth + 1);+ if (state.failed)+ return std::nullopt;+ if (child)+ entries.push_back(TreeEntry{name, KIND_SUBTREE, *child});+ } else if (info->kind == 3) {+ auto target = path_read_symlink(fs_path);+ if (!target) {+ state.failed = true;+ return std::nullopt;+ }+ const Id blob = add_blob_data(txn, bytes_of(*target));+ entries.push_back(TreeEntry{name, KIND_SYMLINK, blob});+ new_cache.push_back(CacheEntry{rel, info->size, info->mtime_ns,+ info->inode, info->kind, false, blob});+ } else if (info->kind == 1) {+ const bool executable = info->executable;+ std::optional<Id> target;+ if (const auto *cached = cache_lookup(cache, rel)) {+ if (cache_matches(*cached, *info, executable, now_ms,+ cache.written_ms)) {+ target = cached->target;+ }+ }+ if (!target) {+ auto data = read_file_opt(fs_path);+ if (!data) {+ state.failed = true;+ return std::nullopt;+ }+ target = add_blob_data(txn, bytes_of(*data));+ }+ new_cache.push_back(CacheEntry{rel, info->size, info->mtime_ns,+ info->inode, info->kind, executable,+ *target});+ entries.push_back(+ TreeEntry{name, executable ? KIND_EXECUTABLE : KIND_FILE, *target});+ }+ }++ if (entries.empty())+ return std::nullopt;+ auto body = encode_tree(entries);+ if (!body) {+ state.failed = true;+ return std::nullopt;+ }+ return txn.add_object(TYPE_TREE, std::move(*body));+}++// ---------------------------------------------------------------------------+// Checkout helpers+// ---------------------------------------------------------------------------++struct WalkEntry {+ std::string path;+ std::uint8_t kind = 0;+ Id target{};+};++bool valid_checkout_component(std::string_view component) {+ if (!valid_name(component))+ return false;+ return !ascii_iequals(bytes_of(component), bytes_of(".git"));+}++bool valid_checkout_path(std::string_view path) {+ if (!valid_path(path))+ return false;+ std::size_t start = 0;+ for (std::size_t i = 0; i <= path.size(); ++i) {+ if (i == path.size() || path[i] == '/') {+ if (!valid_checkout_component(path.substr(start, i - start)))+ return false;+ start = i + 1;+ }+ }+ return true;+}++bool has_symlink_component(const fs::path &root, std::string_view rel) {+ fs::path current = root;+ std::size_t start = 0;+ for (std::size_t i = 0; i < rel.size(); ++i) {+ if (rel[i] == '/') {+ if (i == start)+ return true;+ current /= path_from_bytes(rel.substr(start, i - start));+ const auto info = stat_path(current);+ if (info && info->kind == 3)+ return true;+ start = i + 1;+ }+ }+ return false;+}++bool ensure_safe_dirs(const fs::path &root, std::string_view rel) {+ if (rel.empty())+ return true;+ fs::path current = root;+ std::size_t start = 0;+ for (std::size_t i = 0; i <= rel.size(); ++i) {+ const bool at_end = i == rel.size();+ if (!at_end && rel[i] != '/')+ continue;+ const std::string_view component = rel.substr(start, i - start);+ if (component.empty())+ return false;+ if (at_end)+ break; // final component is the file+ current /= path_from_bytes(component);+ const auto info = stat_path(current);+ if (info) {+ if (info->kind == 3 || info->kind != 2)+ return false;+ } else if (!ensure_directory(current)) {+ return false;+ }+ start = i + 1;+ }+ return true;+}++bool remove_any(const fs::path &path) {+ std::error_code ec;+ if (path_is_dir(path) && !path_is_symlink(path)) {+ fs::remove_all(path, ec);+ return !ec;+ }+ return remove_file(path);+}++bool write_bytes_to_path(const fs::path &root, std::string_view rel, Bytes data,+ bool executable, std::string &error_path) {+ error_path = std::string(rel);+ if (!valid_checkout_path(rel) || has_symlink_component(root, rel))+ return false;+ if (!ensure_safe_dirs(root, rel))+ return false;+ const fs::path final_path = root / path_from_bytes(rel);+ if (path_is_dir(final_path) && !path_is_symlink(final_path))+ return false;+ if (path_is_symlink(final_path))+ (void)remove_file(final_path);+ if (!write_file(final_path, data))+ return false;+#if !defined(_WIN32)+ const mode_t mode = executable ? 0755 : 0644;+ (void)::chmod(final_path.c_str(), mode);+#else+ (void)executable;+#endif+ return true;+}++bool write_symlink_to_path(const fs::path &root, std::string_view rel,+ std::string_view target, std::string &error_path) {+ error_path = std::string(rel);+ if (!valid_checkout_path(rel) || has_symlink_component(root, rel))+ return false;+ if (!ensure_safe_dirs(root, rel))+ return false;+ const fs::path final_path = root / path_from_bytes(rel);+ if (path_is_dir(final_path) && !path_is_symlink(final_path))+ return false;+ if (path_exists(final_path))+ (void)remove_any(final_path);+ std::error_code ec;+ fs::create_symlink(path_from_bytes(target), final_path, ec);+ return !ec;+}++bool write_entry(Store &store, const fs::path &root, const WalkEntry &entry,+ std::string &error_path) {+ if (entry.kind == KIND_SYMLINK) {+ auto data = read_blob(store, entry.target);+ if (!data)+ return false;+ return write_symlink_to_path(root, entry.path, str_of(bytes_of(*data)),+ error_path);+ }+ auto data = read_blob(store, entry.target);+ if (!data)+ return false;+ return write_bytes_to_path(root, entry.path, bytes_of(*data),+ entry.kind == KIND_EXECUTABLE, error_path);+}++bool prune_empty_parents(const fs::path &root, std::string_view rel) {+ std::size_t end = rel.size();+ while (end > 0) {+ const std::size_t slash = rel.rfind('/', end - 1);+ if (slash == std::string_view::npos)+ break;+ const std::string parent(rel.substr(0, slash));+ const fs::path abs = root / path_from_bytes(parent);+ std::error_code ec;+ if (!fs::remove(abs, ec) || ec)+ break;+ end = slash;+ }+ return true;+}++void remove_tracked_path(const fs::path &root, std::string_view rel) {+ const fs::path abs = root / path_from_bytes(rel);+ if (path_exists(abs) || path_is_symlink(abs)) {+ (void)remove_any(abs);+ (void)prune_empty_parents(root, rel);+ }+}++std::vector<std::string> sidecar_suffixes() {+ std::vector<std::string> out = {".base", ".ours", ".theirs"};+ for (int n = 2; n <= 64; ++n) {+ out.push_back(".base" + std::to_string(n));+ out.push_back(".theirs" + std::to_string(n));+ }+ return out;+}++void delete_sidecars(const fs::path &root, std::string_view path) {+ static const auto suffixes = sidecar_suffixes();+ for (const auto &suffix : suffixes) {+ std::string full(path);+ full += suffix;+ remove_tracked_path(root, full);+ }+}++bool delete_stale(Store &store, const fs::path &root,+ const std::vector<FlatEntry> &old_entries,+ const std::vector<FlatEntry> &new_entries) {+ bool ok = true;+ for (const auto &old_entry : old_entries) {+ if (old_entry.kind == KIND_SUBMODULE)+ continue;+ if (find_flat(new_entries, old_entry.path))+ continue;+ const fs::path abs = root / path_from_bytes(old_entry.path);+ if (path_exists(abs) || path_is_symlink(abs)) {+ if (!remove_any(abs))+ ok = false;+ else+ (void)prune_empty_parents(root, old_entry.path);+ }+ if (old_entry.kind == KIND_CONFLICT)+ delete_sidecars(root, old_entry.path);+ }+ (void)store;+ return ok;+}++std::optional<Conflict> load_conflict(Store &store, const Id &id) {+ auto body = store.read_body(id, TYPE_CONFLICT);+ if (!body)+ return std::nullopt;+ auto decoded = decode_conflict(bytes_of(*body));+ if (!decoded)+ return std::nullopt;+ return std::move(*decoded);+}++bool write_tree_side(Store &store, const fs::path &root, const Id &tree_id,+ std::string_view prefix, std::string &error_path) {+ const auto entries = flatten_tree(store, tree_id);+ for (const auto &entry : entries) {+ if (entry.kind == KIND_CONFLICT)+ continue;+ if (entry.kind == KIND_SUBMODULE)+ continue;+ std::string path(prefix);+ if (!path.empty())+ path.push_back('/');+ path += entry.path;+ if (!write_entry(store, root, WalkEntry{path, entry.kind, entry.target},+ error_path))+ return false;+ }+ return true;+}++bool materialize_value(Store &store, const fs::path &root,+ std::string_view path, const ConflictValue &value,+ std::string &error_path) {+ error_path = std::string(path);+ if (value.kind == 0) {+ remove_tracked_path(root, path);+ return true;+ }+ if (!value.target)+ return false;+ if (value.kind == KIND_SUBTREE) {+ remove_tracked_path(root, path);+ return write_tree_side(store, root, *value.target, path, error_path);+ }+ return write_entry(store, root,+ WalkEntry{std::string(path), value.kind, *value.target},+ error_path);+}++bool materialize_conflict(Store &store, const fs::path &root,+ std::string_view path, const Id &target,+ std::string &error_path) {+ auto conflict = load_conflict(store, target);+ if (!conflict) {+ error_path = std::string(path);+ return false;+ }+ bool ok = true;+ for (std::size_t i = 0; i < conflict->removes.size(); ++i) {+ std::string suffix = i == 0 ? ".base" : ".base" + std::to_string(i + 1);+ std::string full(path);+ full += suffix;+ if (!materialize_value(store, root, full, conflict->removes[i], error_path))+ ok = false;+ }+ for (std::size_t i = 0; i < conflict->adds.size(); ++i) {+ std::string suffix;+ if (i == 0)+ suffix = ".ours";+ else if (i == 1)+ suffix = ".theirs";+ else+ suffix = ".theirs" + std::to_string(i + 1);+ std::string full(path);+ full += suffix;+ if (!materialize_value(store, root, full, conflict->adds[i], error_path))+ ok = false;+ }+ if (!conflict->adds.empty()) {+ if (!materialize_value(store, root, path, conflict->adds.front(),+ error_path))+ ok = false;+ } else {+ remove_tracked_path(root, path);+ }+ return ok;+}++int materialize_tree(Store &store, const fs::path &root,+ const std::vector<FlatEntry> &old_entries,+ const Id &new_root) {+ auto checked_entries = flatten_tree_checked(store, new_root);+ if (!checked_entries) {+ error_prefix();+ std::cout << "checkout tree validation failed\n";+ return 1;+ }+ const auto &new_entries = *checked_entries;+ std::set<std::string> dirs;+ std::vector<WalkEntry> files;+ std::vector<FlatEntry> conflicts;+ for (const auto &entry : new_entries) {+ if (!valid_checkout_path(entry.path)) {+ error_prefix();+ std::cout << "checkout tree validation failed at: " << entry.path << "\n";+ return 1;+ }+ std::string dir_path;+ std::size_t start = 0;+ for (std::size_t i = 0; i < entry.path.size(); ++i) {+ if (entry.path[i] == '/') {+ dir_path.append(entry.path.substr(start, i - start));+ dirs.insert(dir_path);+ dir_path.push_back('/');+ start = i + 1;+ }+ }+ if (entry.kind == KIND_CONFLICT) {+ conflicts.push_back(entry);+ } else if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||+ entry.kind == KIND_SYMLINK) {+ files.push_back(WalkEntry{entry.path, entry.kind, entry.target});+ }+ }++ // Sidecar collision check.+ const auto suffixes = sidecar_suffixes();+ for (const auto &conflict : conflicts) {+ for (const auto &suffix : suffixes) {+ std::string full = conflict.path;+ full += suffix;+ if (find_flat(old_entries, full)) {+ error_prefix();+ std::cout << "conflict sidecar would overwrite a tracked path: " << full+ << "\n";+ return 1;+ }+ }+ }++ // Remove sidecars left by a previous materialization.+ for (const auto &entry : old_entries) {+ if (entry.kind == KIND_CONFLICT)+ delete_sidecars(root, entry.path);+ }++ if (!delete_stale(store, root, old_entries, new_entries)) {+ error_prefix();+ std::cout << "cannot remove files that are absent from the target tree\n";+ return 1;+ }++ for (const auto &dir : dirs) {+ if (!ensure_safe_dirs(root, dir + "/x")) {+ error_prefix();+ std::cout << "cannot create directory: " << dir << "\n";+ return 1;+ }+ }++ std::string error_path;+ if (!files.empty()) {+ std::size_t workers = available_cpu_count();+ if (workers == 0)+ workers = 1;+ workers = std::min<std::size_t>(workers, files.size());+ workers = std::min<std::size_t>(workers, 16);+ if (workers > 1)+ store.preload();+ std::atomic<std::size_t> next{0};+ std::atomic<bool> failed{false};+ std::mutex error_mutex;+ std::vector<std::thread> threads;+ threads.reserve(workers);+ for (std::size_t w = 0; w < workers; ++w) {+ threads.emplace_back([&]() {+ for (;;) {+ const std::size_t index = next.fetch_add(1);+ if (index >= files.size() || failed.load(std::memory_order_relaxed))+ return;+ std::string local_error;+ if (!write_entry(store, root, files[index], local_error)) {+ std::lock_guard<std::mutex> lock(error_mutex);+ if (!failed.exchange(true))+ error_path = std::move(local_error);+ return;+ }+ }+ });+ }+ for (auto &thread : threads)+ thread.join();+ if (failed.load()) {+ error_prefix();+ std::cout << "checkout failed at: " << error_path << "\n";+ return 1;+ }+ }+ for (const auto &conflict : conflicts) {+ if (!materialize_conflict(store, root, conflict.path, conflict.target,+ error_path)) {+ error_prefix();+ std::cout << "checkout failed at: " << error_path << "\n";+ return 1;+ }+ }++ info_prefix();+ std::cout << "checked out " << files.size() << " files\n";+ return 0;+}++} // namespace++// ---------------------------------------------------------------------------+// Snapshot+// ---------------------------------------------------------------------------++int snapshot_run(const fs::path &root) {+ Store store = Store::open_all(root);+ const int status = snapshot_run(root, store);+ return status;+}++int snapshot_run(const fs::path &root, Store &store) {+ auto tx = Txn::begin(root, store);+ if (!tx) {+ error_prefix();+ std::cout << "cannot load repository state\n";+ return 1;+ }++ const auto wc = working_copy_id(tx->view());+ std::optional<Commit> old_commit;+ std::optional<Id> old_tree;+ bool have_wc = false;+ if (wc) {+ have_wc = true;+ auto body = tx->store().read_body(*wc, TYPE_COMMIT);+ if (!body) {+ error_prefix();+ std::cout << "missing working-copy commit\n";+ return 1;+ }+ auto decoded = decode_commit(bytes_of(*body));+ if (!decoded) {+ error_prefix();+ std::cout << "corrupt working-copy commit\n";+ return 1;+ }+ old_commit = std::move(*decoded);+ old_tree = old_commit->root_tree;+ }++ IgnoreRules rules = ignore_empty();+ ignore_load_root(rules, root);+ const Cache cache = load_cache(root);+ std::vector<CacheEntry> new_cache;+ const std::int64_t now_ms = unix_now_millis();+ BuildState state;+ auto built = build_dir(*tx, root, "", old_tree, rules, cache, new_cache,+ now_ms, state, 0);++ std::optional<Id> new_root;+ if (!state.failed && built) {+ new_root = built;+ } else if (!state.failed) {+ new_root = empty_tree_id(*tx);+ }+ if (!new_root || state.failed) {+ error_prefix();+ std::cout << "failed to build working-copy tree\n";+ return 1;+ }++ const bool unchanged =+ old_tree && std::memcmp(old_tree->data(), new_root->data(), ID_LEN) == 0;+ if (unchanged) {+ std::vector<CacheEntry> sorted = new_cache;+ std::stable_sort(sorted.begin(), sorted.end(),+ [](const CacheEntry &a, const CacheEntry &b) {+ return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+ });+ (void)save_cache(root, sorted, now_ms);+ return 0;+ }++ const Sig committer = identity_signature(root);+ Sig author = committer;+ std::vector<Id> parents;+ ChangeId change_id{};+ std::string message;+ if (old_commit) {+ author = old_commit->author;+ parents = old_commit->parents;+ change_id = old_commit->change_id;+ message = old_commit->message;+ } else {+ change_id = random_change_id();+ }++ std::vector<Rename> renames;+ if (old_commit)+ renames = old_commit->renames;++ Commit commit;+ commit.version = 1;+ commit.parents = parents;+ commit.root_tree = *new_root;+ commit.change_id = change_id;+ commit.author = author;+ commit.committer = committer;+ commit.message = message;+ commit.renames_state = RENAMES_RECORDED;+ commit.renames = std::move(renames);+ commit.extra = old_commit ? old_commit->extra : std::vector<KeyValue>{};+ const auto encoded = encode_commit(commit);+ const Id new_commit = tx->add_object(TYPE_COMMIT, encoded);++ if (have_wc) {+ remove_head(tx->view(), *wc);+ move_bookmarks(tx->view(), *wc, new_commit);+ }+ set_workspace(tx->view(), new_commit);+ rebuild_heads(tx->view());++ const auto status = tx->finish("snapshot");+ if (!status)+ return 1;+ store.refresh(root);+ (void)mark_native(root, new_commit);++ std::vector<CacheEntry> sorted = new_cache;+ std::stable_sort(sorted.begin(), sorted.end(),+ [](const CacheEntry &a, const CacheEntry &b) {+ return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+ });+ (void)save_cache(root, sorted, now_ms);+ return 0;+}++// ---------------------------------------------------------------------------+// Checkout+// ---------------------------------------------------------------------------++int checkout_materialize_commit(const fs::path &root, Store &store,+ std::optional<Id> old_root,+ const Id &new_root) {+ if (old_root && std::memcmp(old_root->data(), new_root.data(), ID_LEN) == 0)+ return 0;+ const auto old_entries = flatten_or_empty(store, old_root);+ const int status = materialize_tree(store, root, old_entries, new_root);+ if (status == 0)+ clear_stat_cache(root);+ return status;+}++void clear_stat_cache(const fs::path &root) {+ (void)remove_file(working_copy_dir(root) / "stat-cache");+}++int checkout_run(const fs::path &root, std::string_view rev) {+ const int snap = snapshot_run(root);+ if (snap != 0)+ return snap;++ Store store = Store::open_all(root);+ auto view = current_view(root, store);+ if (!view) {+ error_prefix();+ std::cout << "no operation state; import a repository first\n";+ return 1;+ }++ const auto target = resolve_revision(store, *view, rev);+ if (!target) {+ error_prefix();+ std::cout << "unknown revision: " << rev << "\n";+ return 1;+ }+ auto commit_body = store.read_body(*target, TYPE_COMMIT);+ if (!commit_body) {+ error_prefix();+ std::cout << "cannot read commit\n";+ return 1;+ }+ auto commit = decode_commit(bytes_of(*commit_body));+ if (!commit) {+ error_prefix();+ std::cout << "cannot read commit\n";+ return 1;+ }++ const auto wc = working_copy_id(*view);+ std::optional<Id> old_root;+ if (wc) {+ auto old_body = store.read_body(*wc, TYPE_COMMIT);+ if (old_body) {+ auto old_commit = decode_commit(bytes_of(*old_body));+ if (old_commit)+ old_root = old_commit->root_tree;+ }+ }++ const int materialized =+ checkout_materialize_commit(root, store, old_root, commit->root_tree);+ if (materialized != 0)+ return materialized;++ if (!wc || std::memcmp(wc->data(), target->data(), ID_LEN) != 0) {+ auto tx = Txn::begin(root, store);+ if (!tx) {+ error_prefix();+ std::cout << "cannot load repository state\n";+ return 1;+ }+ if (wc)+ remove_head(tx->view(), *wc);+ set_workspace(tx->view(), *target);+ rebuild_heads(tx->view());+ const auto status = tx->finish("checkout");+ if (!status)+ return 1;+ }+ return 0;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/worktree.h@@ -0,0 +1,18 @@+#pragma once++#include "store.h"++#include <optional>+#include <string>++namespace vn {++int snapshot_run(const fs::path &root);+int snapshot_run(const fs::path &root, Store &store);++int checkout_run(const fs::path &root, std::string_view rev);+int checkout_materialize_commit(const fs::path &root, Store &store,+ std::optional<Id> old_root, const Id &new_root);+void clear_stat_cache(const fs::path &root);++} // namespace vn