navid/veins / commit
bfd69df60a59
Navid M <navidmomtahen@gmail.com> · 2026-11-27
parents: 1ea4e3065eb7
Browse files at this commit · Download source
--- a/veins-cpprewrite/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-/build*/-/.cache/-.net-bench/--- a/veins-cpprewrite/BENCHES.md+++ /dev/null@@ -1,200 +0,0 @@-# veins benchmarks--Two reproducible benchmark sets are kept here: a local-core comparison that includes-the Rust subset, and the native network comparison between the C++ rewrite and Spectre.--## Local core: Rust subset vs C++ vs Spectre--Generated 2026-11-27 by `bench/core_bench.py`.--### Environment--| Implementation | Binary |-|:---|:---|-| Rust | `veins-rust v0.1.0 (veins-store 1)` |-| C++ | `veins v0.0.1 (veins-store 1)` |-| Spectre | `veins v0.0.1 (veins-store 1)` |--```-host: Darwin arm64-cpu: Apple M2-repeats: 5 (median reported)-cpu pinning: no-```--### Scope--The Rust binary implements the local-core subset: `init`, `status`, `log`, `go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.-It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache invalidation window as the reference.--The subset does not implement merge/conflict objects, rebase/undo, the git bridge, ignore files, or the network protocol. The workload below contains no renames, ignores, merges, or network traffic, so the measured local operations are directly comparable.--### Workload--- Base snapshot: 2.95 MiB, 42 files.-- 20 edit/commit revisions, 8 checkouts, 5 repeats, median reported.-- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.-- Each `go` performs the same snapshot, describe, and new-empty-change sequence as the reference, including all operation-log writes.-- Store size includes `.veins` packs, indexes, operation heads, the native commit map, and the stat cache.--### Summary--| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |-|:---|---:|---:|---:|---:|---:|-| Commit total [s] | 0.252 (0.250-0.262) | 0.280 (0.279-0.291) | 0.310 (0.309-0.330) | 1.11x | 1.23x |-| Checkout total [s] | 0.162 (0.161-0.165) | 0.175 (0.172-0.179) | 0.181 (0.179-0.196) | 1.08x | 1.12x |-| Store size [MiB] | 8.28 (8.28-8.37) | 8.28 (8.28-8.37) | 10.60 (10.60-10.69) | 1.00x | 1.28x |--Each cell is the median with the observed min-max range in parentheses.-A ratio above 1 means the other implementation took longer or used more space than Rust.--### Repeats--| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |-|:---|---:|---:|---:|---:|---:|---:|-| 1 | 0.262 | 0.291 | 0.330 | 0.165 | 0.172 | 0.195 |-| 2 | 0.250 | 0.280 | 0.310 | 0.162 | 0.172 | 0.196 |-| 3 | 0.252 | 0.281 | 0.309 | 0.161 | 0.179 | 0.179 |-| 4 | 0.252 | 0.279 | 0.309 | 0.162 | 0.175 | 0.179 |-| 5 | 0.257 | 0.280 | 0.311 | 0.165 | 0.177 | 0.181 |--### Notes--- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache racy window.-- Each `go` performs the same snapshot, describe, and new-empty-change sequence in both implementations, including three operation writes.-- The Rust subset omits ignore-file parsing and similarity-based rename detection. This workload has neither ignore files nor renames, so both implementations see the same file set and perform the same exact-rename scan.-- Rust and C++ store sizes are equal at this resolution; Spectre stores the same logical history with a different packing policy.-- This is a single-machine run. Treat differences below roughly 5% as noise.--### Reproduce--```sh-cd veins-rust-cargo build --release-cd ../veins-cpprewrite-python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md-```--## Networking: C++ rewrite vs Spectre--Generated 2026-11-27 16:15:11 UTC by `bench/net_bench.sh`.--The Rust subset is not included in this section because it does not implement a-network transport.--### Environment--```-host: Darwin arm64-cpu: Apple M2-hyperfine: hyperfine 1.20.0-c++ vn: veins v0.0.1 (veins-store 1)-spectre vn: veins v0.0.1 (veins-store 1)-runs: 10 (clone/fetch/push/checkout), 20 (whoami)-warmup: 1 (clone/fetch/push/checkout), 2 (whoami)-```--### Dataset--- `bench_src`: 361 working files, 5.7M on disk including packs.- - 360 small text files in 18 directories.- - 2 MiB `big_old.bin` in the `oldbig` history.- - 1 MiB `big_head.bin` in `main`.-- `push_pristine`: a separate 20-file repository, so push does not transfer the large dataset.--### What each benchmark does--| Benchmark | Operation |-|:---|:---|-| `clone-file` | Full clone over `file://`: handshake, refs, history, head chunks, checkout. Includes spawning one local server per run. |-| `fetch-file` | `vn fetch origin` with no new remote refs. Both clients start from a full `-blobs:all` clone. |-| `lazy-checkout-file` | `vn co oldbig` in a `-blobs:none` clone, fetching the 2 MiB old blob from the promisor over `file://`. |-| `push-file` | Push one new commit from a prepared client to a freshly reset copy of `push_pristine` over `file://`. |-| `whoami-file` | Connect, authenticate, `WHOAMI`, close over `file://`. |-| `clone-ssh` | Full clone over `ssh://`, using a local `ssh` shim that runs the remote `vn serve -stdio` command. |-| `clone-tls` | Full clone over TLS 1.3 with a pinned self-signed certificate. Uses long-running servers. |-| `whoami-tls` | Connect, authenticate, `WHOAMI`, close over TLS 1.3. |--Lower is better. Hyperfine reports wall-clock time; the relative column is against the fastest command.--### Summary--| Benchmark | C++ mean | Spectre mean | Spectre / C++ |-|:---|---:|---:|---:|-| Clone file:// | 35.9 ms | 61.0 ms | 1.70x |-| Fetch file:// | 24.6 ms | 31.2 ms | 1.27x |-| Lazy checkout file:// | 253.1 ms | 420.2 ms | 1.66x |-| Push file:// | 17.0 ms | 16.0 ms | 0.94x |-| Whoami file:// | 9.7 ms | 12.5 ms | 1.28x |-| Clone ssh:// | 42.5 ms | 66.6 ms | 1.57x |-| Clone TLS 1.3 | 37.9 ms | 64.9 ms | 1.71x |-| Whoami TLS 1.3 | 10.0 ms | 14.8 ms | 1.48x |--A ratio above 1 means Spectre took longer than C++.--### Results--#### Clone over file://-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 35.9 ± 0.3 | 35.5 | 36.3 | 1.00 |-| `Spectre` | 61.0 ± 1.8 | 58.2 | 63.4 | 1.70 ± 0.05 |--#### Fetch over file://-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 24.6 ± 0.4 | 23.9 | 25.1 | 1.00 |-| `Spectre` | 31.2 ± 1.0 | 30.2 | 32.6 | 1.27 ± 0.04 |--#### Lazy checkout over file://-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 253.1 ± 7.1 | 247.7 | 272.4 | 1.00 |-| `Spectre` | 420.2 ± 14.5 | 402.5 | 451.8 | 1.66 ± 0.07 |--#### Push over file://-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 17.0 ± 6.8 | 12.3 | 32.0 | 1.06 ± 0.43 |-| `Spectre` | 16.0 ± 0.4 | 15.7 | 16.8 | 1.00 |--#### Whoami over file://-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 9.7 ± 0.6 | 8.7 | 10.5 | 1.00 |-| `Spectre` | 12.5 ± 0.2 | 12.1 | 12.9 | 1.28 ± 0.08 |--#### Clone over ssh://-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 42.5 ± 0.4 | 41.9 | 43.2 | 1.00 |-| `Spectre` | 66.6 ± 1.2 | 64.4 | 67.8 | 1.57 ± 0.03 |--#### Clone over TLS 1.3-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 37.9 ± 1.4 | 35.9 | 39.8 | 1.00 |-| `Spectre` | 64.9 ± 1.6 | 62.0 | 67.7 | 1.71 ± 0.07 |--#### Whoami over TLS 1.3-| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |-|:---|---:|---:|---:|---:|-| `C++` | 10.0 ± 0.2 | 9.4 | 10.4 | 1.00 |-| `Spectre` | 14.8 ± 0.3 | 14.0 | 15.2 | 1.48 ± 0.04 |--### Notes--- Spectre clone destinations are absolute paths on macOS. The reference checkout hardcodes Linux's `AT_FDCWD` value (`-100`); with a relative destination it cannot open the working directory on macOS.-- `file://` and `ssh://` include server process startup. `clone-tls` and `whoami-tls` use long-running servers, so they isolate protocol and TLS cost more closely.-- These runs reproduce the reference's transfer behavior: fetch `haves` are operation heads (so metadata is re-sent), and push sends all objects reachable from the bookmark rather than using `HAVE_QUERY`.-- Lazy checkout fetches one missing chunk per promisor connection in both implementations, so it is intentionally a worst-case/read-ahead-free measurement.-- `push-file` is only a few milliseconds of real work; process startup noise can dominate. Read the min/max columns alongside the mean.-- Treat differences below roughly 10 ms as noise; this is a single-machine run, not a controlled lab measurement.--### Reproduce--```sh-cd veins-cpprewrite-cmake -S . -B build && cmake --build build -j-./bench/net_bench.sh-```--- a/veins-cpprewrite/CMakeLists.txt+++ /dev/null@@ -1,180 +0,0 @@-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)--# Prefer static archives for fetched dependencies (BLAKE3, zstd fallback).-set(BUILD_SHARED_LIBS OFF)--find_package(Threads REQUIRED)--# ----------------------------------------------------------------------------# OpenSSL: TLS 1.3, Ed25519, and cryptographic randomness for the native-# protocol. Homebrew keeps OpenSSL keg-only on macOS, so try `brew` before the-# default search when the caller did not provide an explicit root.-# ----------------------------------------------------------------------------if(APPLE AND NOT OPENSSL_ROOT_DIR AND NOT DEFINED ENV{OPENSSL_ROOT_DIR})- find_program(VN_BREW_EXECUTABLE brew)- if(VN_BREW_EXECUTABLE)- foreach(_formula openssl@3 openssl)- execute_process(- COMMAND "${VN_BREW_EXECUTABLE}" --prefix "${_formula}"- OUTPUT_VARIABLE _prefix- OUTPUT_STRIP_TRAILING_WHITESPACE- ERROR_QUIET- )- if(_prefix AND EXISTS "${_prefix}/include/openssl")- set(OPENSSL_ROOT_DIR "${_prefix}")- break()- endif()- endforeach()- endif()-endif()-find_package(OpenSSL REQUIRED)--# ----------------------------------------------------------------------------# zstd: prefer an installed package, otherwise a system library, otherwise-# fetch a pinned release.-# ----------------------------------------------------------------------------find_package(zstd CONFIG QUIET)-if(TARGET zstd::libzstd_static)- set(VN_ZSTD_TARGET zstd::libzstd_static)-elseif(TARGET libzstd_static)- set(VN_ZSTD_TARGET libzstd_static)-else()- # Ubuntu/Debian's libzstd-dev ships zstd.h and libzstd.{a,so} but no CMake- # config. Never pass "libzstd" to the linker: -llibzstd looks for- # liblibzstd.*. Naming the archive explicitly prefers libzstd.a, which is- # the equivalent of linking with -l:libzstd.a.- find_library(VN_ZSTD_LIBRARY NAMES libzstd.a zstd)- if(VN_ZSTD_LIBRARY)- find_path(VN_ZSTD_INCLUDE_DIR NAMES zstd.h)- add_library(vn_zstd UNKNOWN IMPORTED)- set_target_properties(vn_zstd PROPERTIES- IMPORTED_LOCATION "${VN_ZSTD_LIBRARY}"- )- if(VN_ZSTD_INCLUDE_DIR)- set_target_properties(vn_zstd PROPERTIES- INTERFACE_INCLUDE_DIRECTORIES "${VN_ZSTD_INCLUDE_DIR}"- )- endif()- set(VN_ZSTD_TARGET vn_zstd)- elseif(TARGET zstd::libzstd_shared)- set(VN_ZSTD_TARGET zstd::libzstd_shared)- elseif(TARGET libzstd)- set(VN_ZSTD_TARGET libzstd)- endif()-endif()--if(NOT VN_ZSTD_TARGET)- 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/pathspec.cpp- src/bookmark.cpp- src/remove.cpp- src/exclude.cpp- src/oplog.cpp- src/merge.cpp- src/cli.cpp- src/crypto.cpp- src/net.cpp- src/wire.cpp- src/protocol.cpp- src/auth.cpp- src/server.cpp- src/promisor.cpp- src/net_commands.cpp-)--target_include_directories(vn PRIVATE src)-target_link_libraries(vn PRIVATE- BLAKE3::blake3- ${VN_ZSTD_TARGET}- OpenSSL::SSL- OpenSSL::Crypto- Threads::Threads-)-if(WIN32)- target_link_libraries(vn PRIVATE bcrypt ws2_32 crypt32)-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)--- a/veins-cpprewrite/bench/bench.py+++ /dev/null@@ -1,190 +0,0 @@-#!/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())--- a/veins-cpprewrite/bench/core_bench.md+++ /dev/null@@ -1,69 +0,0 @@-Generated 2026-11-27 by `bench/core_bench.py`.--### Environment--| Implementation | Binary |-|:---|:---|-| Rust | `veins-rust v0.1.0 (veins-store 1)` |-| C++ | `veins v0.0.1 (veins-store 1)` |-| Spectre | `veins v0.0.1 (veins-store 1)` |--```-host: Darwin arm64-cpu: Apple M2-repeats: 5 (median reported)-cpu pinning: no-```--### Scope--The Rust binary implements the local-core subset: `init`, `status`, `log`, `go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.-It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache invalidation window as the reference.--The subset does not implement merge/conflict objects, rebase/undo, the git bridge, ignore files, or the network protocol. The workload below contains no renames, ignores, merges, or network traffic, so the measured local operations are directly comparable.--### Workload--- Base snapshot: 2.95 MiB, 42 files.-- 20 edit/commit revisions, 8 checkouts, 5 repeats, median reported.-- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.-- Each `go` performs the same snapshot, describe, and new-empty-change sequence as the reference, including all operation-log writes.-- Store size includes `.veins` packs, indexes, operation heads, the native commit map, and the stat cache.--### Summary--| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |-|:---|---:|---:|---:|---:|---:|-| Commit total [s] | 0.252 (0.250-0.262) | 0.280 (0.279-0.291) | 0.310 (0.309-0.330) | 1.11x | 1.23x |-| Checkout total [s] | 0.162 (0.161-0.165) | 0.175 (0.172-0.179) | 0.181 (0.179-0.196) | 1.08x | 1.12x |-| Store size [MiB] | 8.28 (8.28-8.37) | 8.28 (8.28-8.37) | 10.60 (10.60-10.69) | 1.00x | 1.28x |--Each cell is the median with the observed min-max range in parentheses.-A ratio above 1 means the other implementation took longer or used more space than Rust.--### Repeats--| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |-|:---|---:|---:|---:|---:|---:|---:|-| 1 | 0.262 | 0.291 | 0.330 | 0.165 | 0.172 | 0.195 |-| 2 | 0.250 | 0.280 | 0.310 | 0.162 | 0.172 | 0.196 |-| 3 | 0.252 | 0.281 | 0.309 | 0.161 | 0.179 | 0.179 |-| 4 | 0.252 | 0.279 | 0.309 | 0.162 | 0.175 | 0.179 |-| 5 | 0.257 | 0.280 | 0.311 | 0.165 | 0.177 | 0.181 |--### Notes--- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache racy window.-- Each `go` performs the same snapshot, describe, and new-empty-change sequence in both implementations, including three operation writes.-- The Rust subset omits ignore-file parsing and similarity-based rename detection. This workload has neither ignore files nor renames, so both implementations see the same file set and perform the same exact-rename scan.-- Rust and C++ store sizes are equal at this resolution; Spectre stores the same logical history with a different packing policy.-- This is a single-machine run. Treat differences below roughly 5% as noise.--### Reproduce--```sh-cd veins-rust-cargo build --release-cd ../veins-cpprewrite-python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md-```--- a/veins-cpprewrite/bench/core_bench.py+++ /dev/null@@ -1,334 +0,0 @@-#!/usr/bin/env python3--from __future__ import annotations--import argparse-import os-import platform-import random-import re-import shutil-import statistics-import subprocess-import sys-import tempfile-import time-from datetime import datetime, timezone-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 environment(binary: Path) -> str:- try:- return run([str(binary), "version"], Path.cwd()).strip()- except Exception:- return "unknown"---def cpu_name() -> str:- try:- return subprocess.run(- ["sysctl", "-n", "machdep.cpu.brand_string"],- stdout=subprocess.PIPE,- stderr=subprocess.DEVNULL,- check=True,- text=True,- ).stdout.strip()- except Exception:- return platform.processor() or platform.machine()---def main() -> int:- parser = argparse.ArgumentParser(description=__doc__)- root = Path(__file__).resolve().parents[2]- parser.add_argument("--spectre", type=Path, default=root / "veins" / "vn")- parser.add_argument("--cpp", type=Path, default=root / "veins-cpprewrite" / "build" / "vn")- parser.add_argument(- "--rust", type=Path, default=root / "veins-rust" / "target" / "release" / "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")- parser.add_argument("--markdown-out", type=Path)- args = parser.parse_args()-- global PREFIX- PREFIX = [] if args.no_pin else command_prefix()-- binaries = {- "rust": args.rust,- "cpp": args.cpp,- "spectre": args.spectre,- }- for label, binary in binaries.items():- if not binary.exists():- print(f"missing {label} binary: {binary}", file=sys.stderr)- return 2-- work = Path(tempfile.mkdtemp(prefix="veins-core-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={'yes' if PREFIX else 'no'}"- )- rows: dict[str, list[tuple[float, float, int]]] = {- "rust": [],- "cpp": [],- "spectre": [],- }- for repeat in range(args.repeats):- print(f"repeat {repeat + 1}/{args.repeats}")- for label, binary in binaries.items():- 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])-- def spread(label: str, index: int) -> str:- values = [row[index] for row in rows[label]]- return f"{statistics.median(values):.3f} ({min(values):.3f}-{max(values):.3f})"-- def spread_mib(label: str) -> str:- values = [row[2] / (1024 * 1024) for row in rows[label]]- return f"{statistics.median(values):.2f} ({min(values):.2f}-{max(values):.2f})"-- values = {- label: (median(label, 0), median(label, 1), median(label, 2))- for label in rows- }- rust_commit, rust_checkout, rust_store = values["rust"]- cpp_commit, cpp_checkout, cpp_store = values["cpp"]- sx_commit, sx_checkout, sx_store = values["spectre"]-- print()- print(f"commit C++/Rust: {cpp_commit / rust_commit:.2f}x")- print(f"commit Spectre/Rust: {sx_commit / rust_commit:.2f}x")- print(f"checkout C++/Rust: {cpp_checkout / rust_checkout:.2f}x")- print(f"checkout Spectre/Rust: {sx_checkout / rust_checkout:.2f}x")- print(f"store C++/Rust: {cpp_store / rust_store:.2f}x")- print(f"store Spectre/Rust: {sx_store / rust_store:.2f}x")-- if args.markdown_out:- lines = [- f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by `bench/core_bench.py`.",- "",- "### Environment",- "",- "| Implementation | Binary |",- "|:---|:---|",- f"| Rust | `{environment(args.rust)}` |",- f"| C++ | `{environment(args.cpp)}` |",- f"| Spectre | `{environment(args.spectre)}` |",- "",- "```",- f"host: {platform.system()} {platform.machine()}",- f"cpu: {cpu_name()}",- f"repeats: {args.repeats} (median reported)",- f"cpu pinning: {'yes' if PREFIX else 'no'}",- "```",- "",- "### Scope",- "",- "The Rust binary implements the local-core subset: `init`, `status`, `log`, "- "`go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.",- "It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, "- "pack/index layout, operation log, and stat-cache invalidation window as "- "the reference.",- "",- "The subset does not implement merge/conflict objects, rebase/undo, the git "- "bridge, ignore files, or the network protocol. The workload below contains "- "no renames, ignores, merges, or network traffic, so the measured local "- "operations are directly comparable.",- "",- "### Workload",- "",- f"- Base snapshot: {size / (1024 * 1024):.2f} MiB, "- f"{args.small_files + 2} files.",- f"- {args.revisions} edit/commit revisions, {args.checkouts} checkouts, "- f"{args.repeats} repeats, median reported.",- "- Each revision rewrites about 1% of a 120,000-line generated C file "- "and three small module files.",- "- Each `go` performs the same snapshot, describe, and new-empty-change "- "sequence as the reference, including all operation-log writes.",- "- Store size includes `.veins` packs, indexes, operation heads, the native "- "commit map, and the stat cache.",- "",- "### Summary",- "",- "| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |",- "|:---|---:|---:|---:|---:|---:|",- f"| Commit total [s] | {spread('rust', 0)} | {spread('cpp', 0)} | "- f"{spread('spectre', 0)} | {cpp_commit / rust_commit:.2f}x | "- f"{sx_commit / rust_commit:.2f}x |",- f"| Checkout total [s] | {spread('rust', 1)} | {spread('cpp', 1)} | "- f"{spread('spectre', 1)} | {cpp_checkout / rust_checkout:.2f}x | "- f"{sx_checkout / rust_checkout:.2f}x |",- f"| Store size [MiB] | {spread_mib('rust')} | {spread_mib('cpp')} | "- f"{spread_mib('spectre')} | {cpp_store / rust_store:.2f}x | "- f"{sx_store / rust_store:.2f}x |",- "",- "Each cell is the median with the observed min-max range in parentheses.",- "A ratio above 1 means the other implementation took longer or used "- "more space than Rust.",- "",- "### Repeats",- "",- "| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | "- "Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |",- "|:---|---:|---:|---:|---:|---:|---:|",- ]- for index in range(args.repeats):- lines.append(- f"| {index + 1} | {rows['rust'][index][0]:.3f} | "- f"{rows['cpp'][index][0]:.3f} | {rows['spectre'][index][0]:.3f} | "- f"{rows['rust'][index][1]:.3f} | {rows['cpp'][index][1]:.3f} | "- f"{rows['spectre'][index][1]:.3f} |"- )- lines.extend(- [- "",- "### Notes",- "",- "- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, "- "zstd level 1, pack/index layout, operation log, and stat-cache racy window.",- "- Each `go` performs the same snapshot, describe, and new-empty-change "- "sequence in both implementations, including three operation writes.",- "- The Rust subset omits ignore-file parsing and similarity-based rename "- "detection. This workload has neither ignore files nor renames, so both "- "implementations see the same file set and perform the same exact-rename scan.",- "- Rust and C++ store sizes are equal at this resolution; Spectre stores the "- "same logical history with a different packing policy.",- "- This is a single-machine run. Treat differences below roughly 5% as noise.",- "",- "### Reproduce",- "",- "```sh",- "cd veins-rust",- "cargo build --release",- "cd ../veins-cpprewrite",- "python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md",- "```",- "",- ]- )- args.markdown_out.write_text("\n".join(lines), encoding="utf-8")- return 0- finally:- shutil.rmtree(work, ignore_errors=True)---if __name__ == "__main__":- raise SystemExit(main())--- a/veins-cpprewrite/bench/net_bench.sh+++ /dev/null@@ -1,510 +0,0 @@-#!/bin/sh-# Compare the C++ rewrite with the Spectre reference over the native protocol.-#-# Requirements: hyperfine, python3, openssl, a built C++ vn, and the Spectre vn-# in ../veins/vn. The script creates a throwaway dataset under bench/.net-bench,-# runs hyperfine, and writes BENCHES.md.-set -eu--SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)-ROOT=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)-REPO=$(CDPATH= cd -- "$ROOT/.." && pwd)--VN_CPP=${VN_CPP:-$ROOT/build/vn}-VN_SPECTRE=${VN_SPECTRE:-$REPO/veins/vn}-HYPERFINE=${HYPERFINE:-hyperfine}-WORK=${WORK:-$ROOT/bench/.net-bench}-OUT=${OUT:-$ROOT/BENCHES.md}-RUNS=${RUNS:-10}-WHOAMI_RUNS=${WHOAMI_RUNS:-20}--SYS_PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"--case "$WORK" in- ""|"/"|".") echo "refusing to use WORK='$WORK'" >&2; exit 1 ;;-esac--CPP_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_CPP")" && pwd)-SX_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_SPECTRE")" && pwd)-VN_CPP="$CPP_DIR/$(basename -- "$VN_CPP")"-VN_SPECTRE="$SX_DIR/$(basename -- "$VN_SPECTRE")"--for tool in "$VN_CPP" "$VN_SPECTRE"; do- if [ ! -x "$tool" ]; then- echo "missing executable: $tool" >&2- echo "build the C++ rewrite first: cmake --build $ROOT/build" >&2- exit 1- fi-done-for tool in "$HYPERFINE" python3 openssl; do- if ! command -v "$tool" >/dev/null 2>&1; then- echo "required tool not found: $tool" >&2- exit 1- fi-done--rm -rf "$WORK"-mkdir -p "$WORK/config" "$WORK/bench_src" "$WORK/push_pristine" "$WORK/fakebin"--XDG_CONFIG_HOME="$WORK/config"-export XDG_CONFIG_HOME--CPP_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$CPP_DIR:$SYS_PATH' '$VN_CPP'"-SX_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"-CPP_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$CPP_DIR:$SYS_PATH' '$VN_CPP'"-SX_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"--run_cpp() {- env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$CPP_DIR:$SYS_PATH" "$VN_CPP" "$@"-}-run_sx() {- env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$SX_DIR:$SYS_PATH" "$VN_SPECTRE" "$@"-}--wait_port() {- python3 - "$1" <<'PY'-import socket, sys, time-port = int(sys.argv[1])-for _ in range(100):- sock = socket.socket()- sock.settimeout(0.1)- try:- sock.connect(("127.0.0.1", port))- sock.close()- sys.exit(0)- except OSError:- sock.close()- time.sleep(0.1)-sys.exit(1)-PY-}--generate_small_files() {- python3 - "$1" "$2" "$3" <<'PY'-import os, sys-root, start, stop = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])-body = ("abcdefghijklmnopqrstuvwxyz" * 70)[:1800]-for d in range(start, stop):- folder = os.path.join(root, "d%02d" % d)- os.makedirs(folder, exist_ok=True)- for f in range(20):- path = os.path.join(folder, "f%02d.txt" % f)- with open(path, "w", encoding="utf-8") as handle:- handle.write("file %d-%d\n" % (d, f))- handle.write(body)- handle.write("\n")-PY-}--# ----------------------------------------------------------------------------# Keys and access-# -----------------------------------------------------------------------------run_cpp key generate benchkey > "$WORK/key.txt"-PUB=$(awk '/public key:/ {print $3}' "$WORK/key.txt")-if [ -z "$PUB" ]; then- echo "could not generate the benchmark key" >&2- exit 1-fi-run_cpp auth use benchkey >/dev/null--grant_access() {- ( cd "$1" && run_cpp access anonymous on && \- run_cpp access add -role write -key "$PUB" -name bench >/dev/null )-}--# ----------------------------------------------------------------------------# Dataset: 360 small files, a 2 MiB old blob, and a 1 MiB head blob.-# -----------------------------------------------------------------------------(- cd "$WORK/bench_src"- run_sx init . >/dev/null- generate_small_files . 0 12- python3 - <<'PY'-import os-with open("big_old.bin", "wb") as handle:- handle.write(os.urandom(2 * 1024 * 1024))-PY- run_sx go -m "base commit" >/dev/null- # Point oldbig at the real base commit, not the movable working-copy commit.- BASE_CHANGE=$(run_sx log | awk '/base commit/ {print $2}' | tail -1)- if [ -z "$BASE_CHANGE" ]; then- echo "could not resolve the base commit" >&2- exit 1- fi- run_sx bmk set oldbig -rev "$BASE_CHANGE" >/dev/null- rm -f big_old.bin- generate_small_files . 12 18- python3 - <<'PY'-import os-with open("big_head.bin", "wb") as handle:- handle.write(os.urandom(1 * 1024 * 1024))-PY- run_sx go -m "head commit" >/dev/null- run_sx bmk set main >/dev/null-)-grant_access "$WORK/bench_src"--# A separate small repository for push, so a push does not transfer the large-# dataset. The reference pushes all reachable objects, as does the rewrite.-(- cd "$WORK/push_pristine"- run_sx init . >/dev/null- generate_small_files . 0 1- run_sx go -m "push base" >/dev/null- run_sx bmk set main >/dev/null-)-grant_access "$WORK/push_pristine"--# ----------------------------------------------------------------------------# Prepared client/server repositories-# -----------------------------------------------------------------------------run_cpp clone "file://$WORK/bench_src" "$WORK/fetch_pristine_cpp" -blobs:all >/dev/null-run_sx clone "file://$WORK/bench_src" "$WORK/fetch_pristine_sx" -blobs:all >/dev/null-run_cpp clone "file://$WORK/bench_src" "$WORK/lazy_pristine_cpp" -blobs:none >/dev/null-run_sx clone "file://$WORK/bench_src" "$WORK/lazy_pristine_sx" -blobs:none >/dev/null--run_cpp clone "file://$WORK/push_pristine" "$WORK/push_client_cpp" >/dev/null-run_sx clone "file://$WORK/push_pristine" "$WORK/push_client_sx" >/dev/null-(- cd "$WORK/push_client_cpp"- printf 'bench push\n' > push.txt- run_cpp go -m "bench push" >/dev/null- run_cpp bmk set main >/dev/null- run_cpp remote set-url origin "file://$WORK/push_srv_cpp"-)-(- cd "$WORK/push_client_sx"- printf 'bench push\n' > push.txt- run_sx go -m "bench push" >/dev/null- run_sx bmk set main >/dev/null- run_sx remote set-url origin "file://$WORK/push_srv_sx"-)--# ----------------------------------------------------------------------------# ssh shim: execute the remote `vn serve -stdio ...` command locally.-# -----------------------------------------------------------------------------cat > "$WORK/fakebin/ssh" <<'SH'-#!/bin/sh-while [ $# -gt 0 ]; do- case "$1" in- -p|-l) shift 2 ;;- -*) shift ;;- *) break ;;- esac-done-host=$1-shift-exec /bin/sh -c "$*"-SH-chmod +x "$WORK/fakebin/ssh"--# ----------------------------------------------------------------------------# TLS certificate and servers-# -----------------------------------------------------------------------------cat > "$WORK/openssl.cnf" <<EOF-[req]-distinguished_name = dn-x509_extensions = v3_req-prompt = no-[dn]-CN = localhost-[v3_req]-subjectAltName = @alt-[alt]-DNS.1 = localhost-IP.1 = 127.0.0.1-EOF-openssl req -x509 -newkey rsa:2048 -nodes \- -keyout "$WORK/key.pem" -out "$WORK/cert.pem" \- -days 2 -config "$WORK/openssl.cnf" >/dev/null 2>&1-PIN=$(openssl x509 -in "$WORK/cert.pem" -noout -fingerprint -sha256 \- | sed 's/.*=//;s/://g' | tr 'A-F' 'a-f')--free_port() {- python3 - <<'PY'-import socket-sock = socket.socket()-sock.bind(("127.0.0.1", 0))-print(sock.getsockname()[1])-sock.close()-PY-}-PORT_CPP=$(free_port)-PORT_SX=$(free_port)-while [ "$PORT_SX" = "$PORT_CPP" ]; do PORT_SX=$(free_port); done--CPP_PID=""-SX_PID=""-cleanup() {- if [ -n "$CPP_PID" ]; then kill "$CPP_PID" 2>/dev/null || true; fi- if [ -n "$SX_PID" ]; then kill "$SX_PID" 2>/dev/null || true; fi- if [ -n "$CPP_PID" ]; then wait "$CPP_PID" 2>/dev/null || true; fi- if [ -n "$SX_PID" ]; then wait "$SX_PID" 2>/dev/null || true; fi-}-trap cleanup EXIT INT TERM--"$VN_CPP" serve -listen "127.0.0.1:$PORT_CPP" -root "$WORK" \- -tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \- >"$WORK/cpp-server.log" 2>&1 &-CPP_PID=$!-"$VN_SPECTRE" serve -listen "127.0.0.1:$PORT_SX" -root "$WORK" \- -tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \- >"$WORK/sx-server.log" 2>&1 &-SX_PID=$!-wait_port "$PORT_CPP"-wait_port "$PORT_SX"--# A tiny repository used only for whoami over TLS.-mkdir -p "$WORK/whoami_repo"-(- cd "$WORK/whoami_repo"- run_cpp init . >/dev/null- run_cpp remote add tls_cpp "veins://localhost:$PORT_CPP/bench_src" \- -key:benchkey -tls-pin:"$PIN" >/dev/null- run_cpp remote add tls_sx "veins://localhost:$PORT_SX/bench_src" \- -key:benchkey -tls-pin:"$PIN" >/dev/null-)--# ----------------------------------------------------------------------------# Hyperfine prepare scripts-# -----------------------------------------------------------------------------write_prepare() {- path="$WORK/$1"- shift- {- echo '#!/bin/sh'- printf '%s\n' "$@"- } > "$path"- chmod +x "$path"-}--write_prepare prepare_clone.sh \- "rm -rf '$WORK/clone_cpp' '$WORK/clone_sx'"-write_prepare prepare_fetch.sh \- "rm -rf '$WORK/fetch_cpp' '$WORK/fetch_sx'" \- "cp -R '$WORK/fetch_pristine_cpp' '$WORK/fetch_cpp'" \- "cp -R '$WORK/fetch_pristine_sx' '$WORK/fetch_sx'"-write_prepare prepare_lazy.sh \- "rm -rf '$WORK/lazy_cpp' '$WORK/lazy_sx'" \- "cp -R '$WORK/lazy_pristine_cpp' '$WORK/lazy_cpp'" \- "cp -R '$WORK/lazy_pristine_sx' '$WORK/lazy_sx'"-write_prepare prepare_push.sh \- "rm -rf '$WORK/push_srv_cpp' '$WORK/push_srv_sx'" \- "cp -R '$WORK/push_pristine' '$WORK/push_srv_cpp'" \- "cp -R '$WORK/push_pristine' '$WORK/push_srv_sx'"-write_prepare prepare_ssh.sh \- "rm -rf '$WORK/clone_ssh_cpp' '$WORK/clone_ssh_sx'"-write_prepare prepare_tls.sh \- "rm -rf '$WORK/clone_tls_cpp' '$WORK/clone_tls_sx'"-write_prepare prepare_noop.sh \- "exit 0"--# ----------------------------------------------------------------------------# Run hyperfine-# -----------------------------------------------------------------------------run_pair() {- name=$1- prepare=$2- runs=$3- warmup=$4- cpp_cmd=$5- sx_cmd=$6- echo- echo "== $name =="- "$HYPERFINE" --style basic --warmup "$warmup" --runs "$runs" \- --prepare "$prepare" \- --export-markdown "$WORK/$name.md" \- --export-json "$WORK/$name.json" \- -n "C++" "$cpp_cmd" \- -n "Spectre" "$sx_cmd"-}--SSH_URL="ssh://localhost/$WORK/bench_src"-TLS_CPP_URL="veins://localhost:$PORT_CPP/bench_src"-TLS_SX_URL="veins://localhost:$PORT_SX/bench_src"--run_pair clone-file "$WORK/prepare_clone.sh" "$RUNS" 1 \- "cd '$WORK' && $CPP_RUN clone 'file://$WORK/bench_src' '$WORK/clone_cpp'" \- "cd '$WORK' && $SX_RUN clone 'file://$WORK/bench_src' '$WORK/clone_sx'"--run_pair fetch-file "$WORK/prepare_fetch.sh" "$RUNS" 1 \- "cd '$WORK/fetch_cpp' && $CPP_RUN fetch origin" \- "cd '$WORK/fetch_sx' && $SX_RUN fetch origin"--run_pair lazy-checkout-file "$WORK/prepare_lazy.sh" "$RUNS" 1 \- "cd '$WORK/lazy_cpp' && $CPP_RUN co oldbig" \- "cd '$WORK/lazy_sx' && $SX_RUN co oldbig"--run_pair push-file "$WORK/prepare_push.sh" "$RUNS" 1 \- "cd '$WORK/push_client_cpp' && $CPP_RUN push origin main" \- "cd '$WORK/push_client_sx' && $SX_RUN push origin main"--run_pair whoami-file "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \- "cd '$WORK' && $CPP_RUN whoami 'file://$WORK/bench_src'" \- "cd '$WORK' && $SX_RUN whoami 'file://$WORK/bench_src'"--run_pair clone-ssh "$WORK/prepare_ssh.sh" "$RUNS" 1 \- "cd '$WORK' && $CPP_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_cpp'" \- "cd '$WORK' && $SX_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_sx'"--run_pair clone-tls "$WORK/prepare_tls.sh" "$RUNS" 1 \- "cd '$WORK' && $CPP_RUN clone '$TLS_CPP_URL' '$WORK/clone_tls_cpp' -pin:'$PIN'" \- "cd '$WORK' && $SX_RUN clone '$TLS_SX_URL' '$WORK/clone_tls_sx' -pin:'$PIN'"--run_pair whoami-tls "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \- "cd '$WORK/whoami_repo' && $CPP_RUN whoami tls_cpp" \- "cd '$WORK/whoami_repo' && $SX_RUN whoami tls_sx"--cleanup-trap - 0 2 15--# ----------------------------------------------------------------------------# BENCHES.md-# -----------------------------------------------------------------------------python3 - "$WORK" > "$WORK/summary.md" <<'PY'-import json, os, sys-work = sys.argv[1]-names = [- ("clone-file", "Clone file://"),- ("fetch-file", "Fetch file://"),- ("lazy-checkout-file", "Lazy checkout file://"),- ("push-file", "Push file://"),- ("whoami-file", "Whoami file://"),- ("clone-ssh", "Clone ssh://"),- ("clone-tls", "Clone TLS 1.3"),- ("whoami-tls", "Whoami TLS 1.3"),-]-print("| Benchmark | C++ mean | Spectre mean | Spectre / C++ |")-print("|:---|---:|---:|---:|")-for key, label in names:- with open(os.path.join(work, key + ".json"), encoding="utf-8") as handle:- data = json.load(handle)- means = {r["command"]: r["mean"] for r in data["results"]}- cpp = means["C++"] * 1000.0- sx = means["Spectre"] * 1000.0- ratio = sx / cpp if cpp else float("nan")- print(f"| {label} | {cpp:.1f} ms | {sx:.1f} ms | {ratio:.2f}x |")-PY--FILE_COUNT=$(find "$WORK/bench_src" -type f -not -path '*/.veins/*' | wc -l | tr -d ' ')-DISK_SIZE=$(du -sh "$WORK/bench_src" | awk '{print $1}')-HOST_TEXT=$(uname -sm)-CPU_TEXT=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -m)-HYPERFINE_VERSION=$("$HYPERFINE" --version)-CPP_VERSION=$("$VN_CPP" version)-SX_VERSION=$("$VN_SPECTRE" version)--{- echo "# veins benchmarks"- echo- echo "Two reproducible benchmark sets are kept here: a local-core comparison that includes"- echo "the Rust subset, and the native network comparison between the C++ rewrite and Spectre."- echo- if [ -f "$ROOT/bench/core_bench.md" ]; then- echo "## Local core: Rust subset vs C++ vs Spectre"- echo- cat "$ROOT/bench/core_bench.md"- echo- fi- echo "## Networking: C++ rewrite vs Spectre"- echo- echo "Generated $(date -u '+%Y-%m-%d %H:%M:%S UTC') by \`bench/net_bench.sh\`."- echo- echo "The Rust subset is not included in this section because it does not implement a"- echo "network transport."- echo- echo "### Environment"- echo- echo '```'- echo "host: $HOST_TEXT"- echo "cpu: $CPU_TEXT"- echo "hyperfine: $HYPERFINE_VERSION"- echo "c++ vn: $CPP_VERSION"- echo "spectre vn: $SX_VERSION"- echo "runs: $RUNS (clone/fetch/push/checkout), $WHOAMI_RUNS (whoami)"- echo "warmup: 1 (clone/fetch/push/checkout), 2 (whoami)"- echo '```'- echo- echo "### Dataset"- echo- echo "- \`bench_src\`: $FILE_COUNT working files, $DISK_SIZE on disk including packs."- echo " - 360 small text files in 18 directories."- echo " - 2 MiB \`big_old.bin\` in the \`oldbig\` history."- echo " - 1 MiB \`big_head.bin\` in \`main\`."- echo "- \`push_pristine\`: a separate 20-file repository, so push does not transfer the large dataset."- echo- echo "### What each benchmark does"- echo- echo "| Benchmark | Operation |"- echo "|:---|:---|"- echo "| \`clone-file\` | Full clone over \`file://\`: handshake, refs, history, head chunks, checkout. Includes spawning one local server per run. |"- echo "| \`fetch-file\` | \`vn fetch origin\` with no new remote refs. Both clients start from a full \`-blobs:all\` clone. |"- echo "| \`lazy-checkout-file\` | \`vn co oldbig\` in a \`-blobs:none\` clone, fetching the 2 MiB old blob from the promisor over \`file://\`. |"- echo "| \`push-file\` | Push one new commit from a prepared client to a freshly reset copy of \`push_pristine\` over \`file://\`. |"- echo "| \`whoami-file\` | Connect, authenticate, \`WHOAMI\`, close over \`file://\`. |"- echo "| \`clone-ssh\` | Full clone over \`ssh://\`, using a local \`ssh\` shim that runs the remote \`vn serve -stdio\` command. |"- echo "| \`clone-tls\` | Full clone over TLS 1.3 with a pinned self-signed certificate. Uses long-running servers. |"- echo "| \`whoami-tls\` | Connect, authenticate, \`WHOAMI\`, close over TLS 1.3. |"- echo- echo "Lower is better. Hyperfine reports wall-clock time; the relative column is against the fastest command."- echo- echo "### Summary"- echo- cat "$WORK/summary.md"- echo- echo "A ratio above 1 means Spectre took longer than C++."- echo- echo "### Results"- echo- echo "#### Clone over file://"- cat "$WORK/clone-file.md"- echo- echo "#### Fetch over file://"- cat "$WORK/fetch-file.md"- echo- echo "#### Lazy checkout over file://"- cat "$WORK/lazy-checkout-file.md"- echo- echo "#### Push over file://"- cat "$WORK/push-file.md"- echo- echo "#### Whoami over file://"- cat "$WORK/whoami-file.md"- echo- echo "#### Clone over ssh://"- cat "$WORK/clone-ssh.md"- echo- echo "#### Clone over TLS 1.3"- cat "$WORK/clone-tls.md"- echo- echo "#### Whoami over TLS 1.3"- cat "$WORK/whoami-tls.md"- echo- echo "### Notes"- echo- echo "- Spectre clone destinations are absolute paths on macOS. The reference checkout hardcodes Linux's \`AT_FDCWD\` value (\`-100\`); with a relative destination it cannot open the working directory on macOS."- echo "- \`file://\` and \`ssh://\` include server process startup. \`clone-tls\` and \`whoami-tls\` use long-running servers, so they isolate protocol and TLS cost more closely."- echo "- These runs reproduce the reference's transfer behavior: fetch \`haves\` are operation heads (so metadata is re-sent), and push sends all objects reachable from the bookmark rather than using \`HAVE_QUERY\`."- echo "- Lazy checkout fetches one missing chunk per promisor connection in both implementations, so it is intentionally a worst-case/read-ahead-free measurement."- echo "- \`push-file\` is only a few milliseconds of real work; process startup noise can dominate. Read the min/max columns alongside the mean."- echo "- Treat differences below roughly 10 ms as noise; this is a single-machine run, not a controlled lab measurement."- echo- echo "### Reproduce"- echo- echo '```sh'- echo "cd veins-cpprewrite"- echo "cmake -S . -B build && cmake --build build -j"- echo "./bench/net_bench.sh"- echo '```'-} > "$OUT"--echo-echo "wrote $OUT"--- a/veins-cpprewrite/src/auth.cpp+++ /dev/null@@ -1,521 +0,0 @@-#include "auth.h"--#include "store.h"--#include <algorithm>-#include <cstdlib>-#include <cstring>--#if defined(_WIN32)-#include <io.h>-#else-#include <sys/stat.h>-#include <unistd.h>-#endif--namespace vn::auth {--namespace {--std::optional<std::string> env_value(const char *name) {- const char *value = std::getenv(name);- if (!value || !*value)- return std::nullopt;- return std::string(value);-}--std::string lower_ascii(std::string_view text) {- std::string out(text);- for (char &c : out) {- if (c >= 'A' && c <= 'Z')- c = static_cast<char>(c + 32);- }- return out;-}--std::string_view trim_view(std::string_view text) {- std::size_t start = 0;- std::size_t end = text.size();- auto blank = [](char c) {- return c == ' ' || c == '\t' || c == '\r' || c == '\n';- };- while (start < end && blank(text[start]))- ++start;- while (end > start && blank(text[end - 1]))- --end;- return text.substr(start, end - start);-}--int file_mode(const fs::path &path) {-#if defined(_WIN32)- (void)path;- return 0600;-#else- struct stat info {};- if (::stat(path.c_str(), &info) != 0)- return -1;- return static_cast<int>(info.st_mode & 07777);-#endif-}--bool set_mode(const fs::path &path, int mode) {-#if defined(_WIN32)- (void)path;- (void)mode;- return true;-#else- return ::chmod(path.c_str(), static_cast<mode_t>(mode)) == 0;-#endif-}--bool valid_key_name(std::string_view name) {- if (name.empty() || name.size() > 128)- return false;- for (char c : name) {- if (c == '/' || c == '\\' || c == '\0')- return false;- }- return true;-}--std::string hex_encode(std::string_view data) {- static constexpr char digits[] = "0123456789abcdef";- std::string out;- out.reserve(data.size() * 2);- for (char raw : data) {- const auto c = static_cast<unsigned char>(raw);- out.push_back(digits[c >> 4]);- out.push_back(digits[c & 15]);- }- return out;-}--std::optional<std::string> hex_decode(std::string_view text) {- if (text.empty() || text.size() % 2 != 0)- return std::nullopt;- auto value = [](char c) -> int {- if (c >= '0' && c <= '9')- return c - '0';- if (c >= 'a' && c <= 'f')- return c - 'a' + 10;- return -1;- };- std::string out;- out.reserve(text.size() / 2);- for (std::size_t i = 0; i < text.size(); i += 2) {- const int high = value(text[i]);- const int low = value(text[i + 1]);- if (high < 0 || low < 0)- return std::nullopt;- out.push_back(static_cast<char>((high << 4) | low));- }- return out;-}--std::string_view strip_user(std::string_view authority) {- const auto at = authority.rfind('@');- if (at != std::string_view::npos)- return authority.substr(at + 1);- return authority;-}--std::optional<std::string> authority_of(std::string_view input) {- std::size_t start = 0;- const auto scheme = input.find("://");- if (scheme != std::string_view::npos)- start = scheme + 3;- if (start >= input.size())- return std::nullopt;- const auto slash = input.find('/', start);- const std::size_t end = slash == std::string_view::npos ? input.size() : slash;- if (end <= start)- return std::nullopt;- const std::string_view raw = input.substr(start, end - start);- const std::string_view host = strip_user(raw);- if (host.empty())- return std::nullopt;- return lower_ascii(host);-}--std::optional<std::string> host_without_port(std::string_view host) {- if (host.empty() || host.front() == '[')- return std::nullopt;- const auto colon = host.rfind(':');- if (colon == std::string_view::npos || colon == 0)- return std::nullopt;- return std::string(host.substr(0, colon));-}--fs::path target_path(const fs::path &dir, std::string_view target) {- return dir / hex_encode(target);-}--std::optional<std::string> read_credential(const fs::path &path) {- auto data = read_file_opt(path);- if (!data)- return std::nullopt;- const std::string_view text(reinterpret_cast<const char *>(data->data()),- data->size());- const std::string_view value = trim_view(text);- if (value.empty())- return std::nullopt;- return std::string(value);-}--std::optional<std::string> lookup_credential(const fs::path &dir,- std::string_view target) {- return read_credential(target_path(dir, target));-}--std::vector<std::string_view> tokenize(std::string_view line) {- std::vector<std::string_view> out;- std::size_t start = 0;- for (std::size_t i = 0; i <= line.size(); ++i) {- const bool at_end = i == line.size();- if (at_end || line[i] == ' ' || line[i] == '\t') {- if (i > start)- out.push_back(line.substr(start, i - start));- start = i + 1;- }- }- return out;-}--Access invalid_access(std::int64_t line) {- Access out;- out.valid = false;- out.error_line = line;- return out;-}--} // namespace--// ----------------------------------------------------------------------------// Client keys-// -----------------------------------------------------------------------------fs::path key_dir() {- if (auto xdg = env_value("XDG_CONFIG_HOME"))- return path_from_bytes(*xdg) / "veins" / "keys";- if (auto home = env_value("HOME"))- return path_from_bytes(*home) / ".config" / "veins" / "keys";-#if defined(_WIN32)- if (auto appdata = env_value("APPDATA"))- return path_from_bytes(*appdata) / "veins" / "keys";-#endif- return fs::path(".veins-keys");-}--fs::path key_path(std::string_view name) {- return key_dir() / (std::string(name) + ".key");-}--std::optional<Key> load_key(std::string_view name) {- if (!valid_key_name(name))- return std::nullopt;- const fs::path path = key_path(name);- const int mode = file_mode(path);- if (mode < 0 || (mode & 63) != 0)- return std::nullopt;- auto data = read_file_opt(path);- if (!data || data->size() != 33 || (*data)[0] != 1)- return std::nullopt;- std::vector<std::uint8_t> seed(data->begin() + 1, data->end());- auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));- if (!public_key)- return std::nullopt;- Key key;- key.name = std::string(name);- key.seed = std::move(seed);- key.public_key = *public_key;- key.fingerprint = key_fingerprint(*public_key);- return key;-}--std::optional<Key> generate_key(std::string_view name) {- if (!valid_key_name(name))- return std::nullopt;- const fs::path dir = key_dir();- if (!ensure_directory(dir))- return std::nullopt;- (void)set_mode(dir, 0700);- const auto seed = secure_random(32);- if (seed.size() != 32)- return std::nullopt;- auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));- if (!public_key)- return std::nullopt;- std::vector<std::uint8_t> body;- body.reserve(33);- body.push_back(1);- body.insert(body.end(), seed.begin(), seed.end());- const fs::path path = key_path(name);- if (!write_file(path, Bytes(body.data(), body.size())))- return std::nullopt;- (void)set_mode(path, 0600);- Key key;- key.name = std::string(name);- key.seed = seed;- key.public_key = *public_key;- key.fingerprint = key_fingerprint(*public_key);- return key;-}--std::vector<std::string> list_key_names() {- std::vector<std::string> out;- const fs::path dir = key_dir();- if (!path_is_dir(dir))- return out;- for (const auto &name : list_directory(dir)) {- if (name.size() > 4 && name.compare(name.size() - 4, 4, ".key") == 0)- out.push_back(name.substr(0, name.size() - 4));- }- return out;-}--// ----------------------------------------------------------------------------// Per-user key selection-// -----------------------------------------------------------------------------fs::path auth_dir() {- const fs::path dir = key_dir();- const fs::path parent = dir.parent_path();- if (parent.empty())- return fs::path(".veins-auth");- return parent / "auth";-}--std::string normalize_target(std::string_view input) {- const std::string_view trimmed = trim_view(input);- if (trimmed.empty() || trimmed == "default")- return "default";- if (auto authority = authority_of(trimmed))- return *authority;- const auto slash = trimmed.find('/');- const std::string_view raw =- slash == std::string_view::npos ? trimmed : trimmed.substr(0, slash);- const std::string_view host = strip_user(raw);- if (host.empty())- return "default";- return lower_ascii(host);-}--bool set_key(std::string_view target, std::string_view key_name) {- if (target.empty() || key_name.empty())- return false;- const fs::path dir = auth_dir();- if (!ensure_directory(dir))- return false;- return write_file(target_path(dir, target), bytes_of(key_name));-}--bool remove_key(std::string_view target) {- return remove_file(target_path(auth_dir(), target));-}--std::vector<std::string> list_credential_lines() {- std::vector<std::string> out;- const fs::path dir = auth_dir();- if (!path_is_dir(dir))- return out;- for (const auto &name : list_directory(dir)) {- auto decoded = hex_decode(name);- if (!decoded)- continue;- auto key = read_credential(target_path(dir, *decoded));- if (!key)- continue;- out.push_back(*decoded + ": " + *key + "\n");- }- return out;-}--bool local_key_exists(std::string_view name) {- if (name.empty() || name.starts_with("ed25519:"))- return false;- return load_key(name).has_value();-}--std::optional<std::string> key_for_url(std::string_view url) {- const fs::path dir = auth_dir();- if (auto host = authority_of(url)) {- if (auto exact = lookup_credential(dir, *host))- return exact;- if (auto base = host_without_port(*host)) {- if (auto without_port = lookup_credential(dir, *base))- return without_port;- }- }- return lookup_credential(dir, "default");-}--// ----------------------------------------------------------------------------// Server access policy-// -----------------------------------------------------------------------------Access empty_access() { return Access{}; }--fs::path access_path(const fs::path &repo_root) {- return veins_dir(repo_root) / "access";-}--Access load_access(const fs::path &repo_root) {- const fs::path path = access_path(repo_root);- const int mode = file_mode(path);- if (mode >= 0 && (mode & 18) != 0)- return invalid_access(0);- auto data = read_file_opt(path);- if (!data)- return empty_access();- const std::string_view text(reinterpret_cast<const char *>(data->data()),- data->size());- Access access;- std::size_t start = 0;- std::int64_t line_no = 0;- std::size_t i = 0;- for (;;) {- const bool at_end = i >= text.size();- if (at_end || text[i] == '\n') {- ++line_no;- const std::string_view line = trim_view(text.substr(start, i - start));- if (!line.empty() && line.front() != '#') {- const auto tokens = tokenize(line);- bool bad = false;- if (tokens.size() == 2 && tokens[0] == "anonymous") {- if (tokens[1] == "read")- access.anonymous_read = true;- else- bad = true;- } else if (tokens.size() >= 3 && tokens[0] == "allow") {- std::uint8_t role = 0;- if (tokens[1] == "read")- role = ROLE_READ;- else if (tokens[1] == "write")- role = ROLE_WRITE;- else- bad = true;- auto public_key = parse_public_key(tokens[2]);- if (!public_key)- bad = true;- if (!bad) {- const bool duplicate =- std::any_of(access.entries.begin(), access.entries.end(),- [&](const AccessEntry &entry) {- return std::memcmp(entry.public_key.data(),- public_key->data(),- public_key->size()) == 0;- });- if (duplicate) {- bad = true;- } else {- AccessEntry entry;- entry.public_key = *public_key;- entry.role = role;- if (tokens.size() >= 4)- entry.name = std::string(tokens[3]);- access.entries.push_back(std::move(entry));- }- }- } else {- bad = true;- }- if (bad)- return invalid_access(line_no);- }- start = i + 1;- }- if (at_end)- break;- ++i;- }- return access;-}--bool write_access(const fs::path &repo_root, const Access &access) {- std::string body = "# veins access policy\n";- if (access.anonymous_read)- body += "anonymous read\n";- for (const auto &entry : access.entries) {- if (entry.name.size() > 64)- return false;- body += "allow ";- body += entry.role == ROLE_WRITE ? "write" : "read";- body += " ";- body += format_public_key(entry.public_key);- if (!entry.name.empty()) {- body += " ";- body += entry.name;- }- body += "\n";- }- const fs::path path = access_path(repo_root);- if (!write_file(path, bytes_of(body)))- return false;- (void)set_mode(path, 0600);- return true;-}--std::uint8_t role_for(const Access &access, const PublicKey *public_key) {- if (!public_key) {- if (access.anonymous_read)- return ROLE_READ;- return ROLE_ANONYMOUS;- }- for (const auto &entry : access.entries) {- if (std::memcmp(entry.public_key.data(), public_key->data(),- public_key->size()) == 0) {- return entry.role;- }- }- return ROLE_UNKNOWN;-}--bool add_access(const fs::path &repo_root, std::uint8_t role,- const PublicKey &public_key, std::string_view name) {- Access access = load_access(repo_root);- if (!access.valid)- return false;- for (const auto &entry : access.entries) {- if (std::memcmp(entry.public_key.data(), public_key.data(),- public_key.size()) == 0)- return false;- }- AccessEntry entry;- entry.public_key = public_key;- entry.role = role;- entry.name = std::string(name);- access.entries.push_back(std::move(entry));- return write_access(repo_root, access);-}--bool remove_access(const fs::path &repo_root, std::string_view fingerprint,- std::string_view name) {- Access access = load_access(repo_root);- if (!access.valid)- return false;- bool removed = false;- std::vector<AccessEntry> kept;- kept.reserve(access.entries.size());- for (const auto &entry : access.entries) {- const bool match_fingerprint =- !fingerprint.empty() && key_fingerprint(entry.public_key) == fingerprint;- const bool match_name = !name.empty() && entry.name == name;- if (match_fingerprint || match_name) {- removed = true;- } else {- kept.push_back(entry);- }- }- access.entries = std::move(kept);- return removed && write_access(repo_root, access);-}--bool set_anonymous(const fs::path &repo_root, bool enabled) {- Access access = load_access(repo_root);- if (!access.valid)- return false;- access.anonymous_read = enabled;- return write_access(repo_root, access);-}--} // namespace vn::auth--- a/veins-cpprewrite/src/auth.h+++ /dev/null@@ -1,75 +0,0 @@-#pragma once--#include "crypto.h"--#include <cstdint>-#include <optional>-#include <string>-#include <string_view>-#include <vector>--namespace vn::auth {--constexpr std::uint8_t ROLE_ANONYMOUS = 0;-constexpr std::uint8_t ROLE_READ = 1;-constexpr std::uint8_t ROLE_WRITE = 2;-constexpr std::uint8_t ROLE_UNKNOWN = 255;--// ----------------------------------------------------------------------------// Client keys-// -----------------------------------------------------------------------------struct Key {- std::string name;- std::vector<std::uint8_t> seed;- PublicKey public_key{};- std::string fingerprint;-};--fs::path key_dir();-fs::path key_path(std::string_view name);-std::optional<Key> load_key(std::string_view name);-std::optional<Key> generate_key(std::string_view name);-std::vector<std::string> list_key_names();--// ----------------------------------------------------------------------------// Per-user key selection-// -----------------------------------------------------------------------------fs::path auth_dir();-std::string normalize_target(std::string_view target);-bool set_key(std::string_view target, std::string_view key_name);-bool remove_key(std::string_view target);-std::vector<std::string> list_credential_lines();-bool local_key_exists(std::string_view name);-std::optional<std::string> key_for_url(std::string_view url);--// ----------------------------------------------------------------------------// Server access policy-// -----------------------------------------------------------------------------struct AccessEntry {- PublicKey public_key{};- std::string name;- std::uint8_t role = ROLE_READ;-};--struct Access {- bool valid = true;- std::int64_t error_line = 0;- bool anonymous_read = false;- std::vector<AccessEntry> entries;-};--Access empty_access();-fs::path access_path(const fs::path &repo_root);-Access load_access(const fs::path &repo_root);-bool write_access(const fs::path &repo_root, const Access &access);-bool add_access(const fs::path &repo_root, std::uint8_t role,- const PublicKey &public_key, std::string_view name);-bool remove_access(const fs::path &repo_root, std::string_view fingerprint,- std::string_view name);-bool set_anonymous(const fs::path &repo_root, bool enabled);-std::uint8_t role_for(const Access &access, const PublicKey *public_key);--} // namespace vn::auth--- a/veins-cpprewrite/src/bookmark.cpp+++ /dev/null@@ -1,356 +0,0 @@-#include "local_commands.h"--#include "pathspec.h"-#include "store.h"-#include "worktree.h"--#include <algorithm>-#include <iostream>--namespace vn {--namespace {--bool bmk_is_flag(std::string_view arg) {- return !arg.empty() && arg.front() == '-';-}--bool bmk_contains(std::string_view name, std::string_view needle) {- return !needle.empty() && name.find(needle) != std::string_view::npos;-}--bool valid_bookmark_name(std::string_view name) {- if (name.empty() || name.size() > MAX_NAME_LEN)- return false;- const auto first = static_cast<unsigned char>(name.front());- if (first == '-' || first == '/' || first == '.')- return false;- const auto last = static_cast<unsigned char>(name.back());- if (last == '/' || last == '.')- return false;- for (char raw : name) {- const auto c = static_cast<unsigned char>(raw);- if (c == 0 || c == ' ' || c < 32 || c == 127)- return false;- if (c == '~' || c == '^' || c == ':' || c == '?' || c == '*' ||- c == '[' || c == '\\')- return false;- }- if (bmk_contains(name, "..") || bmk_contains(name, "@{") ||- bmk_contains(name, "//"))- return false;- if (name == "@")- return false;- if (name.size() >= 5 && name.substr(name.size() - 5) == ".lock")- return false;- return true;-}--std::string short_commit(const Id &id, std::size_t n = 12) {- if (n == 0)- n = 12;- n = std::min<std::size_t>(n, 64);- return hex_encode(id).substr(0, n);-}--void bmk_print_cell(std::string_view text, std::size_t width) {- std::cout << text;- for (std::size_t i = text.size(); i < width; ++i)- std::cout << ' ';-}--bool bookmark_points_at(const Bookmark &bookmark, const Id &target) {- return bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front() &&- std::memcmp(bookmark.targets.adds.front()->data(), target.data(),- ID_LEN) == 0;-}--int bmk_set(const std::vector<std::string> &args, std::size_t start) {- std::string name;- std::string rev;- 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 == "-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 && bmk_is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else if (name.empty()) {- name = arg;- } else if (rev.empty()) {- rev = arg;- } else {- error_prefix();- std::cout << "bmk set accepts a name and one revision\n";- return 1;- }- }- if (name.empty()) {- error_prefix();- std::cout << "bmk set requires a name\n";- return 1;- }- if (!valid_bookmark_name(name)) {- error_prefix();- std::cout << "invalid bookmark name: " << name << "\n";- return 1;- }-- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- 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();- if (rev.empty())- std::cout << "no working-copy commit\n";- else- std::cout << "unknown revision: " << rev << "\n";- return 1;- }-- bool changed = true;- if (const auto existing = find_bookmark(tx->view(), name)) {- auto &bookmark = tx->view().bookmarks[*existing];- if (bookmark_points_at(bookmark, *target)) {- changed = false;- } else {- bookmark.targets.adds = {*target};- bookmark.targets.removes.clear();- }- } else {- Bookmark bookmark;- bookmark.name = name;- bookmark.targets.adds = {*target};- tx->view().bookmarks.push_back(std::move(bookmark));- }-- if (!changed) {- info_prefix();- std::cout << "bookmark " << name << " is already at " << short_commit(*target)- << "\n";- return 0;- }-- rebuild_heads(tx->view());- const auto status = tx->finish("bookmark set " + name);- if (!status)- return 1;- info_prefix();- std::cout << "bookmark " << name << " set to " << short_commit(*target)- << "\n";- return 0;-}--int bmk_delete(const std::vector<std::string> &args, std::size_t start) {- std::string name;- 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 && bmk_is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else if (!name.empty()) {- error_prefix();- std::cout << "bmk rm accepts exactly one name\n";- return 1;- } else {- name = arg;- }- }- if (name.empty()) {- error_prefix();- std::cout << "bmk rm requires a name\n";- return 1;- }-- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- 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 existing = find_bookmark(tx->view(), name);- if (!existing) {- error_prefix();- std::cout << "no such bookmark: " << name << "\n";- return 1;- }- auto &bookmarks = tx->view().bookmarks;- bookmarks.erase(bookmarks.begin() +- static_cast<std::ptrdiff_t>(*existing));- rebuild_heads(tx->view());- const auto status = tx->finish("bookmark delete " + name);- if (!status)- return 1;- info_prefix();- std::cout << "deleted bookmark " << name << "\n";- return 0;-}--int bmk_list(const std::vector<std::string> &args, std::size_t start) {- bool col_titles = true;- 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 == "-no-col-titles") {- col_titles = false;- } else if (!end_flags && bmk_is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- error_prefix();- std::cout << "bmk ls takes no operands\n";- return 1;- }- }-- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- 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);-- constexpr std::size_t w_commit = 12;- constexpr std::size_t w_change = 8;- std::size_t w_name = 8;- for (const auto &bookmark : view->bookmarks)- w_name = std::max(w_name, bookmark.name.size());-- if (col_titles) {- bmk_print_cell("Bookmark", w_name);- std::cout << " ";- bmk_print_cell("Commit", w_commit);- std::cout << " ";- bmk_print_cell("Change", w_change);- std::cout << " Target\n";- }-- for (const auto &bookmark : view->bookmarks) {- bmk_print_cell(bookmark.name, w_name);- std::cout << " ";- bool have_target = false;- bool current = false;- const bool conflicted = bookmark.targets.adds.size() > 1;- std::string commit_text;- std::string change_text;- std::optional<Id> target;- if (!bookmark.targets.adds.empty() && bookmark.targets.adds.front()) {- target = bookmark.targets.adds.front();- have_target = true;- if (wc && std::memcmp(wc->data(), target->data(), ID_LEN) == 0)- current = true;- commit_text = short_commit(*target);- if (auto loaded = load_commit(store, *target))- change_text = base32_encode(loaded->commit.change_id).substr(0, 8);- }- if (!have_target) {- bmk_print_cell("<missing>", w_commit);- std::cout << " ";- bmk_print_cell("", w_change);- std::cout << " (missing)\n";- continue;- }- bmk_print_cell(commit_text, w_commit);- std::cout << " ";- bmk_print_cell(change_text, w_change);- std::cout << " ";- if (current)- print_colored("@", Color::Red, false, false);- if (conflicted) {- if (current)- std::cout << ' ';- print_colored("(conflicted)", Color::BrightRed, false, false);- }- std::cout << "\n";- }-- if (view->bookmarks.empty()) {- info_prefix();- std::cout << "no bookmarks\n";- }- return 0;-}--void bmk_usage() {- std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n";- std::cout << "\n";- std::cout << "manage named, movable pointers to commits (branches)\n";- std::cout << "\n";- std::cout << "subcommands:\n";- std::cout << " set <name> [-rev <rev>] create or move a bookmark (default: @)\n";- std::cout << " mv <name> [-rev <rev>] alias of set\n";- std::cout << " ls [-no-col-titles] list bookmarks\n";- std::cout << " rm <name> delete a bookmark\n";-}--} // namespace--int bmk_run(const std::vector<std::string> &args) {- if (args.size() <= 2) {- bmk_usage();- return 1;- }- const std::string &sub = args[2];- if (sub == "set" || sub == "mv")- return bmk_set(args, 3);- if (sub == "ls")- return bmk_list(args, 3);- if (sub == "rm")- return bmk_delete(args, 3);- if (sub == "help" || sub == "-h") {- bmk_usage();- return 0;- }- error_prefix();- std::cout << "unknown bmk subcommand: " << sub << "\n";- bmk_usage();- return 1;-}--} // namespace vn--- a/veins-cpprewrite/src/cli.cpp+++ /dev/null@@ -1,2323 +0,0 @@-#include "cli.h"--#include "local_commands.h"-#include "merge.h"-#include "net_commands.h"-#include "promisor.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_bmk() {- std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n\n";- std::cout << "manage named, movable pointers to commits (branches)\n\n";- std::cout << "subcommands:\n";- std::cout << " set <name> [-rev <rev>] create or move a bookmark (default: @)\n";- std::cout << " mv <name> [-rev <rev>] alias of set\n";- std::cout << " ls [-no-col-titles] list bookmarks\n";- std::cout << " rm <name> delete a bookmark\n\n";- std::cout << "examples:\n";- std::cout << " vn bmk set main\n";- std::cout << " vn new main\n";- std::cout << " vn co main\n";-}--void show_rm() {- std::cout << "usage: vn rm [-delete] <path>...\n\n";- std::cout << "remove paths from the working-copy tree\n\n";- std::cout- << "files stay on disk by default. Arguments may be paths or globs and are\n";- std::cout- << "resolved relative to the current directory. Supported wildcards are\n";- std::cout << "'*', '?', and '**'; '*' and '?' do not cross directory separators.\n\n";- std::cout << "options:\n";- std::cout- << " -delete delete matching files from disk after untracking\n";-}--void show_mv() {- std::cout << "usage: vn mv <from> <to>\n\n";- std::cout- << "move a tracked file; the following snapshot records the rename\n";-}--void show_ex() {- std::cout << "usage: vn ex <pattern>...\n\n";- std::cout << "append ignore patterns to the repository root .vnexclude\n\n";- std::cout- << "patterns use gitignore syntax and are resolved relative to the current\n";- std::cout- << "directory. Quote wildcard patterns so the shell does not expand them:\n";- std::cout << " vn ex '*.dSYM'\n";-}--void show_undo() {- std::cout << "usage: vn undo\n\n";- std::cout- << "record an operation that restores the previous operation view\n";-}--void show_op() {- std::cout << "usage: vn op <log|restore|revert> [<op>]\n\n";- std::cout << "inspect and restore operations\n";-}--void show_merge() {- std::cout << "usage: vn merge <rev>...\n\n";- std::cout- << "create a merge commit from the working-copy commit and the revisions\n";- std::cout- << "the merge never fails; conflicts are stored as conflict values\n";-}--void show_rebase() {- std::cout << "usage: vn rebase -s <rev> -d <rev>\n\n";- std::cout- << "rewrite the source change and its descendants onto the destination\n\n";- std::cout << "options:\n";- std::cout << " -s, -source <rev> first change to rewrite\n";- std::cout << " -d, -destination <rev> new parent\n";-}--void show_xs() {- std::cout << "usage: vn xs [-porcelain]\n\n";- std::cout- << "list conflicted paths and, for text conflicts, conflicting line ranges\n\n";- std::cout << "porcelain columns (tab-separated):\n";- std::cout << " path, kind, base-ranges, ours-ranges, theirs-ranges\n";-}--void show_resolve() {- std::cout- << "usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...\n";- std::cout << " vn resolve -list\n\n";- std::cout- << "resolve conflicted paths. Without -take, the current file content is\n";- std::cout- << "recorded as the resolution. -tool substitutes $BASE, $OURS, $THEIRS,\n";- std::cout << "and $OUTPUT in the command.\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 == "bmk")- show_bmk();- else if (cmd == "rm")- show_rm();- else if (cmd == "mv")- show_mv();- else if (cmd == "ex")- show_ex();- else if (cmd == "undo")- show_undo();- else if (cmd == "op")- show_op();- else if (cmd == "merge")- show_merge();- else if (cmd == "rebase")- show_rebase();- else if (cmd == "xs")- show_xs();- else if (cmd == "resolve")- show_resolve();- else if (cmd == "self-test")- show_selftest();- else if (cmd == "version")- show_version();- else if (cmd == "help")- show_help();- else if (net_help(cmd)) {- } else if (cmd == "git" || 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) {- install_promisor_fetcher();- 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 == "bmk")- return bmk_run(args);- if (cmd == "rm")- return rm_run(args);- if (cmd == "mv")- return mv_run(args);- if (cmd == "ex")- return ex_run(args);- if (cmd == "op")- return op_run(args);- if (cmd == "undo")- return undo_run(args);- if (cmd == "merge")- return merge_run(args);- if (cmd == "rebase")- return rebase_run(args);- if (cmd == "xs")- return xs_run(args);- if (cmd == "resolve")- return resolve_run(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 == "remote")- return remote_run(args);- if (cmd == "clone")- return clone_run(args);- if (cmd == "fetch")- return fetch_run(args);- if (cmd == "push")- return push_run(args);- if (cmd == "serve")- return serve_run(args);- if (cmd == "key")- return key_run(args);- if (cmd == "auth")- return auth_run(args);- if (cmd == "access")- return access_run(args);- if (cmd == "whoami")- return whoami_run(args);-- if (cmd == "git" || 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--- a/veins-cpprewrite/src/cli.h+++ /dev/null@@ -1,10 +0,0 @@-#pragma once--#include <string>-#include <vector>--namespace vn {--int cli_run(const std::vector<std::string> &args);--} // namespace vn--- a/veins-cpprewrite/src/common.cpp+++ /dev/null@@ -1,1622 +0,0 @@-#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--- a/veins-cpprewrite/src/common.h+++ /dev/null@@ -1,414 +0,0 @@-#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--- a/veins-cpprewrite/src/crypto.cpp+++ /dev/null@@ -1,209 +0,0 @@-#include "crypto.h"--#include <blake3.h>--#include <openssl/evp.h>-#include <openssl/rand.h>--#include <cstring>--namespace vn {--namespace {--// The reference implementation hashes the NUL terminator as well, so the-// domain is 12 bytes rather than the 11 characters in the specification.-constexpr char FINGERPRINT_DOMAIN[] = "veins/key/1";--PublicKey key_from_span(Bytes seed) {- PublicKey out{};- std::memcpy(out.data(), seed.data(), out.size());- return out;-}--} // namespace--std::optional<PublicKey> ed25519_public_from_seed(Bytes seed) {- if (seed.size() != 32)- return std::nullopt;- EVP_PKEY *pkey =- EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);- if (!pkey)- return std::nullopt;- PublicKey out{};- std::size_t len = out.size();- const int ok = EVP_PKEY_get_raw_public_key(pkey, out.data(), &len);- EVP_PKEY_free(pkey);- if (ok != 1 || len != out.size())- return std::nullopt;- return out;-}--std::optional<Signature> ed25519_sign(Bytes seed, Bytes message) {- if (seed.size() != 32)- return std::nullopt;- EVP_PKEY *pkey =- EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);- if (!pkey)- return std::nullopt;- EVP_MD_CTX *ctx = EVP_MD_CTX_new();- if (!ctx) {- EVP_PKEY_free(pkey);- return std::nullopt;- }- Signature out{};- std::size_t sig_len = out.size();- bool ok = false;- if (EVP_DigestSignInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&- EVP_DigestSign(ctx, out.data(), &sig_len, message.data(),- message.size()) == 1 &&- sig_len == out.size()) {- ok = true;- }- EVP_MD_CTX_free(ctx);- EVP_PKEY_free(pkey);- if (!ok)- return std::nullopt;- return out;-}--bool ed25519_verify(const PublicKey &public_key, Bytes message,- Bytes signature) {- if (signature.size() != 64)- return false;- EVP_PKEY *pkey =- EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr,- public_key.data(), public_key.size());- if (!pkey)- return false;- EVP_MD_CTX *ctx = EVP_MD_CTX_new();- if (!ctx) {- EVP_PKEY_free(pkey);- return false;- }- bool ok = false;- if (EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&- EVP_DigestVerify(ctx, signature.data(), signature.size(),- message.data(), message.size()) == 1) {- ok = true;- }- EVP_MD_CTX_free(ctx);- EVP_PKEY_free(pkey);- return ok;-}--FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key) {- blake3_hasher hasher;- blake3_hasher_init(&hasher);- blake3_hasher_update(&hasher, FINGERPRINT_DOMAIN,- sizeof(FINGERPRINT_DOMAIN));- blake3_hasher_update(&hasher, public_key.data(), public_key.size());- std::array<std::uint8_t, 32> digest{};- blake3_hasher_finalize(&hasher, digest.data(), digest.size());- FingerprintBytes out{};- std::memcpy(out.data(), digest.data(), out.size());- return out;-}--std::string key_fingerprint(const PublicKey &public_key) {- const auto raw = key_fingerprint_bytes(public_key);- return base32_text(Bytes(raw.data(), raw.size()));-}--std::string base32_text(Bytes raw) {- static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";- std::string out;- out.reserve((raw.size() * 8) / 5 + 2);- std::uint64_t bits = 0;- std::size_t nbits = 0;- for (std::uint8_t byte : raw) {- bits = (bits << 8) | byte;- nbits += 8;- while (nbits >= 5) {- nbits -= 5;- out.push_back(alphabet[(bits >> nbits) & 31u]);- }- }- if (nbits > 0)- out.push_back(alphabet[(bits << (5 - nbits)) & 31u]);- return out;-}--std::string base64url_encode(Bytes raw) {- static constexpr char alphabet[] =- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";- std::string out;- out.reserve((raw.size() * 4) / 3 + 4);- std::uint32_t acc = 0;- std::size_t bits = 0;- for (std::uint8_t byte : raw) {- acc = (acc << 8) | byte;- bits += 8;- while (bits >= 6) {- bits -= 6;- out.push_back(alphabet[(acc >> bits) & 63u]);- }- }- if (bits > 0)- out.push_back(alphabet[(acc << (6 - bits)) & 63u]);- return out;-}--std::optional<std::vector<std::uint8_t>>-base64url_decode(std::string_view text) {- if (text.empty())- return std::nullopt;- static const auto value_of = [](char c) -> int {- if (c >= 'A' && c <= 'Z')- return c - 'A';- if (c >= 'a' && c <= 'z')- return c - 'a' + 26;- if (c >= '0' && c <= '9')- return c - '0' + 52;- if (c == '-')- return 62;- if (c == '_')- return 63;- return -1;- };- std::vector<std::uint8_t> out;- out.reserve((text.size() * 6) / 8);- std::uint32_t acc = 0;- std::size_t bits = 0;- for (char c : text) {- const int value = value_of(c);- if (value < 0)- return std::nullopt;- acc = (acc << 6) | static_cast<std::uint32_t>(value);- bits += 6;- if (bits >= 8) {- bits -= 8;- out.push_back(static_cast<std::uint8_t>((acc >> bits) & 255u));- }- }- return out;-}--std::string format_public_key(const PublicKey &public_key) {- return "ed25519:" +- base64url_encode(Bytes(public_key.data(), public_key.size()));-}--std::optional<PublicKey> parse_public_key(std::string_view text) {- constexpr std::string_view prefix = "ed25519:";- if (!text.starts_with(prefix))- return std::nullopt;- auto decoded = base64url_decode(text.substr(prefix.size()));- if (!decoded || decoded->size() != 32)- return std::nullopt;- return key_from_span(Bytes(decoded->data(), decoded->size()));-}--std::vector<std::uint8_t> secure_random(std::size_t count) {- std::vector<std::uint8_t> out(count);- if (count != 0 && RAND_bytes(out.data(), static_cast<int>(count)) != 1)- out.clear();- return out;-}--} // namespace vn--- a/veins-cpprewrite/src/crypto.h+++ /dev/null@@ -1,37 +0,0 @@-#pragma once--#include "common.h"--#include <array>-#include <optional>-#include <string>-#include <string_view>-#include <vector>--namespace vn {--using PublicKey = std::array<std::uint8_t, 32>;-using Signature = std::array<std::uint8_t, 64>;-using FingerprintBytes = std::array<std::uint8_t, 16>;--std::optional<PublicKey> ed25519_public_from_seed(Bytes seed);-std::optional<Signature> ed25519_sign(Bytes seed, Bytes message);-bool ed25519_verify(const PublicKey &public_key, Bytes message,- Bytes signature);--FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key);-std::string key_fingerprint(const PublicKey &public_key);--// RFC 4648 base32 with no padding. The reference implementation emits-// fingerprints in uppercase, so this matches it.-std::string base32_text(Bytes raw);-// Unpadded base64url.-std::string base64url_encode(Bytes raw);-std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text);--std::string format_public_key(const PublicKey &public_key);-std::optional<PublicKey> parse_public_key(std::string_view text);--std::vector<std::uint8_t> secure_random(std::size_t count);--} // namespace vn--- a/veins-cpprewrite/src/exclude.cpp+++ /dev/null@@ -1,145 +0,0 @@-#include "local_commands.h"--#include "pathspec.h"-#include "store.h"--#include <iostream>-#include <string_view>--namespace vn {--namespace {--bool ex_is_flag(std::string_view arg) {- return !arg.empty() && arg.front() == '-';-}--std::string_view trim(std::string_view b) {- std::size_t start = 0;- std::size_t end = b.size();- while (start < end) {- const char c = b[start];- if (c != ' ' && c != '\t' && c != '\r' && c != '\n')- break;- ++start;- }- while (end > start) {- const char c = b[end - 1];- if (c != ' ' && c != '\t' && c != '\r' && c != '\n')- break;- --end;- }- return b.substr(start, end - start);-}--bool line_exists(std::string_view data, std::string_view pattern) {- if (data.empty())- return false;- std::size_t start = 0;- for (std::size_t pos = 0; pos <= data.size(); ++pos) {- const bool at_end = pos == data.size();- if (at_end || data[pos] == '\n') {- if (trim(data.substr(start, pos - start)) == pattern)- return true;- start = pos + 1;- }- }- return false;-}--} // namespace--int ex_run(const std::vector<std::string> &args) {- std::vector<std::string> operands;- 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 && ex_is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- operands.push_back(arg);- }- }- if (operands.empty()) {- error_prefix();- std::cout << "ex requires at least one pattern\n";- return 1;- }-- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const auto cwd_rel = cwd_relative(*root);- if (!cwd_rel) {- error_prefix();- std::cout << "cannot determine current directory\n";- return 1;- }-- std::vector<std::string> patterns;- for (const auto &arg : operands) {- auto norm = pathspec_normalize(*root, *cwd_rel, arg);- if (!norm) {- error_prefix();- std::cout << "pattern is outside the repository: " << arg << "\n";- return 1;- }- if (norm->empty() || !valid_path(*norm)) {- error_prefix();- std::cout << arg << "\n";- std::cout << "not a valid exclude pattern\n";- return 1;- }- patterns.push_back(std::move(*norm));- }-- const fs::path exclude_path = *root / ".vnexclude";- std::string data;- if (auto existing = read_file_opt(exclude_path))- data.assign(reinterpret_cast<const char *>(existing->data()),- existing->size());-- std::string additions;- std::vector<std::string> added;- for (const auto &pattern : patterns) {- if (line_exists(data, pattern))- continue;- bool duplicate = false;- for (const auto &prior : added) {- if (prior == pattern) {- duplicate = true;- break;- }- }- if (duplicate)- continue;- if (additions.empty() && !data.empty() && data.back() != '\n')- additions.push_back('\n');- added.push_back(pattern);- additions += pattern;- additions.push_back('\n');- }-- if (added.empty()) {- info_prefix();- std::cout << "no new exclude rules\n";- return 0;- }- if (!append_file(exclude_path, bytes_of(additions))) {- error_prefix();- std::cout << "cannot write .vnexclude\n";- return 1;- }- info_prefix();- std::cout << "added " << added.size() << " exclude rule(s)\n";- return 0;-}--} // namespace vn--- a/veins-cpprewrite/src/local_commands.h+++ /dev/null@@ -1,17 +0,0 @@-#pragma once--#include <string>-#include <vector>--namespace vn {--// Local-only commands. Each receives the full argv-style vector and indexes-// its own arguments (args[0] is the program, args[1] the command).-int bmk_run(const std::vector<std::string> &args);-int rm_run(const std::vector<std::string> &args);-int mv_run(const std::vector<std::string> &args);-int ex_run(const std::vector<std::string> &args);-int op_run(const std::vector<std::string> &args);-int undo_run(const std::vector<std::string> &args);--} // namespace vn--- a/veins-cpprewrite/src/main.cpp+++ /dev/null@@ -1,22 +0,0 @@-#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;- }-}--- a/veins-cpprewrite/src/merge.cpp+++ /dev/null@@ -1,2246 +0,0 @@-#include "merge.h"--#include "pathspec.h"-#include "worktree.h"--#include <algorithm>-#include <cstdlib>-#include <cstring>-#include <iostream>-#include <set>-#include <utility>--namespace vn {--namespace {--// ----------------------------------------------------------------------------// Object access that also sees pending transaction objects-// -----------------------------------------------------------------------------bool same_id(const Id &a, const Id &b) {- return std::memcmp(a.data(), b.data(), ID_LEN) == 0;-}--std::optional<std::vector<std::uint8_t>> read_body_any(Store &store, Txn *tx,- std::uint8_t type,- const Id &id) {- if (tx) {- if (auto cached = tx->writer().find_cached(type, id))- return cached;- }- return store.read_body(id, type);-}--bool append_blob_any(Store &store, Txn *tx, const Id &id,- std::vector<std::uint8_t> &out, std::size_t depth) {- if (depth > 64)- return false;- auto body = read_body_any(store, tx, TYPE_BLOB, id);- 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;- }- for (const auto &entry : blob->entries) {- if (blob->form == BlobForm::Leaf) {- auto chunk = read_body_any(store, tx, TYPE_CHUNK, entry.id);- if (!chunk)- return false;- out.insert(out.end(), chunk->begin(), chunk->end());- } else if (!append_blob_any(store, tx, entry.id, out, depth + 1)) {- return false;- }- }- return true;-}--std::optional<std::vector<std::uint8_t>> read_blob_any(Store &store, Txn *tx,- const Id &id) {- std::vector<std::uint8_t> out;- if (!append_blob_any(store, tx, id, out, 0))- return std::nullopt;- return out;-}--bool collect_chunks_any(Store &store, Txn *tx, const Id &id,- std::vector<Id> &out, std::size_t depth) {- if (depth > 64)- return false;- auto body = read_body_any(store, tx, TYPE_BLOB, id);- if (!body)- return false;- auto blob = decode_blob(bytes_of(*body));- if (!blob)- return false;- if (blob->form == BlobForm::Leaf) {- for (const auto &entry : blob->entries)- out.push_back(entry.id);- return true;- }- if (blob->form == BlobForm::Interior) {- for (const auto &entry : blob->entries) {- if (!collect_chunks_any(store, tx, entry.id, out, depth + 1))- return false;- }- }- return true;-}--bool flatten_any(Store &store, Txn *tx, const Id &tree_id, std::string &prefix,- std::vector<FlatEntry> &out, std::size_t depth) {- if (depth > 4096)- return false;- auto body = read_body_any(store, tx, TYPE_TREE, tree_id);- 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();- if (!prefix.empty())- prefix.push_back('/');- prefix.append(entry.name);- if (entry.kind == KIND_SUBTREE) {- if (!flatten_any(store, tx, 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_any_sorted(Store &store, Txn *tx,- std::optional<Id> tree) {- std::vector<FlatEntry> out;- if (!tree)- return out;- std::string prefix;- (void)flatten_any(store, tx, *tree, 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;-}--const FlatEntry *find_flat_entry(const std::vector<FlatEntry> &entries,- std::string_view path) {- for (const auto &entry : entries) {- if (entry.path == path)- return &entry;- }- return nullptr;-}--bool tree_empty_any(Store &store, Txn *tx, const Id &id) {- auto body = read_body_any(store, tx, TYPE_TREE, id);- if (!body)- return true;- auto tree = decode_tree(bytes_of(*body));- return !tree || tree->entries.empty();-}--Id add_tree(Txn &tx, const std::vector<TreeEntry> &entries) {- auto encoded = encode_tree(entries);- if (!encoded)- return Id{};- return tx.add_object(TYPE_TREE, *encoded);-}--Id add_empty_tree(Txn &tx) { return add_tree(tx, {}); }--Id add_blob(Txn &tx, 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)tx.add_known(object.type, id, std::move(object.body));- }- return build.root;-}--// ----------------------------------------------------------------------------// Three-way line merge-// -----------------------------------------------------------------------------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 + 1 - start);- start = i + 1;- }- }- if (start < data.size())- out.emplace_back(reinterpret_cast<const char *>(data.data() + start),- data.size() - start);- return out;-}--std::vector<DiffOp> fallback_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();- std::size_t prefix = 0;- while (prefix < n && prefix < m && a[prefix] == b[prefix])- ++prefix;- std::size_t suffix = 0;- while (suffix < n - prefix && suffix < m - prefix &&- a[n - 1 - suffix] == b[m - 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 < n - suffix; ++i)- ops.push_back(DiffOp{'-', i, 0});- for (std::size_t j = prefix; j < m - suffix; ++j)- ops.push_back(DiffOp{'+', 0, j});- for (std::size_t k = 0; k < suffix; ++k)- ops.push_back(DiffOp{' ', n - suffix + k, m - suffix + k});- 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();- const std::uint64_t cells =- static_cast<std::uint64_t>(n + 1) * static_cast<std::uint64_t>(m + 1);- if (cells > 8000000)- return fallback_ops(a, b);- const std::size_t cols = m + 1;- std::vector<std::uint32_t> dp(static_cast<std::size_t>(cells), 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 oi = n;- std::size_t oj = m;- while (oi > 0 || oj > 0) {- if (oi > 0 && oj > 0 && a[oi - 1] == b[oj - 1]) {- ops.push_back(DiffOp{' ', oi - 1, oj - 1});- --oi;- --oj;- } else if (oj > 0 &&- (oi == 0 || dp[oi * cols + (oj - 1)] >=- dp[(oi - 1) * cols + oj])) {- ops.push_back(DiffOp{'+', 0, oj - 1});- --oj;- } else {- ops.push_back(DiffOp{'-', oi - 1, 0});- --oi;- }- }- std::reverse(ops.begin(), ops.end());- return ops;-}--struct Hunk {- std::size_t start = 0;- std::size_t end = 0;- std::vector<std::string> lines;-};--std::vector<Hunk> hunks_from_ops(const std::vector<std::string> &side,- const std::vector<DiffOp> &ops) {- std::vector<Hunk> out;- std::size_t base_pos = 0;- std::size_t i = 0;- while (i < ops.size()) {- if (ops[i].tag == ' ') {- ++base_pos;- ++i;- continue;- }- Hunk hunk;- hunk.start = base_pos;- while (i < ops.size() && ops[i].tag != ' ') {- if (ops[i].tag == '-') {- ++base_pos;- } else {- hunk.lines.push_back(side[ops[i].bi]);- }- ++i;- }- hunk.end = base_pos;- out.push_back(std::move(hunk));- }- return out;-}--std::vector<Hunk> diff_hunks(const std::vector<std::string> &base,- const std::vector<std::string> &side) {- return hunks_from_ops(side, build_ops(base, side));-}--struct MergeRange {- std::size_t base_start = 0;- std::size_t base_end = 0;- std::size_t ours_start = 0;- std::size_t ours_end = 0;- std::size_t theirs_start = 0;- std::size_t theirs_end = 0;-};--struct EditResult {- bool conflicted = false;- std::vector<std::uint8_t> data;- std::vector<MergeRange> ranges;-};--void append_lines(std::vector<std::uint8_t> &out,- const std::vector<std::string> &lines, std::size_t start,- std::size_t end) {- for (std::size_t i = start; i < end && i < lines.size(); ++i)- out.insert(out.end(), lines[i].begin(), lines[i].end());-}--void apply_hunks(std::vector<std::uint8_t> &out,- const std::vector<std::string> &base, std::size_t from,- std::size_t to, const std::vector<Hunk> &hunks,- std::size_t first, std::size_t last) {- std::size_t pos = from;- for (std::size_t k = first; k < last; ++k) {- const Hunk &h = hunks[k];- if (h.start > pos && h.start <= to)- append_lines(out, base, pos, h.start);- for (const auto &line : h.lines)- out.insert(out.end(), line.begin(), line.end());- if (h.end > pos)- pos = h.end;- }- if (pos < to)- append_lines(out, base, pos, to);-}--std::size_t map_pos(const std::vector<Hunk> &hunks, std::size_t pos) {- std::ptrdiff_t out = static_cast<std::ptrdiff_t>(pos);- for (const auto &h : hunks) {- if (h.end <= pos) {- const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(h.end - h.start);- const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());- out += fresh - old;- } else if (h.start < pos) {- const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(pos - h.start);- const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());- out += fresh - old;- break;- } else {- break;- }- }- return static_cast<std::size_t>(out);-}--bool same_hunks(const std::vector<Hunk> &ours, std::size_t of, std::size_t ol,- const std::vector<Hunk> &theirs, std::size_t tf,- std::size_t tl) {- std::string a;- std::string b;- for (std::size_t k = of; k < ol; ++k)- for (const auto &line : ours[k].lines)- a += line;- for (std::size_t j = tf; j < tl; ++j)- for (const auto &line : theirs[j].lines)- b += line;- return a == b;-}--EditResult merge_lines(const std::vector<std::string> &base,- const std::vector<std::string> &ours,- const std::vector<std::string> &theirs,- bool adjacent_merge) {- const auto ours_h = diff_hunks(base, ours);- const auto theirs_h = diff_hunks(base, theirs);- EditResult result;- std::size_t oi = 0;- std::size_t ti = 0;- std::size_t pos = 0;- while (oi < ours_h.size() || ti < theirs_h.size()) {- const bool have_o = oi < ours_h.size();- const bool have_t = ti < theirs_h.size();- const std::size_t o_start = have_o ? ours_h[oi].start : 0;- const std::size_t t_start = have_t ? theirs_h[ti].start : 0;- const bool take_ours_cluster = have_o && (!have_t || o_start <= t_start);- const std::size_t cluster_start = take_ours_cluster ? o_start : t_start;- const std::size_t of = oi;- const std::size_t tf = ti;- std::size_t o_last = of;- std::size_t t_last = tf;- std::size_t end = cluster_start;- bool seen_o = false;- bool seen_t = false;- for (;;) {- bool progress = false;- if (o_last < ours_h.size()) {- const Hunk &h = ours_h[o_last];- bool include = h.start <= end;- if (o_last != of)- include = adjacent_merge ? h.start < end : h.start <= end;- if (include) {- seen_o = true;- ++o_last;- if (h.end > end)- end = h.end;- progress = true;- }- }- if (t_last < theirs_h.size()) {- const Hunk &h = theirs_h[t_last];- bool include = h.start <= end;- if (t_last != tf)- include = adjacent_merge ? h.start < end : h.start <= end;- if (include) {- seen_t = true;- ++t_last;- if (h.end > end)- end = h.end;- progress = true;- }- }- if (!progress)- break;- }- if (end < cluster_start)- end = cluster_start;- if (seen_o && !seen_t) {- apply_hunks(result.data, base, pos, end, ours_h, of, o_last);- pos = end;- oi = o_last;- ti = t_last;- } else if (seen_t && !seen_o) {- apply_hunks(result.data, base, pos, end, theirs_h, tf, t_last);- pos = end;- oi = o_last;- ti = t_last;- } else {- if (same_hunks(ours_h, of, o_last, theirs_h, tf, t_last)) {- apply_hunks(result.data, base, pos, end, ours_h, of, o_last);- pos = end;- } else {- result.conflicted = true;- apply_hunks(result.data, base, pos, end, ours_h, of, o_last);- MergeRange range;- range.base_start = cluster_start;- range.base_end = end;- range.ours_start = map_pos(ours_h, cluster_start);- range.ours_end = map_pos(ours_h, end);- range.theirs_start = map_pos(theirs_h, cluster_start);- range.theirs_end = map_pos(theirs_h, end);- result.ranges.push_back(range);- pos = end;- }- oi = o_last;- ti = t_last;- }- }- if (pos < base.size())- append_lines(result.data, base, pos, base.size());- return result;-}--std::optional<EditResult> merge_blobs(Store &store, Txn *tx, const Id &base_id,- const Id &ours_id, const Id &theirs_id,- bool adjacent) {- auto base = read_blob_any(store, tx, base_id);- auto ours = read_blob_any(store, tx, ours_id);- auto theirs = read_blob_any(store, tx, theirs_id);- if (!base || !ours || !theirs)- return std::nullopt;- return merge_lines(split_lines(bytes_of(*base)), split_lines(bytes_of(*ours)),- split_lines(bytes_of(*theirs)), adjacent);-}--// ----------------------------------------------------------------------------// Rename detection-// -----------------------------------------------------------------------------struct RenamePair {- std::string old_path;- std::string new_path;- std::size_t score = 0;- bool old_used = false;- bool new_used = false;-};--std::uint64_t hash_line(std::string_view line) {- std::uint64_t h = 1469598103934665603ull;- for (char raw : line) {- const auto c = static_cast<unsigned char>(raw);- h = (h ^ static_cast<std::uint64_t>(c)) * 1099511628211ull;- }- return h;-}--int line_similarity(Bytes a, Bytes b) {- std::vector<std::uint64_t> la;- std::vector<std::uint64_t> lb;- std::size_t start = 0;- for (std::size_t i = 0; i <= a.size(); ++i) {- if (i == a.size() || a[i] == '\n') {- la.push_back(hash_line(str_of(a.subspan(start, i - start))));- start = i + 1;- }- }- start = 0;- for (std::size_t j = 0; j <= b.size(); ++j) {- if (j == b.size() || b[j] == '\n') {- lb.push_back(hash_line(str_of(b.subspan(start, j - start))));- start = j + 1;- }- }- std::sort(la.begin(), la.end());- std::sort(lb.begin(), lb.end());- std::size_t ia = 0;- std::size_t ib = 0;- std::size_t inter = 0;- while (ia < la.size() && ib < lb.size()) {- if (la[ia] == lb[ib]) {- ++inter;- ++ia;- ++ib;- } else if (la[ia] < lb[ib]) {- ++ia;- } else {- ++ib;- }- }- const std::size_t total = la.size() + lb.size() - inter;- if (total == 0)- return 100;- return static_cast<int>((inter * 100) / total);-}--int chunk_similarity(Store &store, Txn *tx, const Id &a, const Id &b) {- std::vector<Id> ca;- std::vector<Id> cb;- if (!collect_chunks_any(store, tx, a, ca, 0) ||- !collect_chunks_any(store, tx, b, cb, 0))- return 0;- std::size_t inter = 0;- for (const auto &x : ca) {- for (const auto &y : cb) {- if (same_id(x, y)) {- ++inter;- break;- }- }- }- const std::size_t total = ca.size() + cb.size() - inter;- if (total == 0)- return 0;- return static_cast<int>((inter * 100) / total);-}--int similarity(Store &store, Txn *tx, const Id &a, const Id &b) {- if (same_id(a, b))- return 100;- auto da = read_blob_any(store, tx, a);- auto db = read_blob_any(store, tx, b);- if (!da || !db)- return 0;- int result = 0;- if (da->size() >= 131072 && db->size() >= 131072)- result = chunk_similarity(store, tx, a, b);- if (result == 0)- result = line_similarity(bytes_of(*da), bytes_of(*db));- return result;-}--} // namespace--std::vector<Rename> detect_renames(Store &store, Txn *tx,- std::optional<Id> old_tree,- std::optional<Id> new_tree, int similar_pct,- std::uint64_t parent_index) {- const auto old_entries = flatten_any_sorted(store, tx, old_tree);- const auto new_entries = flatten_any_sorted(store, tx, new_tree);- std::vector<FlatEntry> deleted;- std::vector<FlatEntry> added;- for (const auto &entry : old_entries) {- if (!find_flat_entry(new_entries, entry.path))- deleted.push_back(entry);- }- for (const auto &entry : new_entries) {- if (!find_flat_entry(old_entries, entry.path))- added.push_back(entry);- }- std::vector<char> used_old(deleted.size(), 0);- std::vector<char> used_new(added.size(), 0);- std::vector<Rename> out;- for (std::size_t di = 0; di < deleted.size(); ++di) {- if (used_old[di])- continue;- for (std::size_t ai = 0; ai < added.size(); ++ai) {- if (used_new[ai])- continue;- if (same_id(deleted[di].target, added[ai].target)) {- out.push_back(Rename{parent_index, 0, deleted[di].path, added[ai].path});- used_old[di] = 1;- used_new[ai] = 1;- break;- }- }- }- if (similar_pct > 0) {- std::vector<RenamePair> pairs;- constexpr std::size_t candidate_limit = 5000;- for (std::size_t di = 0; di < deleted.size(); ++di) {- if (used_old[di] || (deleted[di].kind != KIND_FILE &&- deleted[di].kind != KIND_EXECUTABLE))- continue;- for (std::size_t ai = 0; ai < added.size() && pairs.size() < candidate_limit;- ++ai) {- if (used_new[ai] || (added[ai].kind != KIND_FILE &&- added[ai].kind != KIND_EXECUTABLE))- continue;- RenamePair pair;- pair.old_path = deleted[di].path;- pair.new_path = added[ai].path;- pair.score = static_cast<std::size_t>(- similarity(store, tx, deleted[di].target, added[ai].target));- pairs.push_back(std::move(pair));- }- }- for (;;) {- std::ptrdiff_t best_i = -1;- std::size_t best = 0;- for (std::size_t i = 0; i < pairs.size(); ++i) {- if (!pairs[i].old_used && !pairs[i].new_used &&- pairs[i].score > best) {- best = pairs[i].score;- best_i = static_cast<std::ptrdiff_t>(i);- }- }- if (best_i < 0 || best < static_cast<std::size_t>(similar_pct))- break;- auto &pair = pairs[static_cast<std::size_t>(best_i)];- pair.old_used = true;- pair.new_used = true;- out.push_back(Rename{parent_index, 0, pair.old_path, pair.new_path});- }- }- std::stable_sort(out.begin(), out.end(), [](const Rename &a, const Rename &b) {- if (a.parent_index != b.parent_index)- return a.parent_index < b.parent_index;- return compare(bytes_of(a.to_path), bytes_of(b.to_path)) < 0;- });- return out;-}--int rename_similar_pct(const fs::path &root) {- if (auto value = repo_config_value(root, "rename.autodetect")) {- if (*value == "off")- return 0;- return 60;- }- return 60;-}--namespace {--// ----------------------------------------------------------------------------// Rename maps-// -----------------------------------------------------------------------------using RenameMap = std::vector<std::pair<std::string, std::string>>;--std::optional<std::string> rename_lookup(const RenameMap &map,- std::string_view path) {- for (const auto &entry : map) {- if (entry.first == path)- return entry.second;- }- return std::nullopt;-}--void rename_apply(RenameMap &map, const std::string &from,- const std::string &to) {- for (auto &entry : map) {- if (entry.second == from) {- entry.second = to;- return;- }- }- for (auto &entry : map) {- if (entry.first == from) {- entry.second = to;- return;- }- }- map.emplace_back(from, to);-}--std::optional<Id> tree_of(Store &store, const Id &commit_id) {- auto loaded = load_commit(store, commit_id);- if (!loaded)- return std::nullopt;- return loaded->commit.root_tree;-}--std::optional<Id> first_parent(Store &store, const Id &commit_id) {- auto loaded = load_commit(store, commit_id);- if (!loaded || loaded->commit.parents.empty())- return std::nullopt;- return loaded->commit.parents.front();-}--RenameMap map_from(Store &store, const Id &base, const Id &side) {- RenameMap map;- if (same_id(base, side))- return map;- std::vector<Id> chain;- Id current = side;- bool reached = false;- for (std::size_t depth = 0; depth < 100000; ++depth) {- if (same_id(current, base)) {- reached = true;- break;- }- chain.push_back(current);- auto parent = first_parent(store, current);- if (!parent)- break;- current = *parent;- }- if (!reached)- return map;- for (std::size_t i = chain.size(); i > 0; --i) {- auto loaded = load_commit(store, chain[i - 1]);- if (!loaded)- continue;- if (loaded->commit.renames_state == RENAMES_RECORDED) {- for (const auto &rename : loaded->commit.renames) {- if (rename.parent_index == 0)- rename_apply(map, rename.from_path, rename.to_path);- }- } else {- auto parent = first_parent(store, chain[i - 1]);- if (!parent)- continue;- auto old_tree = tree_of(store, *parent);- auto new_tree = tree_of(store, chain[i - 1]);- for (const auto &rename :- detect_renames(store, nullptr, old_tree, new_tree, 50, 0))- rename_apply(map, rename.from_path, rename.to_path);- }- }- return map;-}--// ----------------------------------------------------------------------------// Tree merge-// -----------------------------------------------------------------------------struct TreeTerm {- bool positive = true;- bool present = false;- Id id{};-};--struct EntryTerm {- bool positive = true;- bool present = false;- std::uint8_t kind = 0;- std::optional<Id> target;-};--struct OrigEntry {- std::size_t term = 0;- std::string path;- std::uint8_t kind = 0;- Id target{};-};--struct OutEntry {- std::string path;- std::uint8_t kind = 0;- Id target{};-};--struct MergeOutcome {- Id tree{};- std::size_t rerere = 0;-};--bool 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 && same_id(*a.target, *b.target);-}--void flatten_values(Store &store, const std::vector<ConflictValue> &values,- bool positive, std::vector<ConflictValue> &adds,- std::vector<ConflictValue> &removes, std::size_t depth) {- for (const auto &value : values) {- if (value.kind == KIND_CONFLICT && value.target && depth < 64) {- auto body = store.read_body(*value.target, TYPE_CONFLICT);- if (body) {- auto child = decode_conflict(bytes_of(*body));- if (child) {- flatten_values(store, child->adds, positive, adds, removes,- depth + 1);- flatten_values(store, child->removes, !positive, adds, removes,- depth + 1);- continue;- }- }- }- if (positive)- adds.push_back(value);- else- removes.push_back(value);- }-}--Conflict simplify(Store &store, const std::vector<ConflictValue> &adds_in,- const std::vector<ConflictValue> &removes_in) {- std::vector<ConflictValue> flat_adds;- std::vector<ConflictValue> flat_removes;- flatten_values(store, adds_in, true, flat_adds, flat_removes, 0);- flatten_values(store, removes_in, false, flat_adds, flat_removes, 0);-- std::vector<char> used(flat_adds.size(), 0);- std::vector<char> rem_used(flat_removes.size(), 0);- for (std::size_t r = 0; r < flat_removes.size(); ++r) {- for (std::size_t a = 0; a < flat_adds.size(); ++a) {- if (!used[a] && value_equal(flat_adds[a], flat_removes[r])) {- used[a] = 1;- rem_used[r] = 1;- break;- }- }- }- Conflict out;- for (std::size_t a = 0; a < flat_adds.size(); ++a) {- if (!used[a])- out.adds.push_back(flat_adds[a]);- }- for (std::size_t r = 0; r < flat_removes.size(); ++r) {- if (!rem_used[r])- out.removes.push_back(flat_removes[r]);- }- return out;-}--std::optional<ConflictValue> resolved(const Conflict &conflict) {- if (conflict.adds.empty())- return std::nullopt;- for (std::size_t i = 1; i < conflict.adds.size(); ++i) {- if (!value_equal(conflict.adds[0], conflict.adds[i]))- return std::nullopt;- }- return conflict.adds[0];-}--bool all_files(const Conflict &conflict) {- for (const auto &value : conflict.adds) {- if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&- value.kind != 0)- return false;- }- for (const auto &value : conflict.removes) {- if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&- value.kind != 0)- return false;- }- return true;-}--int merge_mode(const Conflict &conflict) {- if (conflict.adds.size() != 2 || conflict.removes.size() != 1)- return -1;- auto mode = [](const ConflictValue &value) -> int {- if (value.kind == 0)- return -1;- return value.kind == KIND_EXECUTABLE ? 1 : 0;- };- const int m0 = mode(conflict.adds[0]);- const int m1 = mode(conflict.adds[1]);- const int mr = mode(conflict.removes[0]);- if (m0 < 0 || m1 < 0)- return -1;- if (m0 == m1)- return m0;- if (mr >= 0 && m0 == mr)- return m1;- if (mr >= 0 && m1 == mr)- return m0;- return -1;-}--bool merge_binary(const fs::path &repo, std::string_view path) {- auto data = read_file_opt(repo / ".veinsattributes");- if (!data)- return false;- const std::string_view text(reinterpret_cast<const char *>(data->data()),- data->size());- bool result = false;- std::size_t start = 0;- for (std::size_t pos = 0; pos <= text.size(); ++pos) {- if (pos != text.size() && text[pos] != '\n')- continue;- std::string_view line = text.substr(start, pos - start);- start = pos + 1;- while (!line.empty() && (line.front() == ' ' || line.front() == '\t' ||- line.front() == '\r' || line.front() == '\n'))- line.remove_prefix(1);- while (!line.empty() && (line.back() == ' ' || line.back() == '\t' ||- line.back() == '\r' || line.back() == '\n'))- line.remove_suffix(1);- if (line.empty() || line.front() == '#')- continue;- std::size_t glob_end = 0;- while (glob_end < line.size() && line[glob_end] != ' ' &&- line[glob_end] != '\t')- ++glob_end;- const std::string_view glob = line.substr(0, glob_end);- std::string_view base = glob;- if (const auto slash = glob.rfind('/'); slash != std::string_view::npos)- base = glob.substr(slash + 1);- const bool matched =- glob_match(glob, path) ||- (glob.find('/') == std::string_view::npos && glob_match(base, path));- if (!matched)- continue;- std::size_t t = glob_end;- while (t < line.size()) {- while (t < line.size() && (line[t] == ' ' || line[t] == '\t'))- ++t;- const std::size_t tok_start = t;- while (t < line.size() && line[t] != ' ' && line[t] != '\t')- ++t;- const std::string_view token = line.substr(tok_start, t - tok_start);- const auto eq = token.find('=');- if (eq != std::string_view::npos) {- const std::string_view key = token.substr(0, eq);- const std::string_view value = token.substr(eq + 1);- if (key == "merge") {- if (value == "binary")- result = true;- else if (value == "text")- result = false;- }- }- }- }- return result;-}--std::optional<Id> resolution_lookup(const fs::path &repo, Bytes body) {- const auto digest = blake3_hash(body);- const std::string key = hex_encode(Bytes(digest.data(), digest.size()));- auto data = read_file_opt(resolutions_dir(repo) / key);- if (!data || data->size() < 64)- return std::nullopt;- const std::string_view text(reinterpret_cast<const char *>(data->data()), 64);- Id id{};- if (!hex_decode(text, MutBytes(id.data(), id.size())))- return std::nullopt;- return id;-}--void resolution_record(const fs::path &repo, Bytes body, const Id &blob) {- const auto digest = blake3_hash(body);- const std::string key = hex_encode(Bytes(digest.data(), digest.size()));- (void)write_file(resolutions_dir(repo) / key, bytes_of(hex_encode(blob)));-}--Id build_level(Txn &tx, const std::vector<OutEntry> &entries,- std::size_t start, std::size_t end, std::size_t prefix_len) {- std::vector<TreeEntry> out;- std::size_t i = start;- while (i < end) {- const OutEntry &entry = entries[i];- const std::size_t name_end = entry.path.find('/', prefix_len);- const std::size_t cut =- name_end == std::string::npos ? entry.path.size() : name_end;- const std::string name = entry.path.substr(prefix_len, cut - prefix_len);- if (cut == entry.path.size()) {- out.push_back(TreeEntry{name, entry.kind, entry.target});- ++i;- } else {- std::size_t j = i + 1;- while (j < end) {- const std::size_t other_end = entries[j].path.find('/', prefix_len);- const std::size_t other_cut = other_end == std::string::npos- ? entries[j].path.size()- : other_end;- if (other_cut != cut ||- entries[j].path.compare(prefix_len, cut - prefix_len, name) != 0)- break;- ++j;- }- const Id child = build_level(tx, entries, i, j, cut + 1);- out.push_back(TreeEntry{name, KIND_SUBTREE, child});- i = j;- }- }- return add_tree(tx, out);-}--Id build_from_entries(Txn &tx, std::vector<OutEntry> &entries) {- if (entries.empty())- return add_empty_tree(tx);- std::stable_sort(entries.begin(), entries.end(),- [](const OutEntry &a, const OutEntry &b) {- return compare(bytes_of(a.path), bytes_of(b.path)) < 0;- });- return build_level(tx, entries, 0, entries.size(), 0);-}--Id build_subtree(Txn &tx, const std::vector<OrigEntry> &canon,- std::size_t term, std::string_view prefix) {- std::vector<OutEntry> rels;- for (const auto &entry : canon) {- if (entry.term != term)- continue;- if (entry.path.size() > prefix.size() &&- entry.path.compare(0, prefix.size(), prefix) == 0 &&- entry.path[prefix.size()] == '/')- rels.push_back(- OutEntry{entry.path.substr(prefix.size() + 1), entry.kind,- entry.target});- }- return build_from_entries(tx, rels);-}--bool has_prefix(std::string_view path, std::string_view prefix) {- return path.size() > prefix.size() &&- path.compare(0, prefix.size(), prefix) == 0 &&- path[prefix.size()] == '/';-}--std::optional<OutEntry> merge_entry(const fs::path &repo, Txn &tx,- Store &store, const std::string &path,- const std::vector<EntryTerm> &terms,- bool adjacent, std::size_t &rerere) {- std::vector<ConflictValue> adds;- std::vector<ConflictValue> removes;- for (const auto &term : terms) {- ConflictValue value;- if (term.present) {- value.kind = term.kind;- value.target = term.target;- }- if (term.positive)- adds.push_back(value);- else- removes.push_back(value);- }- Conflict sum = simplify(store, adds, removes);- if (auto value = resolved(sum)) {- if (value->kind == 0)- return std::nullopt;- return OutEntry{path, value->kind, *value->target};- }- if (all_files(sum) && sum.adds.size() == 2 && sum.removes.size() == 1 &&- sum.adds[0].kind != 0 && sum.adds[1].kind != 0 &&- sum.removes[0].kind != 0 && !merge_binary(repo, path)) {- auto merged = merge_blobs(store, &tx, *sum.removes[0].target,- *sum.adds[0].target, *sum.adds[1].target,- adjacent);- if (merged && !merged->conflicted) {- const Id blob = add_blob(tx, bytes_of(merged->data));- const int mode = merge_mode(sum);- if (mode >= 0)- return OutEntry{path,- static_cast<std::uint8_t>(mode == 1 ? KIND_EXECUTABLE- : KIND_FILE),- blob};- }- }- const auto body = encode_conflict(sum);- if (all_files(sum)) {- if (auto memo = resolution_lookup(repo, bytes_of(body))) {- ++rerere;- return OutEntry{path, KIND_FILE, *memo};- }- }- const Id id = tx.add_object(TYPE_CONFLICT, body);- return OutEntry{path, KIND_CONFLICT, id};-}--MergeOutcome treemerge(const fs::path &repo, Txn &tx, Store &store,- const std::vector<TreeTerm> &terms,- const std::vector<RenameMap> &maps, bool adjacent) {- std::vector<OrigEntry> orig;- for (std::size_t t = 0; t < terms.size(); ++t) {- if (!terms[t].present)- continue;- for (const auto &entry : flatten_any_sorted(store, &tx, terms[t].id))- orig.push_back(OrigEntry{t, entry.path, entry.kind, entry.target});- }-- auto canonical_targets =- [&](const std::string &path) -> std::vector<std::pair<std::size_t, std::string>> {- std::vector<std::pair<std::size_t, std::string>> out;- for (std::size_t i = 0; i < maps.size(); ++i) {- auto dest = rename_lookup(maps[i], path);- if (!dest)- continue;- bool exists = false;- for (const auto &item : out) {- if (item.second == *dest) {- exists = true;- break;- }- }- if (!exists)- out.emplace_back(i, *dest);- }- return out;- };-- auto find_orig = [&](std::size_t term,- const std::string &path) -> const OrigEntry * {- for (const auto &entry : orig) {- if (entry.term == term && entry.path == path)- return &entry;- }- return nullptr;- };-- std::vector<OrigEntry> canon;- std::vector<std::string> special;- std::vector<std::string> consumed;- auto mark_consumed = [&](const std::string &path) {- for (const auto &item : consumed) {- if (item == path)- return;- }- consumed.push_back(path);- };- for (const auto &entry : orig) {- auto targets = canonical_targets(entry.path);- if (targets.size() > 1) {- bool seen = false;- for (const auto &item : special) {- if (item == entry.path) {- seen = true;- break;- }- }- if (!seen)- special.push_back(entry.path);- }- const std::string &canonical =- targets.size() == 1 ? targets[0].second : entry.path;- canon.push_back(OrigEntry{entry.term, canonical, entry.kind, entry.target});- }-- std::vector<OutEntry> out;- std::size_t rerere = 0;-- for (const auto &sp : special) {- auto targets = canonical_targets(sp);- std::vector<EntryTerm> ets;- for (const auto &target : targets) {- EntryTerm term;- term.positive = true;- if (const OrigEntry *found = find_orig(target.first, target.second)) {- term.present = true;- term.kind = found->kind;- term.target = found->target;- }- ets.push_back(term);- mark_consumed(target.second);- }- std::ptrdiff_t base_term = -1;- for (std::size_t ti = 0; ti < terms.size(); ++ti) {- if (!terms[ti].positive) {- base_term = static_cast<std::ptrdiff_t>(ti);- break;- }- }- if (base_term >= 0) {- EntryTerm term;- term.positive = false;- if (const OrigEntry *found =- find_orig(static_cast<std::size_t>(base_term), sp)) {- term.present = true;- term.kind = found->kind;- term.target = found->target;- }- ets.push_back(term);- }- if (auto merged = merge_entry(repo, tx, store, sp, ets, adjacent, rerere))- out.push_back(std::move(*merged));- mark_consumed(sp);- }-- auto find_canon = [&](std::size_t term,- const std::string &path) -> const OrigEntry * {- for (const auto &entry : canon) {- if (entry.term == term && entry.path == path)- return &entry;- }- return nullptr;- };-- std::vector<std::string> paths;- for (const auto &entry : canon) {- bool seen = false;- for (const auto &path : paths) {- if (path == entry.path) {- seen = true;- break;- }- }- if (!seen)- paths.push_back(entry.path);- }- std::sort(paths.begin(), paths.end(),- [](const std::string &a, const std::string &b) {- return compare(bytes_of(a), bytes_of(b)) < 0;- });-- auto is_consumed = [&](const std::string &path) {- for (const auto &item : consumed) {- if (item == path)- return true;- }- return false;- };-- for (const auto &path : paths) {- if (is_consumed(path))- continue;- bool any_exact = false;- bool any_children = false;- for (std::size_t t = 0; t < terms.size(); ++t) {- if (find_canon(t, path))- any_exact = true;- for (const auto &entry : canon) {- if (entry.term == t && has_prefix(entry.path, path)) {- any_children = true;- break;- }- }- }- if (!any_exact)- continue;- const bool mixed = any_children;- std::vector<EntryTerm> ets;- for (std::size_t t = 0; t < terms.size(); ++t) {- EntryTerm term;- term.positive = terms[t].positive;- if (const OrigEntry *exact = find_canon(t, path)) {- term.present = true;- term.kind = exact->kind;- term.target = exact->target;- } else if (mixed) {- bool children = false;- for (const auto &entry : canon) {- if (entry.term == t && has_prefix(entry.path, path)) {- children = true;- break;- }- }- if (children) {- term.present = true;- term.kind = KIND_SUBTREE;- term.target = build_subtree(tx, canon, t, path);- }- }- ets.push_back(term);- }- if (auto merged = merge_entry(repo, tx, store, path, ets, adjacent, rerere))- out.push_back(std::move(*merged));- if (mixed) {- for (const auto &entry : canon) {- if (has_prefix(entry.path, path))- mark_consumed(entry.path);- }- }- }-- return MergeOutcome{build_from_entries(tx, out), rerere};-}--// ----------------------------------------------------------------------------// Commit-level merge helpers-// -----------------------------------------------------------------------------bool contains_id_vec(const std::vector<Id> &ids, const Id &id) {- for (const auto &candidate : ids) {- if (same_id(candidate, id))- return true;- }- return false;-}--std::vector<Id> merge_bases(Store &store, const Id &a, const Id &b) {- const std::vector<Id> aa = collect_commits(store, std::vector<Id>{a});- const std::vector<Id> bb = collect_commits(store, std::vector<Id>{b});- std::vector<Id> common;- for (const auto &x : aa) {- if (contains_id_vec(bb, x))- common.push_back(x);- }- std::vector<Id> out;- for (const auto &c : common) {- bool dominated = false;- for (const auto &d : common) {- if (same_id(c, d))- continue;- const auto descendants = collect_commits(store, std::vector<Id>{c});- if (contains_id_vec(descendants, d)) {- dominated = true;- break;- }- }- if (!dominated)- out.push_back(c);- }- return out;-}--bool is_ancestor(Store &store, const Id &ancestor, const Id &descendant) {- if (same_id(ancestor, descendant))- return true;- return contains_id_vec(collect_commits(store, std::vector<Id>{descendant}),- ancestor);-}--std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,- const std::vector<Id> &bases, bool adjacent);--std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,- const std::vector<Id> &bases, bool adjacent) {- if (bases.empty())- return std::nullopt;- if (bases.size() == 1)- return tree_of(store, bases.front());- auto t0 = tree_of(store, bases[0]);- auto t1 = tree_of(store, bases[1]);- const auto lcas = merge_bases(store, bases[0], bases[1]);- std::vector<TreeTerm> terms;- terms.push_back(TreeTerm{true, t0.has_value(), t0.value_or(Id{})});- terms.push_back(TreeTerm{true, t1.has_value(), t1.value_or(Id{})});- if (!lcas.empty()) {- auto lt = tree_of(store, lcas.front());- terms.push_back(TreeTerm{false, lt.has_value(), lt.value_or(Id{})});- } else {- terms.push_back(TreeTerm{false, false, Id{}});- }- std::vector<RenameMap> maps(3);- return treemerge(repo, tx, store, terms, maps, adjacent).tree;-}--MergeOutcome merge_many(const fs::path &repo, Txn &tx, Store &store,- const std::vector<Id> &heads, bool adjacent) {- if (heads.size() == 1) {- auto t = tree_of(store, heads.front());- std::vector<TreeTerm> terms{- TreeTerm{true, t.has_value(), t.value_or(Id{})}};- return treemerge(repo, tx, store, terms, {RenameMap{}}, adjacent);- }- std::vector<TreeTerm> terms;- std::vector<RenameMap> maps;- std::optional<Id> map_base;- if (heads.size() > 1) {- const auto bases = merge_bases(store, heads[0], heads[1]);- if (!bases.empty())- map_base = bases.front();- }- for (const auto &head : heads) {- auto t = tree_of(store, head);- terms.push_back(TreeTerm{true, t.has_value(), t.value_or(Id{})});- if (map_base)- maps.push_back(map_from(store, *map_base, head));- else- maps.push_back(RenameMap{});- }- for (std::size_t i = 1; i < heads.size(); ++i) {- const auto bases = merge_bases(store, heads[0], heads[i]);- auto bt = base_tree(repo, tx, store, bases, adjacent);- if (bt)- terms.push_back(TreeTerm{false, true, *bt});- else- terms.push_back(TreeTerm{false, false, Id{}});- maps.push_back(RenameMap{});- }- return treemerge(repo, tx, store, terms, maps, adjacent);-}--MergeOutcome rewrite_tree(const fs::path &repo, Txn &tx, Store &store,- const Id &old_commit, const Id &commit_tree,- const std::vector<Id> &old_parents,- const std::vector<Id> &new_parents,- const std::vector<Id> &new_parent_trees,- bool adjacent) {- std::vector<TreeTerm> terms;- std::vector<RenameMap> maps;- terms.push_back(TreeTerm{true, true, commit_tree});- if (!old_parents.empty())- maps.push_back(map_from(store, old_parents.front(), old_commit));- else- maps.push_back(RenameMap{});-- if (old_parents.empty()) {- for (const auto &tree : new_parent_trees) {- terms.push_back(TreeTerm{true, true, tree});- maps.push_back(RenameMap{});- }- terms.push_back(TreeTerm{false, false, Id{}});- maps.push_back(RenameMap{});- } else {- for (std::size_t i = 0; i < old_parents.size(); ++i) {- auto old_tree = tree_of(store, old_parents[i]);- const Id new_tree =- i < new_parent_trees.size() ? new_parent_trees[i] : Id{};- terms.push_back(TreeTerm{true, true, new_tree});- terms.push_back(- TreeTerm{false, old_tree.has_value(), old_tree.value_or(Id{})});- if (i < new_parents.size())- maps.push_back(map_from(store, old_parents[i], new_parents[i]));- else- maps.push_back(RenameMap{});- maps.push_back(RenameMap{});- }- }- return treemerge(repo, tx, store, terms, maps, adjacent);-}--Id make_commit(Txn &tx, Store &store, const fs::path &repo,- const std::vector<Id> &parents, const Id &root,- const ChangeId &change, const Sig &author,- const std::string &message, std::uint8_t renames_state,- const std::vector<KeyValue> &extra) {- Commit commit;- commit.version = 1;- commit.parents = parents;- commit.root_tree = root;- commit.change_id = change;- commit.author = author;- commit.committer = identity_signature(repo);- commit.message = message;- commit.renames_state = renames_state;- commit.extra = extra;- if (renames_state == RENAMES_RECORDED) {- for (std::size_t i = 0; i < parents.size(); ++i) {- auto parent_tree = tree_of(store, parents[i]);- auto detected =- detect_renames(store, &tx, parent_tree, std::optional<Id>{root}, 0, i);- for (auto &rename : detected)- commit.renames.push_back(std::move(rename));- }- }- return tx.add_object(TYPE_COMMIT, encode_commit(commit));-}--std::string rerere_suffix(std::size_t count) {- if (count == 0)- return std::string();- return " (rerere " + std::to_string(count) + ")";-}--std::string join_revs(const std::vector<std::string> &revs) {- std::string out;- for (std::size_t i = 0; i < revs.size(); ++i) {- if (i != 0)- out.push_back(' ');- out += revs[i];- }- return out;-}--bool adjacent_config(const fs::path &root) {- auto value = repo_config_value(root, "merge.adjacent");- return value && *value == "merge";-}--// ----------------------------------------------------------------------------// Tree editing-// -----------------------------------------------------------------------------std::optional<Id> tree_edit_into(Txn &tx, Store &store, const Id &tree_id,- std::string_view path, bool present,- std::uint8_t kind, const Id &target,- std::size_t depth) {- if (depth > 4096)- return std::nullopt;- auto body = read_body_any(store, &tx, TYPE_TREE, tree_id);- if (!body)- return std::nullopt;- auto tree = decode_tree(bytes_of(*body));- if (!tree)- return std::nullopt;- const std::size_t cut = path.find('/');- const std::size_t cut_pos = cut == std::string_view::npos ? path.size() : cut;- const std::string_view name = path.substr(0, cut_pos);- std::vector<TreeEntry> entries;- bool found = false;- for (const auto &entry : tree->entries) {- if (entry.name != name) {- entries.push_back(entry);- continue;- }- found = true;- if (cut_pos == path.size()) {- if (present)- entries.push_back(TreeEntry{entry.name, kind, target});- } else if (entry.kind == KIND_SUBTREE) {- auto child = tree_edit_into(tx, store, entry.target,- path.substr(cut_pos + 1), present, kind,- target, depth + 1);- if (child && !tree_empty_any(store, &tx, *child))- entries.push_back(TreeEntry{entry.name, KIND_SUBTREE, *child});- } else {- entries.push_back(entry);- }- }- if (!found && cut_pos == path.size() && present)- entries.push_back(TreeEntry{std::string(name), kind, target});- return add_tree(tx, entries);-}--std::optional<Id> tree_edit_replace(Txn &tx, Store &store, const Id &root,- std::string_view path, bool present,- std::uint8_t kind, const Id &target) {- auto edited =- tree_edit_into(tx, store, root, path, present, kind, target, 0);- if (!edited)- return std::nullopt;- return edited;-}--// ----------------------------------------------------------------------------// Conflicts-// -----------------------------------------------------------------------------std::string conflict_kind_label(const Conflict &conflict) {- for (const auto &value : conflict.adds) {- if (value.kind == KIND_SUBTREE)- return "tree";- }- for (const auto &value : conflict.removes) {- if (value.kind == KIND_SUBTREE)- return "tree";- }- for (const auto &value : conflict.adds) {- if (value.kind == 0)- return "delete/modify";- }- for (const auto &value : conflict.removes) {- if (value.kind == 0)- return "delete/modify";- }- return "text";-}--void print_range(std::size_t a, std::size_t b) {- if (a == b)- std::cout << a + 1;- else- std::cout << a + 1 << "-" << b;-}--std::optional<EditResult> conflict_ranges(Store &store, const Conflict &conflict,- bool adjacent) {- if (conflict.adds.size() != 2 || conflict.removes.size() != 1)- return std::nullopt;- const auto &ours = conflict.adds[0];- const auto &theirs = conflict.adds[1];- const auto &base = conflict.removes[0];- if (ours.kind == 0 || theirs.kind == 0 || base.kind == 0)- return std::nullopt;- if (ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE ||- base.kind == KIND_SUBTREE)- return std::nullopt;- return merge_blobs(store, nullptr, *base.target, *ours.target,- *theirs.target, adjacent);-}--std::vector<FlatEntry> flatten_store(Store &store, const Id &tree) {- return flatten_any_sorted(store, nullptr, std::optional<Id>{tree});-}--// ----------------------------------------------------------------------------// Commands-// -----------------------------------------------------------------------------int merge_command(const std::vector<std::string> &revs) {- if (revs.empty()) {- error_prefix();- std::cout << "merge requires at least one revision\n";- return 1;- }- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- 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());- if (!wc) {- error_prefix();- std::cout << "no working-copy commit to merge into\n";- return 1;- }-- std::vector<Id> parents{*wc};- bool failed = false;- for (const auto &rev : revs) {- auto resolved = resolve_revision(store, tx->view(), rev);- if (!resolved) {- failed = true;- continue;- }- if (same_id(*resolved, *wc)) {- error_prefix();- std::cout << "cannot merge a commit with itself\n";- failed = true;- continue;- }- parents.push_back(*resolved);- }- if (failed) {- error_prefix();- std::cout << "unknown revision\n";- return 1;- }-- const auto old_root = tree_of(store, *wc);- const bool adjacent = adjacent_config(*root);- MergeOutcome outcome =- merge_many(*root, *tx, store, parents, adjacent);- const Sig author = identity_signature(*root);- const Id new_id = make_commit(- *tx, store, *root, parents, outcome.tree, random_change_id(), author, "",- RENAMES_RECORDED, {});-- remove_head(tx->view(), *wc);- move_bookmarks(tx->view(), *wc, new_id);- set_workspace(tx->view(), new_id);- rebuild_heads(tx->view());- const std::string description =- "merge " + join_revs(revs) + rerere_suffix(outcome.rerere);- const auto status = tx->finish(description);- if (!status)- return 1;- store.refresh(*root);- (void)mark_native(*root, new_id);- if (old_root)- return checkout_materialize_commit(*root, store, old_root, outcome.tree);- return 0;-}--int rebase_command(const std::string &source, const std::string &dest) {- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- 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 src = resolve_revision(store, tx->view(), source);- auto dst = resolve_revision(store, tx->view(), dest);- if (!src || !dst) {- error_prefix();- std::cout << "unknown revision\n";- return 1;- }- const auto wc = working_copy_id(tx->view());- std::optional<Id> old_wc_root;- if (wc)- old_wc_root = tree_of(store, *wc);-- std::vector<Id> set;- for (const auto &commit : all_commits(store, tx->view())) {- if (is_ancestor(store, *src, commit))- set.push_back(commit);- }-- std::vector<Id> old_ids;- std::vector<Id> new_ids;- std::vector<Id> new_tree_ids;- std::vector<Id> remaining = set;- std::size_t rerere_total = 0;- const bool adjacent = adjacent_config(*root);- const Sig fallback_sig = identity_signature(*root);- (void)fallback_sig;-- while (!remaining.empty()) {- std::ptrdiff_t ready_idx = -1;- for (std::size_t i = 0; i < remaining.size(); ++i) {- bool ready = true;- auto loaded = load_commit(store, remaining[i]);- if (!loaded)- continue;- for (const auto &parent : loaded->commit.parents) {- if (contains_id_vec(set, parent) && !contains_id_vec(old_ids, parent) &&- !same_id(remaining[i], *src))- ready = false;- }- if (ready) {- ready_idx = static_cast<std::ptrdiff_t>(i);- break;- }- }- if (ready_idx < 0) {- error_prefix();- std::cout << "rebase could not order commits\n";- break;- }- const Id chosen = remaining[static_cast<std::size_t>(ready_idx)];- auto loaded = load_commit(store, chosen);- if (!loaded)- break;-- std::vector<Id> new_parents;- std::vector<Id> new_parent_trees;- for (std::size_t pi = 0; pi < loaded->commit.parents.size(); ++pi) {- const Id parent = loaded->commit.parents[pi];- if (pi == 0 && same_id(chosen, *src)) {- new_parents.push_back(*dst);- new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));- continue;- }- bool mapped = false;- for (std::size_t mi = 0; mi < old_ids.size(); ++mi) {- if (same_id(old_ids[mi], parent)) {- new_parents.push_back(new_ids[mi]);- new_parent_trees.push_back(new_tree_ids[mi]);- mapped = true;- break;- }- }- if (!mapped) {- new_parents.push_back(parent);- new_parent_trees.push_back(tree_of(store, parent).value_or(Id{}));- }- }- if (loaded->commit.parents.empty()) {- new_parents.push_back(*dst);- new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));- }-- MergeOutcome outcome =- rewrite_tree(*root, *tx, store, chosen, loaded->commit.root_tree,- loaded->commit.parents, new_parents, new_parent_trees,- adjacent);- rerere_total += outcome.rerere;- const Id new_id =- make_commit(*tx, store, *root, new_parents, outcome.tree,- loaded->commit.change_id, loaded->commit.author,- loaded->commit.message, loaded->commit.renames_state,- loaded->commit.extra);- old_ids.push_back(chosen);- new_ids.push_back(new_id);- new_tree_ids.push_back(outcome.tree);- remaining.erase(remaining.begin() +- static_cast<std::ptrdiff_t>(ready_idx));- }-- auto remap = [&](std::optional<Id> &id) {- if (!id)- return;- for (std::size_t i = 0; i < old_ids.size(); ++i) {- if (same_id(old_ids[i], *id)) {- id = new_ids[i];- return;- }- }- };- for (auto &bookmark : tx->view().bookmarks) {- for (auto &id : bookmark.targets.adds)- remap(id);- for (auto &id : bookmark.targets.removes)- remap(id);- }- for (auto &tag : tx->view().tags) {- std::optional<Id> target = tag.target;- remap(target);- if (target)- tag.target = *target;- }- for (auto &workspace : tx->view().working_copies) {- std::optional<Id> target = workspace.target;- remap(target);- if (target)- workspace.target = *target;- }- rebuild_heads(tx->view());- const auto status =- tx->finish("rebase " + source + " onto " + dest +- rerere_suffix(rerere_total));- if (!status)- return 1;- for (const auto &id : new_ids)- (void)mark_native(*root, id);- if (wc) {- for (std::size_t i = 0; i < old_ids.size(); ++i) {- if (same_id(old_ids[i], *wc)) {- Store refreshed = Store::open_all(*root);- return checkout_materialize_commit(*root, refreshed, old_wc_root,- new_tree_ids[i]);- }- }- }- return 0;-}--int xs_command(bool porcelain) {- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- 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::vector<std::pair<std::string, Conflict>> items;- if (const auto wc = working_copy_id(*view)) {- auto loaded = load_commit(store, *wc);- if (loaded) {- for (const auto &entry : flatten_store(store, loaded->commit.root_tree)) {- if (entry.kind != KIND_CONFLICT)- continue;- auto body = store.read_body(entry.target, TYPE_CONFLICT);- if (!body)- continue;- auto conflict = decode_conflict(bytes_of(*body));- if (!conflict)- continue;- items.emplace_back(entry.path, std::move(*conflict));- }- }- }- const bool adjacent = adjacent_config(*root);- bool first = true;- for (const auto &[path, conflict] : items) {- const std::string kind = conflict_kind_label(conflict);- auto ranges = conflict_ranges(store, conflict, adjacent);- if (porcelain) {- std::cout << path << "\t" << kind << "\t";- if (ranges) {- for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {- if (i > 0)- std::cout << ",";- print_range(ranges->ranges[i].base_start,- ranges->ranges[i].base_end);- }- std::cout << "\t";- for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {- if (i > 0)- std::cout << ",";- print_range(ranges->ranges[i].ours_start,- ranges->ranges[i].ours_end);- }- std::cout << "\t";- for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {- if (i > 0)- std::cout << ",";- print_range(ranges->ranges[i].theirs_start,- ranges->ranges[i].theirs_end);- }- } else {- std::cout << "\t\t";- }- std::cout << "\n";- } else {- std::cout << path << ": " << kind << " conflict";- if (ranges && !ranges->ranges.empty()) {- std::cout << " (";- for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {- if (i > 0)- std::cout << ", ";- std::cout << "base ";- print_range(ranges->ranges[i].base_start,- ranges->ranges[i].base_end);- std::cout << ", ours ";- print_range(ranges->ranges[i].ours_start,- ranges->ranges[i].ours_end);- std::cout << ", theirs ";- print_range(ranges->ranges[i].theirs_start,- ranges->ranges[i].theirs_end);- }- std::cout << ")";- }- std::cout << "\n";- }- first = false;- }- if (first) {- info_prefix();- std::cout << "no conflicts\n";- }- return 0;-}--std::string shell_replace(std::string_view command, std::string_view key,- const std::string &value) {- std::string out;- std::size_t i = 0;- while (i < command.size()) {- if (i + key.size() <= command.size() &&- command.compare(i, key.size(), key) == 0) {- out.push_back('\'');- out += value;- out.push_back('\'');- i += key.size();- } else {- out.push_back(command[i]);- ++i;- }- }- return out;-}--bool run_tool(const fs::path &root, std::string_view command,- std::string_view path) {- const std::string base = path_to_bytes(root / path_from_bytes(path));- std::string expanded(command);- expanded = shell_replace(expanded, "$BASE", base + ".base");- expanded = shell_replace(expanded, "$OURS", base + ".ours");- expanded = shell_replace(expanded, "$THEIRS", base + ".theirs");- expanded = shell_replace(expanded, "$OUTPUT", base);- return std::system(expanded.c_str()) == 0;-}--void delete_sidecar(const fs::path &root, std::string_view path,- std::string_view suffix) {- std::string full(path);- full += suffix;- (void)remove_file(root / path_from_bytes(full));-}--void delete_sidecars(const fs::path &root, std::string_view path) {- delete_sidecar(root, path, ".base");- delete_sidecar(root, path, ".ours");- delete_sidecar(root, path, ".theirs");- for (int n = 2; n <= 64; ++n) {- delete_sidecar(root, path, ".base" + std::to_string(n));- delete_sidecar(root, path, ".theirs" + std::to_string(n));- }-}--std::optional<ConflictValue> choose_value(const Conflict &conflict,- std::string_view take) {- if (take == "ours" && !conflict.adds.empty())- return conflict.adds[0];- if (take == "theirs" && conflict.adds.size() > 1)- return conflict.adds[1];- if (take == "base" && !conflict.removes.empty())- return conflict.removes[0];- return std::nullopt;-}--int resolve_command(std::string_view take, std::string_view tool,- const std::vector<std::string> &paths) {- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- 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());- 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 Id old_root = loaded->commit.root_tree;- Id mut_root = old_root;- bool resolved_any = false;- std::vector<std::string> normalized_paths;-- const auto cwd = cwd_relative(*root);- for (const auto &arg : paths) {- auto norm = cwd ? pathspec_normalize(*root, *cwd, arg) : std::nullopt;- if (!norm || norm->empty()) {- error_prefix();- std::cout << "invalid path\n";- continue;- }- normalized_paths.push_back(*norm);- auto flat = flatten_store(store, mut_root);- const FlatEntry *entry = find_flat_entry(flat, *norm);- if (!entry || entry->kind != KIND_CONFLICT) {- error_prefix();- std::cout << "not a conflicted path: " << *norm << "\n";- continue;- }- auto body = store.read_body(entry->target, TYPE_CONFLICT);- if (!body)- continue;- auto conflict = decode_conflict(bytes_of(*body));- if (!conflict)- continue;-- bool present = false;- std::uint8_t new_kind = KIND_FILE;- std::optional<Id> new_target;- if (auto chosen = choose_value(*conflict, take)) {- if (chosen->kind != 0) {- present = true;- new_kind = chosen->kind;- new_target = chosen->target;- }- } else if (!tool.empty()) {- if (run_tool(*root, tool, *norm)) {- if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {- new_target = add_blob(*tx, bytes_of(*data));- present = true;- new_kind = KIND_FILE;- }- }- } else {- if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {- new_target = add_blob(*tx, bytes_of(*data));- present = true;- new_kind = KIND_FILE;- }- }- if (present) {- if (auto info = stat_path(*root / path_from_bytes(*norm))) {- if (info->executable)- new_kind = KIND_EXECUTABLE;- }- if (new_kind == KIND_FILE || new_kind == KIND_EXECUTABLE) {- if (auto conflict_body =- store.read_body(entry->target, TYPE_CONFLICT)) {- resolution_record(*root, bytes_of(*conflict_body),- *new_target);- }- }- }- auto replaced = tree_edit_replace(*tx, store, mut_root, *norm, present,- new_kind, new_target.value_or(Id{}));- if (replaced) {- mut_root = *replaced;- resolved_any = true;- }- }-- if (!resolved_any) {- return 1;- }-- Commit commit = loaded->commit;- commit.root_tree = mut_root;- commit.committer = identity_signature(*root);- const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));- 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("resolve");- if (!status)- return 1;- Store refreshed = Store::open_all(*root);- const int materialized =- checkout_materialize_commit(*root, refreshed, old_root, mut_root);- if (materialized != 0)- return materialized;- for (const auto &path : normalized_paths)- delete_sidecars(*root, path);- return 0;-}--} // namespace--// ----------------------------------------------------------------------------// Argument parsing-// -----------------------------------------------------------------------------int merge_run(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.empty() && arg.front() == '-') {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- revs.push_back(arg);- }- }- return merge_command(revs);-}--int rebase_run(const std::vector<std::string> &args) {- std::string source;- std::string dest;- 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 == "-s" || arg == "-source")) {- if (i + 1 >= args.size()) {- error_prefix();- std::cout << arg << " requires a revision\n";- return 1;- }- source = args[++i];- } else if (!end_flags && (arg == "-d" || arg == "-destination")) {- if (i + 1 >= args.size()) {- error_prefix();- std::cout << arg << " requires a revision\n";- return 1;- }- dest = args[++i];- } else if (!end_flags && !arg.empty() && arg.front() == '-') {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- error_prefix();- std::cout << "unexpected argument: " << arg << "\n";- return 1;- }- }- if (source.empty() || dest.empty()) {- error_prefix();- std::cout << "rebase requires -s <rev> and -d <rev>\n";- return 1;- }- return rebase_command(source, dest);-}--int xs_run(const std::vector<std::string> &args) {- bool porcelain = 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 == "-porcelain" || arg == "-p")) {- porcelain = true;- } else if (!end_flags && !arg.empty() && arg.front() == '-') {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- error_prefix();- std::cout << "unexpected argument: " << arg << "\n";- return 1;- }- }- return xs_command(porcelain);-}--int resolve_run(const std::vector<std::string> &args) {- std::string take;- std::string tool;- bool list_only = false;- std::vector<std::string> paths;- 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 == "-list" || arg == "-l")) {- list_only = true;- } else if (!end_flags && (arg == "-take" || arg == "-t")) {- if (i + 1 >= args.size()) {- error_prefix();- std::cout << arg << " requires ours, theirs, or base\n";- return 1;- }- take = args[++i];- } else if (!end_flags && arg == "-tool") {- if (i + 1 >= args.size()) {- error_prefix();- std::cout << arg << " requires a command\n";- return 1;- }- tool = args[++i];- } else if (!end_flags && !arg.empty() && arg.front() == '-') {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- paths.push_back(arg);- }- }- if (list_only)- return xs_command(false);- if (paths.empty()) {- error_prefix();- std::cout << "resolve requires at least one path\n";- return 1;- }- return resolve_command(take, tool, paths);-}--} // namespace vn--- a/veins-cpprewrite/src/merge.h+++ /dev/null@@ -1,27 +0,0 @@-#pragma once--#include "store.h"--#include <optional>-#include <string>-#include <vector>--namespace vn {--// Detect renames between two trees. `tx` may be provided so trees and blobs that-// have only been added to the pending transaction are visible. Results are-// sorted by (parent_index, to_path).-std::vector<Rename> detect_renames(Store &store, Txn *tx,- std::optional<Id> old_tree,- std::optional<Id> new_tree, int similar_pct,- std::uint64_t parent_index);--// Configured rename similarity threshold (0 disables detection).-int rename_similar_pct(const fs::path &root);--int merge_run(const std::vector<std::string> &args);-int rebase_run(const std::vector<std::string> &args);-int xs_run(const std::vector<std::string> &args);-int resolve_run(const std::vector<std::string> &args);--} // namespace vn--- a/veins-cpprewrite/src/net.cpp+++ /dev/null@@ -1,753 +0,0 @@-#include "net.h"--#include <algorithm>-#include <cerrno>-#include <climits>-#include <cstring>--#if defined(_WIN32)-#ifndef WIN32_LEAN_AND_MEAN-#define WIN32_LEAN_AND_MEAN-#endif-#ifndef NOMINMAX-#define NOMINMAX-#endif-#include <winsock2.h>-#include <ws2tcpip.h>-#include <windows.h>-#include <io.h>-#endif--#include <openssl/err.h>-#include <openssl/ssl.h>-#include <openssl/x509.h>-#include <openssl/x509_vfy.h>--#if !defined(_WIN32)-#include <arpa/inet.h>-#include <fcntl.h>-#include <limits.h>-#include <netdb.h>-#include <netinet/in.h>-#include <signal.h>-#include <sys/socket.h>-#include <sys/types.h>-#include <sys/wait.h>-#include <unistd.h>-#if defined(__APPLE__)-#include <mach-o/dyld.h>-#endif-#endif--namespace vn::net {--namespace {--#if defined(_WIN32)-void ensure_winsock() {- static const bool initialized = [] {- WSADATA data{};- return WSAStartup(MAKEWORD(2, 2), &data) == 0;- }();- (void)initialized;-}--std::wstring widen_utf8(std::string_view text) {- if (text.empty())- return {};- const int len = MultiByteToWideChar(CP_UTF8, 0, text.data(),- static_cast<int>(text.size()), nullptr, 0);- std::wstring out(static_cast<std::size_t>(len), L'\0');- MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()),- out.data(), len);- return out;-}--// Quote one argument for CreateProcessW's command line.-std::wstring quote_windows_arg(std::wstring_view arg) {- if (!arg.empty() &&- arg.find_first_of(L" \t\n\v\"") == std::wstring_view::npos)- return std::wstring(arg);- std::wstring out = L"\"";- for (std::size_t i = 0; i < arg.size(); ++i) {- std::size_t backslashes = 0;- while (i < arg.size() && arg[i] == L'\\') {- ++backslashes;- ++i;- }- if (i == arg.size()) {- out.append(backslashes * 2, L'\\');- break;- }- if (arg[i] == L'"') {- out.append(backslashes * 2 + 1, L'\\');- out.push_back(L'"');- } else {- out.append(backslashes, L'\\');- out.push_back(arg[i]);- }- }- out.push_back(L'"');- return out;-}--std::wstring build_windows_command_line(- const std::vector<std::string> &argv) {- std::wstring out;- for (std::size_t i = 0; i < argv.size(); ++i) {- if (i != 0)- out.push_back(L' ');- out += quote_windows_arg(widen_utf8(argv[i]));- }- return out;-}-#endif--std::string ssl_error_string() {- unsigned long code = ERR_get_error();- if (code == 0)- return {};- char buffer[256];- ERR_error_string_n(code, buffer, sizeof(buffer));- return std::string(buffer);-}--} // namespace--// ----------------------------------------------------------------------------// Stream-// -----------------------------------------------------------------------------Stream::Stream(Stream &&other) noexcept { *this = std::move(other); }--Stream &Stream::operator=(Stream &&other) noexcept {- if (this == &other)- return *this;- close();- kind_ = other.kind_;- fd_in_ = other.fd_in_;- fd_out_ = other.fd_out_;- ssl_ = other.ssl_;-#if defined(_WIN32)- process_ = other.process_;- process_id_ = other.process_id_;-#else- pid_ = other.pid_;-#endif- open_ = other.open_;- other.open_ = false;- other.ssl_ = nullptr;- other.fd_in_ = 0;- other.fd_out_ = 0;-#if defined(_WIN32)- other.process_ = nullptr;- other.process_id_ = 0;-#else- other.pid_ = 0;-#endif- return *this;-}--Stream::~Stream() { close(); }--Stream Stream::stdio_stream() {- Stream stream;- stream.kind_ = Kind::Stdio;-#if defined(_WIN32)- stream.fd_in_ =- reinterpret_cast<Socket>(GetStdHandle(STD_INPUT_HANDLE));- stream.fd_out_ =- reinterpret_cast<Socket>(GetStdHandle(STD_OUTPUT_HANDLE));-#else- stream.fd_in_ = 0;- stream.fd_out_ = 1;-#endif- stream.open_ = true;- return stream;-}--Stream Stream::fd_stream(Socket fd) {- Stream stream;- stream.kind_ = Kind::Fd;- stream.fd_in_ = fd;- stream.fd_out_ = fd;- stream.open_ = true;- return stream;-}--Stream Stream::tls_stream(Socket fd, void *ssl) {- Stream stream;- stream.kind_ = Kind::Tls;- stream.fd_in_ = fd;- stream.fd_out_ = fd;- stream.ssl_ = ssl;- stream.open_ = true;- return stream;-}--std::optional<Stream> Stream::spawn_argv(const std::vector<std::string> &argv) {- return vn::net::spawn_argv(argv);-}--std::int64_t Stream::read(void *buffer, std::size_t count) {- if (!open_ || count == 0)- return count == 0 ? 0 : -1;- if (kind_ == Kind::Tls) {- const int n = SSL_read(static_cast<SSL *>(ssl_), buffer,- static_cast<int>(std::min<std::size_t>(- count, static_cast<std::size_t>(INT_MAX))));- if (n > 0)- return n;- if (n == 0)- return 0;- return -1;- }-#if defined(_WIN32)- if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {- DWORD got = 0;- if (!ReadFile(reinterpret_cast<HANDLE>(fd_in_), buffer,- static_cast<DWORD>(std::min<std::size_t>(- count, static_cast<std::size_t>(MAXDWORD))),- &got, nullptr))- return -1;- return static_cast<std::int64_t>(got);- }- const int n = recv(static_cast<SOCKET>(fd_in_),- static_cast<char *>(buffer),- static_cast<int>(std::min<std::size_t>(- count, static_cast<std::size_t>(INT_MAX))),- 0);- return n;-#else- const int fd = kind_ == Kind::Stdio ? 0 : static_cast<int>(fd_in_);- ssize_t n = 0;- do {- n = ::read(fd, buffer, count);- } while (n < 0 && errno == EINTR);- return n;-#endif-}--bool Stream::write_all(Bytes data) {- if (!open_)- return false;- std::size_t offset = 0;- while (offset < data.size()) {- const std::size_t remaining = data.size() - offset;- std::int64_t written = -1;- if (kind_ == Kind::Tls) {- const int n = SSL_write(- static_cast<SSL *>(ssl_), data.data() + offset,- static_cast<int>(std::min<std::size_t>(remaining,- static_cast<std::size_t>(- INT_MAX))));- written = n;- }-#if defined(_WIN32)- else if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {- DWORD count = 0;- if (!WriteFile(reinterpret_cast<HANDLE>(fd_out_), data.data() + offset,- static_cast<DWORD>(std::min<std::size_t>(- remaining, static_cast<std::size_t>(MAXDWORD))),- &count, nullptr))- return false;- written = static_cast<std::int64_t>(count);- } else {- const int n = send(- static_cast<SOCKET>(fd_out_),- reinterpret_cast<const char *>(data.data() + offset),- static_cast<int>(std::min<std::size_t>(- remaining, static_cast<std::size_t>(INT_MAX))),- 0);- written = n;- }-#else- else {- ssize_t n = 0;- do {- n = ::write(kind_ == Kind::Stdio ? 1 : static_cast<int>(fd_out_),- data.data() + offset, remaining);- } while (n < 0 && errno == EINTR);- written = n;- }-#endif- if (written <= 0)- return false;- offset += static_cast<std::size_t>(written);- }- return true;-}--void Stream::close() {- if (!open_)- return;- open_ = false;- if (kind_ == Kind::Tls) {- if (ssl_)- tls_free(ssl_);- ssl_ = nullptr;-#if defined(_WIN32)- closesocket(static_cast<SOCKET>(fd_in_));-#else- if (static_cast<int>(fd_in_) > 2)- ::close(static_cast<int>(fd_in_));-#endif- return;- }- if (kind_ == Kind::Proc) {-#if defined(_WIN32)- if (fd_in_ != 0)- CloseHandle(reinterpret_cast<HANDLE>(fd_in_));- if (fd_out_ != 0)- CloseHandle(reinterpret_cast<HANDLE>(fd_out_));- if (process_) {- WaitForSingleObject(reinterpret_cast<HANDLE>(process_), INFINITE);- CloseHandle(reinterpret_cast<HANDLE>(process_));- process_ = nullptr;- }-#else- if (static_cast<int>(fd_in_) > 2)- ::close(static_cast<int>(fd_in_));- if (static_cast<int>(fd_out_) > 2)- ::close(static_cast<int>(fd_out_));- if (pid_ > 0) {- int status = 0;- while (waitpid(pid_, &status, 0) < 0 && errno == EINTR) {- }- pid_ = 0;- }-#endif- return;- }- if (kind_ == Kind::Fd) {-#if defined(_WIN32)- closesocket(static_cast<SOCKET>(fd_in_));-#else- if (static_cast<int>(fd_in_) > 2)- ::close(static_cast<int>(fd_in_));-#endif- }-}--// ----------------------------------------------------------------------------// Process spawning-// -----------------------------------------------------------------------------#if defined(_WIN32)-std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {- if (argv.empty())- return std::nullopt;- ensure_winsock();- SECURITY_ATTRIBUTES attributes{};- attributes.nLength = sizeof(attributes);- attributes.bInheritHandle = TRUE;- HANDLE child_stdin_read = nullptr;- HANDLE child_stdin_write = nullptr;- HANDLE child_stdout_read = nullptr;- HANDLE child_stdout_write = nullptr;- if (!CreatePipe(&child_stdin_read, &child_stdin_write, &attributes, 0) ||- !CreatePipe(&child_stdout_read, &child_stdout_write, &attributes, 0)) {- if (child_stdin_read)- CloseHandle(child_stdin_read);- if (child_stdin_write)- CloseHandle(child_stdin_write);- return std::nullopt;- }- SetHandleInformation(child_stdin_write, HANDLE_FLAG_INHERIT, 0);- SetHandleInformation(child_stdout_read, HANDLE_FLAG_INHERIT, 0);- STARTUPINFOW startup{};- startup.cb = sizeof(startup);- startup.dwFlags = STARTF_USESTDHANDLES;- startup.hStdInput = child_stdin_read;- startup.hStdOutput = child_stdout_write;- startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);- PROCESS_INFORMATION process{};- std::wstring command_line = build_windows_command_line(argv);- const BOOL started =- CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0,- nullptr, nullptr, &startup, &process);- CloseHandle(child_stdin_read);- CloseHandle(child_stdout_write);- if (!started) {- CloseHandle(child_stdin_write);- CloseHandle(child_stdout_read);- return std::nullopt;- }- CloseHandle(process.hThread);- Stream stream;- stream.kind_ = Stream::Kind::Proc;- stream.fd_in_ = reinterpret_cast<Socket>(child_stdout_read);- stream.fd_out_ = reinterpret_cast<Socket>(child_stdin_write);- stream.process_ = process.hProcess;- stream.process_id_ = process.dwProcessId;- stream.open_ = true;- return stream;-}-#else-std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {- if (argv.empty())- return std::nullopt;- int in_pipe[2];- int out_pipe[2];- if (::pipe(in_pipe) != 0)- return std::nullopt;- if (::pipe(out_pipe) != 0) {- ::close(in_pipe[0]);- ::close(in_pipe[1]);- return std::nullopt;- }- std::vector<char *> raw;- raw.reserve(argv.size() + 1);- for (const auto &item : argv)- raw.push_back(const_cast<char *>(item.c_str()));- raw.push_back(nullptr);- const pid_t pid = ::fork();- if (pid == 0) {- (void)::dup2(in_pipe[0], 0);- (void)::dup2(out_pipe[1], 1);- ::close(in_pipe[0]);- ::close(in_pipe[1]);- ::close(out_pipe[0]);- ::close(out_pipe[1]);- ::execvp(raw[0], raw.data());- ::_exit(127);- }- ::close(in_pipe[0]);- ::close(out_pipe[1]);- if (pid < 0) {- ::close(in_pipe[1]);- ::close(out_pipe[0]);- return std::nullopt;- }- Stream stream;- stream.kind_ = Stream::Kind::Proc;- stream.fd_in_ = out_pipe[0];- stream.fd_out_ = in_pipe[1];- stream.pid_ = pid;- stream.open_ = true;- return stream;-}-#endif--// ----------------------------------------------------------------------------// TCP-// -----------------------------------------------------------------------------std::optional<Socket> tcp_connect(std::string_view host, int port) {- if (host.empty())- return std::nullopt;-#if defined(_WIN32)- ensure_winsock();-#endif- addrinfo hints{};- hints.ai_family = AF_UNSPEC;- hints.ai_socktype = SOCK_STREAM;- const std::string service = std::to_string(port);- const std::string host_text(host);- addrinfo *results = nullptr;- if (getaddrinfo(host_text.c_str(), service.c_str(), &hints, &results) != 0)- return std::nullopt;- Socket connected = INVALID_SOCKET_VALUE;- for (addrinfo *it = results; it != nullptr; it = it->ai_next) {-#if defined(_WIN32)- SOCKET socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);- if (socket == INVALID_SOCKET)- continue;- if (::connect(socket, it->ai_addr, static_cast<int>(it->ai_addrlen)) == 0) {- connected = static_cast<Socket>(socket);- break;- }- closesocket(socket);-#else- const int socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);- if (socket < 0)- continue;- if (::connect(socket, it->ai_addr, it->ai_addrlen) == 0) {- connected = socket;- break;- }- ::close(socket);-#endif- }- freeaddrinfo(results);- return connected == INVALID_SOCKET_VALUE- ? std::nullopt- : std::optional<Socket>(connected);-}--Socket tcp_listen(int port, int backlog) {-#if defined(_WIN32)- ensure_winsock();- SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);- if (listener == INVALID_SOCKET)- return INVALID_SOCKET_VALUE;- BOOL reuse = TRUE;- setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,- reinterpret_cast<const char *>(&reuse), sizeof(reuse));- sockaddr_in address{};- address.sin_family = AF_INET;- address.sin_addr.s_addr = htonl(INADDR_ANY);- address.sin_port = htons(static_cast<u_short>(port));- if (::bind(listener, reinterpret_cast<sockaddr *>(&address),- sizeof(address)) == SOCKET_ERROR ||- ::listen(listener, backlog) == SOCKET_ERROR) {- closesocket(listener);- return INVALID_SOCKET_VALUE;- }- return static_cast<Socket>(listener);-#else- const int listener = ::socket(AF_INET, SOCK_STREAM, 0);- if (listener < 0)- return INVALID_SOCKET_VALUE;- int reuse = 1;- (void)setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));- sockaddr_in address{};- address.sin_family = AF_INET;- address.sin_addr.s_addr = htonl(INADDR_ANY);- address.sin_port = htons(static_cast<std::uint16_t>(port));- if (::bind(listener, reinterpret_cast<sockaddr *>(&address),- sizeof(address)) != 0 ||- ::listen(listener, backlog) != 0) {- ::close(listener);- return INVALID_SOCKET_VALUE;- }- return listener;-#endif-}--std::optional<Socket> tcp_accept(Socket listener) {-#if defined(_WIN32)- const SOCKET accepted = ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);- if (accepted == INVALID_SOCKET)- return std::nullopt;- return static_cast<Socket>(accepted);-#else- const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);- if (accepted < 0)- return std::nullopt;- return accepted;-#endif-}--void close_socket(Socket socket) {- if (socket == INVALID_SOCKET_VALUE)- return;-#if defined(_WIN32)- closesocket(static_cast<SOCKET>(socket));-#else- if (static_cast<int>(socket) > 2)- ::close(static_cast<int>(socket));-#endif-}--// ----------------------------------------------------------------------------// Process/platform helpers-// -----------------------------------------------------------------------------void ignore_sigpipe() {-#if !defined(_WIN32)- (void)::signal(SIGPIPE, SIG_IGN);-#endif-}--fs::path self_exe() {-#if defined(_WIN32)- std::wstring buffer(32768, L'\0');- const DWORD len =- GetModuleFileNameW(nullptr, buffer.data(),- static_cast<DWORD>(buffer.size()));- if (len > 0) {- buffer.resize(len);- return fs::path(buffer);- }- return fs::path("vn.exe");-#elif defined(__APPLE__)- std::uint32_t size = 0;- _NSGetExecutablePath(nullptr, &size);- std::string buffer(size, '\0');- if (_NSGetExecutablePath(buffer.data(), &size) == 0) {- char resolved[PATH_MAX];- if (::realpath(buffer.c_str(), resolved))- return fs::path(resolved);- buffer.resize(std::strlen(buffer.c_str()));- return fs::path(buffer);- }- return fs::path("vn");-#else- std::string buffer(4096, '\0');- const ssize_t len = ::readlink("/proc/self/exe", buffer.data(),- buffer.size() - 1);- if (len > 0) {- buffer.resize(static_cast<std::size_t>(len));- return fs::path(buffer);- }- return fs::path("vn");-#endif-}--std::string quote_shell(std::string_view word) {- std::string out;- out.reserve(word.size() + 2);- out.push_back('\'');- for (char c : word) {- if (c == '\'')- out += "'\\''";- else- out.push_back(c);- }- out.push_back('\'');- return out;-}--std::string build_shell_command(const std::vector<std::string> &parts) {- std::string out;- for (const auto &part : parts) {- if (!out.empty())- out.push_back(' ');- out += quote_shell(part);- }- return out;-}--// ----------------------------------------------------------------------------// TLS-// -----------------------------------------------------------------------------void *tls_server_ctx(std::string_view cert_path, std::string_view key_path) {- SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());- if (!ctx)- return nullptr;- if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1)- goto fail;- if (SSL_CTX_use_certificate_chain_file(ctx,- std::string(cert_path).c_str()) != 1)- goto fail;- if (SSL_CTX_use_PrivateKey_file(ctx, std::string(key_path).c_str(),- SSL_FILETYPE_PEM) != 1)- goto fail;- if (SSL_CTX_check_private_key(ctx) != 1)- goto fail;- return ctx;-fail:- SSL_CTX_free(ctx);- return nullptr;-}--void *tls_client_ctx(bool pinned) {- SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());- if (!ctx)- return nullptr;- if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {- SSL_CTX_free(ctx);- return nullptr;- }- if (pinned) {- SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);- return ctx;- }- SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);- if (SSL_CTX_set_default_verify_paths(ctx) != 1) {- SSL_CTX_free(ctx);- return nullptr;- }- return ctx;-}--void *tls_accept(void *ctx, Socket fd) {- SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));- if (!ssl)- return nullptr;- if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1 ||- SSL_accept(ssl) != 1) {- SSL_free(ssl);- return nullptr;- }- return ssl;-}--void *tls_connect(void *ctx, Socket fd, std::string_view host) {- SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));- if (!ssl)- return nullptr;- if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1) {- SSL_free(ssl);- return nullptr;- }- if (!host.empty()) {- const std::string text(host);- SSL_set_tlsext_host_name(ssl, text.c_str());- X509_VERIFY_PARAM *param = SSL_get0_param(ssl);- X509_VERIFY_PARAM_set1_host(param, text.c_str(), 0);- }- if (SSL_connect(ssl) != 1) {- SSL_free(ssl);- return nullptr;- }- return ssl;-}--bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len) {- static constexpr char label[] = "EXPORTER-veins-auth/1";- return SSL_export_keying_material(static_cast<SSL *>(ssl), out, len, label,- sizeof(label) - 1, nullptr, 0, 0) == 1;-}--bool tls_peer_sha256(void *ssl, std::uint8_t *out) {- X509 *cert = SSL_get1_peer_certificate(static_cast<SSL *>(ssl));- if (!cert)- return false;- unsigned int len = 0;- const bool ok =- X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;- X509_free(cert);- return ok;-}--void tls_free(void *ssl) {- if (!ssl)- return;- SSL_shutdown(static_cast<SSL *>(ssl));- SSL_free(static_cast<SSL *>(ssl));-}--void tls_ctx_free(void *ctx) {- if (ctx)- SSL_CTX_free(static_cast<SSL_CTX *>(ctx));-}--std::string tls_error() { return ssl_error_string(); }--std::string to_hex(Bytes data) {- static constexpr char digits[] = "0123456789abcdef";- std::string out;- out.reserve(data.size() * 2);- for (std::uint8_t byte : data) {- out.push_back(digits[byte >> 4]);- out.push_back(digits[byte & 15]);- }- return out;-}--bool hex_equal(std::string_view a, std::string_view b) {- auto skip = [](std::string_view text, std::size_t &index) {- while (index < text.size() && text[index] == ':')- ++index;- };- std::size_t ai = 0;- std::size_t bi = 0;- for (;;) {- skip(a, ai);- skip(b, bi);- if (ai >= a.size() || bi >= b.size())- return ai >= a.size() && bi >= b.size();- auto lower = [](char c) {- return static_cast<char>((c >= 'A' && c <= 'Z') ? c + 32 : c);- };- if (lower(a[ai]) != lower(b[bi]))- return false;- ++ai;- ++bi;- }-}--} // namespace vn::net--- a/veins-cpprewrite/src/net.h+++ /dev/null@@ -1,102 +0,0 @@-#pragma once--#include "common.h"--#include <cstdint>-#include <optional>-#include <string>-#include <string_view>-#include <vector>--namespace vn::net {--#if defined(_WIN32)-using Socket = std::uintptr_t;-constexpr Socket INVALID_SOCKET_VALUE = static_cast<Socket>(~0ull);-#else-using Socket = int;-constexpr Socket INVALID_SOCKET_VALUE = -1;-#endif--// A reliable, ordered byte stream over stdio, a file descriptor/socket, TLS,-// or a child process.-class Stream {-public:- enum class Kind : std::uint8_t { Stdio, Fd, Tls, Proc };-- Stream() = default;- ~Stream();-- Stream(Stream &&other) noexcept;- Stream &operator=(Stream &&other) noexcept;- Stream(const Stream &) = delete;- Stream &operator=(const Stream &) = delete;-- static Stream stdio_stream();- static Stream fd_stream(Socket fd);- static Stream tls_stream(Socket fd, void *ssl);- static std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);-- friend std::optional<Stream>- spawn_argv(const std::vector<std::string> &argv);-- [[nodiscard]] Kind kind() const { return kind_; }- [[nodiscard]] void *ssl() const { return ssl_; }- [[nodiscard]] Socket fd() const { return fd_in_; }- [[nodiscard]] bool valid() const { return open_; }-- // Returns the number of bytes read, 0 at clean end of stream, -1 on error.- std::int64_t read(void *buffer, std::size_t count);- bool write_all(Bytes data);- bool write_all(std::string_view text) {- return write_all(Bytes(reinterpret_cast<const std::uint8_t *>(text.data()),- text.size()));- }- void close();--private:- Kind kind_ = Kind::Stdio;- Socket fd_in_ = 0;- Socket fd_out_ = 0;- void *ssl_ = nullptr;-#if defined(_WIN32)- void *process_ = nullptr;- std::uint32_t process_id_ = 0;-#else- int pid_ = 0;-#endif- bool open_ = false;-};--// Run argv[0] with the given arguments. stdin/stdout are connected to the-// stream; stderr is inherited.-std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);--std::optional<Socket> tcp_connect(std::string_view host, int port);-Socket tcp_listen(int port, int backlog = 64);-std::optional<Socket> tcp_accept(Socket listener);-void close_socket(Socket socket);--void ignore_sigpipe();-fs::path self_exe();-std::string quote_shell(std::string_view word);-std::string build_shell_command(const std::vector<std::string> &parts);--// ----------------------------------------------------------------------------// TLS 1.3-// -----------------------------------------------------------------------------void *tls_server_ctx(std::string_view cert_path, std::string_view key_path);-void *tls_client_ctx(bool pinned);-void *tls_accept(void *ctx, Socket fd);-void *tls_connect(void *ctx, Socket fd, std::string_view host);-bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len);-bool tls_peer_sha256(void *ssl, std::uint8_t *out);-void tls_free(void *ssl);-void tls_ctx_free(void *ctx);-std::string tls_error();--std::string to_hex(Bytes data);-bool hex_equal(std::string_view a, std::string_view b);--} // namespace vn::net--- a/veins-cpprewrite/src/net_commands.cpp+++ /dev/null@@ -1,1296 +0,0 @@-#include "net_commands.h"--#include "auth.h"-#include "crypto.h"-#include "promisor.h"-#include "protocol.h"-#include "server.h"-#include "store.h"-#include "worktree.h"--#include <algorithm>-#include <cstddef>-#include <cstring>-#include <iostream>-#include <optional>-#include <set>-#include <string>-#include <vector>--namespace vn {--namespace {--bool starts_with(std::string_view text, std::string_view prefix) {- return text.size() >= prefix.size() && text.substr(0, prefix.size()) == prefix;-}--bool is_flag(std::string_view arg) { return !arg.empty() && arg.front() == '-'; }--std::string arg_at(const std::vector<std::string> &args, std::size_t index) {- return index < args.size() ? args[index] : std::string();-}--std::string trim_text(std::string_view text) {- std::size_t start = 0;- std::size_t end = text.size();- auto blank = [](char c) {- return c == ' ' || c == '\t' || c == '\r' || c == '\n';- };- while (start < end && blank(text[start]))- ++start;- while (end > start && blank(text[end - 1]))- --end;- return std::string(text.substr(start, end - start));-}--std::string remote_key(std::string_view remote, std::string_view field) {- std::string out = "remote.";- out += remote;- out.push_back('.');- out += field;- return out;-}--std::string last_segment(std::string_view path) {- while (path.size() > 1 && path.back() == '/')- path.remove_suffix(1);- const auto slash = path.rfind('/');- if (slash != std::string_view::npos && slash + 1 < path.size())- return std::string(path.substr(slash + 1));- if (!path.empty() && path != "/")- return std::string(path);- return "repo";-}--bool same_id(const Id &a, const Id &b) {- return std::memcmp(a.data(), b.data(), ID_LEN) == 0;-}--void report_client_error(const proto::Client &client,- std::string_view context) {- error_prefix();- if (!client.error().empty())- std::cout << context << ": " << client.error() << "\n";- else- std::cout << context << "\n";-}--std::optional<Id> default_target(const std::vector<proto::RefInfo> &refs) {- for (const auto &ref : refs) {- if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))- return ref.target;- }- for (const auto &ref : refs) {- if (ref.kind == 0)- return ref.target;- }- return std::nullopt;-}--std::vector<Id> selected_commits(const std::vector<proto::RefInfo> &refs,- std::string_view policy) {- std::vector<Id> out;- if (policy == "none")- return out;- if (policy == "head") {- if (auto target = default_target(refs))- out.push_back(*target);- return out;- }- for (const auto &ref : refs)- out.push_back(ref.target);- return out;-}--bool set_bookmark(View &view, std::string_view name, const Id &target) {- if (auto index = find_bookmark(view, name)) {- view.bookmarks[*index].targets.adds = {target};- view.bookmarks[*index].targets.removes.clear();- return true;- }- Bookmark bookmark;- bookmark.name = std::string(name);- bookmark.targets.adds = {target};- view.bookmarks.push_back(std::move(bookmark));- return true;-}--bool set_tag(View &view, std::string_view name, const Id &target) {- if (auto index = find_tag(view, name)) {- view.tags[*index].target = target;- return true;- }- view.tags.push_back(TagRef{std::string(name), target});- return true;-}--bool set_remote_ref(View &view, std::string_view remote, std::string_view name,- const Id &target) {- for (auto &ref : view.remote_refs) {- if (ref.remote == remote && ref.name == name) {- ref.target = target;- return true;- }- }- view.remote_refs.push_back(- RemoteRef{std::string(remote), std::string(name), target});- return true;-}--bool apply_refs(const fs::path &root, const std::vector<proto::RefInfo> &refs,- std::string_view remote, bool clone) {- Store store = Store::open_all(root);- auto tx = Txn::begin(root, store);- if (!tx)- return false;- for (const auto &ref : refs) {- if (ref.kind == 1) {- set_tag(tx->view(), ref.name, ref.target);- } else if (clone) {- set_bookmark(tx->view(), ref.name, ref.target);- } else {- set_remote_ref(tx->view(), remote, ref.name, ref.target);- if (!find_bookmark(tx->view(), ref.name))- set_bookmark(tx->view(), ref.name, ref.target);- }- }- rebuild_heads(tx->view());- if (clone) {- if (auto target = default_target(refs))- set_workspace(tx->view(), *target);- }- return tx->finish("clone").has_value();-}--struct Walker {- Walker(Store &store, bool want_objects)- : store(store), want_objects(want_objects) {}-- Store &store;- bool want_objects = false;- std::set<Id> blobs;- std::set<Id> conflicts;- std::set<Id> chunks;- std::set<Id> objects;- std::vector<Id> chunk_out;- std::vector<Id> object_out;-- void add_object(const Id &id) {- if (want_objects && objects.insert(id).second)- object_out.push_back(id);- }-- void walk_blob(const Id &id) {- if (!blobs.insert(id).second)- return;- add_object(id);- auto body = store.read_body(id, TYPE_BLOB);- if (!body)- return;- auto blob = decode_blob(bytes_of(*body));- if (!blob)- return;- if (blob->form == BlobForm::Leaf) {- for (const auto &entry : blob->entries) {- if (chunks.insert(entry.id).second)- chunk_out.push_back(entry.id);- add_object(entry.id);- }- } else if (blob->form == BlobForm::Interior) {- for (const auto &entry : blob->entries)- walk_blob(entry.id);- }- }-- void walk_conflict(const Id &id) {- if (!conflicts.insert(id).second)- return;- add_object(id);- auto body = store.read_body(id, TYPE_CONFLICT);- if (!body)- return;- auto conflict = decode_conflict(bytes_of(*body));- if (!conflict)- return;- for (const auto &value : conflict->adds) {- if (value.target)- walk_value(value.kind, *value.target);- }- for (const auto &value : conflict->removes) {- if (value.target)- walk_value(value.kind, *value.target);- }- }-- void walk_value(std::uint8_t kind, const Id &id) {- if (kind == KIND_SUBTREE)- walk_tree(id);- else if (kind == KIND_CONFLICT)- walk_conflict(id);- else- walk_blob(id);- }-- void walk_tree(const Id &id) {- add_object(id);- auto body = store.read_body(id, TYPE_TREE);- if (!body)- return;- auto tree = decode_tree(bytes_of(*body));- if (!tree)- return;- for (const auto &entry : tree->entries) {- if (entry.kind == KIND_SUBTREE)- walk_tree(entry.target);- else if (entry.kind == KIND_CONFLICT)- walk_conflict(entry.target);- else if (entry.kind != KIND_SUBMODULE)- walk_blob(entry.target);- }- }-};--std::vector<Id> chunks_for_commits(Store &store,- const std::vector<Id> &commits) {- Walker walker{store, false};- for (const auto &id : commits) {- auto loaded = load_commit(store, id);- if (loaded)- walker.walk_tree(loaded->commit.root_tree);- }- return std::move(walker.chunk_out);-}--std::vector<Id> objects_for_commits(Store &store,- const std::vector<Id> &commits) {- Walker walker{store, true};- for (const auto &id : commits) {- walker.add_object(id);- auto loaded = load_commit(store, id);- if (loaded)- walker.walk_tree(loaded->commit.root_tree);- }- return std::move(walker.object_out);-}--bool send_chunks(proto::Client &client, const fs::path &root,- const std::vector<Id> &chunks) {- constexpr std::size_t BATCH = 4096;- for (std::size_t offset = 0; offset < chunks.size(); offset += BATCH) {- const std::size_t end = std::min(offset + BATCH, chunks.size());- std::vector<Id> batch(chunks.begin() + static_cast<std::ptrdiff_t>(offset),- chunks.begin() + static_cast<std::ptrdiff_t>(end));- if (!client.get_chunks(root, batch))- return false;- }- return true;-}--bool send_missing_chunks(proto::Client &client, const fs::path &root,- const std::vector<Id> &chunks) {- Store store = Store::open_all(root);- std::vector<Id> missing;- for (const auto &id : chunks) {- if (!store.find(id))- missing.push_back(id);- }- return send_chunks(client, root, missing);-}--std::optional<std::string> config_value(const fs::path &root,- std::string_view key) {- return repo_config_value(root, key);-}--std::vector<std::string> list_remote_names(const fs::path &root) {- std::vector<std::string> out;- auto data = read_file_opt(config_path(root));- if (!data)- return out;- const std::string_view text(reinterpret_cast<const char *>(data->data()),- data->size());- std::size_t start = 0;- for (std::size_t i = 0; i <= text.size(); ++i) {- if (i != text.size() && text[i] != '\n')- continue;- const std::string_view line = text.substr(start, i - start);- if (starts_with(line, "remote.")) {- const auto dot = line.find(".url", 7);- if (dot != std::string_view::npos && dot > 7)- out.emplace_back(line.substr(7, dot - 7));- }- start = i + 1;- }- return out;-}--std::string role_text(std::uint8_t role) {- if (role == 2)- return "write";- if (role == 1)- return "read";- return "anonymous";-}--void print_key(const auth::Key &key) {- std::cout << "name: " << key.name << "\n";- std::cout << "public key: " << format_public_key(key.public_key) << "\n";- std::cout << "fingerprint: " << key.fingerprint << "\n";-}--void auth_usage() {- std::cout << "usage: vn auth <use|list|remove> ...\n";- std::cout << " vn auth use <key> [<host|url>] set the default or host key\n";- std::cout << " vn auth list show stored key mappings\n";- std::cout << " vn auth remove [<host|url>] remove a mapping (default if "- "omitted)\n";-}--std::optional<PublicKey> read_public_key(std::string_view arg) {- if (starts_with(arg, "ed25519:"))- return parse_public_key(arg);- auto data = read_file_opt(path_from_bytes(arg));- if (!data)- return std::nullopt;- const std::string text = trim_text(- std::string_view(reinterpret_cast<const char *>(data->data()),- data->size()));- return parse_public_key(text);-}--} // namespace--// ----------------------------------------------------------------------------// remote-// -----------------------------------------------------------------------------int remote_run(const std::vector<std::string> &args) {- const std::string sub = arg_at(args, 2);- if (sub.empty()) {- error_prefix();- std::cout << "expected a remote subcommand (add, set-url, list, remove)\n";- return 1;- }- auto repo = discover_repo(".");- if (!repo) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const fs::path root = *repo;-- if (sub == "add" || sub == "set-url") {- const bool replace = sub == "set-url";- std::string name;- std::string url;- std::optional<std::string> key;- std::optional<std::string> pin;- for (std::size_t i = 3; i < args.size(); ++i) {- const std::string &arg = args[i];- if (starts_with(arg, "-key:")) {- key = arg.substr(5);- } else if (starts_with(arg, "-tls-pin:")) {- pin = arg.substr(9);- } else if (is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else if (name.empty()) {- name = arg;- } else if (url.empty()) {- url = arg;- } else {- error_prefix();- std::cout << "too many arguments\n";- return 1;- }- }- if (name.empty() || url.empty()) {- error_prefix();- std::cout << (replace ? "remote set-url requires a name and URL\n"- : "remote add requires a name and URL\n");- return 1;- }- const std::string url_key = remote_key(name, "url");- const auto existing = config_value(root, url_key);- if (existing && !replace) {- error_prefix();- std::cout << "remote already exists: " << name << "\n";- return 1;- }- if (!existing && replace) {- error_prefix();- std::cout << "unknown remote: " << name << "\n";- return 1;- }- if (!repo_config_set(root, url_key, url)) {- error_prefix();- std::cout << "cannot write repository config\n";- return 1;- }- if (key) {- const std::string field = remote_key(name, "key");- const bool ok = key->empty() ? repo_config_remove(root, field)- : repo_config_set(root, field, *key);- if (!ok) {- error_prefix();- std::cout << "cannot write repository config\n";- return 1;- }- }- if (pin) {- const std::string field = remote_key(name, "tls-pin");- const bool ok = pin->empty() ? repo_config_remove(root, field)- : repo_config_set(root, field, *pin);- if (!ok) {- error_prefix();- std::cout << "cannot write repository config\n";- return 1;- }- }- return 0;- }-- if (sub == "list" || sub == "ls") {- for (const auto &name : list_remote_names(root)) {- const auto url = config_value(root, remote_key(name, "url"));- std::cout << name << "\t" << (url ? *url : std::string()) << "\n";- }- return 0;- }-- if (sub == "remove" || sub == "rm") {- const std::string name = arg_at(args, 3);- if (name.empty()) {- error_prefix();- std::cout << "remote remove requires a name\n";- return 1;- }- if (!config_value(root, remote_key(name, "url"))) {- error_prefix();- std::cout << "unknown remote: " << name << "\n";- return 1;- }- (void)repo_config_remove(root, remote_key(name, "url"));- (void)repo_config_remove(root, remote_key(name, "key"));- (void)repo_config_remove(root, remote_key(name, "tls-pin"));- return 0;- }-- error_prefix();- std::cout << "unknown remote subcommand: " << sub << "\n";- return 1;-}--// ----------------------------------------------------------------------------// clone-// -----------------------------------------------------------------------------int clone_run(const std::vector<std::string> &args) {- std::string url;- std::string path;- std::string policy = "head";- std::string key_name;- bool key_explicit = false;- std::string tls_pin;- for (std::size_t i = 2; i < args.size(); ++i) {- const std::string &arg = args[i];- if (starts_with(arg, "-blobs:")) {- policy = arg.substr(7);- } else if (starts_with(arg, "-key:")) {- key_name = arg.substr(5);- if (starts_with(key_name, "ed25519:")) {- error_prefix();- std::cout << "-key: expects a local key name, not a public key\n";- return 1;- }- key_explicit = true;- } else if (starts_with(arg, "-pin:")) {- tls_pin = arg.substr(5);- } else if (is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else if (url.empty()) {- url = arg;- } else {- path = arg;- }- }- if (url.empty()) {- error_prefix();- std::cout << "clone requires a URL\n";- return 1;- }- const auto parsed = proto::parse_url(url);- if (!parsed) {- error_prefix();- std::cout << "unsupported URL\n";- return 1;- }- if (path.empty())- path = last_segment(parsed->path);- auto repo = init_repo(path_from_bytes(path));- if (!repo) {- error_prefix();- std::cout << "cannot create repository\n";- return 1;- }- const fs::path root = *repo;-- if (key_name.empty()) {- if (auto fallback = auth::key_for_url(url))- key_name = *fallback;- }- (void)repo_config_set(root, remote_key("origin", "url"), url);- if (key_explicit && !key_name.empty())- (void)repo_config_set(root, remote_key("origin", "key"), key_name);- if (!tls_pin.empty())- (void)repo_config_set(root, remote_key("origin", "tls-pin"), tls_pin);-- const std::string repo_name = proto::url_repo_name(url);- auto client = proto::Client::connect(url, key_name, repo_name, tls_pin);- if (!client) {- error_prefix();- std::cout << "cannot connect or authenticate\n";- return 1;- }- std::vector<proto::RefInfo> refs;- if (!client->list_refs(refs)) {- report_client_error(*client, "cannot list remote refs");- return 1;- }- std::vector<Id> wants;- for (const auto &ref : refs)- wants.push_back(ref.target);- if (wants.empty()) {- info_prefix();- std::cout << "cloned empty repository into " << path << "\n";- return 0;- }- if (!client->negotiate(wants, {})) {- report_client_error(*client, "negotiation failed");- return 1;- }- if (!client->fetch_skeleton(root, wants)) {- report_client_error(*client, "fetch failed");- return 1;- }- {- Store store = Store::open_all(root);- const auto commits = selected_commits(refs, policy);- const auto chunks = chunks_for_commits(store, commits);- if (!send_chunks(*client, root, chunks)) {- report_client_error(*client, "chunk fetch failed");- return 1;- }- }- if (!apply_refs(root, refs, "origin", true)) {- error_prefix();- std::cout << "cannot write repository state\n";- return 1;- }- (void)repo_config_set(root, "promisor", "origin");- install_promisor_fetcher();- if (policy == "none") {- info_prefix();- std::cout << "cloned metadata only; blobs are promised\n";- }-- int checkout_status = 1;- {- Store store = Store::open_all(root);- auto view = current_view(root, store);- if (view) {- if (auto wc = working_copy_id(*view)) {- auto body = store.read_body(*wc, TYPE_COMMIT);- if (body) {- auto commit = decode_commit(bytes_of(*body));- if (commit) {- checkout_status = checkout_materialize_commit(- root, store, std::nullopt, commit->root_tree);- }- }- }- }- }- if (checkout_status != 0) {- info_prefix();- std::cout << "cloned; checkout reported " << checkout_status << "\n";- }- info_prefix();- std::cout << "cloned into " << path << "\n";- return 0;-}--// ----------------------------------------------------------------------------// fetch-// -----------------------------------------------------------------------------int fetch_run(const std::vector<std::string> &args) {- std::string remote_name = "origin";- std::string path = ".";- std::string explicit_key;- std::string explicit_pin;- bool have_remote = false;- for (std::size_t i = 2; i < args.size(); ++i) {- const std::string &arg = args[i];- if (starts_with(arg, "-key:")) {- explicit_key = arg.substr(5);- if (starts_with(explicit_key, "ed25519:")) {- error_prefix();- std::cout << "-key: expects a local key name, not a public key\n";- return 1;- }- } else if (starts_with(arg, "-pin:")) {- explicit_pin = arg.substr(5);- } else if (is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else if (!have_remote) {- remote_name = arg;- have_remote = true;- } else {- path = arg;- }- }- auto repo = discover_repo(path_from_bytes(path));- if (!repo) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const fs::path root = *repo;- auto url = config_value(root, remote_key(remote_name, "url"));- if (!url) {- error_prefix();- std::cout << "unknown remote\n";- return 1;- }- std::string key;- if (!explicit_key.empty()) {- key = explicit_key;- } else {- auto configured = config_value(root, remote_key(remote_name, "key"));- if (configured && auth::local_key_exists(*configured))- key = *configured;- if (key.empty()) {- if (auto fallback = auth::key_for_url(*url))- key = *fallback;- }- }- std::string pin;- if (!explicit_pin.empty()) {- pin = explicit_pin;- } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {- pin = *configured;- }- const std::string repo_name = proto::url_repo_name(*url);- auto client = proto::Client::connect(*url, key, repo_name, pin);- if (!client) {- error_prefix();- std::cout << "cannot connect or authenticate\n";- return 1;- }- std::vector<proto::RefInfo> refs;- if (!client->list_refs(refs)) {- report_client_error(*client, "cannot list remote refs");- return 1;- }- std::vector<Id> haves = read_heads(root);- std::vector<Id> wants;- for (const auto &ref : refs)- wants.push_back(ref.target);- if (wants.empty()) {- info_prefix();- std::cout << "no refs to fetch\n";- return 0;- }- if (!client->negotiate(wants, haves)) {- report_client_error(*client, "negotiation failed");- return 1;- }- if (!client->fetch_skeleton(root, wants)) {- report_client_error(*client, "fetch failed");- return 1;- }- {- Store store = Store::open_all(root);- const auto chunks = chunks_for_commits(store, wants);- if (!send_missing_chunks(*client, root, chunks)) {- report_client_error(*client, "chunk fetch failed");- return 1;- }- }- if (!apply_refs(root, refs, remote_name, false)) {- error_prefix();- std::cout << "cannot write repository state\n";- return 1;- }- info_prefix();- std::cout << "fetched from " << remote_name << "\n";- return 0;-}--// ----------------------------------------------------------------------------// push-// -----------------------------------------------------------------------------int push_run(const std::vector<std::string> &args) {- std::string remote_name = "origin";- std::string bookmark;- std::string explicit_key;- std::string explicit_pin;- std::string path = ".";- bool have_remote = false;- for (std::size_t i = 2; i < args.size(); ++i) {- const std::string &arg = args[i];- if (starts_with(arg, "-key:")) {- explicit_key = arg.substr(5);- if (starts_with(explicit_key, "ed25519:")) {- error_prefix();- std::cout << "-key: expects a local key name, not a public key\n";- return 1;- }- } else if (starts_with(arg, "-pin:")) {- explicit_pin = arg.substr(5);- } else if (is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else if (!have_remote) {- remote_name = arg;- have_remote = true;- } else if (bookmark.empty()) {- bookmark = arg;- } else {- path = arg;- }- }- if (bookmark.empty()) {- error_prefix();- std::cout << "push requires a bookmark name\n";- return 1;- }- auto repo = discover_repo(path_from_bytes(path));- if (!repo) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const fs::path root = *repo;- auto url = config_value(root, remote_key(remote_name, "url"));- if (!url) {- error_prefix();- std::cout << "unknown remote\n";- return 1;- }- std::string key;- if (!explicit_key.empty()) {- key = explicit_key;- } else {- auto configured = config_value(root, remote_key(remote_name, "key"));- if (configured && auth::local_key_exists(*configured))- key = *configured;- if (key.empty()) {- if (auto fallback = auth::key_for_url(*url))- key = *fallback;- }- }- std::string pin;- if (!explicit_pin.empty()) {- pin = explicit_pin;- } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {- pin = *configured;- }-- std::optional<Id> target;- std::vector<Id> commits;- std::vector<Id> objects;- {- Store store = Store::open_all(root);- auto view = current_view(root, store);- View empty;- const View ¤t = view ? *view : empty;- target = resolve_revision(store, current, bookmark);- if (!target) {- error_prefix();- std::cout << "unknown bookmark: " << bookmark << "\n";- return 1;- }- const std::array<Id, 1> roots{*target};- commits = collect_commits(store, roots);- objects = objects_for_commits(store, commits);- }- const std::string repo_name = proto::url_repo_name(*url);- auto client = proto::Client::connect(*url, key, repo_name, pin);- if (!client) {- error_prefix();- std::cout << "cannot connect or authenticate\n";- return 1;- }- std::vector<proto::RefInfo> refs;- if (!client->list_refs(refs)) {- report_client_error(*client, "cannot list remote refs");- return 1;- }- std::optional<Id> old;- for (const auto &ref : refs) {- if (ref.name == bookmark)- old = ref.target;- }- if (old && same_id(*old, *target)) {- info_prefix();- std::cout << "nothing to push, everything is up to date\n";- return 0;- }- if (!client->push_objects(root, objects)) {- report_client_error(*client, "push failed");- return 1;- }- std::vector<proto::UpdateRef> updates;- updates.push_back(proto::UpdateRef{bookmark, old, target});- if (!client->update_refs(updates)) {- report_client_error(*client, "ref update rejected");- return 1;- }- info_prefix();- std::cout << "pushed " << bookmark << " to " << remote_name << "\n";- return 0;-}--// ----------------------------------------------------------------------------// serve-// -----------------------------------------------------------------------------int serve_run(const std::vector<std::string> &args) {- bool stdio_mode = false;- std::string listen;- std::string root = ".";- std::string cert;- std::string key;- std::string repo_path = ".";- for (std::size_t i = 2; i < args.size(); ++i) {- const std::string &arg = args[i];- if (arg == "-stdio") {- stdio_mode = true;- if (i + 1 < args.size())- repo_path = args[++i];- } else if (arg == "-listen") {- if (i + 1 < args.size())- listen = args[++i];- } else if (arg == "-root") {- if (i + 1 < args.size())- root = args[++i];- } else if (arg == "-tls-cert") {- if (i + 1 < args.size())- cert = args[++i];- } else if (arg == "-tls-key") {- if (i + 1 < args.size())- key = args[++i];- } else {- error_prefix();- std::cout << "unknown serve option: " << arg << "\n";- return 1;- }- }- if (stdio_mode) {- auto repo = discover_repo(path_from_bytes(repo_path));- if (!repo) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- return server::serve_stdio(*repo);- }- if (listen.empty()) {- error_prefix();- std::cout << "serve requires -stdio or -listen\n";- return 1;- }- if (cert.empty() || key.empty()) {- error_prefix();- std::cout << "TLS requires -tls-cert and -tls-key\n";- return 1;- }- return server::serve_listen(listen, path_from_bytes(root), cert, key);-}--// ----------------------------------------------------------------------------// key-// -----------------------------------------------------------------------------int key_run(const std::vector<std::string> &args) {- const std::string sub = arg_at(args, 2);- if (sub.empty()) {- error_prefix();- std::cout- << "expected key subcommand (generate, list, show, import)\n";- return 1;- }- if (sub == "generate") {- const std::string name = arg_at(args, 3);- if (name.empty()) {- error_prefix();- std::cout << "key generate requires a name\n";- return 1;- }- auto key = auth::generate_key(name);- if (!key) {- error_prefix();- std::cout << "cannot create key\n";- return 1;- }- print_key(*key);- return 0;- }- if (sub == "list") {- for (const auto &name : auth::list_key_names()) {- if (auto key = auth::load_key(name))- print_key(*key);- }- return 0;- }- if (sub == "show") {- const std::string name = arg_at(args, 3);- if (name.empty()) {- error_prefix();- std::cout << "key show requires a name\n";- return 1;- }- auto key = auth::load_key(name);- if (!key) {- error_prefix();- std::cout << "key not found or has unsafe permissions\n";- return 1;- }- print_key(*key);- return 0;- }- if (sub == "import") {- error_prefix();- std::cout << "OpenSSH key import is not supported\n";- return 1;- }- error_prefix();- std::cout << "unknown key subcommand: " << sub << "\n";- return 1;-}--// ----------------------------------------------------------------------------// auth-// -----------------------------------------------------------------------------int auth_run(const std::vector<std::string> &args) {- const std::string sub = arg_at(args, 2);- if (sub.empty()) {- auth_usage();- return 1;- }- if (sub == "use") {- const std::string name = arg_at(args, 3);- if (name.empty()) {- auth_usage();- return 1;- }- if (!auth::load_key(name)) {- error_prefix();- std::cout << "key not found or has unsafe permissions: " << name- << "\n";- return 1;- }- const std::string target = auth::normalize_target(arg_at(args, 4));- if (!auth::set_key(target, name)) {- error_prefix();- std::cout << "cannot write auth configuration\n";- return 1;- }- if (target == "default")- std::cout << "default key set to " << name << "\n";- else- std::cout << "key for " << target << " set to " << name << "\n";- return 0;- }- if (sub == "list") {- const auto lines = auth::list_credential_lines();- if (lines.empty())- std::cout << "no stored credentials\n";- for (const auto &line : lines)- std::cout << line;- return 0;- }- if (sub == "remove") {- const std::string target = auth::normalize_target(arg_at(args, 3));- if (auth::remove_key(target)) {- std::cout << "removed " << target << "\n";- return 0;- }- error_prefix();- std::cout << "no credential for " << target << "\n";- return 1;- }- error_prefix();- std::cout << "unknown auth subcommand: " << sub << "\n";- auth_usage();- return 1;-}--// ----------------------------------------------------------------------------// access-// -----------------------------------------------------------------------------int access_run(const std::vector<std::string> &args) {- const std::string sub = arg_at(args, 2);- if (sub.empty()) {- error_prefix();- std::cout << "expected access subcommand\n";- return 1;- }- auto repo = discover_repo(".");- if (!repo) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const fs::path root = *repo;- if (sub == "add") {- std::string role;- std::string key_arg;- std::string name;- for (std::size_t i = 3; i < args.size(); ++i) {- const std::string &arg = args[i];- if (arg == "-role" && i + 1 < args.size()) {- role = args[++i];- } else if (arg == "-key" && i + 1 < args.size()) {- key_arg = args[++i];- } else if (arg == "-name" && i + 1 < args.size()) {- name = args[++i];- } else {- error_prefix();- std::cout << "unknown access add option: " << arg << "\n";- return 1;- }- }- if (role.empty() || key_arg.empty()) {- error_prefix();- std::cout << "access add requires -role and -key\n";- return 1;- }- std::uint8_t role_code = auth::ROLE_READ;- if (role == "write") {- role_code = auth::ROLE_WRITE;- } else if (role != "read") {- error_prefix();- std::cout << "role must be read or write\n";- return 1;- }- auto public_key = read_public_key(key_arg);- if (!public_key) {- error_prefix();- std::cout << "invalid public key\n";- return 1;- }- if (!auth::add_access(root, role_code, *public_key, name)) {- error_prefix();- std::cout << "cannot add key\n";- return 1;- }- info_prefix();- std::cout << "access granted\n";- return 0;- }- if (sub == "list") {- const auth::Access access = auth::load_access(root);- if (!access.valid) {- error_prefix();- std::cout << "invalid access file at line " << access.error_line << "\n";- return 1;- }- std::cout << "anonymous: " << (access.anonymous_read ? "read" : "off")- << "\n";- for (const auto &entry : access.entries) {- std::cout << (entry.role == auth::ROLE_WRITE ? "write" : "read") << " "- << key_fingerprint(entry.public_key) << " " << entry.name- << "\n";- }- return 0;- }- if (sub == "remove") {- const std::string arg = arg_at(args, 3);- if (arg.empty()) {- error_prefix();- std::cout << "access remove requires a fingerprint or name\n";- return 1;- }- const bool is_fingerprint = arg.size() == 26;- const std::string fingerprint = is_fingerprint ? arg : std::string();- const std::string name = is_fingerprint ? std::string() : arg;- if (!auth::remove_access(root, fingerprint, name)) {- error_prefix();- std::cout << "key not found or cannot write access file\n";- return 1;- }- info_prefix();- std::cout << "access removed\n";- return 0;- }- if (sub == "anonymous") {- const bool on = arg_at(args, 3) == "on";- if (!auth::set_anonymous(root, on)) {- error_prefix();- std::cout << "cannot update access file\n";- return 1;- }- return 0;- }- error_prefix();- std::cout << "unknown access subcommand: " << sub << "\n";- return 1;-}--// ----------------------------------------------------------------------------// whoami-// -----------------------------------------------------------------------------int whoami_run(const std::vector<std::string> &args) {- std::string remote = "origin";- std::string url;- std::string key;- std::string repo_name;- std::string pin;- const std::string arg = arg_at(args, 2);- if (!arg.empty()) {- if (starts_with(arg, "file://") || starts_with(arg, "ssh://") ||- starts_with(arg, "veins://")) {- url = arg;- repo_name = proto::url_repo_name(url);- } else {- remote = arg;- }- }- if (url.empty()) {- auto repo = discover_repo(".");- if (!repo) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const fs::path root = *repo;- auto configured = config_value(root, remote_key(remote, "url"));- if (!configured) {- error_prefix();- std::cout << "unknown remote\n";- return 1;- }- url = *configured;- if (auto k = config_value(root, remote_key(remote, "key"))) {- if (auth::local_key_exists(*k))- key = *k;- }- if (auto p = config_value(root, remote_key(remote, "tls-pin")))- pin = *p;- repo_name = proto::url_repo_name(url);- }- if (key.empty()) {- if (auto fallback = auth::key_for_url(url))- key = *fallback;- }- auto client = proto::Client::connect(url, key, repo_name, pin);- if (!client) {- error_prefix();- std::cout << "cannot authenticate\n";- return 1;- }- std::uint8_t role = 0;- std::string fingerprint;- if (!client->whoami(role, fingerprint)) {- error_prefix();- std::cout << "cannot authenticate\n";- return 1;- }- std::cout << "role: " << role_text(role) << "\n";- std::cout << "fingerprint: " << base32_text(bytes_of(fingerprint)) << "\n";- return 0;-}--// ----------------------------------------------------------------------------// Help-// -----------------------------------------------------------------------------bool net_help(std::string_view command) {- if (command == "remote") {- std::cout << "usage: vn remote <add|set-url|list|remove> ...\n\n";- std::cout << "manage native remotes stored in .veins/config\n\n";- std::cout << "subcommands:\n";- std::cout << " add <name> <url> [-key:<name>] [-tls-pin:<hash>]\n";- std::cout << " add a remote\n";- std::cout << " set-url <name> <url> [-key:<name>] [-tls-pin:<hash>]\n";- std::cout << " change a remote URL (and "- "optionally key/pin)\n";- std::cout << " list list remotes\n";- std::cout << " remove <name> remove a remote\n\n";- std::cout << "an empty -key: or -tls-pin: value clears that setting\n\n";- std::cout << "examples:\n";- std::cout << " vn remote add origin veins://127.0.0.1:7419/navid-m/veins2\n";- std::cout << " vn remote set-url origin veins://example/repo -key:my-key\n";- return true;- }- if (command == "clone") {- std::cout << "usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] "- "[-pin:<sha256>] [path]\n\n";- std::cout << "clone a repository over file://, ssh://, or veins://\n\n";- std::cout << "without -key, the key stored by 'vn auth use' is used when "- "available\n";- return true;- }- if (command == "fetch") {- std::cout << "usage: vn fetch [-key:<name>] [<remote>] [path]\n\n";- std::cout << "fetch new history and chunks from a configured native "- "remote\n\n";- std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";- return true;- }- if (command == "push") {- std::cout << "usage: vn push [-key:<name>] [<remote>] <bookmark> [path]\n\n";- std::cout << "push a bookmark to a configured native remote\n\n";- std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";- return true;- }- if (command == "serve") {- std::cout << "usage: vn serve -stdio <repo>\n";- std::cout << " vn serve -listen <addr:port> -root <dir> -tls-cert "- "<file> -tls-key <file>\n\n";- std::cout << "run the native server over standard input/output or TLS 1.3\n";- return true;- }- if (command == "key") {- std::cout << "usage: vn key <generate|list|show> [name]\n\n";- std::cout << "manage local Ed25519 keys in the user key directory\n";- return true;- }- if (command == "auth") {- std::cout << "usage: vn auth <use|list|remove> ...\n\n";- std::cout << "remember which key clone/fetch/push should use\n\n";- std::cout << " vn auth use <key> [<host|url>] set the default or host "- "key\n";- std::cout << " vn auth list show stored key mappings\n";- std::cout << " vn auth remove [<host|url>] remove a mapping\n";- return true;- }- if (command == "access") {- std::cout << "usage: vn access <add|list|remove|anonymous> ...\n\n";- std::cout << "manage a served repository's .veins/access policy\n";- return true;- }- if (command == "whoami") {- std::cout << "usage: vn whoami [<remote>|<url>]\n\n";- std::cout << "connect to a server and report the granted role and key "- "fingerprint\n";- return true;- }- return false;-}--} // namespace vn--- a/veins-cpprewrite/src/net_commands.h+++ /dev/null@@ -1,23 +0,0 @@-#pragma once--#include <string>-#include <string_view>-#include <vector>--namespace vn {--int remote_run(const std::vector<std::string> &args);-int clone_run(const std::vector<std::string> &args);-int fetch_run(const std::vector<std::string> &args);-int push_run(const std::vector<std::string> &args);-int serve_run(const std::vector<std::string> &args);-int key_run(const std::vector<std::string> &args);-int auth_run(const std::vector<std::string> &args);-int access_run(const std::vector<std::string> &args);-int whoami_run(const std::vector<std::string> &args);--// Print help for a network command. Returns false when `command` is not one of-// them.-bool net_help(std::string_view command);--} // namespace vn--- a/veins-cpprewrite/src/object.cpp+++ /dev/null@@ -1,1026 +0,0 @@-#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--- a/veins-cpprewrite/src/object.h+++ /dev/null@@ -1,251 +0,0 @@-#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--- a/veins-cpprewrite/src/oplog.cpp+++ /dev/null@@ -1,246 +0,0 @@-#include "local_commands.h"--#include "store.h"-#include "worktree.h"--#include <algorithm>-#include <iostream>--namespace vn {--namespace {--struct OpRec {- Id id{};- Operation op;-};--std::vector<OpRec> collect_operations(Store &store,- const std::vector<Id> &heads) {- std::vector<OpRec> out;- std::vector<Id> seen;- std::vector<Id> stack(heads.rbegin(), heads.rend());- while (!stack.empty()) {- const Id id = stack.back();- stack.pop_back();- if (contains_id(seen, id))- continue;- seen.push_back(id);- auto op = store.read_operation(id);- if (!op)- continue;- for (const auto &parent : op->parents) {- if (!contains_id(seen, parent))- stack.push_back(parent);- }- out.push_back(OpRec{id, std::move(*op)});- }- return out;-}--void sort_operations(std::vector<OpRec> &recs) {- std::stable_sort(recs.begin(), recs.end(), [](const OpRec &a, const OpRec &b) {- return a.op.end.ms > b.op.end.ms;- });-}--std::optional<std::size_t> resolve_operation(- const std::vector<OpRec> &recs, std::string_view text) {- std::optional<std::size_t> found;- std::size_t count = 0;- for (std::size_t i = 0; i < recs.size(); ++i) {- const std::string full = hex_encode(recs[i].id);- if (full.size() >= text.size() && full.compare(0, text.size(), text) == 0) {- found = i;- ++count;- }- }- if (count == 1)- return found;- return std::nullopt;-}--std::optional<Id> wc_tree(Store &store, const View &view) {- const auto wc = working_copy_id(view);- if (!wc)- return std::nullopt;- auto loaded = load_commit(store, *wc);- if (!loaded)- return std::nullopt;- return loaded->commit.root_tree;-}--int write_view(const fs::path &root, Store &store, const View &next,- std::string_view description) {- auto tx = Txn::begin(root, store);- if (!tx) {- error_prefix();- std::cout << "cannot load repository state\n";- return 1;- }- const auto old_tree = wc_tree(store, tx->view());- const auto new_tree = wc_tree(store, next);- tx->view() = next;- if (!tx->finish(description))- return 1;- return checkout_materialize_optional(root, store, old_tree, new_tree);-}--int op_log(const std::vector<std::string> &) {- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- Store store = Store::open_all(*root);- const auto heads = read_heads(*root);- auto recs = collect_operations(store, heads);- sort_operations(recs);- for (const auto &rec : recs) {- const std::string marker = contains_id(heads, rec.id) ? "@" : " ";- const std::string stamp =- format_utc(rec.op.end.ms / 1000);- std::cout << marker << " " << hex_encode(rec.id).substr(0, 12) << " "- << stamp << " " << rec.op.description << "\n";- }- return 0;-}--int op_restore(const std::vector<std::string> &args, std::size_t start) {- if (start >= args.size()) {- error_prefix();- std::cout << "op restore requires an operation id\n";- return 1;- }- const std::string &text = args[start];- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const int snap = snapshot_run(*root);- if (snap != 0)- return snap;- Store store = Store::open_all(*root);- const auto heads = read_heads(*root);- auto recs = collect_operations(store, heads);- const auto target = resolve_operation(recs, text);- if (!target) {- error_prefix();- std::cout << "unknown operation\n";- return 1;- }- auto target_view = store.read_view(recs[*target].op.view);- if (!target_view) {- error_prefix();- std::cout << "cannot read operation view\n";- return 1;- }- return write_view(*root, store, *target_view, "op restore");-}--int op_revert(const std::vector<std::string> &args, std::size_t start) {- if (start >= args.size()) {- error_prefix();- std::cout << "op revert requires an operation id\n";- return 1;- }- const std::string &text = args[start];- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const int snap = snapshot_run(*root);- if (snap != 0)- return snap;- Store store = Store::open_all(*root);- const auto heads = read_heads(*root);- auto recs = collect_operations(store, heads);- const auto target = resolve_operation(recs, text);- if (!target) {- error_prefix();- std::cout << "unknown operation\n";- return 1;- }- const auto &op = recs[*target].op;- View view;- if (!op.parents.empty()) {- auto parent = store.read_operation(op.parents.front());- if (parent) {- auto parent_view = store.read_view(parent->view);- if (parent_view)- view = std::move(*parent_view);- }- }- return write_view(*root, store, view, "op revert");-}--} // namespace--int op_run(const std::vector<std::string> &args) {- if (args.size() <= 2) {- error_prefix();- std::cout << "expected an op subcommand (log, restore, revert)\n";- return 1;- }- const std::string &sub = args[2];- if (sub == "log")- return op_log(args);- if (sub == "restore")- return op_restore(args, 3);- if (sub == "revert")- return op_revert(args, 3);- error_prefix();- std::cout << "unknown op subcommand: " << sub << "\n";- return 1;-}--int undo_run(const std::vector<std::string> &) {- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const int snap = snapshot_run(*root);- if (snap != 0)- return snap;- Store store = Store::open_all(*root);- const auto heads = read_heads(*root);- if (heads.empty()) {- error_prefix();- std::cout << "no operations to undo\n";- return 1;- }- auto recs = collect_operations(store, heads);- sort_operations(recs);- if (recs.empty()) {- error_prefix();- std::cout << "cannot resolve undo target\n";- return 1;- }- const auto &latest = recs.front().op;- View view;- if (!latest.parents.empty()) {- auto parent = store.read_operation(latest.parents.front());- if (!parent) {- error_prefix();- std::cout << "cannot resolve undo target\n";- return 1;- }- auto parent_view = store.read_view(parent->view);- if (!parent_view) {- error_prefix();- std::cout << "cannot resolve undo target\n";- return 1;- }- view = std::move(*parent_view);- }- return write_view(*root, store, view, "undo");-}--} // namespace vn--- a/veins-cpprewrite/src/pathspec.cpp+++ /dev/null@@ -1,96 +0,0 @@-#include "pathspec.h"--#include <vector>--namespace vn {--namespace {--// Collapse "." and ".." components and drop empty components.-std::optional<std::string> normalize_components(std::string_view input) {- std::vector<std::string_view> comps;- std::size_t start = 0;- for (std::size_t i = 0; i <= input.size(); ++i) {- const bool at_end = i == input.size();- if (!at_end && input[i] != '/')- continue;- const std::string_view comp = input.substr(start, i - start);- if (!comp.empty() && comp != ".") {- if (comp == "..") {- if (comps.empty())- return std::nullopt;- comps.pop_back();- } else {- comps.push_back(comp);- }- }- start = i + 1;- }- std::string out;- for (std::size_t i = 0; i < comps.size(); ++i) {- if (i != 0)- out.push_back('/');- out.append(comps[i]);- }- return out;-}--std::string join_relative(std::string_view base, std::string_view arg) {- if (base.empty())- return std::string(arg);- if (arg.empty())- return std::string(base);- std::string out(base);- out.push_back('/');- out.append(arg);- return out;-}--} // namespace--std::optional<std::string> cwd_relative(const fs::path &root) {- std::error_code ec;- fs::path cwd = fs::current_path(ec);- if (ec)- return std::nullopt;- cwd = fs::weakly_canonical(cwd, ec);- if (ec)- return std::nullopt;- const std::string canon = path_to_bytes(cwd);- const std::string root_bytes = path_to_bytes(root);- if (canon == root_bytes)- return std::string();- if (canon.size() > root_bytes.size() &&- canon.compare(0, root_bytes.size(), root_bytes) == 0 &&- canon[root_bytes.size()] == '/')- return canon.substr(root_bytes.size() + 1);- return std::nullopt;-}--std::optional<std::string> pathspec_normalize(const fs::path &root,- std::string_view cwd_rel,- std::string_view arg) {- if (arg.empty())- return std::nullopt;- if (arg.front() == '/') {- auto norm = normalize_components(arg);- if (!norm)- return std::nullopt;- std::string root_view = path_to_bytes(root);- if (!root_view.empty() && root_view.front() == '/')- root_view.erase(0, 1);- if (norm->size() > root_view.size() &&- norm->compare(0, root_view.size(), root_view) == 0 &&- (*norm)[root_view.size()] == '/')- return norm->substr(root_view.size() + 1);- return std::nullopt;- }- return normalize_components(join_relative(cwd_rel, arg));-}--bool pathspec_has_glob(std::string_view value) {- return value.find('*') != std::string_view::npos ||- value.find('?') != std::string_view::npos;-}--} // namespace vn--- a/veins-cpprewrite/src/pathspec.h+++ /dev/null@@ -1,23 +0,0 @@-#pragma once--#include "common.h"--#include <optional>-#include <string>--namespace vn {--// Current directory relative to the repository root, or nullopt when the-// process is outside the repository.-std::optional<std::string> cwd_relative(const fs::path &root);--// Normalize one command-line operand into a repository-relative path. Relative-// operands are resolved against `cwd_rel`; absolute operands must live inside-// `root`. Glob metacharacters are preserved.-std::optional<std::string> pathspec_normalize(const fs::path &root,- std::string_view cwd_rel,- std::string_view arg);--bool pathspec_has_glob(std::string_view value);--} // namespace vn--- a/veins-cpprewrite/src/promisor.cpp+++ /dev/null@@ -1,57 +0,0 @@-#include "promisor.h"--#include "protocol.h"-#include "store.h"--#include <optional>-#include <string>-#include <vector>--namespace vn {--namespace {--std::string remote_field(std::string_view remote, std::string_view field) {- std::string out = "remote.";- out += remote;- out.push_back('.');- out += field;- return out;-}--bool fetch_missing_chunk(const fs::path &root, const Id &id) {- static thread_local bool active = false;- if (active)- return false;- active = true;- struct Guard {- bool &flag;- ~Guard() { flag = false; }- } guard{active};-- auto promisor = repo_config_value(root, "promisor");- if (!promisor || promisor->empty())- return false;- auto url = repo_config_value(root, remote_field(*promisor, "url"));- if (!url || url->empty())- return false;- auto key = repo_config_value(root, remote_field(*promisor, "key"));- auto pin = repo_config_value(root, remote_field(*promisor, "tls-pin"));- const std::string repo_name = proto::url_repo_name(*url);- auto client = proto::Client::connect(*url, key ? *key : std::string(),- repo_name, pin ? *pin : std::string());- if (!client)- return false;- const std::vector<Id> ids = {id};- return client->get_chunks(root, ids);-}--} // namespace--void install_promisor_fetcher() {- set_promisor_fetcher([](const fs::path &root, const Id &id) {- return fetch_missing_chunk(root, id);- });-}--} // namespace vn--- a/veins-cpprewrite/src/promisor.h+++ /dev/null@@ -1,9 +0,0 @@-#pragma once--namespace vn {--// Register the lazy-chunk fetch hook used by the store. Safe to call more than-// once; the last registration wins.-void install_promisor_fetcher();--} // namespace vn--- a/veins-cpprewrite/src/protocol.cpp+++ /dev/null@@ -1,901 +0,0 @@-#include "protocol.h"--#include "auth.h"-#include "store.h"--#include <blake3.h>--#include <algorithm>-#include <array>-#include <cstring>--namespace vn::proto {--namespace {--void put_u16_be(ByteWriter &writer, std::uint16_t value) {- writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));- writer.u8(static_cast<std::uint8_t>(value & 255u));-}--std::optional<std::uint16_t> read_u16_be(Reader &reader) {- const auto high = reader.u8();- if (!high)- return std::nullopt;- const auto low = reader.u8();- if (!low)- return std::nullopt;- return static_cast<std::uint16_t>((static_cast<std::uint16_t>(*high) << 8) |- *low);-}--std::vector<std::uint8_t>-encode_string_list(const std::vector<std::string> &items) {- ByteWriter writer(128);- writer.varint(items.size());- for (const auto &item : items)- writer.length_prefixed(item);- return writer.take();-}--std::optional<std::vector<std::string>> decode_string_list(Reader &reader,- std::size_t max) {- const auto count = reader.list_len(max);- if (!count)- return std::nullopt;- std::vector<std::string> out;- out.reserve(*count);- for (std::size_t i = 0; i < *count; ++i) {- const auto value = reader.bytes(4096);- if (!value)- return std::nullopt;- out.emplace_back(str_of(*value));- }- return out;-}--std::string bytes_to_string(Bytes data) { return std::string(str_of(data)); }--void append_id(ByteWriter &writer, const Id &id) {- writer.raw(Bytes(id.data(), id.size()));-}--std::optional<Id> read_id(Reader &reader) {- const auto id = reader.id();- if (!id)- return std::nullopt;- return *id;-}--std::size_t find_char(std::string_view text, char needle) {- const auto at = text.find(needle);- return at == std::string_view::npos ? std::string_view::npos : at;-}--struct Authority {- std::string host;- int port = 0;-};--Authority parse_authority(std::string_view authority, int default_port,- bool strip_user) {- if (strip_user) {- const auto at = find_char(authority, '@');- if (at != std::string_view::npos)- authority.remove_prefix(at + 1);- }- Authority out;- out.host = std::string(authority);- out.port = default_port;- const auto colon = find_char(authority, ':');- if (colon != std::string_view::npos) {- out.host = std::string(authority.substr(0, colon));- const std::string_view port_text = authority.substr(colon + 1);- if (!port_text.empty()) {- int port = 0;- bool numeric = true;- for (char c : port_text) {- if (c < '0' || c > '9') {- numeric = false;- break;- }- if (port > 1000000)- port = 1000000;- port = port * 10 + (c - '0');- }- if (numeric)- out.port = port;- }- }- return out;-}--std::optional<net::Stream> connect_stream(const Url &url,- std::string_view tls_pin,- std::string &binding) {- if (url.ssh) {- std::vector<std::string> remote = {"vn", "serve", "-stdio", url.path};- const std::string remote_command = net::build_shell_command(remote);- std::vector<std::string> argv = {"ssh"};- if (url.port != 22) {- argv.push_back("-p");- argv.push_back(std::to_string(url.port));- }- argv.push_back(url.host);- argv.push_back(remote_command);- return net::Stream::spawn_argv(argv);- }- if (url.tls) {- auto fd = net::tcp_connect(url.host, url.port);- if (!fd)- return std::nullopt;- void *ctx = net::tls_client_ctx(!tls_pin.empty());- if (!ctx) {- net::close_socket(*fd);- return std::nullopt;- }- void *ssl = net::tls_connect(ctx, *fd, url.host);- net::tls_ctx_free(ctx);- if (!ssl) {- net::close_socket(*fd);- return std::nullopt;- }- std::array<std::uint8_t, 32> exported{};- if (net::tls_exporter(ssl, exported.data(), exported.size()))- binding.assign(reinterpret_cast<const char *>(exported.data()),- exported.size());- if (!tls_pin.empty()) {- std::array<std::uint8_t, 32> digest{};- const bool got = net::tls_peer_sha256(ssl, digest.data());- const std::string hex = net::to_hex(Bytes(digest.data(), digest.size()));- if (!got || !net::hex_equal(hex, tls_pin)) {- net::close_socket(*fd);- net::tls_free(ssl);- return std::nullopt;- }- }- return net::Stream::tls_stream(*fd, ssl);- }- std::vector<std::string> argv = {path_to_bytes(net::self_exe()), "serve",- "-stdio", url.path};- return net::Stream::spawn_argv(argv);-}--std::string id_text(const Id &id) { return hex_encode(id); }--} // namespace--// ----------------------------------------------------------------------------// Message codecs-// -----------------------------------------------------------------------------std::vector<std::uint8_t> encode_hello(const Hello &hello) {- ByteWriter writer(128);- put_u16_be(writer, hello.min_version);- put_u16_be(writer, hello.max_version);- writer.raw(Bytes(encode_string_list(hello.capabilities)));- writer.length_prefixed(hello.repo);- writer.length_prefixed(hello.client_nonce);- return writer.take();-}--std::optional<Hello> decode_hello(Bytes data) {- Reader reader(data);- const auto min_version = read_u16_be(reader);- if (!min_version)- return std::nullopt;- const auto max_version = read_u16_be(reader);- if (!max_version)- return std::nullopt;- auto capabilities = decode_string_list(reader, 64);- if (!capabilities)- return std::nullopt;- const auto repo = reader.bytes(4096);- if (!repo)- return std::nullopt;- const auto nonce = reader.bytes(64);- if (!nonce)- return std::nullopt;- if (!reader.finish())- return std::nullopt;- Hello out;- out.min_version = *min_version;- out.max_version = *max_version;- out.capabilities = std::move(*capabilities);- out.repo = bytes_to_string(*repo);- out.client_nonce = bytes_to_string(*nonce);- return out;-}--std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello) {- ByteWriter writer(128);- put_u16_be(writer, hello.version);- writer.raw(Bytes(encode_string_list(hello.capabilities)));- writer.length_prefixed(hello.server_nonce);- writer.u8(hello.auth_required);- return writer.take();-}--std::optional<HelloOk> decode_hello_ok(Bytes data) {- Reader reader(data);- const auto version = read_u16_be(reader);- if (!version)- return std::nullopt;- auto capabilities = decode_string_list(reader, 64);- if (!capabilities)- return std::nullopt;- const auto nonce = reader.bytes(64);- if (!nonce)- return std::nullopt;- const auto auth = reader.u8();- if (!auth)- return std::nullopt;- if (!reader.finish())- return std::nullopt;- HelloOk out;- out.version = *version;- out.capabilities = std::move(*capabilities);- out.server_nonce = bytes_to_string(*nonce);- out.auth_required = *auth;- return out;-}--std::vector<std::uint8_t> encode_auth(const Auth &auth) {- ByteWriter writer(128);- writer.length_prefixed(auth.public_key);- writer.length_prefixed(auth.signature);- return writer.take();-}--std::optional<Auth> decode_auth(Bytes data) {- Reader reader(data);- const auto public_key = reader.bytes(64);- if (!public_key)- return std::nullopt;- const auto signature = reader.bytes(128);- if (!signature)- return std::nullopt;- if (!reader.finish())- return std::nullopt;- return Auth{bytes_to_string(*public_key), bytes_to_string(*signature)};-}--std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth) {- ByteWriter writer(64);- writer.u8(auth.role);- writer.length_prefixed(auth.fingerprint);- return writer.take();-}--std::optional<AuthOk> decode_auth_ok(Bytes data) {- Reader reader(data);- const auto role = reader.u8();- if (!role)- return std::nullopt;- const auto fingerprint = reader.bytes(64);- if (!fingerprint)- return std::nullopt;- if (!reader.finish())- return std::nullopt;- return AuthOk{*role, bytes_to_string(*fingerprint)};-}--std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs) {- ByteWriter writer(256);- writer.varint(refs.size());- for (const auto &ref : refs) {- writer.length_prefixed(ref.name);- append_id(writer, ref.target);- writer.length_prefixed(ref.change_id);- writer.u8(ref.kind);- }- return writer.take();-}--std::optional<std::vector<RefInfo>> decode_refs(Bytes data) {- Reader reader(data);- const auto count = reader.list_len(1000000);- if (!count)- return std::nullopt;- std::vector<RefInfo> out;- out.reserve(*count);- for (std::size_t i = 0; i < *count; ++i) {- const auto name = reader.bytes(4096);- if (!name)- return std::nullopt;- const auto target = read_id(reader);- if (!target)- return std::nullopt;- const auto change_id = reader.bytes(64);- if (!change_id)- return std::nullopt;- const auto kind = reader.u8();- if (!kind)- return std::nullopt;- RefInfo ref;- ref.name = bytes_to_string(*name);- ref.target = *target;- ref.change_id = bytes_to_string(*change_id);- ref.kind = *kind;- out.push_back(std::move(ref));- }- if (!reader.finish())- return std::nullopt;- return out;-}--std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids) {- ByteWriter writer(ids.size() * 32 + 8);- writer.varint(ids.size());- for (const auto &id : ids)- append_id(writer, id);- return writer.take();-}--std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max) {- Reader reader(data);- const auto count = reader.list_len(max);- if (!count)- return std::nullopt;- std::vector<Id> out;- out.reserve(*count);- for (std::size_t i = 0; i < *count; ++i) {- const auto id = read_id(reader);- if (!id)- return std::nullopt;- out.push_back(*id);- }- if (!reader.finish())- return std::nullopt;- return out;-}--std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,- const std::vector<Id> &haves) {- ByteWriter writer(256);- writer.varint(wants.size());- for (const auto &id : wants)- append_id(writer, id);- writer.varint(haves.size());- for (const auto &id : haves)- append_id(writer, id);- return writer.take();-}--std::optional<Negotiate> decode_negotiate(Bytes data) {- Reader reader(data);- const auto want_count = reader.list_len(1000000);- if (!want_count)- return std::nullopt;- Negotiate out;- out.wants.reserve(*want_count);- for (std::size_t i = 0; i < *want_count; ++i) {- const auto id = read_id(reader);- if (!id)- return std::nullopt;- out.wants.push_back(*id);- }- const auto have_count = reader.list_len(1000000);- if (!have_count)- return std::nullopt;- out.haves.reserve(*have_count);- for (std::size_t i = 0; i < *have_count; ++i) {- const auto id = read_id(reader);- if (!id)- return std::nullopt;- out.haves.push_back(*id);- }- if (!reader.finish())- return std::nullopt;- return out;-}--std::vector<std::uint8_t>-encode_negotiate_ok(const std::vector<std::uint8_t> &known,- std::uint8_t enough) {- ByteWriter writer(known.size() + 16);- writer.u8(enough);- writer.varint(known.size());- for (std::uint8_t bit : known)- writer.u8(bit);- return writer.take();-}--std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data) {- Reader reader(data);- const auto enough = reader.u8();- if (!enough)- return std::nullopt;- const auto count = reader.list_len(1000000);- if (!count)- return std::nullopt;- std::vector<std::uint8_t> out;- out.reserve(*count);- for (std::size_t i = 0; i < *count; ++i) {- const auto bit = reader.u8();- if (!bit)- return std::nullopt;- out.push_back(*bit);- }- if (!reader.finish())- return std::nullopt;- return out;-}--std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits) {- ByteWriter writer(bits.size() + 8);- writer.varint(bits.size());- for (std::uint8_t bit : bits)- writer.u8(bit);- return writer.take();-}--std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data) {- Reader reader(data);- const auto count = reader.list_len(1000000);- if (!count)- return std::nullopt;- std::vector<std::uint8_t> out;- out.reserve(*count);- for (std::size_t i = 0; i < *count; ++i) {- const auto bit = reader.u8();- if (!bit)- return std::nullopt;- out.push_back(*bit);- }- if (!reader.finish())- return std::nullopt;- return out;-}--std::vector<std::uint8_t>-encode_update_refs(const std::vector<UpdateRef> &updates) {- ByteWriter writer(256);- writer.varint(updates.size());- for (const auto &update : updates) {- writer.length_prefixed(update.name);- writer.opt_id(update.expected);- writer.opt_id(update.target);- }- return writer.take();-}--std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data) {- Reader reader(data);- const auto count = reader.list_len(1000000);- if (!count)- return std::nullopt;- std::vector<UpdateRef> out;- out.reserve(*count);- for (std::size_t i = 0; i < *count; ++i) {- const auto name = reader.bytes(4096);- if (!name)- return std::nullopt;- const auto expected = reader.opt_id();- if (!expected)- return std::nullopt;- const auto target = reader.opt_id();- if (!target)- return std::nullopt;- UpdateRef update;- update.name = bytes_to_string(*name);- update.expected = *expected;- update.target = *target;- out.push_back(std::move(update));- }- if (!reader.finish())- return std::nullopt;- return out;-}--std::string auth_message(std::uint16_t version, std::string_view repo,- Bytes server_nonce, Bytes client_nonce, Bytes binding) {- ByteWriter writer(128);- writer.raw(std::string_view("veins-auth/1"));- writer.u8(0);- writer.u8(static_cast<std::uint8_t>((version >> 8) & 255u));- writer.u8(static_cast<std::uint8_t>(version & 255u));- writer.length_prefixed(repo);- writer.raw(server_nonce);- writer.raw(client_nonce);- writer.raw(binding);- return std::string(str_of(writer.view()));-}--std::string_view role_name(std::uint8_t role) {- if (role == 2)- return "write";- if (role == 1)- return "read";- return "anonymous";-}--// ----------------------------------------------------------------------------// URLs-// -----------------------------------------------------------------------------std::optional<Url> parse_url(std::string_view url) {- constexpr std::string_view file_prefix = "file://";- constexpr std::string_view ssh_prefix = "ssh://";- constexpr std::string_view veins_prefix = "veins://";- if (url.starts_with(file_prefix))- return Url{false, false, {}, 0, std::string(url.substr(file_prefix.size()))};- if (url.starts_with(ssh_prefix)) {- std::string_view rest = url.substr(ssh_prefix.size());- const auto slash = rest.find('/');- if (slash == std::string_view::npos)- return std::nullopt;- const auto authority = parse_authority(rest.substr(0, slash), 22, true);- return Url{false, true, authority.host, authority.port,- std::string(rest.substr(slash + 1))};- }- if (url.starts_with(veins_prefix)) {- std::string_view rest = url.substr(veins_prefix.size());- const auto slash = rest.find('/');- if (slash == std::string_view::npos)- return std::nullopt;- const auto authority = parse_authority(rest.substr(0, slash), 7419, false);- return Url{true, false, authority.host, authority.port,- std::string(rest.substr(slash + 1))};- }- return std::nullopt;-}--std::string url_repo_name(std::string_view url) {- auto parsed = parse_url(url);- if (!parsed || !parsed->tls)- return {};- return parsed->path;-}--// ----------------------------------------------------------------------------// Client-// -----------------------------------------------------------------------------void Client::set_error(std::string text) { last_error_ = std::move(text); }--void Client::set_error_frame(const wire::Frame &frame) {- const std::uint8_t code = wire::read_error(frame.payload);- const std::string_view name = wire::error_code_name(code);- const std::string message = wire::error_message(frame.payload);- std::string text = "server error: ";- text += name;- if (!message.empty()) {- text += ": ";- text += message;- }- set_error(std::move(text));-}--std::optional<wire::Frame> Client::request(std::uint8_t kind, Bytes payload) {- const std::uint32_t rid =- static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);- if (!wire::write_frame(stream_, kind, rid, payload)) {- set_error("connection closed while sending request");- return std::nullopt;- }- auto frame = wire::read_frame(stream_);- if (!frame) {- set_error("connection closed while waiting for server response");- return std::nullopt;- }- if (frame->kind == wire::ERROR) {- set_error_frame(*frame);- return std::nullopt;- }- return frame;-}--std::optional<Client> Client::connect(std::string_view url,- std::string_view key_name,- std::string_view repo_name,- std::string_view tls_pin) {- auto parsed = parse_url(url);- if (!parsed)- return std::nullopt;- std::string binding;- auto stream = connect_stream(*parsed, tls_pin, binding);- if (!stream)- return std::nullopt;-- const auto nonce_bytes = secure_random(32);- if (nonce_bytes.size() != 32) {- stream->close();- return std::nullopt;- }- const std::string client_nonce(reinterpret_cast<const char *>(- nonce_bytes.data()),- nonce_bytes.size());-- Hello hello;- hello.capabilities = {"zstd-records", "lazy-chunks", "push", "auth-ed25519"};- hello.repo = std::string(repo_name);- hello.client_nonce = client_nonce;- const auto hello_body = encode_hello(hello);- if (!wire::write_frame(*stream, wire::HELLO, 1, hello_body)) {- stream->close();- return std::nullopt;- }- auto hello_frame = wire::read_frame(*stream);- if (!hello_frame || hello_frame->kind != wire::HELLO_OK) {- stream->close();- return std::nullopt;- }- auto hello_ok = decode_hello_ok(hello_frame->payload);- if (!hello_ok) {- stream->close();- return std::nullopt;- }-- Client client;- client.stream_ = std::move(*stream);- client.binding_ = std::move(binding);- client.version_ = hello_ok->version;-- std::string selected_key(key_name);- if (selected_key.empty() && hello_ok->auth_required != 0)- selected_key = "default";-- if (!selected_key.empty()) {- auto key = auth::load_key(selected_key);- if (key) {- const std::string message = auth_message(- hello_ok->version, repo_name,- Bytes(reinterpret_cast<const std::uint8_t *>(- hello_ok->server_nonce.data()),- hello_ok->server_nonce.size()),- Bytes(reinterpret_cast<const std::uint8_t *>(client_nonce.data()),- client_nonce.size()),- Bytes(reinterpret_cast<const std::uint8_t *>(client.binding_.data()),- client.binding_.size()));- auto signature = ed25519_sign(Bytes(key->seed.data(), key->seed.size()),- Bytes(reinterpret_cast<const std::uint8_t *>(- message.data()),- message.size()));- if (signature) {- Auth auth;- auth.public_key.assign(- reinterpret_cast<const char *>(key->public_key.data()),- key->public_key.size());- auth.signature.assign(- reinterpret_cast<const char *>(signature->data()),- signature->size());- const auto body = encode_auth(auth);- if (wire::write_frame(client.stream_, wire::AUTH, 2, body)) {- auto reply = wire::read_frame(client.stream_);- if (reply && reply->kind == wire::AUTH_OK) {- auto ok = decode_auth_ok(reply->payload);- if (ok) {- client.role_ = ok->role;- client.authed_ = true;- client.fingerprint_ = std::move(ok->fingerprint);- }- }- }- }- }- }-- if (hello_ok->auth_required != 0 && !client.authed_) {- client.stream_.close();- return std::nullopt;- }- return client;-}--bool Client::list_refs(std::vector<RefInfo> &refs) {- auto frame = request(wire::LIST_REFS, Bytes{});- if (!frame)- return false;- if (frame->kind != wire::REFS) {- set_error("unexpected response to ref listing (message kind " +- std::to_string(frame->kind) + ")");- return false;- }- auto decoded = decode_refs(frame->payload);- if (!decoded)- return false;- refs = std::move(*decoded);- return true;-}--bool Client::negotiate(const std::vector<Id> &wants,- const std::vector<Id> &haves) {- const auto body = encode_negotiate(wants, haves);- auto frame = request(wire::NEGOTIATE, body);- if (!frame)- return false;- if (frame->kind != wire::NEGOTIATE_OK) {- set_error("unexpected response to negotiation (message kind " +- std::to_string(frame->kind) + ")");- return false;- }- return true;-}--bool Client::receive_stream(const fs::path &repo) {- blake3_hasher hasher;- blake3_hasher_init(&hasher);- Writer writer;- bool good = true;-- for (;;) {- auto frame = wire::read_frame(stream_);- if (!frame) {- set_error("connection closed while receiving data");- return false;- }- if (frame->kind == wire::END) {- std::array<std::uint8_t, 32> digest{};- blake3_hasher_finalize(&hasher, digest.data(), digest.size());- if (frame->payload.size() != digest.size() ||- std::memcmp(frame->payload.data(), digest.data(), digest.size()) !=- 0) {- set_error("server sent a corrupt transfer checksum");- return false;- }- break;- }- if (frame->kind == wire::ERROR) {- set_error_frame(*frame);- return false;- }- if (frame->kind != wire::RECORDS) {- set_error("unexpected message while receiving data (message kind " +- std::to_string(frame->kind) + ")");- return false;- }- blake3_hasher_update(&hasher, frame->payload.data(), frame->payload.size());- auto record = wire::parse_record(bytes_of(frame->payload));- if (!record) {- good = false;- } else {- const Id computed =- object_id(record->kind, bytes_of(record->body));- if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {- good = false;- } else {- writer.add_known(record->kind, record->id, std::move(record->body));- }- }- if (!good)- return false;- }-- if (!writer.finish(repo)) {- set_error("cannot write incoming objects to the store");- return false;- }- return true;-}--bool Client::fetch_skeleton(const fs::path &repo,- const std::vector<Id> &wants) {- const auto body = encode_ids(wants);- const std::uint32_t rid =- static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);- if (!wire::write_frame(stream_, wire::FETCH_SKELETON, rid, body)) {- set_error("connection closed while requesting objects");- return false;- }- return receive_stream(repo);-}--bool Client::get_chunks(const fs::path &repo, const std::vector<Id> &ids) {- if (ids.empty())- return true;- const auto body = encode_ids(ids);- const std::uint32_t rid =- static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);- if (!wire::write_frame(stream_, wire::GET_CHUNKS, rid, body)) {- set_error("connection closed while requesting chunks");- return false;- }- return receive_stream(repo);-}--bool Client::have_query(const std::vector<Id> &ids,- std::vector<std::uint8_t> &bits) {- const auto body = encode_ids(ids);- auto frame = request(wire::HAVE_QUERY, body);- if (!frame)- return false;- if (frame->kind != wire::HAVE_BITMAP)- return false;- auto decoded = decode_bitmap(frame->payload);- if (!decoded)- return false;- bits = std::move(*decoded);- return true;-}--bool Client::push_objects(const fs::path &repo, const std::vector<Id> &ids) {- const std::uint32_t rid =- static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);- if (!wire::write_frame(stream_, wire::PUT_RECORDS, rid, Bytes{})) {- set_error("connection closed while starting push");- return false;- }- Store store = Store::open_all(repo);- blake3_hasher hasher;- blake3_hasher_init(&hasher);- bool good = true;- for (const auto &id : ids) {- const auto loc = store.find(id);- if (!loc) {- set_error("local object is missing from the store: " + id_text(id));- good = false;- break;- }- auto body = store.read_body(id, loc->kind);- if (!body) {- set_error("cannot read local object from the store: " + id_text(id));- good = false;- break;- }- const auto record = wire::make_record(id, loc->kind, bytes_of(*body));- blake3_hasher_update(&hasher, record.data(), record.size());- if (!wire::write_frame(stream_, wire::RECORDS, rid,- Bytes(record.data(), record.size()))) {- set_error("connection closed while sending object: " + id_text(id));- good = false;- break;- }- }- std::array<std::uint8_t, 32> digest{};- blake3_hasher_finalize(&hasher, digest.data(), digest.size());- if (!good)- return false;- if (!wire::write_frame(stream_, wire::END, rid,- Bytes(digest.data(), digest.size()))) {- set_error("connection closed while finishing push");- return false;- }- auto ack = wire::read_frame(stream_);- if (!ack) {- set_error("server closed the connection before acknowledging the push");- return false;- }- if (ack->kind == wire::END)- return true;- if (ack->kind == wire::ERROR) {- set_error_frame(*ack);- return false;- }- set_error("unexpected response to object push (message kind " +- std::to_string(ack->kind) + ")");- return false;-}--bool Client::update_refs(const std::vector<UpdateRef> &updates) {- const auto body = encode_update_refs(updates);- auto frame = request(wire::UPDATE_REFS, body);- if (!frame)- return false;- if (frame->kind != wire::UPDATE_REFS_OK) {- set_error("unexpected response to ref update (message kind " +- std::to_string(frame->kind) + ")");- return false;- }- return true;-}--bool Client::whoami(std::uint8_t &role, std::string &fingerprint) {- auto frame = request(wire::WHOAMI, Bytes{});- if (!frame)- return false;- if (frame->kind != wire::WHOAMI_OK)- return false;- Reader reader(frame->payload);- const auto role_value = reader.u8();- if (!role_value)- return false;- const auto fp = reader.bytes(64);- if (!fp)- return false;- role = *role_value;- fingerprint = bytes_to_string(*fp);- return true;-}--} // namespace vn::proto--- a/veins-cpprewrite/src/protocol.h+++ /dev/null@@ -1,162 +0,0 @@-#pragma once--#include "crypto.h"-#include "net.h"-#include "wire.h"--#include <cstdint>-#include <optional>-#include <string>-#include <string_view>-#include <vector>--namespace vn::proto {--constexpr std::uint16_t PROTOCOL_VERSION = 1;--struct Hello {- std::uint16_t min_version = PROTOCOL_VERSION;- std::uint16_t max_version = PROTOCOL_VERSION;- std::vector<std::string> capabilities;- std::string repo;- std::string client_nonce;-};--struct HelloOk {- std::uint16_t version = 0;- std::vector<std::string> capabilities;- std::string server_nonce;- std::uint8_t auth_required = 0;-};--struct Auth {- std::string public_key;- std::string signature;-};--struct AuthOk {- std::uint8_t role = 0;- std::string fingerprint;-};--struct RefInfo {- std::string name;- Id target{};- std::string change_id;- std::uint8_t kind = 0; // 0 bookmark, 1 tag-};--struct Negotiate {- std::vector<Id> wants;- std::vector<Id> haves;-};--struct UpdateRef {- std::string name;- std::optional<Id> expected;- std::optional<Id> target;-};--std::vector<std::uint8_t> encode_hello(const Hello &hello);-std::optional<Hello> decode_hello(Bytes data);--std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello);-std::optional<HelloOk> decode_hello_ok(Bytes data);--std::vector<std::uint8_t> encode_auth(const Auth &auth);-std::optional<Auth> decode_auth(Bytes data);--std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth);-std::optional<AuthOk> decode_auth_ok(Bytes data);--std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs);-std::optional<std::vector<RefInfo>> decode_refs(Bytes data);--std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids);-std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max);--std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,- const std::vector<Id> &haves);-std::optional<Negotiate> decode_negotiate(Bytes data);--std::vector<std::uint8_t> encode_negotiate_ok(const std::vector<std::uint8_t> &known,- std::uint8_t enough);-std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data);--std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits);-std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data);--std::vector<std::uint8_t> encode_update_refs(const std::vector<UpdateRef> &updates);-std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data);--// The bytes signed in AUTH.-std::string auth_message(std::uint16_t version, std::string_view repo,- Bytes server_nonce, Bytes client_nonce, Bytes binding);-std::string_view role_name(std::uint8_t role);--// ----------------------------------------------------------------------------// URLs-// -----------------------------------------------------------------------------struct Url {- bool tls = false;- bool ssh = false;- std::string host;- int port = 0;- std::string path;-};--std::optional<Url> parse_url(std::string_view url);-std::string url_repo_name(std::string_view url);--// ----------------------------------------------------------------------------// Client-// -----------------------------------------------------------------------------class Client {-public:- Client() = default;- ~Client() = default;- Client(Client &&) noexcept = default;- Client &operator=(Client &&) noexcept = default;- Client(const Client &) = delete;- Client &operator=(const Client &) = delete;-- // Connect and authenticate. An empty key name means anonymous unless the- // server requires authentication, in which case "default" is used.- static std::optional<Client> connect(std::string_view url,- std::string_view key_name,- std::string_view repo_name,- std::string_view tls_pin = {});-- bool list_refs(std::vector<RefInfo> &refs);- bool negotiate(const std::vector<Id> &wants, const std::vector<Id> &haves);- bool fetch_skeleton(const fs::path &repo, const std::vector<Id> &wants);- bool get_chunks(const fs::path &repo, const std::vector<Id> &ids);- bool have_query(const std::vector<Id> &ids, std::vector<std::uint8_t> &bits);- bool push_objects(const fs::path &repo, const std::vector<Id> &ids);- bool update_refs(const std::vector<UpdateRef> &updates);- bool whoami(std::uint8_t &role, std::string &fingerprint);-- [[nodiscard]] const std::string &error() const { return last_error_; }- [[nodiscard]] std::uint8_t role() const { return role_; }- [[nodiscard]] bool authenticated() const { return authed_; }- [[nodiscard]] const std::string &fingerprint() const { return fingerprint_; }- [[nodiscard]] bool has_connection() const { return stream_.valid(); }--private:- std::optional<wire::Frame> request(std::uint8_t kind, Bytes payload);- bool receive_stream(const fs::path &repo);- void set_error(std::string text);- void set_error_frame(const wire::Frame &frame);-- net::Stream stream_;- std::string binding_;- std::uint16_t version_ = PROTOCOL_VERSION;- std::uint8_t role_ = 0;- bool authed_ = false;- std::string fingerprint_;- std::string last_error_;-};--} // namespace vn::proto--- a/veins-cpprewrite/src/remove.cpp+++ /dev/null@@ -1,415 +0,0 @@-#include "local_commands.h"--#include "pathspec.h"-#include "store.h"-#include "worktree.h"--#include <algorithm>-#include <iostream>-#include <set>-#include <system_error>--namespace vn {--namespace {--bool rm_is_flag(std::string_view arg) {- return !arg.empty() && arg.front() == '-';-}--bool starts_with_child(std::string_view path, std::string_view parent) {- return path.size() > parent.size() &&- path.compare(0, parent.size(), parent) == 0 &&- path[parent.size()] == '/';-}--bool literal_matches(std::string_view operand, std::string_view path) {- return path == operand || starts_with_child(path, operand);-}--bool glob_matches(std::string_view operand, std::string_view path) {- if (glob_match(operand, path))- return true;- for (std::size_t i = 0; i < path.size(); ++i) {- if (path[i] == '/' && glob_match(operand, path.substr(0, i)))- return true;- }- return false;-}--bool operand_matches(std::string_view operand, std::string_view path) {- if (pathspec_has_glob(operand))- return glob_matches(operand, path);- return literal_matches(operand, path);-}--bool subtree_affected(std::string_view prefix,- const std::vector<std::string> &removes) {- if (prefix.empty())- return !removes.empty();- for (const auto &r : removes) {- if (prefix == r || starts_with_child(r, prefix) ||- starts_with_child(prefix, r))- return true;- }- return false;-}--bool path_removed(std::string_view path,- const std::vector<std::string> &removes) {- for (const auto &r : removes) {- if (path == r || starts_with_child(path, r))- return true;- }- return false;-}--std::string join_path(std::string_view prefix, std::string_view name) {- if (prefix.empty())- return std::string(name);- std::string out(prefix);- out.push_back('/');- out.append(name);- return out;-}--Id empty_tree_id(Txn &tx) {- auto body = encode_tree({});- if (!body)- return Id{};- return tx.add_object(TYPE_TREE, *body);-}--std::optional<Id> filter_tree(Txn &tx, Store &store, const Id &tree_id,- std::string_view prefix,- const std::vector<std::string> &removes,- std::size_t depth) {- if (depth > 4096)- return tree_id;- if (!subtree_affected(prefix, removes))- return tree_id;- auto body = store.read_body(tree_id, TYPE_TREE);- if (!body)- return tree_id;- auto tree = decode_tree(bytes_of(*body));- if (!tree)- return tree_id;-- std::vector<TreeEntry> entries;- entries.reserve(tree->entries.size());- for (const auto &entry : tree->entries) {- const std::string full = join_path(prefix, entry.name);- if (path_removed(full, removes))- continue;- if (entry.kind == KIND_SUBTREE && subtree_affected(full, removes)) {- auto child = filter_tree(tx, store, entry.target, full, removes, depth + 1);- if (child)- entries.push_back(TreeEntry{entry.name, entry.kind, *child});- } else {- entries.push_back(entry);- }- }- if (entries.empty())- return std::nullopt;- auto encoded = encode_tree(entries);- if (!encoded)- return std::nullopt;- return tx.add_object(TYPE_TREE, *encoded);-}--std::optional<std::string> parent_of(std::string_view path) {- const auto slash = path.rfind('/');- if (slash == std::string_view::npos)- return std::nullopt;- return std::string(path.substr(0, slash));-}--bool delete_one(const fs::path &root, std::string_view rel) {- std::error_code ec;- const fs::path full = root / path_from_bytes(rel);- const bool removed = fs::remove(full, ec);- return removed && !ec;-}--void prune_empty_parents(const fs::path &root, std::string_view rel) {- std::string current(rel);- for (;;) {- const auto slash = current.rfind('/');- if (slash == std::string::npos)- break;- current.resize(slash);- std::error_code ec;- const fs::path dir = root / path_from_bytes(current);- if (!fs::is_directory(dir, ec))- break;- if (!fs::remove(dir, ec) || ec)- break;- }-}--int delete_paths(const fs::path &root, const std::vector<std::string> &removes) {- std::size_t failed = 0;- for (const auto &rel : removes) {- if (!delete_one(root, rel))- ++failed;- else- prune_empty_parents(root, rel);- }- if (failed > 0) {- warning_prefix();- std::cout << "could not delete " << failed << " path(s) from disk\n";- return 1;- }- return 0;-}--int run_removal(const fs::path &root, const std::vector<std::string> &operands,- bool delete_mode) {- 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());- 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;- }-- std::vector<bool> matched(operands.size(), false);- std::vector<std::string> removes;- std::set<std::string> seen;- for (const auto &entry : flatten_tree(store, loaded->commit.root_tree)) {- for (std::size_t i = 0; i < operands.size(); ++i) {- if (operand_matches(operands[i], entry.path)) {- matched[i] = true;- if (seen.insert(entry.path).second)- removes.push_back(entry.path);- }- }- }-- bool unmatched = false;- for (std::size_t i = 0; i < operands.size(); ++i) {- if (!matched[i]) {- error_prefix();- std::cout << "path is not tracked: " << operands[i] << "\n";- unmatched = true;- }- }- if (unmatched)- return 1;-- if (!delete_mode) {- for (const auto &rel : removes) {- if (!ignore_path_ignored(root, rel)) {- warning_prefix();- std::cout << rel- << " is not ignored and will be re-added on the next snapshot\n";- }- }- }-- auto new_root = filter_tree(*tx, store, loaded->commit.root_tree, "", removes, 0);- Id root_id{};- if (new_root)- root_id = *new_root;- else- root_id = empty_tree_id(*tx);- if (std::memcmp(root_id.data(), loaded->commit.root_tree.data(), ID_LEN) == 0) {- error_prefix();- std::cout << "no tracked paths to remove\n";- return 1;- }-- const Sig sig = identity_signature(root);- Commit commit = loaded->commit;- commit.root_tree = root_id;- commit.committer = sig;- commit.renames_state = RENAMES_RECORDED;- commit.renames.clear();- const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));-- remove_head(tx->view(), *wc);- move_bookmarks(tx->view(), *wc, new_id);- set_workspace(tx->view(), new_id);- rebuild_heads(tx->view());-- int status = 0;- const auto finished = tx->finish("rm");- if (!finished)- status = 1;- if (status == 0)- (void)mark_native(root, new_id);-- if (status == 0) {- if (delete_mode) {- const int del = delete_paths(root, removes);- if (del != 0)- status = del;- }- info_prefix();- std::cout << "untracked " << removes.size() << " path(s)\n";- }- return status;-}--int rm_command(const std::vector<std::string> &args, std::size_t start) {- bool delete_mode = false;- std::vector<std::string> operands;- 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 == "-delete") {- delete_mode = true;- } else if (!end_flags && rm_is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- operands.push_back(arg);- }- }- if (operands.empty()) {- error_prefix();- std::cout << "rm requires at least one path\n";- return 1;- }-- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const int snap = snapshot_run(*root);- if (snap != 0)- return snap;-- const auto cwd_rel = cwd_relative(*root);- if (!cwd_rel) {- error_prefix();- std::cout << "cannot determine current directory\n";- return 1;- }-- std::vector<std::string> normalized;- for (const auto &arg : operands) {- auto norm = pathspec_normalize(*root, *cwd_rel, arg);- if (!norm) {- error_prefix();- std::cout << "path is outside the repository: " << arg << "\n";- return 1;- }- if (norm->empty() || !valid_path(*norm)) {- error_prefix();- std::cout << "invalid path: " << arg << "\n";- return 1;- }- normalized.push_back(std::move(*norm));- }- if (normalized.empty()) {- error_prefix();- std::cout << "rm requires at least one path\n";- return 1;- }- return run_removal(*root, normalized, delete_mode);-}--} // namespace--int rm_run(const std::vector<std::string> &args) { return rm_command(args, 2); }--int mv_run(const std::vector<std::string> &args) {- std::vector<std::string> operands;- 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 && rm_is_flag(arg)) {- error_prefix();- std::cout << "unknown flag: " << arg << "\n";- return 1;- } else {- operands.push_back(arg);- }- }-- const auto root = discover_repo(".");- if (!root) {- error_prefix();- std::cout << "not a veins repository\n";- return 1;- }- const int snap = snapshot_run(*root);- if (snap != 0)- return snap;-- if (operands.size() != 2) {- error_prefix();- std::cout << "mv requires a source and a destination\n";- return 1;- }-- const auto cwd_rel = cwd_relative(*root);- if (!cwd_rel) {- error_prefix();- std::cout << "cannot determine current directory\n";- return 1;- }- auto src = pathspec_normalize(*root, *cwd_rel, operands[0]);- if (!src) {- error_prefix();- std::cout << "invalid path\n";- return 1;- }- auto dst = pathspec_normalize(*root, *cwd_rel, operands[1]);- if (!dst) {- error_prefix();- std::cout << "invalid path\n";- return 1;- }-- const fs::path src_abs = *root / path_from_bytes(*src);- const fs::path dst_abs = *root / path_from_bytes(*dst);- if (!stat_path(src_abs)) {- error_prefix();- std::cout << "not a tracked path: " << *src << "\n";- return 1;- }- if (stat_path(dst_abs)) {- error_prefix();- std::cout << "destination already exists: " << *dst << "\n";- return 1;- }-- if (const auto parent = parent_of(*dst)) {- if (!ensure_directory(*root / path_from_bytes(*parent))) {- error_prefix();- std::cout << "cannot create destination directory\n";- return 1;- }- }- std::error_code ec;- fs::rename(src_abs, dst_abs, ec);- if (ec) {- error_prefix();- std::cout << "cannot move path\n";- return 1;- }- return snapshot_run(*root);-}--} // namespace vn--- a/veins-cpprewrite/src/server.cpp+++ /dev/null@@ -1,912 +0,0 @@-#include "server.h"--#include "auth.h"-#include "crypto.h"-#include "net.h"-#include "protocol.h"-#include "store.h"-#include "wire.h"--#include <blake3.h>--#include <algorithm>-#include <cstddef>-#include <cstring>-#include <iostream>-#include <optional>-#include <set>-#include <string>--namespace vn::server {--namespace {--constexpr std::size_t MAX_CHUNKS_PER_REQUEST = 4096;--struct Session {- net::Stream stream;- fs::path repo_root;- bool repo_present = false;- Store store;- bool store_open = false;- auth::Access access;- std::string hello_repo;- std::string server_nonce;- std::string client_nonce;- std::string binding;- std::uint16_t version = proto::PROTOCOL_VERSION;- bool authed = false;- std::uint8_t role = auth::ROLE_ANONYMOUS;- PublicKey public_key{};- bool has_public_key = false;- std::string fingerprint;- std::vector<Id> haves;- int failed_auth = 0;- bool closing = false;- fs::path root;-};--std::uint8_t effective_role(const Session &session) {- if (session.authed)- return session.role;- if (session.access.valid && session.access.anonymous_read &&- session.repo_present)- return auth::ROLE_READ;- return auth::ROLE_ANONYMOUS;-}--bool deny(Session &session, std::uint32_t request_id, bool write) {- const std::uint8_t role = effective_role(session);- if (write) {- if (role == auth::ROLE_WRITE)- return false;- if (!session.authed) {- wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,- "authentication required");- } else {- wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,- "write role required");- }- return true;- }- if (role == auth::ROLE_READ || role == auth::ROLE_WRITE)- return false;- if (!session.authed) {- wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,- "authentication required");- } else {- wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,- "read role required");- }- return true;-}--void log_line(Session &session, std::string_view text) {- if (!session.repo_present)- return;- (void)append_file(veins_dir(session.repo_root) / "server.log",- bytes_of(text));-}--void log_outcome(Session &session, std::string_view outcome) {- if (!session.repo_present)- return;- const std::string line =- std::to_string(unix_now_millis()) + " " +- std::string(proto::role_name(effective_role(session))) + " " +- std::string(outcome) + " " + session.hello_repo + "\n";- log_line(session, line);-}--bool safe_repo_name(std::string_view name) {- if (name.empty() || name.size() > 4096)- return false;- if (name.front() == '/')- return false;- if (name.find('\0') != std::string_view::npos ||- name.find('\\') != std::string_view::npos)- return false;- std::size_t start = 0;- for (std::size_t i = 0; i <= name.size(); ++i) {- if (i == name.size() || name[i] == '/') {- if (i - start == 2 && name[start] == '.' && name[start + 1] == '.')- return false;- start = i + 1;- }- }- return true;-}--void open_session_store(Session &session) {- if (session.store_open)- return;- session.store = Store::open_all(session.repo_root);- session.store_open = true;-}--void select_repo(Session &session, bool has_root) {- if (session.repo_present || !has_root)- return;- if (!safe_repo_name(session.hello_repo))- return;- const fs::path joined = session.root / path_from_bytes(session.hello_repo);- if (auto found = discover_repo(joined)) {- session.repo_root = *found;- session.repo_present = true;- }-}--std::string change_id_of(Session &session, const Id &id) {- auto loaded = load_commit(session.store, id);- if (!loaded)- return {};- return std::string(reinterpret_cast<const char *>(loaded->commit.change_id.data()),- loaded->commit.change_id.size());-}--bool send_record(Session &session, std::uint32_t request_id,- blake3_hasher &hasher, const Id &id, std::uint8_t kind,- Bytes body) {- const auto record = wire::make_record(id, kind, body);- blake3_hasher_update(&hasher, record.data(), record.size());- return wire::write_frame(session.stream, wire::RECORDS, request_id,- Bytes(record.data(), record.size()));-}--bool send_end(Session &session, std::uint32_t request_id,- blake3_hasher &hasher) {- std::array<std::uint8_t, 32> digest{};- blake3_hasher_finalize(&hasher, digest.data(), digest.size());- return wire::write_frame(session.stream, wire::END, request_id,- Bytes(digest.data(), digest.size()));-}--std::uint8_t value_kind_to_type(std::uint8_t kind) {- if (kind == KIND_SUBTREE)- return TYPE_TREE;- if (kind == KIND_CONFLICT)- return TYPE_CONFLICT;- if (kind == KIND_FILE || kind == KIND_EXECUTABLE || kind == KIND_SYMLINK)- return TYPE_BLOB;- return 0;-}--void collect_object(Session &session, std::uint32_t request_id,- blake3_hasher &hasher, const Id &id, std::uint8_t kind,- std::set<Id> &seen, bool send, bool &failed);--void collect_tree(Session &session, std::uint32_t request_id,- blake3_hasher &hasher, const Id &id, std::set<Id> &seen,- bool send, bool &failed) {- if (!seen.insert(id).second)- return;- auto body = session.store.read_body(id, TYPE_TREE);- if (!body) {- failed = true;- return;- }- if (send && !send_record(session, request_id, hasher, id, TYPE_TREE,- bytes_of(*body))) {- failed = true;- }- auto tree = decode_tree(bytes_of(*body));- if (!tree) {- failed = true;- return;- }- for (const auto &entry : tree->entries) {- if (entry.kind == KIND_SUBTREE) {- collect_tree(session, request_id, hasher, entry.target, seen, send,- failed);- } else if (entry.kind == KIND_CONFLICT) {- collect_object(session, request_id, hasher, entry.target, TYPE_CONFLICT,- seen, send, failed);- } else if (entry.kind != KIND_SUBMODULE) {- collect_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen,- send, failed);- }- if (failed)- return;- }-}--void collect_object(Session &session, std::uint32_t request_id,- blake3_hasher &hasher, const Id &id, std::uint8_t kind,- std::set<Id> &seen, bool send, bool &failed) {- if (!seen.insert(id).second)- return;- auto body = session.store.read_body(id, kind);- if (!body) {- failed = true;- return;- }- if (send && !send_record(session, request_id, hasher, id, kind,- bytes_of(*body))) {- failed = true;- }- if (kind == TYPE_BLOB) {- auto blob = decode_blob(bytes_of(*body));- if (!blob) {- failed = true;- return;- }- if (blob->form == BlobForm::Interior) {- for (const auto &entry : blob->entries) {- collect_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen,- send, failed);- if (failed)- return;- }- }- } else if (kind == TYPE_CONFLICT) {- auto conflict = decode_conflict(bytes_of(*body));- if (!conflict) {- failed = true;- return;- }- for (const auto &value : conflict->adds) {- if (!value.target)- continue;- const std::uint8_t child = value_kind_to_type(value.kind);- if (child != 0)- collect_object(session, request_id, hasher, *value.target, child, seen,- send, failed);- if (failed)- return;- }- for (const auto &value : conflict->removes) {- if (!value.target)- continue;- const std::uint8_t child = value_kind_to_type(value.kind);- if (child != 0)- collect_object(session, request_id, hasher, *value.target, child, seen,- send, failed);- if (failed)- return;- }- }-}--bool handle_hello(Session &session, const wire::Frame &frame, bool has_root) {- auto hello = proto::decode_hello(bytes_of(frame.payload));- if (!hello) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "bad HELLO");- return false;- }- if (hello->min_version > proto::PROTOCOL_VERSION ||- hello->max_version < proto::PROTOCOL_VERSION) {- wire::write_error(session.stream, frame.request_id,- wire::ERR_UNSUPPORTED_VERSION, "no common version");- return false;- }- session.version = proto::PROTOCOL_VERSION;- session.hello_repo = std::move(hello->repo);- session.client_nonce = std::move(hello->client_nonce);- select_repo(session, has_root);- if (!session.repo_present && !session.hello_repo.empty()) {- error_prefix();- std::cout << "repository not found: " << session.hello_repo << "\n";- wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,- "repository not found");- return false;- }- if (session.repo_present) {- session.access = auth::load_access(session.repo_root);- if (!session.access.valid) {- error_prefix();- std::cout << "access file error at line " << session.access.error_line- << " in " << path_display(session.repo_root) << "\n";- wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,- "invalid access file");- return false;- }- open_session_store(session);- }- log_outcome(session, "hello");-- const auto nonce = secure_random(32);- if (nonce.size() != 32) {- wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,- "cannot generate nonce");- return false;- }- session.server_nonce.assign(reinterpret_cast<const char *>(nonce.data()),- nonce.size());-- proto::HelloOk hello_ok;- hello_ok.version = session.version;- hello_ok.capabilities = {"zstd-records", "lazy-chunks", "push",- "auth-ed25519"};- hello_ok.server_nonce = session.server_nonce;- hello_ok.auth_required =- (session.repo_present && session.access.anonymous_read) ? 0 : 1;- const auto body = proto::encode_hello_ok(hello_ok);- return wire::write_frame(session.stream, wire::HELLO_OK, frame.request_id,- body);-}--bool handle_auth(Session &session, const wire::Frame &frame) {- if (session.authed) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "repeated AUTH");- session.closing = true;- return false;- }- auto auth = proto::decode_auth(bytes_of(frame.payload));- if (!auth) {- ++session.failed_auth;- wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,- "authentication failed");- return false;- }- PublicKey public_key{};- const bool key_well_formed = auth->public_key.size() == public_key.size();- if (key_well_formed) {- std::memcpy(public_key.data(), auth->public_key.data(),- public_key.size());- }- std::uint8_t role = auth::ROLE_UNKNOWN;- if (key_well_formed && session.repo_present && session.access.valid)- role = auth::role_for(session.access, &public_key);-- const std::string message = proto::auth_message(- session.version, session.hello_repo, bytes_of(session.server_nonce),- bytes_of(session.client_nonce), bytes_of(session.binding));- const bool signature_ok =- role != auth::ROLE_UNKNOWN &&- ed25519_verify(public_key, bytes_of(message), bytes_of(auth->signature));- if (!signature_ok) {- ++session.failed_auth;- wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,- "authentication failed");- if (session.failed_auth >= 3)- session.closing = true;- return false;- }-- session.authed = true;- session.role = role;- session.public_key = public_key;- session.has_public_key = true;- const auto raw_fingerprint = key_fingerprint_bytes(public_key);- session.fingerprint.assign(- reinterpret_cast<const char *>(raw_fingerprint.data()),- raw_fingerprint.size());-- proto::AuthOk auth_ok;- auth_ok.role = role;- auth_ok.fingerprint = session.fingerprint;- const auto body = proto::encode_auth_ok(auth_ok);- const bool wrote = wire::write_frame(session.stream, wire::AUTH_OK,- frame.request_id, body);- log_outcome(session, "auth-ok");- return wrote;-}--bool handle_whoami(Session &session, const wire::Frame &frame) {- ByteWriter writer(64);- writer.u8(effective_role(session));- writer.length_prefixed(session.fingerprint);- return wire::write_frame(session.stream, wire::WHOAMI_OK, frame.request_id,- writer.view());-}--bool handle_list_refs(Session &session, const wire::Frame &frame) {- if (deny(session, frame.request_id, false))- return true;- log_outcome(session, "list-refs");- std::optional<View> view = current_view(session.repo_root, session.store);- if (!view) {- const auto heads = read_heads(session.repo_root);- if (!heads.empty()) {- wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,- "cannot read operation state");- log_outcome(session, "list-refs-error");- return true;- }- view = empty_view();- }- std::vector<proto::RefInfo> refs;- for (const auto &bookmark : view->bookmarks) {- if (bookmark.targets.adds.size() != 1 || !bookmark.targets.adds.front())- continue;- proto::RefInfo ref;- ref.name = bookmark.name;- ref.target = *bookmark.targets.adds.front();- ref.change_id = change_id_of(session, ref.target);- ref.kind = 0;- refs.push_back(std::move(ref));- }- for (const auto &tag : view->tags) {- proto::RefInfo ref;- ref.name = tag.name;- ref.target = tag.target;- ref.change_id = change_id_of(session, tag.target);- ref.kind = 1;- refs.push_back(std::move(ref));- }- const auto body = proto::encode_refs(refs);- const bool wrote =- wire::write_frame(session.stream, wire::REFS, frame.request_id, body);- if (!wrote)- log_outcome(session, "list-refs-write-error");- return wrote;-}--bool handle_negotiate(Session &session, const wire::Frame &frame) {- if (deny(session, frame.request_id, false))- return true;- auto negotiate = proto::decode_negotiate(bytes_of(frame.payload));- if (!negotiate) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "bad NEGOTIATE");- return true;- }- session.haves = std::move(negotiate->haves);- std::vector<std::uint8_t> known;- known.reserve(session.haves.size());- bool any_known = false;- for (const auto &id : session.haves) {- const bool found = session.store.find(id).has_value();- known.push_back(found ? 1 : 0);- any_known = any_known || found;- }- const std::uint8_t enough =- (session.haves.empty() || any_known) ? 1 : 0;- const auto body = proto::encode_negotiate_ok(known, enough);- return wire::write_frame(session.stream, wire::NEGOTIATE_OK,- frame.request_id, body);-}--bool handle_fetch(Session &session, const wire::Frame &frame) {- if (deny(session, frame.request_id, false))- return true;- auto wants = proto::decode_ids(bytes_of(frame.payload), 1000000);- if (!wants) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "bad wants");- return true;- }- if (wants->empty()) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "empty wants");- return true;- }- const auto all = collect_commits(session.store, *wants);- std::set<Id> exclude;- for (const auto &have : session.haves) {- const std::array<Id, 1> roots{have};- for (const auto &id : collect_commits(session.store, roots))- exclude.insert(id);- }-- blake3_hasher hasher;- blake3_hasher_init(&hasher);- bool failed = false;- std::set<Id> seen;- for (const auto &id : all) {- if (exclude.contains(id))- continue;- auto loaded = load_commit(session.store, id);- if (!loaded) {- failed = true;- break;- }- if (!send_record(session, frame.request_id, hasher, id, TYPE_COMMIT,- bytes_of(loaded->body))) {- failed = true;- break;- }- collect_tree(session, frame.request_id, hasher, loaded->commit.root_tree,- seen, true, failed);- if (failed)- break;- }- if (!failed)- (void)send_end(session, frame.request_id, hasher);- log_outcome(session, "fetch");- return !failed;-}--bool handle_get_chunks(Session &session, const wire::Frame &frame) {- if (deny(session, frame.request_id, false))- return true;- auto ids = proto::decode_ids(bytes_of(frame.payload),- MAX_CHUNKS_PER_REQUEST);- if (!ids) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "bad chunk list");- return true;- }- blake3_hasher hasher;- blake3_hasher_init(&hasher);- bool failed = false;- for (const auto &id : *ids) {- const auto loc = session.store.find(id);- if (!loc || loc->kind != TYPE_CHUNK) {- failed = true;- break;- }- auto body = session.store.get(*loc);- if (!body) {- failed = true;- break;- }- if (!send_record(session, frame.request_id, hasher, id, TYPE_CHUNK,- bytes_of(*body))) {- failed = true;- break;- }- }- if (failed) {- wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,- "chunk not found");- } else {- (void)send_end(session, frame.request_id, hasher);- }- return !failed;-}--bool handle_have_query(Session &session, const wire::Frame &frame) {- if (deny(session, frame.request_id, true))- return true;- auto ids = proto::decode_ids(bytes_of(frame.payload), 1000000);- if (!ids) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "bad HAVE_QUERY");- return true;- }- std::vector<std::uint8_t> bits;- bits.reserve(ids->size());- for (const auto &id : *ids)- bits.push_back(session.store.find(id).has_value() ? 1 : 0);- const auto body = proto::encode_bitmap(bits);- return wire::write_frame(session.stream, wire::HAVE_BITMAP,- frame.request_id, body);-}--bool object_exists(Session &session, const Id &id) {- return session.store.find(id).has_value();-}--bool check_closure(Session &session, const Id &id, std::uint8_t kind) {- auto body = session.store.read_body(id, kind);- if (!body)- return false;- bool fine = true;- if (kind == TYPE_COMMIT) {- auto commit = decode_commit(bytes_of(*body));- if (!commit)- return false;- if (!object_exists(session, commit->root_tree))- fine = false;- for (const auto &parent : commit->parents) {- if (!object_exists(session, parent))- fine = false;- }- } else if (kind == TYPE_TREE) {- auto tree = decode_tree(bytes_of(*body));- if (!tree)- return false;- for (const auto &entry : tree->entries) {- if (entry.kind != KIND_SUBMODULE && !object_exists(session, entry.target))- fine = false;- }- } else if (kind == TYPE_BLOB) {- auto blob = decode_blob(bytes_of(*body));- if (!blob)- return false;- for (const auto &entry : blob->entries) {- if (!object_exists(session, entry.id))- fine = false;- }- } else if (kind == TYPE_CONFLICT) {- auto conflict = decode_conflict(bytes_of(*body));- if (!conflict)- return false;- for (const auto &value : conflict->adds) {- if (value.target && !object_exists(session, *value.target))- fine = false;- }- for (const auto &value : conflict->removes) {- if (value.target && !object_exists(session, *value.target))- fine = false;- }- }- return fine;-}--bool handle_put_records(Session &session, const wire::Frame &frame) {- if (deny(session, frame.request_id, true))- return true;- Writer writer;- blake3_hasher hasher;- blake3_hasher_init(&hasher);- bool failed = false;- std::vector<Id> accepted;-- for (;;) {- auto frame_opt = wire::read_frame(session.stream);- if (!frame_opt) {- failed = true;- break;- }- const auto &incoming = *frame_opt;- if (incoming.kind == wire::END) {- std::array<std::uint8_t, 32> digest{};- blake3_hasher_finalize(&hasher, digest.data(), digest.size());- if (incoming.payload.size() != digest.size() ||- std::memcmp(incoming.payload.data(), digest.data(), digest.size()) !=- 0) {- failed = true;- }- break;- }- if (incoming.kind != wire::RECORDS) {- failed = true;- break;- }- blake3_hasher_update(&hasher, incoming.payload.data(),- incoming.payload.size());- auto record = wire::parse_record(bytes_of(incoming.payload));- if (!record) {- failed = true;- break;- }- const Id computed = object_id(record->kind, bytes_of(record->body));- if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {- failed = true;- break;- }- writer.add_known(record->kind, record->id, std::move(record->body));- accepted.push_back(record->id);- }-- if (failed) {- wire::write_error(session.stream, frame.request_id,- wire::ERR_HASH_MISMATCH, "record rejected");- return true;- }- if (!writer.finish(session.repo_root)) {- wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,- "pack write failed");- return true;- }- open_session_store(session);- session.store.refresh(session.repo_root);-- bool closure_ok = true;- for (const auto &id : accepted) {- const auto loc = session.store.find(id);- if (!loc)- continue;- if (!check_closure(session, id, loc->kind)) {- closure_ok = false;- break;- }- }- if (!closure_ok) {- wire::write_error(session.stream, frame.request_id,- wire::ERR_MISSING_CLOSURE, "missing object closure");- return true;- }- return wire::write_frame(session.stream, wire::END, frame.request_id,- Bytes{});-}--std::optional<Id> first_target(const TargetSet &targets) {- if (targets.adds.empty())- return std::nullopt;- return targets.adds.front();-}--bool ref_matches(const View &view, std::string_view name,- const std::optional<Id> &expected) {- std::optional<Id> current;- if (auto index = find_bookmark(view, name)) {- current = first_target(view.bookmarks[*index].targets);- } else if (auto index = find_tag(view, name)) {- current = view.tags[*index].target;- }- if (!expected)- return !current.has_value();- if (!current)- return false;- return std::memcmp(current->data(), expected->data(), ID_LEN) == 0;-}--void apply_ref(View &view, std::string_view name,- const std::optional<Id> &target) {- if (!target) {- if (auto index = find_bookmark(view, name))- view.bookmarks.erase(view.bookmarks.begin() +- static_cast<std::ptrdiff_t>(*index));- if (auto index = find_tag(view, name))- view.tags.erase(view.tags.begin() +- static_cast<std::ptrdiff_t>(*index));- return;- }- if (auto index = find_bookmark(view, name)) {- auto &bookmark = view.bookmarks[*index];- bookmark.targets.adds = {*target};- bookmark.targets.removes.clear();- return;- }- if (auto index = find_tag(view, name)) {- view.tags[*index].target = *target;- return;- }- Bookmark bookmark;- bookmark.name = std::string(name);- bookmark.targets.adds = {*target};- view.bookmarks.push_back(std::move(bookmark));-}--bool handle_update_refs(Session &session, const wire::Frame &frame) {- if (deny(session, frame.request_id, true))- return true;- auto updates = proto::decode_update_refs(bytes_of(frame.payload));- if (!updates) {- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "bad UPDATE_REFS");- return true;- }- auto tx = Txn::begin(session.repo_root, session.store);- if (!tx) {- wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,- "cannot update refs");- return true;- }- for (const auto &update : *updates) {- if (!ref_matches(tx->view(), update.name, update.expected)) {- wire::write_error(session.stream, frame.request_id,- wire::ERR_REF_CONFLICT, "ref changed");- return true;- }- }- for (const auto &update : *updates)- apply_ref(tx->view(), update.name, update.target);- rebuild_heads(tx->view());- const auto status = tx->finish("remote push");- if (!status) {- wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,- "commit failed");- return true;- }- session.store.refresh(session.repo_root);- const std::string line = std::to_string(unix_now_millis()) + " " +- base32_text(bytes_of(session.fingerprint)) +- " update-refs\n";- log_line(session, line);- return wire::write_simple(session.stream, wire::UPDATE_REFS_OK,- frame.request_id);-}--bool dispatch(Session &session, const wire::Frame &frame) {- if (frame.kind == wire::HELLO)- return handle_hello(session, frame, !session.root.empty());- if (frame.kind == wire::AUTH)- return handle_auth(session, frame);- if (frame.kind == wire::WHOAMI)- return handle_whoami(session, frame);- if (!session.repo_present) {- wire::write_error(session.stream, frame.request_id,- wire::ERR_UNAUTHENTICATED, "authentication required");- return true;- }- if (frame.kind == wire::LIST_REFS)- return handle_list_refs(session, frame);- if (frame.kind == wire::NEGOTIATE)- return handle_negotiate(session, frame);- if (frame.kind == wire::FETCH_SKELETON)- return handle_fetch(session, frame);- if (frame.kind == wire::GET_CHUNKS)- return handle_get_chunks(session, frame);- if (frame.kind == wire::HAVE_QUERY)- return handle_have_query(session, frame);- if (frame.kind == wire::PUT_RECORDS)- return handle_put_records(session, frame);- if (frame.kind == wire::UPDATE_REFS)- return handle_update_refs(session, frame);- wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,- "unknown request");- return true;-}--void run_session(net::Stream stream, std::optional<fs::path> fixed,- std::optional<fs::path> root, std::string binding) {- Session session;- session.stream = std::move(stream);- session.binding = std::move(binding);- if (root)- session.root = *root;- if (fixed) {- session.repo_root = *fixed;- session.repo_present = true;- session.access = auth::load_access(session.repo_root);- if (session.access.valid)- open_session_store(session);- }- while (!session.closing) {- auto frame = wire::read_frame(session.stream);- if (!frame)- break;- const bool keep = dispatch(session, *frame);- if (!keep)- break;- }- log_outcome(session, "close");- session.stream.close();-}--std::optional<int> parse_port(std::string_view address) {- const auto colon = address.rfind(':');- if (colon == std::string_view::npos || colon + 1 >= address.size())- return std::nullopt;- int port = 0;- for (char c : address.substr(colon + 1)) {- if (c < '0' || c > '9')- return std::nullopt;- port = port * 10 + (c - '0');- if (port > 65535)- return std::nullopt;- }- return port;-}--} // namespace--int serve_stdio(const fs::path &repo) {- run_session(net::Stream::stdio_stream(), repo, std::nullopt, {});- return 0;-}--int serve_listen(std::string_view address, const fs::path &root,- std::string_view cert_path, std::string_view key_path) {- net::ignore_sigpipe();- auto port = parse_port(address);- if (!port) {- error_prefix();- std::cout << "invalid listen address\n";- return 1;- }- void *ctx = net::tls_server_ctx(cert_path, key_path);- if (!ctx) {- error_prefix();- std::cout << "cannot load TLS certificate or key\n";- return 1;- }- const net::Socket listener = net::tcp_listen(*port);- if (listener == net::INVALID_SOCKET_VALUE) {- error_prefix();- std::cout << "cannot listen on port " << *port << "\n";- net::tls_ctx_free(ctx);- return 1;- }- info_prefix();- std::cout << "listening on " << address << "\n";- for (;;) {- auto accepted = net::tcp_accept(listener);- if (!accepted)- break;- void *ssl = net::tls_accept(ctx, *accepted);- if (!ssl) {- net::close_socket(*accepted);- continue;- }- std::array<std::uint8_t, 32> exported{};- std::string binding;- if (net::tls_exporter(ssl, exported.data(), exported.size())) {- binding.assign(reinterpret_cast<const char *>(exported.data()),- exported.size());- }- run_session(net::Stream::tls_stream(*accepted, ssl), std::nullopt, root,- std::move(binding));- }- net::close_socket(listener);- net::tls_ctx_free(ctx);- return 0;-}--} // namespace vn::server--- a/veins-cpprewrite/src/server.h+++ /dev/null@@ -1,13 +0,0 @@-#pragma once--#include "common.h"--#include <string_view>--namespace vn::server {--int serve_stdio(const fs::path &repo);-int serve_listen(std::string_view address, const fs::path &root,- std::string_view cert_path, std::string_view key_path);--} // namespace vn::server--- a/veins-cpprewrite/src/store.cpp+++ /dev/null@@ -1,1939 +0,0 @@-#include "store.h"--#include <algorithm>-#include <atomic>-#include <cstring>-#include <iostream>-#include <thread>-#include <unordered_set>--#include <zstd.h>--namespace vn {--namespace {-PromisorFetcher promisor_fetcher;-} // namespace--void set_promisor_fetcher(PromisorFetcher fetcher) {- promisor_fetcher = std::move(fetcher);-}--// ----------------------------------------------------------------------------// 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;- store.root_ = 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;- 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) {- auto loc = find(id);- if (!loc && expected == TYPE_CHUNK && promisor_fetcher && !root_.empty()) {- if (promisor_fetcher(root_, id)) {- refresh(root_);- 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--- a/veins-cpprewrite/src/store.h+++ /dev/null@@ -1,241 +0,0 @@-#pragma once--#include "object.h"--#include <functional>-#include <memory>-#include <optional>-#include <set>-#include <string>-#include <vector>--namespace vn {--// Called when a promised chunk is missing. Returns true when the object was-// fetched and written to a pack.-using PromisorFetcher = std::function<bool(const fs::path &, const Id &)>;-void set_promisor_fetcher(PromisorFetcher fetcher);--// ----------------------------------------------------------------------------// 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_; }- const fs::path &root() const { return root_; }- void preload();--private:- bool ensure_index(StoreHandle &handle);- bool ensure_pack(StoreHandle &handle);- fs::path root_;- 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--- a/veins-cpprewrite/src/wire.cpp+++ /dev/null@@ -1,185 +0,0 @@-#include "wire.h"--#include <zstd.h>--#include <array>-#include <cstring>--namespace vn::wire {--namespace {--bool read_exact(net::Stream &stream, std::uint8_t *out, std::size_t count) {- std::size_t got = 0;- while (got < count) {- const std::int64_t n = stream.read(out + got, count - got);- if (n <= 0)- return false;- got += static_cast<std::size_t>(n);- }- return true;-}--} // namespace--std::optional<Frame> read_frame(net::Stream &stream) {- std::array<std::uint8_t, 4> head{};- if (!read_exact(stream, head.data(), head.size()))- return std::nullopt;- const std::uint32_t length = (static_cast<std::uint32_t>(head[0]) << 24) |- (static_cast<std::uint32_t>(head[1]) << 16) |- (static_cast<std::uint32_t>(head[2]) << 8) |- static_cast<std::uint32_t>(head[3]);- if (length < 5 || length > MAX_FRAME)- return std::nullopt;- std::vector<std::uint8_t> body(length);- if (!read_exact(stream, body.data(), body.size()))- return std::nullopt;- Frame frame;- frame.kind = body[0];- frame.request_id = (static_cast<std::uint32_t>(body[1]) << 24) |- (static_cast<std::uint32_t>(body[2]) << 16) |- (static_cast<std::uint32_t>(body[3]) << 8) |- static_cast<std::uint32_t>(body[4]);- frame.payload.assign(body.begin() + 5, body.end());- return frame;-}--bool write_frame(net::Stream &stream, std::uint8_t kind,- std::uint32_t request_id, Bytes payload) {- if (payload.size() > MAX_FRAME - 5)- return false;- const std::uint32_t length = static_cast<std::uint32_t>(5 + payload.size());- std::array<std::uint8_t, 9> head{};- head[0] = static_cast<std::uint8_t>((length >> 24) & 255u);- head[1] = static_cast<std::uint8_t>((length >> 16) & 255u);- head[2] = static_cast<std::uint8_t>((length >> 8) & 255u);- head[3] = static_cast<std::uint8_t>(length & 255u);- head[4] = kind;- head[5] = static_cast<std::uint8_t>((request_id >> 24) & 255u);- head[6] = static_cast<std::uint8_t>((request_id >> 16) & 255u);- head[7] = static_cast<std::uint8_t>((request_id >> 8) & 255u);- head[8] = static_cast<std::uint8_t>(request_id & 255u);- if (!stream.write_all(Bytes(head.data(), head.size())))- return false;- return payload.empty() || stream.write_all(payload);-}--bool write_simple(net::Stream &stream, std::uint8_t kind,- std::uint32_t request_id) {- return write_frame(stream, kind, request_id, Bytes{});-}--bool write_error(net::Stream &stream, std::uint32_t request_id,- std::uint8_t code, std::string_view message) {- ByteWriter writer(64);- writer.u8(code);- writer.length_prefixed(message);- return write_frame(stream, ERROR, request_id, writer.view());-}--std::uint8_t read_error(Bytes payload) {- if (payload.empty())- return ERR_INTERNAL;- return payload[0];-}--std::string error_message(Bytes payload) {- if (payload.size() < 2)- return {};- Reader reader(payload.subspan(1));- auto value = reader.bytes(4096);- if (!value)- return {};- return std::string(str_of(*value));-}--std::string_view error_code_name(std::uint8_t code) {- switch (code) {- case ERR_UNSUPPORTED_VERSION:- return "unsupported protocol version";- case ERR_BAD_FRAME:- return "bad frame";- case ERR_NOT_FOUND:- return "object not found";- case ERR_HASH_MISMATCH:- return "hash mismatch";- case ERR_NON_CANONICAL:- return "non-canonical object";- case ERR_MISSING_CLOSURE:- return "missing object closure";- case ERR_REF_CONFLICT:- return "ref conflict";- case ERR_REJECTED:- return "request rejected";- case ERR_INTERNAL:- return "server internal error";- case ERR_UNAUTHENTICATED:- return "authentication required";- case ERR_FORBIDDEN:- return "permission denied";- case ERR_AUTH_FAILED:- return "authentication failed";- default:- return "unknown server error";- }-}--std::optional<IncomingRecord> parse_record(Bytes data) {- if (data.size() < 35)- return std::nullopt;- Reader reader(data);- const auto id = reader.id();- if (!id)- return std::nullopt;- const auto kind = reader.u8();- if (!kind)- return std::nullopt;- const auto compression = reader.u8();- if (!compression)- return std::nullopt;- const auto raw_len = reader.varint();- if (!raw_len)- return std::nullopt;- const auto stored_len = reader.varint();- if (!stored_len)- return std::nullopt;- if (*raw_len == 0 || *raw_len > 64u * 1024u * 1024u ||- *stored_len > MAX_FRAME)- return std::nullopt;- const auto stored = reader.raw(static_cast<std::size_t>(*stored_len));- if (!stored)- return std::nullopt;- if (!reader.at_end())- return std::nullopt;- IncomingRecord record;- record.id = *id;- record.kind = *kind;- if (*compression == 0) {- if (stored->size() != static_cast<std::size_t>(*raw_len))- return std::nullopt;- record.body.assign(stored->begin(), stored->end());- return record;- }- record.body.resize(static_cast<std::size_t>(*raw_len));- const std::size_t result =- ZSTD_decompress(record.body.data(), record.body.size(), stored->data(),- stored->size());- if (ZSTD_isError(result) || result != record.body.size())- return std::nullopt;- return record;-}--std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,- Bytes body) {- ByteWriter writer(body.size() + 64);- writer.raw(Bytes(id.data(), id.size()));- writer.u8(kind);- writer.u8(0);- writer.varint(body.size());- writer.varint(body.size());- writer.raw(body);- return writer.take();-}--} // namespace vn::wire--- a/veins-cpprewrite/src/wire.h+++ /dev/null@@ -1,80 +0,0 @@-#pragma once--#include "net.h"--#include <cstdint>-#include <optional>-#include <string>-#include <vector>--namespace vn::wire {--constexpr std::size_t MAX_FRAME = 16u * 1024u * 1024u;--enum Kind : std::uint8_t {- HELLO = 1,- HELLO_OK = 2,- AUTH = 3,- AUTH_OK = 4,- WHOAMI = 5,- WHOAMI_OK = 6,- LIST_REFS = 7,- REFS = 8,- NEGOTIATE = 9,- NEGOTIATE_OK = 10,- FETCH_SKELETON = 11,- GET_CHUNKS = 12,- HAVE_QUERY = 13,- HAVE_BITMAP = 14,- PUT_RECORDS = 15,- UPDATE_REFS = 16,- UPDATE_REFS_OK = 17,- RECORDS = 18,- END = 19,- ERROR = 20,-};--enum ErrorCode : std::uint8_t {- ERR_UNSUPPORTED_VERSION = 1,- ERR_BAD_FRAME = 2,- ERR_NOT_FOUND = 3,- ERR_HASH_MISMATCH = 4,- ERR_NON_CANONICAL = 5,- ERR_MISSING_CLOSURE = 6,- ERR_REF_CONFLICT = 7,- ERR_REJECTED = 8,- ERR_INTERNAL = 9,- ERR_UNAUTHENTICATED = 10,- ERR_FORBIDDEN = 11,- ERR_AUTH_FAILED = 12,-};--struct Frame {- std::uint8_t kind = 0;- std::uint32_t request_id = 0;- std::vector<std::uint8_t> payload;-};--std::optional<Frame> read_frame(net::Stream &stream);-bool write_frame(net::Stream &stream, std::uint8_t kind,- std::uint32_t request_id, Bytes payload);-bool write_simple(net::Stream &stream, std::uint8_t kind,- std::uint32_t request_id);-bool write_error(net::Stream &stream, std::uint32_t request_id,- std::uint8_t code, std::string_view message);--std::uint8_t read_error(Bytes payload);-std::string error_message(Bytes payload);-std::string_view error_code_name(std::uint8_t code);--// Encode/decode the record layout shared by packs and RECORDS frames.-struct IncomingRecord {- Id id{};- std::uint8_t kind = 0;- std::vector<std::uint8_t> body;-};-std::optional<IncomingRecord> parse_record(Bytes data);-std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,- Bytes body);--} // namespace vn::wire--- a/veins-cpprewrite/src/worktree.cpp+++ /dev/null@@ -1,990 +0,0 @@-#include "worktree.h"--#include "merge.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;- if (old_tree &&- std::memcmp(old_tree->data(), new_root->data(), ID_LEN) != 0) {- auto detected = detect_renames(- tx->store(), &*tx, old_tree, std::optional<Id>{*new_root},- rename_similar_pct(root), 0);- for (auto &rename : detected)- renames.push_back(std::move(rename));- }- std::stable_sort(renames.begin(), renames.end(),- [](const Rename &a, const Rename &b) {- if (a.parent_index != b.parent_index)- return a.parent_index < b.parent_index;- return compare(bytes_of(a.to_path), bytes_of(b.to_path)) <- 0;- });-- 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_materialize_optional(const fs::path &root, Store &store,- std::optional<Id> old_root,- std::optional<Id> new_root) {- if (new_root)- return checkout_materialize_commit(root, store, old_root, *new_root);- const auto old_entries = flatten_or_empty(store, old_root);- if (old_entries.empty()) {- clear_stat_cache(root);- return 0;- }- if (!delete_stale(store, root, old_entries, {})) {- error_prefix();- std::cout << "cannot remove files absent from the restored view\n";- return 1;- }- clear_stat_cache(root);- return 0;-}--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--- a/veins-cpprewrite/src/worktree.h+++ /dev/null@@ -1,21 +0,0 @@-#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);-int checkout_materialize_optional(const fs::path &root, Store &store,- std::optional<Id> old_root,- std::optional<Id> new_root);-void clear_stat_cache(const fs::path &root);--} // namespace vn--- /dev/null+++ b/xveins/.gitignore@@ -0,0 +1,3 @@+/build*/+/.cache/+.net-bench/--- /dev/null+++ b/xveins/BENCHES.md@@ -0,0 +1,200 @@+# veins benchmarks++Two reproducible benchmark sets are kept here: a local-core comparison that includes+the Rust subset, and the native network comparison between the C++ rewrite and Spectre.++## Local core: Rust subset vs C++ vs Spectre++Generated 2026-11-27 by `bench/core_bench.py`.++### Environment++| Implementation | Binary |+|:---|:---|+| Rust | `veins-rust v0.1.0 (veins-store 1)` |+| C++ | `veins v0.0.1 (veins-store 1)` |+| Spectre | `veins v0.0.1 (veins-store 1)` |++```+host: Darwin arm64+cpu: Apple M2+repeats: 5 (median reported)+cpu pinning: no+```++### Scope++The Rust binary implements the local-core subset: `init`, `status`, `log`, `go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.+It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache invalidation window as the reference.++The subset does not implement merge/conflict objects, rebase/undo, the git bridge, ignore files, or the network protocol. The workload below contains no renames, ignores, merges, or network traffic, so the measured local operations are directly comparable.++### Workload++- Base snapshot: 2.95 MiB, 42 files.+- 20 edit/commit revisions, 8 checkouts, 5 repeats, median reported.+- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence as the reference, including all operation-log writes.+- Store size includes `.veins` packs, indexes, operation heads, the native commit map, and the stat cache.++### Summary++| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |+|:---|---:|---:|---:|---:|---:|+| Commit total [s] | 0.252 (0.250-0.262) | 0.280 (0.279-0.291) | 0.310 (0.309-0.330) | 1.11x | 1.23x |+| Checkout total [s] | 0.162 (0.161-0.165) | 0.175 (0.172-0.179) | 0.181 (0.179-0.196) | 1.08x | 1.12x |+| Store size [MiB] | 8.28 (8.28-8.37) | 8.28 (8.28-8.37) | 10.60 (10.60-10.69) | 1.00x | 1.28x |++Each cell is the median with the observed min-max range in parentheses.+A ratio above 1 means the other implementation took longer or used more space than Rust.++### Repeats++| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |+|:---|---:|---:|---:|---:|---:|---:|+| 1 | 0.262 | 0.291 | 0.330 | 0.165 | 0.172 | 0.195 |+| 2 | 0.250 | 0.280 | 0.310 | 0.162 | 0.172 | 0.196 |+| 3 | 0.252 | 0.281 | 0.309 | 0.161 | 0.179 | 0.179 |+| 4 | 0.252 | 0.279 | 0.309 | 0.162 | 0.175 | 0.179 |+| 5 | 0.257 | 0.280 | 0.311 | 0.165 | 0.177 | 0.181 |++### Notes++- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache racy window.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence in both implementations, including three operation writes.+- The Rust subset omits ignore-file parsing and similarity-based rename detection. This workload has neither ignore files nor renames, so both implementations see the same file set and perform the same exact-rename scan.+- Rust and C++ store sizes are equal at this resolution; Spectre stores the same logical history with a different packing policy.+- This is a single-machine run. Treat differences below roughly 5% as noise.++### Reproduce++```sh+cd veins-rust+cargo build --release+cd ../veins-cpprewrite+python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md+```++## Networking: C++ rewrite vs Spectre++Generated 2026-11-27 16:15:11 UTC by `bench/net_bench.sh`.++The Rust subset is not included in this section because it does not implement a+network transport.++### Environment++```+host: Darwin arm64+cpu: Apple M2+hyperfine: hyperfine 1.20.0+c++ vn: veins v0.0.1 (veins-store 1)+spectre vn: veins v0.0.1 (veins-store 1)+runs: 10 (clone/fetch/push/checkout), 20 (whoami)+warmup: 1 (clone/fetch/push/checkout), 2 (whoami)+```++### Dataset++- `bench_src`: 361 working files, 5.7M on disk including packs.+ - 360 small text files in 18 directories.+ - 2 MiB `big_old.bin` in the `oldbig` history.+ - 1 MiB `big_head.bin` in `main`.+- `push_pristine`: a separate 20-file repository, so push does not transfer the large dataset.++### What each benchmark does++| Benchmark | Operation |+|:---|:---|+| `clone-file` | Full clone over `file://`: handshake, refs, history, head chunks, checkout. Includes spawning one local server per run. |+| `fetch-file` | `vn fetch origin` with no new remote refs. Both clients start from a full `-blobs:all` clone. |+| `lazy-checkout-file` | `vn co oldbig` in a `-blobs:none` clone, fetching the 2 MiB old blob from the promisor over `file://`. |+| `push-file` | Push one new commit from a prepared client to a freshly reset copy of `push_pristine` over `file://`. |+| `whoami-file` | Connect, authenticate, `WHOAMI`, close over `file://`. |+| `clone-ssh` | Full clone over `ssh://`, using a local `ssh` shim that runs the remote `vn serve -stdio` command. |+| `clone-tls` | Full clone over TLS 1.3 with a pinned self-signed certificate. Uses long-running servers. |+| `whoami-tls` | Connect, authenticate, `WHOAMI`, close over TLS 1.3. |++Lower is better. Hyperfine reports wall-clock time; the relative column is against the fastest command.++### Summary++| Benchmark | C++ mean | Spectre mean | Spectre / C++ |+|:---|---:|---:|---:|+| Clone file:// | 35.9 ms | 61.0 ms | 1.70x |+| Fetch file:// | 24.6 ms | 31.2 ms | 1.27x |+| Lazy checkout file:// | 253.1 ms | 420.2 ms | 1.66x |+| Push file:// | 17.0 ms | 16.0 ms | 0.94x |+| Whoami file:// | 9.7 ms | 12.5 ms | 1.28x |+| Clone ssh:// | 42.5 ms | 66.6 ms | 1.57x |+| Clone TLS 1.3 | 37.9 ms | 64.9 ms | 1.71x |+| Whoami TLS 1.3 | 10.0 ms | 14.8 ms | 1.48x |++A ratio above 1 means Spectre took longer than C++.++### Results++#### Clone over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 35.9 ± 0.3 | 35.5 | 36.3 | 1.00 |+| `Spectre` | 61.0 ± 1.8 | 58.2 | 63.4 | 1.70 ± 0.05 |++#### Fetch over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 24.6 ± 0.4 | 23.9 | 25.1 | 1.00 |+| `Spectre` | 31.2 ± 1.0 | 30.2 | 32.6 | 1.27 ± 0.04 |++#### Lazy checkout over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 253.1 ± 7.1 | 247.7 | 272.4 | 1.00 |+| `Spectre` | 420.2 ± 14.5 | 402.5 | 451.8 | 1.66 ± 0.07 |++#### Push over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 17.0 ± 6.8 | 12.3 | 32.0 | 1.06 ± 0.43 |+| `Spectre` | 16.0 ± 0.4 | 15.7 | 16.8 | 1.00 |++#### Whoami over file://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 9.7 ± 0.6 | 8.7 | 10.5 | 1.00 |+| `Spectre` | 12.5 ± 0.2 | 12.1 | 12.9 | 1.28 ± 0.08 |++#### Clone over ssh://+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 42.5 ± 0.4 | 41.9 | 43.2 | 1.00 |+| `Spectre` | 66.6 ± 1.2 | 64.4 | 67.8 | 1.57 ± 0.03 |++#### Clone over TLS 1.3+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 37.9 ± 1.4 | 35.9 | 39.8 | 1.00 |+| `Spectre` | 64.9 ± 1.6 | 62.0 | 67.7 | 1.71 ± 0.07 |++#### Whoami over TLS 1.3+| Command | Mean [ms] | Min [ms] | Max [ms] | Relative |+|:---|---:|---:|---:|---:|+| `C++` | 10.0 ± 0.2 | 9.4 | 10.4 | 1.00 |+| `Spectre` | 14.8 ± 0.3 | 14.0 | 15.2 | 1.48 ± 0.04 |++### Notes++- Spectre clone destinations are absolute paths on macOS. The reference checkout hardcodes Linux's `AT_FDCWD` value (`-100`); with a relative destination it cannot open the working directory on macOS.+- `file://` and `ssh://` include server process startup. `clone-tls` and `whoami-tls` use long-running servers, so they isolate protocol and TLS cost more closely.+- These runs reproduce the reference's transfer behavior: fetch `haves` are operation heads (so metadata is re-sent), and push sends all objects reachable from the bookmark rather than using `HAVE_QUERY`.+- Lazy checkout fetches one missing chunk per promisor connection in both implementations, so it is intentionally a worst-case/read-ahead-free measurement.+- `push-file` is only a few milliseconds of real work; process startup noise can dominate. Read the min/max columns alongside the mean.+- Treat differences below roughly 10 ms as noise; this is a single-machine run, not a controlled lab measurement.++### Reproduce++```sh+cd veins-cpprewrite+cmake -S . -B build && cmake --build build -j+./bench/net_bench.sh+```--- /dev/null+++ b/xveins/CMakeLists.txt@@ -0,0 +1,180 @@+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)++# Prefer static archives for fetched dependencies (BLAKE3, zstd fallback).+set(BUILD_SHARED_LIBS OFF)++find_package(Threads REQUIRED)++# ---------------------------------------------------------------------------+# OpenSSL: TLS 1.3, Ed25519, and cryptographic randomness for the native+# protocol. Homebrew keeps OpenSSL keg-only on macOS, so try `brew` before the+# default search when the caller did not provide an explicit root.+# ---------------------------------------------------------------------------+if(APPLE AND NOT OPENSSL_ROOT_DIR AND NOT DEFINED ENV{OPENSSL_ROOT_DIR})+ find_program(VN_BREW_EXECUTABLE brew)+ if(VN_BREW_EXECUTABLE)+ foreach(_formula openssl@3 openssl)+ execute_process(+ COMMAND "${VN_BREW_EXECUTABLE}" --prefix "${_formula}"+ OUTPUT_VARIABLE _prefix+ OUTPUT_STRIP_TRAILING_WHITESPACE+ ERROR_QUIET+ )+ if(_prefix AND EXISTS "${_prefix}/include/openssl")+ set(OPENSSL_ROOT_DIR "${_prefix}")+ break()+ endif()+ endforeach()+ endif()+endif()+find_package(OpenSSL REQUIRED)++# ---------------------------------------------------------------------------+# zstd: prefer an installed package, otherwise a system library, otherwise+# fetch a pinned release.+# ---------------------------------------------------------------------------+find_package(zstd CONFIG QUIET)+if(TARGET zstd::libzstd_static)+ set(VN_ZSTD_TARGET zstd::libzstd_static)+elseif(TARGET libzstd_static)+ set(VN_ZSTD_TARGET libzstd_static)+else()+ # Ubuntu/Debian's libzstd-dev ships zstd.h and libzstd.{a,so} but no CMake+ # config. Never pass "libzstd" to the linker: -llibzstd looks for+ # liblibzstd.*. Naming the archive explicitly prefers libzstd.a, which is+ # the equivalent of linking with -l:libzstd.a.+ find_library(VN_ZSTD_LIBRARY NAMES libzstd.a zstd)+ if(VN_ZSTD_LIBRARY)+ find_path(VN_ZSTD_INCLUDE_DIR NAMES zstd.h)+ add_library(vn_zstd UNKNOWN IMPORTED)+ set_target_properties(vn_zstd PROPERTIES+ IMPORTED_LOCATION "${VN_ZSTD_LIBRARY}"+ )+ if(VN_ZSTD_INCLUDE_DIR)+ set_target_properties(vn_zstd PROPERTIES+ INTERFACE_INCLUDE_DIRECTORIES "${VN_ZSTD_INCLUDE_DIR}"+ )+ endif()+ set(VN_ZSTD_TARGET vn_zstd)+ elseif(TARGET zstd::libzstd_shared)+ set(VN_ZSTD_TARGET zstd::libzstd_shared)+ elseif(TARGET libzstd)+ set(VN_ZSTD_TARGET libzstd)+ endif()+endif()++if(NOT VN_ZSTD_TARGET)+ 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/pathspec.cpp+ src/bookmark.cpp+ src/remove.cpp+ src/exclude.cpp+ src/oplog.cpp+ src/merge.cpp+ src/cli.cpp+ src/crypto.cpp+ src/net.cpp+ src/wire.cpp+ src/protocol.cpp+ src/auth.cpp+ src/server.cpp+ src/promisor.cpp+ src/net_commands.cpp+)++target_include_directories(vn PRIVATE src)+target_link_libraries(vn PRIVATE+ BLAKE3::blake3+ ${VN_ZSTD_TARGET}+ OpenSSL::SSL+ OpenSSL::Crypto+ Threads::Threads+)+if(WIN32)+ target_link_libraries(vn PRIVATE bcrypt ws2_32 crypt32)+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/xveins/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/xveins/bench/core_bench.md@@ -0,0 +1,69 @@+Generated 2026-11-27 by `bench/core_bench.py`.++### Environment++| Implementation | Binary |+|:---|:---|+| Rust | `veins-rust v0.1.0 (veins-store 1)` |+| C++ | `veins v0.0.1 (veins-store 1)` |+| Spectre | `veins v0.0.1 (veins-store 1)` |++```+host: Darwin arm64+cpu: Apple M2+repeats: 5 (median reported)+cpu pinning: no+```++### Scope++The Rust binary implements the local-core subset: `init`, `status`, `log`, `go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.+It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache invalidation window as the reference.++The subset does not implement merge/conflict objects, rebase/undo, the git bridge, ignore files, or the network protocol. The workload below contains no renames, ignores, merges, or network traffic, so the measured local operations are directly comparable.++### Workload++- Base snapshot: 2.95 MiB, 42 files.+- 20 edit/commit revisions, 8 checkouts, 5 repeats, median reported.+- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence as the reference, including all operation-log writes.+- Store size includes `.veins` packs, indexes, operation heads, the native commit map, and the stat cache.++### Summary++| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |+|:---|---:|---:|---:|---:|---:|+| Commit total [s] | 0.252 (0.250-0.262) | 0.280 (0.279-0.291) | 0.310 (0.309-0.330) | 1.11x | 1.23x |+| Checkout total [s] | 0.162 (0.161-0.165) | 0.175 (0.172-0.179) | 0.181 (0.179-0.196) | 1.08x | 1.12x |+| Store size [MiB] | 8.28 (8.28-8.37) | 8.28 (8.28-8.37) | 10.60 (10.60-10.69) | 1.00x | 1.28x |++Each cell is the median with the observed min-max range in parentheses.+A ratio above 1 means the other implementation took longer or used more space than Rust.++### Repeats++| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |+|:---|---:|---:|---:|---:|---:|---:|+| 1 | 0.262 | 0.291 | 0.330 | 0.165 | 0.172 | 0.195 |+| 2 | 0.250 | 0.280 | 0.310 | 0.162 | 0.172 | 0.196 |+| 3 | 0.252 | 0.281 | 0.309 | 0.161 | 0.179 | 0.179 |+| 4 | 0.252 | 0.279 | 0.309 | 0.162 | 0.175 | 0.179 |+| 5 | 0.257 | 0.280 | 0.311 | 0.165 | 0.177 | 0.181 |++### Notes++- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache racy window.+- Each `go` performs the same snapshot, describe, and new-empty-change sequence in both implementations, including three operation writes.+- The Rust subset omits ignore-file parsing and similarity-based rename detection. This workload has neither ignore files nor renames, so both implementations see the same file set and perform the same exact-rename scan.+- Rust and C++ store sizes are equal at this resolution; Spectre stores the same logical history with a different packing policy.+- This is a single-machine run. Treat differences below roughly 5% as noise.++### Reproduce++```sh+cd veins-rust+cargo build --release+cd ../veins-cpprewrite+python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md+```--- /dev/null+++ b/xveins/bench/core_bench.py@@ -0,0 +1,334 @@+#!/usr/bin/env python3++from __future__ import annotations++import argparse+import os+import platform+import random+import re+import shutil+import statistics+import subprocess+import sys+import tempfile+import time+from datetime import datetime, timezone+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 environment(binary: Path) -> str:+ try:+ return run([str(binary), "version"], Path.cwd()).strip()+ except Exception:+ return "unknown"+++def cpu_name() -> str:+ try:+ return subprocess.run(+ ["sysctl", "-n", "machdep.cpu.brand_string"],+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ check=True,+ text=True,+ ).stdout.strip()+ except Exception:+ return platform.processor() or platform.machine()+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ root = Path(__file__).resolve().parents[2]+ parser.add_argument("--spectre", type=Path, default=root / "veins" / "vn")+ parser.add_argument("--cpp", type=Path, default=root / "veins-cpprewrite" / "build" / "vn")+ parser.add_argument(+ "--rust", type=Path, default=root / "veins-rust" / "target" / "release" / "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")+ parser.add_argument("--markdown-out", type=Path)+ args = parser.parse_args()++ global PREFIX+ PREFIX = [] if args.no_pin else command_prefix()++ binaries = {+ "rust": args.rust,+ "cpp": args.cpp,+ "spectre": args.spectre,+ }+ for label, binary in binaries.items():+ if not binary.exists():+ print(f"missing {label} binary: {binary}", file=sys.stderr)+ return 2++ work = Path(tempfile.mkdtemp(prefix="veins-core-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={'yes' if PREFIX else 'no'}"+ )+ rows: dict[str, list[tuple[float, float, int]]] = {+ "rust": [],+ "cpp": [],+ "spectre": [],+ }+ for repeat in range(args.repeats):+ print(f"repeat {repeat + 1}/{args.repeats}")+ for label, binary in binaries.items():+ 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])++ def spread(label: str, index: int) -> str:+ values = [row[index] for row in rows[label]]+ return f"{statistics.median(values):.3f} ({min(values):.3f}-{max(values):.3f})"++ def spread_mib(label: str) -> str:+ values = [row[2] / (1024 * 1024) for row in rows[label]]+ return f"{statistics.median(values):.2f} ({min(values):.2f}-{max(values):.2f})"++ values = {+ label: (median(label, 0), median(label, 1), median(label, 2))+ for label in rows+ }+ rust_commit, rust_checkout, rust_store = values["rust"]+ cpp_commit, cpp_checkout, cpp_store = values["cpp"]+ sx_commit, sx_checkout, sx_store = values["spectre"]++ print()+ print(f"commit C++/Rust: {cpp_commit / rust_commit:.2f}x")+ print(f"commit Spectre/Rust: {sx_commit / rust_commit:.2f}x")+ print(f"checkout C++/Rust: {cpp_checkout / rust_checkout:.2f}x")+ print(f"checkout Spectre/Rust: {sx_checkout / rust_checkout:.2f}x")+ print(f"store C++/Rust: {cpp_store / rust_store:.2f}x")+ print(f"store Spectre/Rust: {sx_store / rust_store:.2f}x")++ if args.markdown_out:+ lines = [+ f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by `bench/core_bench.py`.",+ "",+ "### Environment",+ "",+ "| Implementation | Binary |",+ "|:---|:---|",+ f"| Rust | `{environment(args.rust)}` |",+ f"| C++ | `{environment(args.cpp)}` |",+ f"| Spectre | `{environment(args.spectre)}` |",+ "",+ "```",+ f"host: {platform.system()} {platform.machine()}",+ f"cpu: {cpu_name()}",+ f"repeats: {args.repeats} (median reported)",+ f"cpu pinning: {'yes' if PREFIX else 'no'}",+ "```",+ "",+ "### Scope",+ "",+ "The Rust binary implements the local-core subset: `init`, `status`, `log`, "+ "`go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.",+ "It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, "+ "pack/index layout, operation log, and stat-cache invalidation window as "+ "the reference.",+ "",+ "The subset does not implement merge/conflict objects, rebase/undo, the git "+ "bridge, ignore files, or the network protocol. The workload below contains "+ "no renames, ignores, merges, or network traffic, so the measured local "+ "operations are directly comparable.",+ "",+ "### Workload",+ "",+ f"- Base snapshot: {size / (1024 * 1024):.2f} MiB, "+ f"{args.small_files + 2} files.",+ f"- {args.revisions} edit/commit revisions, {args.checkouts} checkouts, "+ f"{args.repeats} repeats, median reported.",+ "- Each revision rewrites about 1% of a 120,000-line generated C file "+ "and three small module files.",+ "- Each `go` performs the same snapshot, describe, and new-empty-change "+ "sequence as the reference, including all operation-log writes.",+ "- Store size includes `.veins` packs, indexes, operation heads, the native "+ "commit map, and the stat cache.",+ "",+ "### Summary",+ "",+ "| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |",+ "|:---|---:|---:|---:|---:|---:|",+ f"| Commit total [s] | {spread('rust', 0)} | {spread('cpp', 0)} | "+ f"{spread('spectre', 0)} | {cpp_commit / rust_commit:.2f}x | "+ f"{sx_commit / rust_commit:.2f}x |",+ f"| Checkout total [s] | {spread('rust', 1)} | {spread('cpp', 1)} | "+ f"{spread('spectre', 1)} | {cpp_checkout / rust_checkout:.2f}x | "+ f"{sx_checkout / rust_checkout:.2f}x |",+ f"| Store size [MiB] | {spread_mib('rust')} | {spread_mib('cpp')} | "+ f"{spread_mib('spectre')} | {cpp_store / rust_store:.2f}x | "+ f"{sx_store / rust_store:.2f}x |",+ "",+ "Each cell is the median with the observed min-max range in parentheses.",+ "A ratio above 1 means the other implementation took longer or used "+ "more space than Rust.",+ "",+ "### Repeats",+ "",+ "| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | "+ "Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |",+ "|:---|---:|---:|---:|---:|---:|---:|",+ ]+ for index in range(args.repeats):+ lines.append(+ f"| {index + 1} | {rows['rust'][index][0]:.3f} | "+ f"{rows['cpp'][index][0]:.3f} | {rows['spectre'][index][0]:.3f} | "+ f"{rows['rust'][index][1]:.3f} | {rows['cpp'][index][1]:.3f} | "+ f"{rows['spectre'][index][1]:.3f} |"+ )+ lines.extend(+ [+ "",+ "### Notes",+ "",+ "- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, "+ "zstd level 1, pack/index layout, operation log, and stat-cache racy window.",+ "- Each `go` performs the same snapshot, describe, and new-empty-change "+ "sequence in both implementations, including three operation writes.",+ "- The Rust subset omits ignore-file parsing and similarity-based rename "+ "detection. This workload has neither ignore files nor renames, so both "+ "implementations see the same file set and perform the same exact-rename scan.",+ "- Rust and C++ store sizes are equal at this resolution; Spectre stores the "+ "same logical history with a different packing policy.",+ "- This is a single-machine run. Treat differences below roughly 5% as noise.",+ "",+ "### Reproduce",+ "",+ "```sh",+ "cd veins-rust",+ "cargo build --release",+ "cd ../veins-cpprewrite",+ "python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md",+ "```",+ "",+ ]+ )+ args.markdown_out.write_text("\n".join(lines), encoding="utf-8")+ return 0+ finally:+ shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+ raise SystemExit(main())--- /dev/null+++ b/xveins/bench/net_bench.sh@@ -0,0 +1,510 @@+#!/bin/sh+# Compare the C++ rewrite with the Spectre reference over the native protocol.+#+# Requirements: hyperfine, python3, openssl, a built C++ vn, and the Spectre vn+# in ../veins/vn. The script creates a throwaway dataset under bench/.net-bench,+# runs hyperfine, and writes BENCHES.md.+set -eu++SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)+ROOT=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)+REPO=$(CDPATH= cd -- "$ROOT/.." && pwd)++VN_CPP=${VN_CPP:-$ROOT/build/vn}+VN_SPECTRE=${VN_SPECTRE:-$REPO/veins/vn}+HYPERFINE=${HYPERFINE:-hyperfine}+WORK=${WORK:-$ROOT/bench/.net-bench}+OUT=${OUT:-$ROOT/BENCHES.md}+RUNS=${RUNS:-10}+WHOAMI_RUNS=${WHOAMI_RUNS:-20}++SYS_PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"++case "$WORK" in+ ""|"/"|".") echo "refusing to use WORK='$WORK'" >&2; exit 1 ;;+esac++CPP_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_CPP")" && pwd)+SX_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_SPECTRE")" && pwd)+VN_CPP="$CPP_DIR/$(basename -- "$VN_CPP")"+VN_SPECTRE="$SX_DIR/$(basename -- "$VN_SPECTRE")"++for tool in "$VN_CPP" "$VN_SPECTRE"; do+ if [ ! -x "$tool" ]; then+ echo "missing executable: $tool" >&2+ echo "build the C++ rewrite first: cmake --build $ROOT/build" >&2+ exit 1+ fi+done+for tool in "$HYPERFINE" python3 openssl; do+ if ! command -v "$tool" >/dev/null 2>&1; then+ echo "required tool not found: $tool" >&2+ exit 1+ fi+done++rm -rf "$WORK"+mkdir -p "$WORK/config" "$WORK/bench_src" "$WORK/push_pristine" "$WORK/fakebin"++XDG_CONFIG_HOME="$WORK/config"+export XDG_CONFIG_HOME++CPP_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$CPP_DIR:$SYS_PATH' '$VN_CPP'"+SX_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"+CPP_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$CPP_DIR:$SYS_PATH' '$VN_CPP'"+SX_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"++run_cpp() {+ env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$CPP_DIR:$SYS_PATH" "$VN_CPP" "$@"+}+run_sx() {+ env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$SX_DIR:$SYS_PATH" "$VN_SPECTRE" "$@"+}++wait_port() {+ python3 - "$1" <<'PY'+import socket, sys, time+port = int(sys.argv[1])+for _ in range(100):+ sock = socket.socket()+ sock.settimeout(0.1)+ try:+ sock.connect(("127.0.0.1", port))+ sock.close()+ sys.exit(0)+ except OSError:+ sock.close()+ time.sleep(0.1)+sys.exit(1)+PY+}++generate_small_files() {+ python3 - "$1" "$2" "$3" <<'PY'+import os, sys+root, start, stop = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])+body = ("abcdefghijklmnopqrstuvwxyz" * 70)[:1800]+for d in range(start, stop):+ folder = os.path.join(root, "d%02d" % d)+ os.makedirs(folder, exist_ok=True)+ for f in range(20):+ path = os.path.join(folder, "f%02d.txt" % f)+ with open(path, "w", encoding="utf-8") as handle:+ handle.write("file %d-%d\n" % (d, f))+ handle.write(body)+ handle.write("\n")+PY+}++# ---------------------------------------------------------------------------+# Keys and access+# ---------------------------------------------------------------------------++run_cpp key generate benchkey > "$WORK/key.txt"+PUB=$(awk '/public key:/ {print $3}' "$WORK/key.txt")+if [ -z "$PUB" ]; then+ echo "could not generate the benchmark key" >&2+ exit 1+fi+run_cpp auth use benchkey >/dev/null++grant_access() {+ ( cd "$1" && run_cpp access anonymous on && \+ run_cpp access add -role write -key "$PUB" -name bench >/dev/null )+}++# ---------------------------------------------------------------------------+# Dataset: 360 small files, a 2 MiB old blob, and a 1 MiB head blob.+# ---------------------------------------------------------------------------++(+ cd "$WORK/bench_src"+ run_sx init . >/dev/null+ generate_small_files . 0 12+ python3 - <<'PY'+import os+with open("big_old.bin", "wb") as handle:+ handle.write(os.urandom(2 * 1024 * 1024))+PY+ run_sx go -m "base commit" >/dev/null+ # Point oldbig at the real base commit, not the movable working-copy commit.+ BASE_CHANGE=$(run_sx log | awk '/base commit/ {print $2}' | tail -1)+ if [ -z "$BASE_CHANGE" ]; then+ echo "could not resolve the base commit" >&2+ exit 1+ fi+ run_sx bmk set oldbig -rev "$BASE_CHANGE" >/dev/null+ rm -f big_old.bin+ generate_small_files . 12 18+ python3 - <<'PY'+import os+with open("big_head.bin", "wb") as handle:+ handle.write(os.urandom(1 * 1024 * 1024))+PY+ run_sx go -m "head commit" >/dev/null+ run_sx bmk set main >/dev/null+)+grant_access "$WORK/bench_src"++# A separate small repository for push, so a push does not transfer the large+# dataset. The reference pushes all reachable objects, as does the rewrite.+(+ cd "$WORK/push_pristine"+ run_sx init . >/dev/null+ generate_small_files . 0 1+ run_sx go -m "push base" >/dev/null+ run_sx bmk set main >/dev/null+)+grant_access "$WORK/push_pristine"++# ---------------------------------------------------------------------------+# Prepared client/server repositories+# ---------------------------------------------------------------------------++run_cpp clone "file://$WORK/bench_src" "$WORK/fetch_pristine_cpp" -blobs:all >/dev/null+run_sx clone "file://$WORK/bench_src" "$WORK/fetch_pristine_sx" -blobs:all >/dev/null+run_cpp clone "file://$WORK/bench_src" "$WORK/lazy_pristine_cpp" -blobs:none >/dev/null+run_sx clone "file://$WORK/bench_src" "$WORK/lazy_pristine_sx" -blobs:none >/dev/null++run_cpp clone "file://$WORK/push_pristine" "$WORK/push_client_cpp" >/dev/null+run_sx clone "file://$WORK/push_pristine" "$WORK/push_client_sx" >/dev/null+(+ cd "$WORK/push_client_cpp"+ printf 'bench push\n' > push.txt+ run_cpp go -m "bench push" >/dev/null+ run_cpp bmk set main >/dev/null+ run_cpp remote set-url origin "file://$WORK/push_srv_cpp"+)+(+ cd "$WORK/push_client_sx"+ printf 'bench push\n' > push.txt+ run_sx go -m "bench push" >/dev/null+ run_sx bmk set main >/dev/null+ run_sx remote set-url origin "file://$WORK/push_srv_sx"+)++# ---------------------------------------------------------------------------+# ssh shim: execute the remote `vn serve -stdio ...` command locally.+# ---------------------------------------------------------------------------++cat > "$WORK/fakebin/ssh" <<'SH'+#!/bin/sh+while [ $# -gt 0 ]; do+ case "$1" in+ -p|-l) shift 2 ;;+ -*) shift ;;+ *) break ;;+ esac+done+host=$1+shift+exec /bin/sh -c "$*"+SH+chmod +x "$WORK/fakebin/ssh"++# ---------------------------------------------------------------------------+# TLS certificate and servers+# ---------------------------------------------------------------------------++cat > "$WORK/openssl.cnf" <<EOF+[req]+distinguished_name = dn+x509_extensions = v3_req+prompt = no+[dn]+CN = localhost+[v3_req]+subjectAltName = @alt+[alt]+DNS.1 = localhost+IP.1 = 127.0.0.1+EOF+openssl req -x509 -newkey rsa:2048 -nodes \+ -keyout "$WORK/key.pem" -out "$WORK/cert.pem" \+ -days 2 -config "$WORK/openssl.cnf" >/dev/null 2>&1+PIN=$(openssl x509 -in "$WORK/cert.pem" -noout -fingerprint -sha256 \+ | sed 's/.*=//;s/://g' | tr 'A-F' 'a-f')++free_port() {+ python3 - <<'PY'+import socket+sock = socket.socket()+sock.bind(("127.0.0.1", 0))+print(sock.getsockname()[1])+sock.close()+PY+}+PORT_CPP=$(free_port)+PORT_SX=$(free_port)+while [ "$PORT_SX" = "$PORT_CPP" ]; do PORT_SX=$(free_port); done++CPP_PID=""+SX_PID=""+cleanup() {+ if [ -n "$CPP_PID" ]; then kill "$CPP_PID" 2>/dev/null || true; fi+ if [ -n "$SX_PID" ]; then kill "$SX_PID" 2>/dev/null || true; fi+ if [ -n "$CPP_PID" ]; then wait "$CPP_PID" 2>/dev/null || true; fi+ if [ -n "$SX_PID" ]; then wait "$SX_PID" 2>/dev/null || true; fi+}+trap cleanup EXIT INT TERM++"$VN_CPP" serve -listen "127.0.0.1:$PORT_CPP" -root "$WORK" \+ -tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \+ >"$WORK/cpp-server.log" 2>&1 &+CPP_PID=$!+"$VN_SPECTRE" serve -listen "127.0.0.1:$PORT_SX" -root "$WORK" \+ -tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \+ >"$WORK/sx-server.log" 2>&1 &+SX_PID=$!+wait_port "$PORT_CPP"+wait_port "$PORT_SX"++# A tiny repository used only for whoami over TLS.+mkdir -p "$WORK/whoami_repo"+(+ cd "$WORK/whoami_repo"+ run_cpp init . >/dev/null+ run_cpp remote add tls_cpp "veins://localhost:$PORT_CPP/bench_src" \+ -key:benchkey -tls-pin:"$PIN" >/dev/null+ run_cpp remote add tls_sx "veins://localhost:$PORT_SX/bench_src" \+ -key:benchkey -tls-pin:"$PIN" >/dev/null+)++# ---------------------------------------------------------------------------+# Hyperfine prepare scripts+# ---------------------------------------------------------------------------++write_prepare() {+ path="$WORK/$1"+ shift+ {+ echo '#!/bin/sh'+ printf '%s\n' "$@"+ } > "$path"+ chmod +x "$path"+}++write_prepare prepare_clone.sh \+ "rm -rf '$WORK/clone_cpp' '$WORK/clone_sx'"+write_prepare prepare_fetch.sh \+ "rm -rf '$WORK/fetch_cpp' '$WORK/fetch_sx'" \+ "cp -R '$WORK/fetch_pristine_cpp' '$WORK/fetch_cpp'" \+ "cp -R '$WORK/fetch_pristine_sx' '$WORK/fetch_sx'"+write_prepare prepare_lazy.sh \+ "rm -rf '$WORK/lazy_cpp' '$WORK/lazy_sx'" \+ "cp -R '$WORK/lazy_pristine_cpp' '$WORK/lazy_cpp'" \+ "cp -R '$WORK/lazy_pristine_sx' '$WORK/lazy_sx'"+write_prepare prepare_push.sh \+ "rm -rf '$WORK/push_srv_cpp' '$WORK/push_srv_sx'" \+ "cp -R '$WORK/push_pristine' '$WORK/push_srv_cpp'" \+ "cp -R '$WORK/push_pristine' '$WORK/push_srv_sx'"+write_prepare prepare_ssh.sh \+ "rm -rf '$WORK/clone_ssh_cpp' '$WORK/clone_ssh_sx'"+write_prepare prepare_tls.sh \+ "rm -rf '$WORK/clone_tls_cpp' '$WORK/clone_tls_sx'"+write_prepare prepare_noop.sh \+ "exit 0"++# ---------------------------------------------------------------------------+# Run hyperfine+# ---------------------------------------------------------------------------++run_pair() {+ name=$1+ prepare=$2+ runs=$3+ warmup=$4+ cpp_cmd=$5+ sx_cmd=$6+ echo+ echo "== $name =="+ "$HYPERFINE" --style basic --warmup "$warmup" --runs "$runs" \+ --prepare "$prepare" \+ --export-markdown "$WORK/$name.md" \+ --export-json "$WORK/$name.json" \+ -n "C++" "$cpp_cmd" \+ -n "Spectre" "$sx_cmd"+}++SSH_URL="ssh://localhost/$WORK/bench_src"+TLS_CPP_URL="veins://localhost:$PORT_CPP/bench_src"+TLS_SX_URL="veins://localhost:$PORT_SX/bench_src"++run_pair clone-file "$WORK/prepare_clone.sh" "$RUNS" 1 \+ "cd '$WORK' && $CPP_RUN clone 'file://$WORK/bench_src' '$WORK/clone_cpp'" \+ "cd '$WORK' && $SX_RUN clone 'file://$WORK/bench_src' '$WORK/clone_sx'"++run_pair fetch-file "$WORK/prepare_fetch.sh" "$RUNS" 1 \+ "cd '$WORK/fetch_cpp' && $CPP_RUN fetch origin" \+ "cd '$WORK/fetch_sx' && $SX_RUN fetch origin"++run_pair lazy-checkout-file "$WORK/prepare_lazy.sh" "$RUNS" 1 \+ "cd '$WORK/lazy_cpp' && $CPP_RUN co oldbig" \+ "cd '$WORK/lazy_sx' && $SX_RUN co oldbig"++run_pair push-file "$WORK/prepare_push.sh" "$RUNS" 1 \+ "cd '$WORK/push_client_cpp' && $CPP_RUN push origin main" \+ "cd '$WORK/push_client_sx' && $SX_RUN push origin main"++run_pair whoami-file "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \+ "cd '$WORK' && $CPP_RUN whoami 'file://$WORK/bench_src'" \+ "cd '$WORK' && $SX_RUN whoami 'file://$WORK/bench_src'"++run_pair clone-ssh "$WORK/prepare_ssh.sh" "$RUNS" 1 \+ "cd '$WORK' && $CPP_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_cpp'" \+ "cd '$WORK' && $SX_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_sx'"++run_pair clone-tls "$WORK/prepare_tls.sh" "$RUNS" 1 \+ "cd '$WORK' && $CPP_RUN clone '$TLS_CPP_URL' '$WORK/clone_tls_cpp' -pin:'$PIN'" \+ "cd '$WORK' && $SX_RUN clone '$TLS_SX_URL' '$WORK/clone_tls_sx' -pin:'$PIN'"++run_pair whoami-tls "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \+ "cd '$WORK/whoami_repo' && $CPP_RUN whoami tls_cpp" \+ "cd '$WORK/whoami_repo' && $SX_RUN whoami tls_sx"++cleanup+trap - 0 2 15++# ---------------------------------------------------------------------------+# BENCHES.md+# ---------------------------------------------------------------------------++python3 - "$WORK" > "$WORK/summary.md" <<'PY'+import json, os, sys+work = sys.argv[1]+names = [+ ("clone-file", "Clone file://"),+ ("fetch-file", "Fetch file://"),+ ("lazy-checkout-file", "Lazy checkout file://"),+ ("push-file", "Push file://"),+ ("whoami-file", "Whoami file://"),+ ("clone-ssh", "Clone ssh://"),+ ("clone-tls", "Clone TLS 1.3"),+ ("whoami-tls", "Whoami TLS 1.3"),+]+print("| Benchmark | C++ mean | Spectre mean | Spectre / C++ |")+print("|:---|---:|---:|---:|")+for key, label in names:+ with open(os.path.join(work, key + ".json"), encoding="utf-8") as handle:+ data = json.load(handle)+ means = {r["command"]: r["mean"] for r in data["results"]}+ cpp = means["C++"] * 1000.0+ sx = means["Spectre"] * 1000.0+ ratio = sx / cpp if cpp else float("nan")+ print(f"| {label} | {cpp:.1f} ms | {sx:.1f} ms | {ratio:.2f}x |")+PY++FILE_COUNT=$(find "$WORK/bench_src" -type f -not -path '*/.veins/*' | wc -l | tr -d ' ')+DISK_SIZE=$(du -sh "$WORK/bench_src" | awk '{print $1}')+HOST_TEXT=$(uname -sm)+CPU_TEXT=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -m)+HYPERFINE_VERSION=$("$HYPERFINE" --version)+CPP_VERSION=$("$VN_CPP" version)+SX_VERSION=$("$VN_SPECTRE" version)++{+ echo "# veins benchmarks"+ echo+ echo "Two reproducible benchmark sets are kept here: a local-core comparison that includes"+ echo "the Rust subset, and the native network comparison between the C++ rewrite and Spectre."+ echo+ if [ -f "$ROOT/bench/core_bench.md" ]; then+ echo "## Local core: Rust subset vs C++ vs Spectre"+ echo+ cat "$ROOT/bench/core_bench.md"+ echo+ fi+ echo "## Networking: C++ rewrite vs Spectre"+ echo+ echo "Generated $(date -u '+%Y-%m-%d %H:%M:%S UTC') by \`bench/net_bench.sh\`."+ echo+ echo "The Rust subset is not included in this section because it does not implement a"+ echo "network transport."+ echo+ echo "### Environment"+ echo+ echo '```'+ echo "host: $HOST_TEXT"+ echo "cpu: $CPU_TEXT"+ echo "hyperfine: $HYPERFINE_VERSION"+ echo "c++ vn: $CPP_VERSION"+ echo "spectre vn: $SX_VERSION"+ echo "runs: $RUNS (clone/fetch/push/checkout), $WHOAMI_RUNS (whoami)"+ echo "warmup: 1 (clone/fetch/push/checkout), 2 (whoami)"+ echo '```'+ echo+ echo "### Dataset"+ echo+ echo "- \`bench_src\`: $FILE_COUNT working files, $DISK_SIZE on disk including packs."+ echo " - 360 small text files in 18 directories."+ echo " - 2 MiB \`big_old.bin\` in the \`oldbig\` history."+ echo " - 1 MiB \`big_head.bin\` in \`main\`."+ echo "- \`push_pristine\`: a separate 20-file repository, so push does not transfer the large dataset."+ echo+ echo "### What each benchmark does"+ echo+ echo "| Benchmark | Operation |"+ echo "|:---|:---|"+ echo "| \`clone-file\` | Full clone over \`file://\`: handshake, refs, history, head chunks, checkout. Includes spawning one local server per run. |"+ echo "| \`fetch-file\` | \`vn fetch origin\` with no new remote refs. Both clients start from a full \`-blobs:all\` clone. |"+ echo "| \`lazy-checkout-file\` | \`vn co oldbig\` in a \`-blobs:none\` clone, fetching the 2 MiB old blob from the promisor over \`file://\`. |"+ echo "| \`push-file\` | Push one new commit from a prepared client to a freshly reset copy of \`push_pristine\` over \`file://\`. |"+ echo "| \`whoami-file\` | Connect, authenticate, \`WHOAMI\`, close over \`file://\`. |"+ echo "| \`clone-ssh\` | Full clone over \`ssh://\`, using a local \`ssh\` shim that runs the remote \`vn serve -stdio\` command. |"+ echo "| \`clone-tls\` | Full clone over TLS 1.3 with a pinned self-signed certificate. Uses long-running servers. |"+ echo "| \`whoami-tls\` | Connect, authenticate, \`WHOAMI\`, close over TLS 1.3. |"+ echo+ echo "Lower is better. Hyperfine reports wall-clock time; the relative column is against the fastest command."+ echo+ echo "### Summary"+ echo+ cat "$WORK/summary.md"+ echo+ echo "A ratio above 1 means Spectre took longer than C++."+ echo+ echo "### Results"+ echo+ echo "#### Clone over file://"+ cat "$WORK/clone-file.md"+ echo+ echo "#### Fetch over file://"+ cat "$WORK/fetch-file.md"+ echo+ echo "#### Lazy checkout over file://"+ cat "$WORK/lazy-checkout-file.md"+ echo+ echo "#### Push over file://"+ cat "$WORK/push-file.md"+ echo+ echo "#### Whoami over file://"+ cat "$WORK/whoami-file.md"+ echo+ echo "#### Clone over ssh://"+ cat "$WORK/clone-ssh.md"+ echo+ echo "#### Clone over TLS 1.3"+ cat "$WORK/clone-tls.md"+ echo+ echo "#### Whoami over TLS 1.3"+ cat "$WORK/whoami-tls.md"+ echo+ echo "### Notes"+ echo+ echo "- Spectre clone destinations are absolute paths on macOS. The reference checkout hardcodes Linux's \`AT_FDCWD\` value (\`-100\`); with a relative destination it cannot open the working directory on macOS."+ echo "- \`file://\` and \`ssh://\` include server process startup. \`clone-tls\` and \`whoami-tls\` use long-running servers, so they isolate protocol and TLS cost more closely."+ echo "- These runs reproduce the reference's transfer behavior: fetch \`haves\` are operation heads (so metadata is re-sent), and push sends all objects reachable from the bookmark rather than using \`HAVE_QUERY\`."+ echo "- Lazy checkout fetches one missing chunk per promisor connection in both implementations, so it is intentionally a worst-case/read-ahead-free measurement."+ echo "- \`push-file\` is only a few milliseconds of real work; process startup noise can dominate. Read the min/max columns alongside the mean."+ echo "- Treat differences below roughly 10 ms as noise; this is a single-machine run, not a controlled lab measurement."+ echo+ echo "### Reproduce"+ echo+ echo '```sh'+ echo "cd veins-cpprewrite"+ echo "cmake -S . -B build && cmake --build build -j"+ echo "./bench/net_bench.sh"+ echo '```'+} > "$OUT"++echo+echo "wrote $OUT"--- /dev/null+++ b/xveins/src/auth.cpp@@ -0,0 +1,521 @@+#include "auth.h"++#include "store.h"++#include <algorithm>+#include <cstdlib>+#include <cstring>++#if defined(_WIN32)+#include <io.h>+#else+#include <sys/stat.h>+#include <unistd.h>+#endif++namespace vn::auth {++namespace {++std::optional<std::string> env_value(const char *name) {+ const char *value = std::getenv(name);+ if (!value || !*value)+ return std::nullopt;+ return std::string(value);+}++std::string lower_ascii(std::string_view text) {+ std::string out(text);+ for (char &c : out) {+ if (c >= 'A' && c <= 'Z')+ c = static_cast<char>(c + 32);+ }+ return out;+}++std::string_view trim_view(std::string_view text) {+ std::size_t start = 0;+ std::size_t end = text.size();+ auto blank = [](char c) {+ return c == ' ' || c == '\t' || c == '\r' || c == '\n';+ };+ while (start < end && blank(text[start]))+ ++start;+ while (end > start && blank(text[end - 1]))+ --end;+ return text.substr(start, end - start);+}++int file_mode(const fs::path &path) {+#if defined(_WIN32)+ (void)path;+ return 0600;+#else+ struct stat info {};+ if (::stat(path.c_str(), &info) != 0)+ return -1;+ return static_cast<int>(info.st_mode & 07777);+#endif+}++bool set_mode(const fs::path &path, int mode) {+#if defined(_WIN32)+ (void)path;+ (void)mode;+ return true;+#else+ return ::chmod(path.c_str(), static_cast<mode_t>(mode)) == 0;+#endif+}++bool valid_key_name(std::string_view name) {+ if (name.empty() || name.size() > 128)+ return false;+ for (char c : name) {+ if (c == '/' || c == '\\' || c == '\0')+ return false;+ }+ return true;+}++std::string hex_encode(std::string_view data) {+ static constexpr char digits[] = "0123456789abcdef";+ std::string out;+ out.reserve(data.size() * 2);+ for (char raw : data) {+ const auto c = static_cast<unsigned char>(raw);+ out.push_back(digits[c >> 4]);+ out.push_back(digits[c & 15]);+ }+ return out;+}++std::optional<std::string> hex_decode(std::string_view text) {+ if (text.empty() || text.size() % 2 != 0)+ return std::nullopt;+ auto value = [](char c) -> int {+ if (c >= '0' && c <= '9')+ return c - '0';+ if (c >= 'a' && c <= 'f')+ return c - 'a' + 10;+ return -1;+ };+ std::string out;+ out.reserve(text.size() / 2);+ for (std::size_t i = 0; i < text.size(); i += 2) {+ const int high = value(text[i]);+ const int low = value(text[i + 1]);+ if (high < 0 || low < 0)+ return std::nullopt;+ out.push_back(static_cast<char>((high << 4) | low));+ }+ return out;+}++std::string_view strip_user(std::string_view authority) {+ const auto at = authority.rfind('@');+ if (at != std::string_view::npos)+ return authority.substr(at + 1);+ return authority;+}++std::optional<std::string> authority_of(std::string_view input) {+ std::size_t start = 0;+ const auto scheme = input.find("://");+ if (scheme != std::string_view::npos)+ start = scheme + 3;+ if (start >= input.size())+ return std::nullopt;+ const auto slash = input.find('/', start);+ const std::size_t end = slash == std::string_view::npos ? input.size() : slash;+ if (end <= start)+ return std::nullopt;+ const std::string_view raw = input.substr(start, end - start);+ const std::string_view host = strip_user(raw);+ if (host.empty())+ return std::nullopt;+ return lower_ascii(host);+}++std::optional<std::string> host_without_port(std::string_view host) {+ if (host.empty() || host.front() == '[')+ return std::nullopt;+ const auto colon = host.rfind(':');+ if (colon == std::string_view::npos || colon == 0)+ return std::nullopt;+ return std::string(host.substr(0, colon));+}++fs::path target_path(const fs::path &dir, std::string_view target) {+ return dir / hex_encode(target);+}++std::optional<std::string> read_credential(const fs::path &path) {+ auto data = read_file_opt(path);+ if (!data)+ return std::nullopt;+ const std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ const std::string_view value = trim_view(text);+ if (value.empty())+ return std::nullopt;+ return std::string(value);+}++std::optional<std::string> lookup_credential(const fs::path &dir,+ std::string_view target) {+ return read_credential(target_path(dir, target));+}++std::vector<std::string_view> tokenize(std::string_view line) {+ std::vector<std::string_view> out;+ std::size_t start = 0;+ for (std::size_t i = 0; i <= line.size(); ++i) {+ const bool at_end = i == line.size();+ if (at_end || line[i] == ' ' || line[i] == '\t') {+ if (i > start)+ out.push_back(line.substr(start, i - start));+ start = i + 1;+ }+ }+ return out;+}++Access invalid_access(std::int64_t line) {+ Access out;+ out.valid = false;+ out.error_line = line;+ return out;+}++} // namespace++// ---------------------------------------------------------------------------+// Client keys+// ---------------------------------------------------------------------------++fs::path key_dir() {+ if (auto xdg = env_value("XDG_CONFIG_HOME"))+ return path_from_bytes(*xdg) / "veins" / "keys";+ if (auto home = env_value("HOME"))+ return path_from_bytes(*home) / ".config" / "veins" / "keys";+#if defined(_WIN32)+ if (auto appdata = env_value("APPDATA"))+ return path_from_bytes(*appdata) / "veins" / "keys";+#endif+ return fs::path(".veins-keys");+}++fs::path key_path(std::string_view name) {+ return key_dir() / (std::string(name) + ".key");+}++std::optional<Key> load_key(std::string_view name) {+ if (!valid_key_name(name))+ return std::nullopt;+ const fs::path path = key_path(name);+ const int mode = file_mode(path);+ if (mode < 0 || (mode & 63) != 0)+ return std::nullopt;+ auto data = read_file_opt(path);+ if (!data || data->size() != 33 || (*data)[0] != 1)+ return std::nullopt;+ std::vector<std::uint8_t> seed(data->begin() + 1, data->end());+ auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));+ if (!public_key)+ return std::nullopt;+ Key key;+ key.name = std::string(name);+ key.seed = std::move(seed);+ key.public_key = *public_key;+ key.fingerprint = key_fingerprint(*public_key);+ return key;+}++std::optional<Key> generate_key(std::string_view name) {+ if (!valid_key_name(name))+ return std::nullopt;+ const fs::path dir = key_dir();+ if (!ensure_directory(dir))+ return std::nullopt;+ (void)set_mode(dir, 0700);+ const auto seed = secure_random(32);+ if (seed.size() != 32)+ return std::nullopt;+ auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));+ if (!public_key)+ return std::nullopt;+ std::vector<std::uint8_t> body;+ body.reserve(33);+ body.push_back(1);+ body.insert(body.end(), seed.begin(), seed.end());+ const fs::path path = key_path(name);+ if (!write_file(path, Bytes(body.data(), body.size())))+ return std::nullopt;+ (void)set_mode(path, 0600);+ Key key;+ key.name = std::string(name);+ key.seed = seed;+ key.public_key = *public_key;+ key.fingerprint = key_fingerprint(*public_key);+ return key;+}++std::vector<std::string> list_key_names() {+ std::vector<std::string> out;+ const fs::path dir = key_dir();+ if (!path_is_dir(dir))+ return out;+ for (const auto &name : list_directory(dir)) {+ if (name.size() > 4 && name.compare(name.size() - 4, 4, ".key") == 0)+ out.push_back(name.substr(0, name.size() - 4));+ }+ return out;+}++// ---------------------------------------------------------------------------+// Per-user key selection+// ---------------------------------------------------------------------------++fs::path auth_dir() {+ const fs::path dir = key_dir();+ const fs::path parent = dir.parent_path();+ if (parent.empty())+ return fs::path(".veins-auth");+ return parent / "auth";+}++std::string normalize_target(std::string_view input) {+ const std::string_view trimmed = trim_view(input);+ if (trimmed.empty() || trimmed == "default")+ return "default";+ if (auto authority = authority_of(trimmed))+ return *authority;+ const auto slash = trimmed.find('/');+ const std::string_view raw =+ slash == std::string_view::npos ? trimmed : trimmed.substr(0, slash);+ const std::string_view host = strip_user(raw);+ if (host.empty())+ return "default";+ return lower_ascii(host);+}++bool set_key(std::string_view target, std::string_view key_name) {+ if (target.empty() || key_name.empty())+ return false;+ const fs::path dir = auth_dir();+ if (!ensure_directory(dir))+ return false;+ return write_file(target_path(dir, target), bytes_of(key_name));+}++bool remove_key(std::string_view target) {+ return remove_file(target_path(auth_dir(), target));+}++std::vector<std::string> list_credential_lines() {+ std::vector<std::string> out;+ const fs::path dir = auth_dir();+ if (!path_is_dir(dir))+ return out;+ for (const auto &name : list_directory(dir)) {+ auto decoded = hex_decode(name);+ if (!decoded)+ continue;+ auto key = read_credential(target_path(dir, *decoded));+ if (!key)+ continue;+ out.push_back(*decoded + ": " + *key + "\n");+ }+ return out;+}++bool local_key_exists(std::string_view name) {+ if (name.empty() || name.starts_with("ed25519:"))+ return false;+ return load_key(name).has_value();+}++std::optional<std::string> key_for_url(std::string_view url) {+ const fs::path dir = auth_dir();+ if (auto host = authority_of(url)) {+ if (auto exact = lookup_credential(dir, *host))+ return exact;+ if (auto base = host_without_port(*host)) {+ if (auto without_port = lookup_credential(dir, *base))+ return without_port;+ }+ }+ return lookup_credential(dir, "default");+}++// ---------------------------------------------------------------------------+// Server access policy+// ---------------------------------------------------------------------------++Access empty_access() { return Access{}; }++fs::path access_path(const fs::path &repo_root) {+ return veins_dir(repo_root) / "access";+}++Access load_access(const fs::path &repo_root) {+ const fs::path path = access_path(repo_root);+ const int mode = file_mode(path);+ if (mode >= 0 && (mode & 18) != 0)+ return invalid_access(0);+ auto data = read_file_opt(path);+ if (!data)+ return empty_access();+ const std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ Access access;+ std::size_t start = 0;+ std::int64_t line_no = 0;+ std::size_t i = 0;+ for (;;) {+ const bool at_end = i >= text.size();+ if (at_end || text[i] == '\n') {+ ++line_no;+ const std::string_view line = trim_view(text.substr(start, i - start));+ if (!line.empty() && line.front() != '#') {+ const auto tokens = tokenize(line);+ bool bad = false;+ if (tokens.size() == 2 && tokens[0] == "anonymous") {+ if (tokens[1] == "read")+ access.anonymous_read = true;+ else+ bad = true;+ } else if (tokens.size() >= 3 && tokens[0] == "allow") {+ std::uint8_t role = 0;+ if (tokens[1] == "read")+ role = ROLE_READ;+ else if (tokens[1] == "write")+ role = ROLE_WRITE;+ else+ bad = true;+ auto public_key = parse_public_key(tokens[2]);+ if (!public_key)+ bad = true;+ if (!bad) {+ const bool duplicate =+ std::any_of(access.entries.begin(), access.entries.end(),+ [&](const AccessEntry &entry) {+ return std::memcmp(entry.public_key.data(),+ public_key->data(),+ public_key->size()) == 0;+ });+ if (duplicate) {+ bad = true;+ } else {+ AccessEntry entry;+ entry.public_key = *public_key;+ entry.role = role;+ if (tokens.size() >= 4)+ entry.name = std::string(tokens[3]);+ access.entries.push_back(std::move(entry));+ }+ }+ } else {+ bad = true;+ }+ if (bad)+ return invalid_access(line_no);+ }+ start = i + 1;+ }+ if (at_end)+ break;+ ++i;+ }+ return access;+}++bool write_access(const fs::path &repo_root, const Access &access) {+ std::string body = "# veins access policy\n";+ if (access.anonymous_read)+ body += "anonymous read\n";+ for (const auto &entry : access.entries) {+ if (entry.name.size() > 64)+ return false;+ body += "allow ";+ body += entry.role == ROLE_WRITE ? "write" : "read";+ body += " ";+ body += format_public_key(entry.public_key);+ if (!entry.name.empty()) {+ body += " ";+ body += entry.name;+ }+ body += "\n";+ }+ const fs::path path = access_path(repo_root);+ if (!write_file(path, bytes_of(body)))+ return false;+ (void)set_mode(path, 0600);+ return true;+}++std::uint8_t role_for(const Access &access, const PublicKey *public_key) {+ if (!public_key) {+ if (access.anonymous_read)+ return ROLE_READ;+ return ROLE_ANONYMOUS;+ }+ for (const auto &entry : access.entries) {+ if (std::memcmp(entry.public_key.data(), public_key->data(),+ public_key->size()) == 0) {+ return entry.role;+ }+ }+ return ROLE_UNKNOWN;+}++bool add_access(const fs::path &repo_root, std::uint8_t role,+ const PublicKey &public_key, std::string_view name) {+ Access access = load_access(repo_root);+ if (!access.valid)+ return false;+ for (const auto &entry : access.entries) {+ if (std::memcmp(entry.public_key.data(), public_key.data(),+ public_key.size()) == 0)+ return false;+ }+ AccessEntry entry;+ entry.public_key = public_key;+ entry.role = role;+ entry.name = std::string(name);+ access.entries.push_back(std::move(entry));+ return write_access(repo_root, access);+}++bool remove_access(const fs::path &repo_root, std::string_view fingerprint,+ std::string_view name) {+ Access access = load_access(repo_root);+ if (!access.valid)+ return false;+ bool removed = false;+ std::vector<AccessEntry> kept;+ kept.reserve(access.entries.size());+ for (const auto &entry : access.entries) {+ const bool match_fingerprint =+ !fingerprint.empty() && key_fingerprint(entry.public_key) == fingerprint;+ const bool match_name = !name.empty() && entry.name == name;+ if (match_fingerprint || match_name) {+ removed = true;+ } else {+ kept.push_back(entry);+ }+ }+ access.entries = std::move(kept);+ return removed && write_access(repo_root, access);+}++bool set_anonymous(const fs::path &repo_root, bool enabled) {+ Access access = load_access(repo_root);+ if (!access.valid)+ return false;+ access.anonymous_read = enabled;+ return write_access(repo_root, access);+}++} // namespace vn::auth--- /dev/null+++ b/xveins/src/auth.h@@ -0,0 +1,75 @@+#pragma once++#include "crypto.h"++#include <cstdint>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn::auth {++constexpr std::uint8_t ROLE_ANONYMOUS = 0;+constexpr std::uint8_t ROLE_READ = 1;+constexpr std::uint8_t ROLE_WRITE = 2;+constexpr std::uint8_t ROLE_UNKNOWN = 255;++// ---------------------------------------------------------------------------+// Client keys+// ---------------------------------------------------------------------------++struct Key {+ std::string name;+ std::vector<std::uint8_t> seed;+ PublicKey public_key{};+ std::string fingerprint;+};++fs::path key_dir();+fs::path key_path(std::string_view name);+std::optional<Key> load_key(std::string_view name);+std::optional<Key> generate_key(std::string_view name);+std::vector<std::string> list_key_names();++// ---------------------------------------------------------------------------+// Per-user key selection+// ---------------------------------------------------------------------------++fs::path auth_dir();+std::string normalize_target(std::string_view target);+bool set_key(std::string_view target, std::string_view key_name);+bool remove_key(std::string_view target);+std::vector<std::string> list_credential_lines();+bool local_key_exists(std::string_view name);+std::optional<std::string> key_for_url(std::string_view url);++// ---------------------------------------------------------------------------+// Server access policy+// ---------------------------------------------------------------------------++struct AccessEntry {+ PublicKey public_key{};+ std::string name;+ std::uint8_t role = ROLE_READ;+};++struct Access {+ bool valid = true;+ std::int64_t error_line = 0;+ bool anonymous_read = false;+ std::vector<AccessEntry> entries;+};++Access empty_access();+fs::path access_path(const fs::path &repo_root);+Access load_access(const fs::path &repo_root);+bool write_access(const fs::path &repo_root, const Access &access);+bool add_access(const fs::path &repo_root, std::uint8_t role,+ const PublicKey &public_key, std::string_view name);+bool remove_access(const fs::path &repo_root, std::string_view fingerprint,+ std::string_view name);+bool set_anonymous(const fs::path &repo_root, bool enabled);+std::uint8_t role_for(const Access &access, const PublicKey *public_key);++} // namespace vn::auth--- /dev/null+++ b/xveins/src/bookmark.cpp@@ -0,0 +1,356 @@+#include "local_commands.h"++#include "pathspec.h"+#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <iostream>++namespace vn {++namespace {++bool bmk_is_flag(std::string_view arg) {+ return !arg.empty() && arg.front() == '-';+}++bool bmk_contains(std::string_view name, std::string_view needle) {+ return !needle.empty() && name.find(needle) != std::string_view::npos;+}++bool valid_bookmark_name(std::string_view name) {+ if (name.empty() || name.size() > MAX_NAME_LEN)+ return false;+ const auto first = static_cast<unsigned char>(name.front());+ if (first == '-' || first == '/' || first == '.')+ return false;+ const auto last = static_cast<unsigned char>(name.back());+ if (last == '/' || last == '.')+ return false;+ for (char raw : name) {+ const auto c = static_cast<unsigned char>(raw);+ if (c == 0 || c == ' ' || c < 32 || c == 127)+ return false;+ if (c == '~' || c == '^' || c == ':' || c == '?' || c == '*' ||+ c == '[' || c == '\\')+ return false;+ }+ if (bmk_contains(name, "..") || bmk_contains(name, "@{") ||+ bmk_contains(name, "//"))+ return false;+ if (name == "@")+ return false;+ if (name.size() >= 5 && name.substr(name.size() - 5) == ".lock")+ return false;+ return true;+}++std::string short_commit(const Id &id, std::size_t n = 12) {+ if (n == 0)+ n = 12;+ n = std::min<std::size_t>(n, 64);+ return hex_encode(id).substr(0, n);+}++void bmk_print_cell(std::string_view text, std::size_t width) {+ std::cout << text;+ for (std::size_t i = text.size(); i < width; ++i)+ std::cout << ' ';+}++bool bookmark_points_at(const Bookmark &bookmark, const Id &target) {+ return bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front() &&+ std::memcmp(bookmark.targets.adds.front()->data(), target.data(),+ ID_LEN) == 0;+}++int bmk_set(const std::vector<std::string> &args, std::size_t start) {+ std::string name;+ std::string rev;+ 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 == "-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 && bmk_is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (name.empty()) {+ name = arg;+ } else if (rev.empty()) {+ rev = arg;+ } else {+ error_prefix();+ std::cout << "bmk set accepts a name and one revision\n";+ return 1;+ }+ }+ if (name.empty()) {+ error_prefix();+ std::cout << "bmk set requires a name\n";+ return 1;+ }+ if (!valid_bookmark_name(name)) {+ error_prefix();+ std::cout << "invalid bookmark name: " << name << "\n";+ return 1;+ }++ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ 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();+ if (rev.empty())+ std::cout << "no working-copy commit\n";+ else+ std::cout << "unknown revision: " << rev << "\n";+ return 1;+ }++ bool changed = true;+ if (const auto existing = find_bookmark(tx->view(), name)) {+ auto &bookmark = tx->view().bookmarks[*existing];+ if (bookmark_points_at(bookmark, *target)) {+ changed = false;+ } else {+ bookmark.targets.adds = {*target};+ bookmark.targets.removes.clear();+ }+ } else {+ Bookmark bookmark;+ bookmark.name = name;+ bookmark.targets.adds = {*target};+ tx->view().bookmarks.push_back(std::move(bookmark));+ }++ if (!changed) {+ info_prefix();+ std::cout << "bookmark " << name << " is already at " << short_commit(*target)+ << "\n";+ return 0;+ }++ rebuild_heads(tx->view());+ const auto status = tx->finish("bookmark set " + name);+ if (!status)+ return 1;+ info_prefix();+ std::cout << "bookmark " << name << " set to " << short_commit(*target)+ << "\n";+ return 0;+}++int bmk_delete(const std::vector<std::string> &args, std::size_t start) {+ std::string name;+ 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 && bmk_is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (!name.empty()) {+ error_prefix();+ std::cout << "bmk rm accepts exactly one name\n";+ return 1;+ } else {+ name = arg;+ }+ }+ if (name.empty()) {+ error_prefix();+ std::cout << "bmk rm requires a name\n";+ return 1;+ }++ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ 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 existing = find_bookmark(tx->view(), name);+ if (!existing) {+ error_prefix();+ std::cout << "no such bookmark: " << name << "\n";+ return 1;+ }+ auto &bookmarks = tx->view().bookmarks;+ bookmarks.erase(bookmarks.begin() ++ static_cast<std::ptrdiff_t>(*existing));+ rebuild_heads(tx->view());+ const auto status = tx->finish("bookmark delete " + name);+ if (!status)+ return 1;+ info_prefix();+ std::cout << "deleted bookmark " << name << "\n";+ return 0;+}++int bmk_list(const std::vector<std::string> &args, std::size_t start) {+ bool col_titles = true;+ 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 == "-no-col-titles") {+ col_titles = false;+ } else if (!end_flags && bmk_is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ error_prefix();+ std::cout << "bmk ls takes no operands\n";+ return 1;+ }+ }++ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ 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);++ constexpr std::size_t w_commit = 12;+ constexpr std::size_t w_change = 8;+ std::size_t w_name = 8;+ for (const auto &bookmark : view->bookmarks)+ w_name = std::max(w_name, bookmark.name.size());++ if (col_titles) {+ bmk_print_cell("Bookmark", w_name);+ std::cout << " ";+ bmk_print_cell("Commit", w_commit);+ std::cout << " ";+ bmk_print_cell("Change", w_change);+ std::cout << " Target\n";+ }++ for (const auto &bookmark : view->bookmarks) {+ bmk_print_cell(bookmark.name, w_name);+ std::cout << " ";+ bool have_target = false;+ bool current = false;+ const bool conflicted = bookmark.targets.adds.size() > 1;+ std::string commit_text;+ std::string change_text;+ std::optional<Id> target;+ if (!bookmark.targets.adds.empty() && bookmark.targets.adds.front()) {+ target = bookmark.targets.adds.front();+ have_target = true;+ if (wc && std::memcmp(wc->data(), target->data(), ID_LEN) == 0)+ current = true;+ commit_text = short_commit(*target);+ if (auto loaded = load_commit(store, *target))+ change_text = base32_encode(loaded->commit.change_id).substr(0, 8);+ }+ if (!have_target) {+ bmk_print_cell("<missing>", w_commit);+ std::cout << " ";+ bmk_print_cell("", w_change);+ std::cout << " (missing)\n";+ continue;+ }+ bmk_print_cell(commit_text, w_commit);+ std::cout << " ";+ bmk_print_cell(change_text, w_change);+ std::cout << " ";+ if (current)+ print_colored("@", Color::Red, false, false);+ if (conflicted) {+ if (current)+ std::cout << ' ';+ print_colored("(conflicted)", Color::BrightRed, false, false);+ }+ std::cout << "\n";+ }++ if (view->bookmarks.empty()) {+ info_prefix();+ std::cout << "no bookmarks\n";+ }+ return 0;+}++void bmk_usage() {+ std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n";+ std::cout << "\n";+ std::cout << "manage named, movable pointers to commits (branches)\n";+ std::cout << "\n";+ std::cout << "subcommands:\n";+ std::cout << " set <name> [-rev <rev>] create or move a bookmark (default: @)\n";+ std::cout << " mv <name> [-rev <rev>] alias of set\n";+ std::cout << " ls [-no-col-titles] list bookmarks\n";+ std::cout << " rm <name> delete a bookmark\n";+}++} // namespace++int bmk_run(const std::vector<std::string> &args) {+ if (args.size() <= 2) {+ bmk_usage();+ return 1;+ }+ const std::string &sub = args[2];+ if (sub == "set" || sub == "mv")+ return bmk_set(args, 3);+ if (sub == "ls")+ return bmk_list(args, 3);+ if (sub == "rm")+ return bmk_delete(args, 3);+ if (sub == "help" || sub == "-h") {+ bmk_usage();+ return 0;+ }+ error_prefix();+ std::cout << "unknown bmk subcommand: " << sub << "\n";+ bmk_usage();+ return 1;+}++} // namespace vn--- /dev/null+++ b/xveins/src/cli.cpp@@ -0,0 +1,2323 @@+#include "cli.h"++#include "local_commands.h"+#include "merge.h"+#include "net_commands.h"+#include "promisor.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_bmk() {+ std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n\n";+ std::cout << "manage named, movable pointers to commits (branches)\n\n";+ std::cout << "subcommands:\n";+ std::cout << " set <name> [-rev <rev>] create or move a bookmark (default: @)\n";+ std::cout << " mv <name> [-rev <rev>] alias of set\n";+ std::cout << " ls [-no-col-titles] list bookmarks\n";+ std::cout << " rm <name> delete a bookmark\n\n";+ std::cout << "examples:\n";+ std::cout << " vn bmk set main\n";+ std::cout << " vn new main\n";+ std::cout << " vn co main\n";+}++void show_rm() {+ std::cout << "usage: vn rm [-delete] <path>...\n\n";+ std::cout << "remove paths from the working-copy tree\n\n";+ std::cout+ << "files stay on disk by default. Arguments may be paths or globs and are\n";+ std::cout+ << "resolved relative to the current directory. Supported wildcards are\n";+ std::cout << "'*', '?', and '**'; '*' and '?' do not cross directory separators.\n\n";+ std::cout << "options:\n";+ std::cout+ << " -delete delete matching files from disk after untracking\n";+}++void show_mv() {+ std::cout << "usage: vn mv <from> <to>\n\n";+ std::cout+ << "move a tracked file; the following snapshot records the rename\n";+}++void show_ex() {+ std::cout << "usage: vn ex <pattern>...\n\n";+ std::cout << "append ignore patterns to the repository root .vnexclude\n\n";+ std::cout+ << "patterns use gitignore syntax and are resolved relative to the current\n";+ std::cout+ << "directory. Quote wildcard patterns so the shell does not expand them:\n";+ std::cout << " vn ex '*.dSYM'\n";+}++void show_undo() {+ std::cout << "usage: vn undo\n\n";+ std::cout+ << "record an operation that restores the previous operation view\n";+}++void show_op() {+ std::cout << "usage: vn op <log|restore|revert> [<op>]\n\n";+ std::cout << "inspect and restore operations\n";+}++void show_merge() {+ std::cout << "usage: vn merge <rev>...\n\n";+ std::cout+ << "create a merge commit from the working-copy commit and the revisions\n";+ std::cout+ << "the merge never fails; conflicts are stored as conflict values\n";+}++void show_rebase() {+ std::cout << "usage: vn rebase -s <rev> -d <rev>\n\n";+ std::cout+ << "rewrite the source change and its descendants onto the destination\n\n";+ std::cout << "options:\n";+ std::cout << " -s, -source <rev> first change to rewrite\n";+ std::cout << " -d, -destination <rev> new parent\n";+}++void show_xs() {+ std::cout << "usage: vn xs [-porcelain]\n\n";+ std::cout+ << "list conflicted paths and, for text conflicts, conflicting line ranges\n\n";+ std::cout << "porcelain columns (tab-separated):\n";+ std::cout << " path, kind, base-ranges, ours-ranges, theirs-ranges\n";+}++void show_resolve() {+ std::cout+ << "usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...\n";+ std::cout << " vn resolve -list\n\n";+ std::cout+ << "resolve conflicted paths. Without -take, the current file content is\n";+ std::cout+ << "recorded as the resolution. -tool substitutes $BASE, $OURS, $THEIRS,\n";+ std::cout << "and $OUTPUT in the command.\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 == "bmk")+ show_bmk();+ else if (cmd == "rm")+ show_rm();+ else if (cmd == "mv")+ show_mv();+ else if (cmd == "ex")+ show_ex();+ else if (cmd == "undo")+ show_undo();+ else if (cmd == "op")+ show_op();+ else if (cmd == "merge")+ show_merge();+ else if (cmd == "rebase")+ show_rebase();+ else if (cmd == "xs")+ show_xs();+ else if (cmd == "resolve")+ show_resolve();+ else if (cmd == "self-test")+ show_selftest();+ else if (cmd == "version")+ show_version();+ else if (cmd == "help")+ show_help();+ else if (net_help(cmd)) {+ } else if (cmd == "git" || 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) {+ install_promisor_fetcher();+ 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 == "bmk")+ return bmk_run(args);+ if (cmd == "rm")+ return rm_run(args);+ if (cmd == "mv")+ return mv_run(args);+ if (cmd == "ex")+ return ex_run(args);+ if (cmd == "op")+ return op_run(args);+ if (cmd == "undo")+ return undo_run(args);+ if (cmd == "merge")+ return merge_run(args);+ if (cmd == "rebase")+ return rebase_run(args);+ if (cmd == "xs")+ return xs_run(args);+ if (cmd == "resolve")+ return resolve_run(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 == "remote")+ return remote_run(args);+ if (cmd == "clone")+ return clone_run(args);+ if (cmd == "fetch")+ return fetch_run(args);+ if (cmd == "push")+ return push_run(args);+ if (cmd == "serve")+ return serve_run(args);+ if (cmd == "key")+ return key_run(args);+ if (cmd == "auth")+ return auth_run(args);+ if (cmd == "access")+ return access_run(args);+ if (cmd == "whoami")+ return whoami_run(args);++ if (cmd == "git" || 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/xveins/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/xveins/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/xveins/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/xveins/src/crypto.cpp@@ -0,0 +1,209 @@+#include "crypto.h"++#include <blake3.h>++#include <openssl/evp.h>+#include <openssl/rand.h>++#include <cstring>++namespace vn {++namespace {++// The reference implementation hashes the NUL terminator as well, so the+// domain is 12 bytes rather than the 11 characters in the specification.+constexpr char FINGERPRINT_DOMAIN[] = "veins/key/1";++PublicKey key_from_span(Bytes seed) {+ PublicKey out{};+ std::memcpy(out.data(), seed.data(), out.size());+ return out;+}++} // namespace++std::optional<PublicKey> ed25519_public_from_seed(Bytes seed) {+ if (seed.size() != 32)+ return std::nullopt;+ EVP_PKEY *pkey =+ EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);+ if (!pkey)+ return std::nullopt;+ PublicKey out{};+ std::size_t len = out.size();+ const int ok = EVP_PKEY_get_raw_public_key(pkey, out.data(), &len);+ EVP_PKEY_free(pkey);+ if (ok != 1 || len != out.size())+ return std::nullopt;+ return out;+}++std::optional<Signature> ed25519_sign(Bytes seed, Bytes message) {+ if (seed.size() != 32)+ return std::nullopt;+ EVP_PKEY *pkey =+ EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);+ if (!pkey)+ return std::nullopt;+ EVP_MD_CTX *ctx = EVP_MD_CTX_new();+ if (!ctx) {+ EVP_PKEY_free(pkey);+ return std::nullopt;+ }+ Signature out{};+ std::size_t sig_len = out.size();+ bool ok = false;+ if (EVP_DigestSignInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&+ EVP_DigestSign(ctx, out.data(), &sig_len, message.data(),+ message.size()) == 1 &&+ sig_len == out.size()) {+ ok = true;+ }+ EVP_MD_CTX_free(ctx);+ EVP_PKEY_free(pkey);+ if (!ok)+ return std::nullopt;+ return out;+}++bool ed25519_verify(const PublicKey &public_key, Bytes message,+ Bytes signature) {+ if (signature.size() != 64)+ return false;+ EVP_PKEY *pkey =+ EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr,+ public_key.data(), public_key.size());+ if (!pkey)+ return false;+ EVP_MD_CTX *ctx = EVP_MD_CTX_new();+ if (!ctx) {+ EVP_PKEY_free(pkey);+ return false;+ }+ bool ok = false;+ if (EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&+ EVP_DigestVerify(ctx, signature.data(), signature.size(),+ message.data(), message.size()) == 1) {+ ok = true;+ }+ EVP_MD_CTX_free(ctx);+ EVP_PKEY_free(pkey);+ return ok;+}++FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key) {+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ blake3_hasher_update(&hasher, FINGERPRINT_DOMAIN,+ sizeof(FINGERPRINT_DOMAIN));+ blake3_hasher_update(&hasher, public_key.data(), public_key.size());+ std::array<std::uint8_t, 32> digest{};+ blake3_hasher_finalize(&hasher, digest.data(), digest.size());+ FingerprintBytes out{};+ std::memcpy(out.data(), digest.data(), out.size());+ return out;+}++std::string key_fingerprint(const PublicKey &public_key) {+ const auto raw = key_fingerprint_bytes(public_key);+ return base32_text(Bytes(raw.data(), raw.size()));+}++std::string base32_text(Bytes raw) {+ static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+ std::string out;+ out.reserve((raw.size() * 8) / 5 + 2);+ std::uint64_t bits = 0;+ std::size_t nbits = 0;+ for (std::uint8_t byte : raw) {+ bits = (bits << 8) | byte;+ nbits += 8;+ while (nbits >= 5) {+ nbits -= 5;+ out.push_back(alphabet[(bits >> nbits) & 31u]);+ }+ }+ if (nbits > 0)+ out.push_back(alphabet[(bits << (5 - nbits)) & 31u]);+ return out;+}++std::string base64url_encode(Bytes raw) {+ static constexpr char alphabet[] =+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";+ std::string out;+ out.reserve((raw.size() * 4) / 3 + 4);+ std::uint32_t acc = 0;+ std::size_t bits = 0;+ for (std::uint8_t byte : raw) {+ acc = (acc << 8) | byte;+ bits += 8;+ while (bits >= 6) {+ bits -= 6;+ out.push_back(alphabet[(acc >> bits) & 63u]);+ }+ }+ if (bits > 0)+ out.push_back(alphabet[(acc << (6 - bits)) & 63u]);+ return out;+}++std::optional<std::vector<std::uint8_t>>+base64url_decode(std::string_view text) {+ if (text.empty())+ return std::nullopt;+ static const auto value_of = [](char c) -> int {+ if (c >= 'A' && c <= 'Z')+ return c - 'A';+ if (c >= 'a' && c <= 'z')+ return c - 'a' + 26;+ if (c >= '0' && c <= '9')+ return c - '0' + 52;+ if (c == '-')+ return 62;+ if (c == '_')+ return 63;+ return -1;+ };+ std::vector<std::uint8_t> out;+ out.reserve((text.size() * 6) / 8);+ std::uint32_t acc = 0;+ std::size_t bits = 0;+ for (char c : text) {+ const int value = value_of(c);+ if (value < 0)+ return std::nullopt;+ acc = (acc << 6) | static_cast<std::uint32_t>(value);+ bits += 6;+ if (bits >= 8) {+ bits -= 8;+ out.push_back(static_cast<std::uint8_t>((acc >> bits) & 255u));+ }+ }+ return out;+}++std::string format_public_key(const PublicKey &public_key) {+ return "ed25519:" ++ base64url_encode(Bytes(public_key.data(), public_key.size()));+}++std::optional<PublicKey> parse_public_key(std::string_view text) {+ constexpr std::string_view prefix = "ed25519:";+ if (!text.starts_with(prefix))+ return std::nullopt;+ auto decoded = base64url_decode(text.substr(prefix.size()));+ if (!decoded || decoded->size() != 32)+ return std::nullopt;+ return key_from_span(Bytes(decoded->data(), decoded->size()));+}++std::vector<std::uint8_t> secure_random(std::size_t count) {+ std::vector<std::uint8_t> out(count);+ if (count != 0 && RAND_bytes(out.data(), static_cast<int>(count)) != 1)+ out.clear();+ return out;+}++} // namespace vn--- /dev/null+++ b/xveins/src/crypto.h@@ -0,0 +1,37 @@+#pragma once++#include "common.h"++#include <array>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn {++using PublicKey = std::array<std::uint8_t, 32>;+using Signature = std::array<std::uint8_t, 64>;+using FingerprintBytes = std::array<std::uint8_t, 16>;++std::optional<PublicKey> ed25519_public_from_seed(Bytes seed);+std::optional<Signature> ed25519_sign(Bytes seed, Bytes message);+bool ed25519_verify(const PublicKey &public_key, Bytes message,+ Bytes signature);++FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key);+std::string key_fingerprint(const PublicKey &public_key);++// RFC 4648 base32 with no padding. The reference implementation emits+// fingerprints in uppercase, so this matches it.+std::string base32_text(Bytes raw);+// Unpadded base64url.+std::string base64url_encode(Bytes raw);+std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text);++std::string format_public_key(const PublicKey &public_key);+std::optional<PublicKey> parse_public_key(std::string_view text);++std::vector<std::uint8_t> secure_random(std::size_t count);++} // namespace vn--- /dev/null+++ b/xveins/src/exclude.cpp@@ -0,0 +1,145 @@+#include "local_commands.h"++#include "pathspec.h"+#include "store.h"++#include <iostream>+#include <string_view>++namespace vn {++namespace {++bool ex_is_flag(std::string_view arg) {+ return !arg.empty() && arg.front() == '-';+}++std::string_view trim(std::string_view b) {+ std::size_t start = 0;+ std::size_t end = b.size();+ while (start < end) {+ const char c = b[start];+ if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+ break;+ ++start;+ }+ while (end > start) {+ const char c = b[end - 1];+ if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+ break;+ --end;+ }+ return b.substr(start, end - start);+}++bool line_exists(std::string_view data, std::string_view pattern) {+ if (data.empty())+ return false;+ std::size_t start = 0;+ for (std::size_t pos = 0; pos <= data.size(); ++pos) {+ const bool at_end = pos == data.size();+ if (at_end || data[pos] == '\n') {+ if (trim(data.substr(start, pos - start)) == pattern)+ return true;+ start = pos + 1;+ }+ }+ return false;+}++} // namespace++int ex_run(const std::vector<std::string> &args) {+ std::vector<std::string> operands;+ 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 && ex_is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ operands.push_back(arg);+ }+ }+ if (operands.empty()) {+ error_prefix();+ std::cout << "ex requires at least one pattern\n";+ return 1;+ }++ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const auto cwd_rel = cwd_relative(*root);+ if (!cwd_rel) {+ error_prefix();+ std::cout << "cannot determine current directory\n";+ return 1;+ }++ std::vector<std::string> patterns;+ for (const auto &arg : operands) {+ auto norm = pathspec_normalize(*root, *cwd_rel, arg);+ if (!norm) {+ error_prefix();+ std::cout << "pattern is outside the repository: " << arg << "\n";+ return 1;+ }+ if (norm->empty() || !valid_path(*norm)) {+ error_prefix();+ std::cout << arg << "\n";+ std::cout << "not a valid exclude pattern\n";+ return 1;+ }+ patterns.push_back(std::move(*norm));+ }++ const fs::path exclude_path = *root / ".vnexclude";+ std::string data;+ if (auto existing = read_file_opt(exclude_path))+ data.assign(reinterpret_cast<const char *>(existing->data()),+ existing->size());++ std::string additions;+ std::vector<std::string> added;+ for (const auto &pattern : patterns) {+ if (line_exists(data, pattern))+ continue;+ bool duplicate = false;+ for (const auto &prior : added) {+ if (prior == pattern) {+ duplicate = true;+ break;+ }+ }+ if (duplicate)+ continue;+ if (additions.empty() && !data.empty() && data.back() != '\n')+ additions.push_back('\n');+ added.push_back(pattern);+ additions += pattern;+ additions.push_back('\n');+ }++ if (added.empty()) {+ info_prefix();+ std::cout << "no new exclude rules\n";+ return 0;+ }+ if (!append_file(exclude_path, bytes_of(additions))) {+ error_prefix();+ std::cout << "cannot write .vnexclude\n";+ return 1;+ }+ info_prefix();+ std::cout << "added " << added.size() << " exclude rule(s)\n";+ return 0;+}++} // namespace vn--- /dev/null+++ b/xveins/src/local_commands.h@@ -0,0 +1,17 @@+#pragma once++#include <string>+#include <vector>++namespace vn {++// Local-only commands. Each receives the full argv-style vector and indexes+// its own arguments (args[0] is the program, args[1] the command).+int bmk_run(const std::vector<std::string> &args);+int rm_run(const std::vector<std::string> &args);+int mv_run(const std::vector<std::string> &args);+int ex_run(const std::vector<std::string> &args);+int op_run(const std::vector<std::string> &args);+int undo_run(const std::vector<std::string> &args);++} // namespace vn--- /dev/null+++ b/xveins/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/xveins/src/merge.cpp@@ -0,0 +1,2246 @@+#include "merge.h"++#include "pathspec.h"+#include "worktree.h"++#include <algorithm>+#include <cstdlib>+#include <cstring>+#include <iostream>+#include <set>+#include <utility>++namespace vn {++namespace {++// ---------------------------------------------------------------------------+// Object access that also sees pending transaction objects+// ---------------------------------------------------------------------------++bool same_id(const Id &a, const Id &b) {+ return std::memcmp(a.data(), b.data(), ID_LEN) == 0;+}++std::optional<std::vector<std::uint8_t>> read_body_any(Store &store, Txn *tx,+ std::uint8_t type,+ const Id &id) {+ if (tx) {+ if (auto cached = tx->writer().find_cached(type, id))+ return cached;+ }+ return store.read_body(id, type);+}++bool append_blob_any(Store &store, Txn *tx, const Id &id,+ std::vector<std::uint8_t> &out, std::size_t depth) {+ if (depth > 64)+ return false;+ auto body = read_body_any(store, tx, TYPE_BLOB, id);+ 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;+ }+ for (const auto &entry : blob->entries) {+ if (blob->form == BlobForm::Leaf) {+ auto chunk = read_body_any(store, tx, TYPE_CHUNK, entry.id);+ if (!chunk)+ return false;+ out.insert(out.end(), chunk->begin(), chunk->end());+ } else if (!append_blob_any(store, tx, entry.id, out, depth + 1)) {+ return false;+ }+ }+ return true;+}++std::optional<std::vector<std::uint8_t>> read_blob_any(Store &store, Txn *tx,+ const Id &id) {+ std::vector<std::uint8_t> out;+ if (!append_blob_any(store, tx, id, out, 0))+ return std::nullopt;+ return out;+}++bool collect_chunks_any(Store &store, Txn *tx, const Id &id,+ std::vector<Id> &out, std::size_t depth) {+ if (depth > 64)+ return false;+ auto body = read_body_any(store, tx, TYPE_BLOB, id);+ if (!body)+ return false;+ auto blob = decode_blob(bytes_of(*body));+ if (!blob)+ return false;+ if (blob->form == BlobForm::Leaf) {+ for (const auto &entry : blob->entries)+ out.push_back(entry.id);+ return true;+ }+ if (blob->form == BlobForm::Interior) {+ for (const auto &entry : blob->entries) {+ if (!collect_chunks_any(store, tx, entry.id, out, depth + 1))+ return false;+ }+ }+ return true;+}++bool flatten_any(Store &store, Txn *tx, const Id &tree_id, std::string &prefix,+ std::vector<FlatEntry> &out, std::size_t depth) {+ if (depth > 4096)+ return false;+ auto body = read_body_any(store, tx, TYPE_TREE, tree_id);+ 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();+ if (!prefix.empty())+ prefix.push_back('/');+ prefix.append(entry.name);+ if (entry.kind == KIND_SUBTREE) {+ if (!flatten_any(store, tx, 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_any_sorted(Store &store, Txn *tx,+ std::optional<Id> tree) {+ std::vector<FlatEntry> out;+ if (!tree)+ return out;+ std::string prefix;+ (void)flatten_any(store, tx, *tree, 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;+}++const FlatEntry *find_flat_entry(const std::vector<FlatEntry> &entries,+ std::string_view path) {+ for (const auto &entry : entries) {+ if (entry.path == path)+ return &entry;+ }+ return nullptr;+}++bool tree_empty_any(Store &store, Txn *tx, const Id &id) {+ auto body = read_body_any(store, tx, TYPE_TREE, id);+ if (!body)+ return true;+ auto tree = decode_tree(bytes_of(*body));+ return !tree || tree->entries.empty();+}++Id add_tree(Txn &tx, const std::vector<TreeEntry> &entries) {+ auto encoded = encode_tree(entries);+ if (!encoded)+ return Id{};+ return tx.add_object(TYPE_TREE, *encoded);+}++Id add_empty_tree(Txn &tx) { return add_tree(tx, {}); }++Id add_blob(Txn &tx, 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)tx.add_known(object.type, id, std::move(object.body));+ }+ return build.root;+}++// ---------------------------------------------------------------------------+// Three-way line merge+// ---------------------------------------------------------------------------++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 + 1 - start);+ start = i + 1;+ }+ }+ if (start < data.size())+ out.emplace_back(reinterpret_cast<const char *>(data.data() + start),+ data.size() - start);+ return out;+}++std::vector<DiffOp> fallback_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();+ std::size_t prefix = 0;+ while (prefix < n && prefix < m && a[prefix] == b[prefix])+ ++prefix;+ std::size_t suffix = 0;+ while (suffix < n - prefix && suffix < m - prefix &&+ a[n - 1 - suffix] == b[m - 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 < n - suffix; ++i)+ ops.push_back(DiffOp{'-', i, 0});+ for (std::size_t j = prefix; j < m - suffix; ++j)+ ops.push_back(DiffOp{'+', 0, j});+ for (std::size_t k = 0; k < suffix; ++k)+ ops.push_back(DiffOp{' ', n - suffix + k, m - suffix + k});+ 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();+ const std::uint64_t cells =+ static_cast<std::uint64_t>(n + 1) * static_cast<std::uint64_t>(m + 1);+ if (cells > 8000000)+ return fallback_ops(a, b);+ const std::size_t cols = m + 1;+ std::vector<std::uint32_t> dp(static_cast<std::size_t>(cells), 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 oi = n;+ std::size_t oj = m;+ while (oi > 0 || oj > 0) {+ if (oi > 0 && oj > 0 && a[oi - 1] == b[oj - 1]) {+ ops.push_back(DiffOp{' ', oi - 1, oj - 1});+ --oi;+ --oj;+ } else if (oj > 0 &&+ (oi == 0 || dp[oi * cols + (oj - 1)] >=+ dp[(oi - 1) * cols + oj])) {+ ops.push_back(DiffOp{'+', 0, oj - 1});+ --oj;+ } else {+ ops.push_back(DiffOp{'-', oi - 1, 0});+ --oi;+ }+ }+ std::reverse(ops.begin(), ops.end());+ return ops;+}++struct Hunk {+ std::size_t start = 0;+ std::size_t end = 0;+ std::vector<std::string> lines;+};++std::vector<Hunk> hunks_from_ops(const std::vector<std::string> &side,+ const std::vector<DiffOp> &ops) {+ std::vector<Hunk> out;+ std::size_t base_pos = 0;+ std::size_t i = 0;+ while (i < ops.size()) {+ if (ops[i].tag == ' ') {+ ++base_pos;+ ++i;+ continue;+ }+ Hunk hunk;+ hunk.start = base_pos;+ while (i < ops.size() && ops[i].tag != ' ') {+ if (ops[i].tag == '-') {+ ++base_pos;+ } else {+ hunk.lines.push_back(side[ops[i].bi]);+ }+ ++i;+ }+ hunk.end = base_pos;+ out.push_back(std::move(hunk));+ }+ return out;+}++std::vector<Hunk> diff_hunks(const std::vector<std::string> &base,+ const std::vector<std::string> &side) {+ return hunks_from_ops(side, build_ops(base, side));+}++struct MergeRange {+ std::size_t base_start = 0;+ std::size_t base_end = 0;+ std::size_t ours_start = 0;+ std::size_t ours_end = 0;+ std::size_t theirs_start = 0;+ std::size_t theirs_end = 0;+};++struct EditResult {+ bool conflicted = false;+ std::vector<std::uint8_t> data;+ std::vector<MergeRange> ranges;+};++void append_lines(std::vector<std::uint8_t> &out,+ const std::vector<std::string> &lines, std::size_t start,+ std::size_t end) {+ for (std::size_t i = start; i < end && i < lines.size(); ++i)+ out.insert(out.end(), lines[i].begin(), lines[i].end());+}++void apply_hunks(std::vector<std::uint8_t> &out,+ const std::vector<std::string> &base, std::size_t from,+ std::size_t to, const std::vector<Hunk> &hunks,+ std::size_t first, std::size_t last) {+ std::size_t pos = from;+ for (std::size_t k = first; k < last; ++k) {+ const Hunk &h = hunks[k];+ if (h.start > pos && h.start <= to)+ append_lines(out, base, pos, h.start);+ for (const auto &line : h.lines)+ out.insert(out.end(), line.begin(), line.end());+ if (h.end > pos)+ pos = h.end;+ }+ if (pos < to)+ append_lines(out, base, pos, to);+}++std::size_t map_pos(const std::vector<Hunk> &hunks, std::size_t pos) {+ std::ptrdiff_t out = static_cast<std::ptrdiff_t>(pos);+ for (const auto &h : hunks) {+ if (h.end <= pos) {+ const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(h.end - h.start);+ const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());+ out += fresh - old;+ } else if (h.start < pos) {+ const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(pos - h.start);+ const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());+ out += fresh - old;+ break;+ } else {+ break;+ }+ }+ return static_cast<std::size_t>(out);+}++bool same_hunks(const std::vector<Hunk> &ours, std::size_t of, std::size_t ol,+ const std::vector<Hunk> &theirs, std::size_t tf,+ std::size_t tl) {+ std::string a;+ std::string b;+ for (std::size_t k = of; k < ol; ++k)+ for (const auto &line : ours[k].lines)+ a += line;+ for (std::size_t j = tf; j < tl; ++j)+ for (const auto &line : theirs[j].lines)+ b += line;+ return a == b;+}++EditResult merge_lines(const std::vector<std::string> &base,+ const std::vector<std::string> &ours,+ const std::vector<std::string> &theirs,+ bool adjacent_merge) {+ const auto ours_h = diff_hunks(base, ours);+ const auto theirs_h = diff_hunks(base, theirs);+ EditResult result;+ std::size_t oi = 0;+ std::size_t ti = 0;+ std::size_t pos = 0;+ while (oi < ours_h.size() || ti < theirs_h.size()) {+ const bool have_o = oi < ours_h.size();+ const bool have_t = ti < theirs_h.size();+ const std::size_t o_start = have_o ? ours_h[oi].start : 0;+ const std::size_t t_start = have_t ? theirs_h[ti].start : 0;+ const bool take_ours_cluster = have_o && (!have_t || o_start <= t_start);+ const std::size_t cluster_start = take_ours_cluster ? o_start : t_start;+ const std::size_t of = oi;+ const std::size_t tf = ti;+ std::size_t o_last = of;+ std::size_t t_last = tf;+ std::size_t end = cluster_start;+ bool seen_o = false;+ bool seen_t = false;+ for (;;) {+ bool progress = false;+ if (o_last < ours_h.size()) {+ const Hunk &h = ours_h[o_last];+ bool include = h.start <= end;+ if (o_last != of)+ include = adjacent_merge ? h.start < end : h.start <= end;+ if (include) {+ seen_o = true;+ ++o_last;+ if (h.end > end)+ end = h.end;+ progress = true;+ }+ }+ if (t_last < theirs_h.size()) {+ const Hunk &h = theirs_h[t_last];+ bool include = h.start <= end;+ if (t_last != tf)+ include = adjacent_merge ? h.start < end : h.start <= end;+ if (include) {+ seen_t = true;+ ++t_last;+ if (h.end > end)+ end = h.end;+ progress = true;+ }+ }+ if (!progress)+ break;+ }+ if (end < cluster_start)+ end = cluster_start;+ if (seen_o && !seen_t) {+ apply_hunks(result.data, base, pos, end, ours_h, of, o_last);+ pos = end;+ oi = o_last;+ ti = t_last;+ } else if (seen_t && !seen_o) {+ apply_hunks(result.data, base, pos, end, theirs_h, tf, t_last);+ pos = end;+ oi = o_last;+ ti = t_last;+ } else {+ if (same_hunks(ours_h, of, o_last, theirs_h, tf, t_last)) {+ apply_hunks(result.data, base, pos, end, ours_h, of, o_last);+ pos = end;+ } else {+ result.conflicted = true;+ apply_hunks(result.data, base, pos, end, ours_h, of, o_last);+ MergeRange range;+ range.base_start = cluster_start;+ range.base_end = end;+ range.ours_start = map_pos(ours_h, cluster_start);+ range.ours_end = map_pos(ours_h, end);+ range.theirs_start = map_pos(theirs_h, cluster_start);+ range.theirs_end = map_pos(theirs_h, end);+ result.ranges.push_back(range);+ pos = end;+ }+ oi = o_last;+ ti = t_last;+ }+ }+ if (pos < base.size())+ append_lines(result.data, base, pos, base.size());+ return result;+}++std::optional<EditResult> merge_blobs(Store &store, Txn *tx, const Id &base_id,+ const Id &ours_id, const Id &theirs_id,+ bool adjacent) {+ auto base = read_blob_any(store, tx, base_id);+ auto ours = read_blob_any(store, tx, ours_id);+ auto theirs = read_blob_any(store, tx, theirs_id);+ if (!base || !ours || !theirs)+ return std::nullopt;+ return merge_lines(split_lines(bytes_of(*base)), split_lines(bytes_of(*ours)),+ split_lines(bytes_of(*theirs)), adjacent);+}++// ---------------------------------------------------------------------------+// Rename detection+// ---------------------------------------------------------------------------++struct RenamePair {+ std::string old_path;+ std::string new_path;+ std::size_t score = 0;+ bool old_used = false;+ bool new_used = false;+};++std::uint64_t hash_line(std::string_view line) {+ std::uint64_t h = 1469598103934665603ull;+ for (char raw : line) {+ const auto c = static_cast<unsigned char>(raw);+ h = (h ^ static_cast<std::uint64_t>(c)) * 1099511628211ull;+ }+ return h;+}++int line_similarity(Bytes a, Bytes b) {+ std::vector<std::uint64_t> la;+ std::vector<std::uint64_t> lb;+ std::size_t start = 0;+ for (std::size_t i = 0; i <= a.size(); ++i) {+ if (i == a.size() || a[i] == '\n') {+ la.push_back(hash_line(str_of(a.subspan(start, i - start))));+ start = i + 1;+ }+ }+ start = 0;+ for (std::size_t j = 0; j <= b.size(); ++j) {+ if (j == b.size() || b[j] == '\n') {+ lb.push_back(hash_line(str_of(b.subspan(start, j - start))));+ start = j + 1;+ }+ }+ std::sort(la.begin(), la.end());+ std::sort(lb.begin(), lb.end());+ std::size_t ia = 0;+ std::size_t ib = 0;+ std::size_t inter = 0;+ while (ia < la.size() && ib < lb.size()) {+ if (la[ia] == lb[ib]) {+ ++inter;+ ++ia;+ ++ib;+ } else if (la[ia] < lb[ib]) {+ ++ia;+ } else {+ ++ib;+ }+ }+ const std::size_t total = la.size() + lb.size() - inter;+ if (total == 0)+ return 100;+ return static_cast<int>((inter * 100) / total);+}++int chunk_similarity(Store &store, Txn *tx, const Id &a, const Id &b) {+ std::vector<Id> ca;+ std::vector<Id> cb;+ if (!collect_chunks_any(store, tx, a, ca, 0) ||+ !collect_chunks_any(store, tx, b, cb, 0))+ return 0;+ std::size_t inter = 0;+ for (const auto &x : ca) {+ for (const auto &y : cb) {+ if (same_id(x, y)) {+ ++inter;+ break;+ }+ }+ }+ const std::size_t total = ca.size() + cb.size() - inter;+ if (total == 0)+ return 0;+ return static_cast<int>((inter * 100) / total);+}++int similarity(Store &store, Txn *tx, const Id &a, const Id &b) {+ if (same_id(a, b))+ return 100;+ auto da = read_blob_any(store, tx, a);+ auto db = read_blob_any(store, tx, b);+ if (!da || !db)+ return 0;+ int result = 0;+ if (da->size() >= 131072 && db->size() >= 131072)+ result = chunk_similarity(store, tx, a, b);+ if (result == 0)+ result = line_similarity(bytes_of(*da), bytes_of(*db));+ return result;+}++} // namespace++std::vector<Rename> detect_renames(Store &store, Txn *tx,+ std::optional<Id> old_tree,+ std::optional<Id> new_tree, int similar_pct,+ std::uint64_t parent_index) {+ const auto old_entries = flatten_any_sorted(store, tx, old_tree);+ const auto new_entries = flatten_any_sorted(store, tx, new_tree);+ std::vector<FlatEntry> deleted;+ std::vector<FlatEntry> added;+ for (const auto &entry : old_entries) {+ if (!find_flat_entry(new_entries, entry.path))+ deleted.push_back(entry);+ }+ for (const auto &entry : new_entries) {+ if (!find_flat_entry(old_entries, entry.path))+ added.push_back(entry);+ }+ std::vector<char> used_old(deleted.size(), 0);+ std::vector<char> used_new(added.size(), 0);+ std::vector<Rename> out;+ for (std::size_t di = 0; di < deleted.size(); ++di) {+ if (used_old[di])+ continue;+ for (std::size_t ai = 0; ai < added.size(); ++ai) {+ if (used_new[ai])+ continue;+ if (same_id(deleted[di].target, added[ai].target)) {+ out.push_back(Rename{parent_index, 0, deleted[di].path, added[ai].path});+ used_old[di] = 1;+ used_new[ai] = 1;+ break;+ }+ }+ }+ if (similar_pct > 0) {+ std::vector<RenamePair> pairs;+ constexpr std::size_t candidate_limit = 5000;+ for (std::size_t di = 0; di < deleted.size(); ++di) {+ if (used_old[di] || (deleted[di].kind != KIND_FILE &&+ deleted[di].kind != KIND_EXECUTABLE))+ continue;+ for (std::size_t ai = 0; ai < added.size() && pairs.size() < candidate_limit;+ ++ai) {+ if (used_new[ai] || (added[ai].kind != KIND_FILE &&+ added[ai].kind != KIND_EXECUTABLE))+ continue;+ RenamePair pair;+ pair.old_path = deleted[di].path;+ pair.new_path = added[ai].path;+ pair.score = static_cast<std::size_t>(+ similarity(store, tx, deleted[di].target, added[ai].target));+ pairs.push_back(std::move(pair));+ }+ }+ for (;;) {+ std::ptrdiff_t best_i = -1;+ std::size_t best = 0;+ for (std::size_t i = 0; i < pairs.size(); ++i) {+ if (!pairs[i].old_used && !pairs[i].new_used &&+ pairs[i].score > best) {+ best = pairs[i].score;+ best_i = static_cast<std::ptrdiff_t>(i);+ }+ }+ if (best_i < 0 || best < static_cast<std::size_t>(similar_pct))+ break;+ auto &pair = pairs[static_cast<std::size_t>(best_i)];+ pair.old_used = true;+ pair.new_used = true;+ out.push_back(Rename{parent_index, 0, pair.old_path, pair.new_path});+ }+ }+ std::stable_sort(out.begin(), out.end(), [](const Rename &a, const Rename &b) {+ if (a.parent_index != b.parent_index)+ return a.parent_index < b.parent_index;+ return compare(bytes_of(a.to_path), bytes_of(b.to_path)) < 0;+ });+ return out;+}++int rename_similar_pct(const fs::path &root) {+ if (auto value = repo_config_value(root, "rename.autodetect")) {+ if (*value == "off")+ return 0;+ return 60;+ }+ return 60;+}++namespace {++// ---------------------------------------------------------------------------+// Rename maps+// ---------------------------------------------------------------------------++using RenameMap = std::vector<std::pair<std::string, std::string>>;++std::optional<std::string> rename_lookup(const RenameMap &map,+ std::string_view path) {+ for (const auto &entry : map) {+ if (entry.first == path)+ return entry.second;+ }+ return std::nullopt;+}++void rename_apply(RenameMap &map, const std::string &from,+ const std::string &to) {+ for (auto &entry : map) {+ if (entry.second == from) {+ entry.second = to;+ return;+ }+ }+ for (auto &entry : map) {+ if (entry.first == from) {+ entry.second = to;+ return;+ }+ }+ map.emplace_back(from, to);+}++std::optional<Id> tree_of(Store &store, const Id &commit_id) {+ auto loaded = load_commit(store, commit_id);+ if (!loaded)+ return std::nullopt;+ return loaded->commit.root_tree;+}++std::optional<Id> first_parent(Store &store, const Id &commit_id) {+ auto loaded = load_commit(store, commit_id);+ if (!loaded || loaded->commit.parents.empty())+ return std::nullopt;+ return loaded->commit.parents.front();+}++RenameMap map_from(Store &store, const Id &base, const Id &side) {+ RenameMap map;+ if (same_id(base, side))+ return map;+ std::vector<Id> chain;+ Id current = side;+ bool reached = false;+ for (std::size_t depth = 0; depth < 100000; ++depth) {+ if (same_id(current, base)) {+ reached = true;+ break;+ }+ chain.push_back(current);+ auto parent = first_parent(store, current);+ if (!parent)+ break;+ current = *parent;+ }+ if (!reached)+ return map;+ for (std::size_t i = chain.size(); i > 0; --i) {+ auto loaded = load_commit(store, chain[i - 1]);+ if (!loaded)+ continue;+ if (loaded->commit.renames_state == RENAMES_RECORDED) {+ for (const auto &rename : loaded->commit.renames) {+ if (rename.parent_index == 0)+ rename_apply(map, rename.from_path, rename.to_path);+ }+ } else {+ auto parent = first_parent(store, chain[i - 1]);+ if (!parent)+ continue;+ auto old_tree = tree_of(store, *parent);+ auto new_tree = tree_of(store, chain[i - 1]);+ for (const auto &rename :+ detect_renames(store, nullptr, old_tree, new_tree, 50, 0))+ rename_apply(map, rename.from_path, rename.to_path);+ }+ }+ return map;+}++// ---------------------------------------------------------------------------+// Tree merge+// ---------------------------------------------------------------------------++struct TreeTerm {+ bool positive = true;+ bool present = false;+ Id id{};+};++struct EntryTerm {+ bool positive = true;+ bool present = false;+ std::uint8_t kind = 0;+ std::optional<Id> target;+};++struct OrigEntry {+ std::size_t term = 0;+ std::string path;+ std::uint8_t kind = 0;+ Id target{};+};++struct OutEntry {+ std::string path;+ std::uint8_t kind = 0;+ Id target{};+};++struct MergeOutcome {+ Id tree{};+ std::size_t rerere = 0;+};++bool 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 && same_id(*a.target, *b.target);+}++void flatten_values(Store &store, const std::vector<ConflictValue> &values,+ bool positive, std::vector<ConflictValue> &adds,+ std::vector<ConflictValue> &removes, std::size_t depth) {+ for (const auto &value : values) {+ if (value.kind == KIND_CONFLICT && value.target && depth < 64) {+ auto body = store.read_body(*value.target, TYPE_CONFLICT);+ if (body) {+ auto child = decode_conflict(bytes_of(*body));+ if (child) {+ flatten_values(store, child->adds, positive, adds, removes,+ depth + 1);+ flatten_values(store, child->removes, !positive, adds, removes,+ depth + 1);+ continue;+ }+ }+ }+ if (positive)+ adds.push_back(value);+ else+ removes.push_back(value);+ }+}++Conflict simplify(Store &store, const std::vector<ConflictValue> &adds_in,+ const std::vector<ConflictValue> &removes_in) {+ std::vector<ConflictValue> flat_adds;+ std::vector<ConflictValue> flat_removes;+ flatten_values(store, adds_in, true, flat_adds, flat_removes, 0);+ flatten_values(store, removes_in, false, flat_adds, flat_removes, 0);++ std::vector<char> used(flat_adds.size(), 0);+ std::vector<char> rem_used(flat_removes.size(), 0);+ for (std::size_t r = 0; r < flat_removes.size(); ++r) {+ for (std::size_t a = 0; a < flat_adds.size(); ++a) {+ if (!used[a] && value_equal(flat_adds[a], flat_removes[r])) {+ used[a] = 1;+ rem_used[r] = 1;+ break;+ }+ }+ }+ Conflict out;+ for (std::size_t a = 0; a < flat_adds.size(); ++a) {+ if (!used[a])+ out.adds.push_back(flat_adds[a]);+ }+ for (std::size_t r = 0; r < flat_removes.size(); ++r) {+ if (!rem_used[r])+ out.removes.push_back(flat_removes[r]);+ }+ return out;+}++std::optional<ConflictValue> resolved(const Conflict &conflict) {+ if (conflict.adds.empty())+ return std::nullopt;+ for (std::size_t i = 1; i < conflict.adds.size(); ++i) {+ if (!value_equal(conflict.adds[0], conflict.adds[i]))+ return std::nullopt;+ }+ return conflict.adds[0];+}++bool all_files(const Conflict &conflict) {+ for (const auto &value : conflict.adds) {+ if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&+ value.kind != 0)+ return false;+ }+ for (const auto &value : conflict.removes) {+ if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&+ value.kind != 0)+ return false;+ }+ return true;+}++int merge_mode(const Conflict &conflict) {+ if (conflict.adds.size() != 2 || conflict.removes.size() != 1)+ return -1;+ auto mode = [](const ConflictValue &value) -> int {+ if (value.kind == 0)+ return -1;+ return value.kind == KIND_EXECUTABLE ? 1 : 0;+ };+ const int m0 = mode(conflict.adds[0]);+ const int m1 = mode(conflict.adds[1]);+ const int mr = mode(conflict.removes[0]);+ if (m0 < 0 || m1 < 0)+ return -1;+ if (m0 == m1)+ return m0;+ if (mr >= 0 && m0 == mr)+ return m1;+ if (mr >= 0 && m1 == mr)+ return m0;+ return -1;+}++bool merge_binary(const fs::path &repo, std::string_view path) {+ auto data = read_file_opt(repo / ".veinsattributes");+ if (!data)+ return false;+ const std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ bool result = false;+ std::size_t start = 0;+ for (std::size_t pos = 0; pos <= text.size(); ++pos) {+ if (pos != text.size() && text[pos] != '\n')+ continue;+ std::string_view line = text.substr(start, pos - start);+ start = pos + 1;+ while (!line.empty() && (line.front() == ' ' || line.front() == '\t' ||+ line.front() == '\r' || line.front() == '\n'))+ line.remove_prefix(1);+ while (!line.empty() && (line.back() == ' ' || line.back() == '\t' ||+ line.back() == '\r' || line.back() == '\n'))+ line.remove_suffix(1);+ if (line.empty() || line.front() == '#')+ continue;+ std::size_t glob_end = 0;+ while (glob_end < line.size() && line[glob_end] != ' ' &&+ line[glob_end] != '\t')+ ++glob_end;+ const std::string_view glob = line.substr(0, glob_end);+ std::string_view base = glob;+ if (const auto slash = glob.rfind('/'); slash != std::string_view::npos)+ base = glob.substr(slash + 1);+ const bool matched =+ glob_match(glob, path) ||+ (glob.find('/') == std::string_view::npos && glob_match(base, path));+ if (!matched)+ continue;+ std::size_t t = glob_end;+ while (t < line.size()) {+ while (t < line.size() && (line[t] == ' ' || line[t] == '\t'))+ ++t;+ const std::size_t tok_start = t;+ while (t < line.size() && line[t] != ' ' && line[t] != '\t')+ ++t;+ const std::string_view token = line.substr(tok_start, t - tok_start);+ const auto eq = token.find('=');+ if (eq != std::string_view::npos) {+ const std::string_view key = token.substr(0, eq);+ const std::string_view value = token.substr(eq + 1);+ if (key == "merge") {+ if (value == "binary")+ result = true;+ else if (value == "text")+ result = false;+ }+ }+ }+ }+ return result;+}++std::optional<Id> resolution_lookup(const fs::path &repo, Bytes body) {+ const auto digest = blake3_hash(body);+ const std::string key = hex_encode(Bytes(digest.data(), digest.size()));+ auto data = read_file_opt(resolutions_dir(repo) / key);+ if (!data || data->size() < 64)+ return std::nullopt;+ const std::string_view text(reinterpret_cast<const char *>(data->data()), 64);+ Id id{};+ if (!hex_decode(text, MutBytes(id.data(), id.size())))+ return std::nullopt;+ return id;+}++void resolution_record(const fs::path &repo, Bytes body, const Id &blob) {+ const auto digest = blake3_hash(body);+ const std::string key = hex_encode(Bytes(digest.data(), digest.size()));+ (void)write_file(resolutions_dir(repo) / key, bytes_of(hex_encode(blob)));+}++Id build_level(Txn &tx, const std::vector<OutEntry> &entries,+ std::size_t start, std::size_t end, std::size_t prefix_len) {+ std::vector<TreeEntry> out;+ std::size_t i = start;+ while (i < end) {+ const OutEntry &entry = entries[i];+ const std::size_t name_end = entry.path.find('/', prefix_len);+ const std::size_t cut =+ name_end == std::string::npos ? entry.path.size() : name_end;+ const std::string name = entry.path.substr(prefix_len, cut - prefix_len);+ if (cut == entry.path.size()) {+ out.push_back(TreeEntry{name, entry.kind, entry.target});+ ++i;+ } else {+ std::size_t j = i + 1;+ while (j < end) {+ const std::size_t other_end = entries[j].path.find('/', prefix_len);+ const std::size_t other_cut = other_end == std::string::npos+ ? entries[j].path.size()+ : other_end;+ if (other_cut != cut ||+ entries[j].path.compare(prefix_len, cut - prefix_len, name) != 0)+ break;+ ++j;+ }+ const Id child = build_level(tx, entries, i, j, cut + 1);+ out.push_back(TreeEntry{name, KIND_SUBTREE, child});+ i = j;+ }+ }+ return add_tree(tx, out);+}++Id build_from_entries(Txn &tx, std::vector<OutEntry> &entries) {+ if (entries.empty())+ return add_empty_tree(tx);+ std::stable_sort(entries.begin(), entries.end(),+ [](const OutEntry &a, const OutEntry &b) {+ return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+ });+ return build_level(tx, entries, 0, entries.size(), 0);+}++Id build_subtree(Txn &tx, const std::vector<OrigEntry> &canon,+ std::size_t term, std::string_view prefix) {+ std::vector<OutEntry> rels;+ for (const auto &entry : canon) {+ if (entry.term != term)+ continue;+ if (entry.path.size() > prefix.size() &&+ entry.path.compare(0, prefix.size(), prefix) == 0 &&+ entry.path[prefix.size()] == '/')+ rels.push_back(+ OutEntry{entry.path.substr(prefix.size() + 1), entry.kind,+ entry.target});+ }+ return build_from_entries(tx, rels);+}++bool has_prefix(std::string_view path, std::string_view prefix) {+ return path.size() > prefix.size() &&+ path.compare(0, prefix.size(), prefix) == 0 &&+ path[prefix.size()] == '/';+}++std::optional<OutEntry> merge_entry(const fs::path &repo, Txn &tx,+ Store &store, const std::string &path,+ const std::vector<EntryTerm> &terms,+ bool adjacent, std::size_t &rerere) {+ std::vector<ConflictValue> adds;+ std::vector<ConflictValue> removes;+ for (const auto &term : terms) {+ ConflictValue value;+ if (term.present) {+ value.kind = term.kind;+ value.target = term.target;+ }+ if (term.positive)+ adds.push_back(value);+ else+ removes.push_back(value);+ }+ Conflict sum = simplify(store, adds, removes);+ if (auto value = resolved(sum)) {+ if (value->kind == 0)+ return std::nullopt;+ return OutEntry{path, value->kind, *value->target};+ }+ if (all_files(sum) && sum.adds.size() == 2 && sum.removes.size() == 1 &&+ sum.adds[0].kind != 0 && sum.adds[1].kind != 0 &&+ sum.removes[0].kind != 0 && !merge_binary(repo, path)) {+ auto merged = merge_blobs(store, &tx, *sum.removes[0].target,+ *sum.adds[0].target, *sum.adds[1].target,+ adjacent);+ if (merged && !merged->conflicted) {+ const Id blob = add_blob(tx, bytes_of(merged->data));+ const int mode = merge_mode(sum);+ if (mode >= 0)+ return OutEntry{path,+ static_cast<std::uint8_t>(mode == 1 ? KIND_EXECUTABLE+ : KIND_FILE),+ blob};+ }+ }+ const auto body = encode_conflict(sum);+ if (all_files(sum)) {+ if (auto memo = resolution_lookup(repo, bytes_of(body))) {+ ++rerere;+ return OutEntry{path, KIND_FILE, *memo};+ }+ }+ const Id id = tx.add_object(TYPE_CONFLICT, body);+ return OutEntry{path, KIND_CONFLICT, id};+}++MergeOutcome treemerge(const fs::path &repo, Txn &tx, Store &store,+ const std::vector<TreeTerm> &terms,+ const std::vector<RenameMap> &maps, bool adjacent) {+ std::vector<OrigEntry> orig;+ for (std::size_t t = 0; t < terms.size(); ++t) {+ if (!terms[t].present)+ continue;+ for (const auto &entry : flatten_any_sorted(store, &tx, terms[t].id))+ orig.push_back(OrigEntry{t, entry.path, entry.kind, entry.target});+ }++ auto canonical_targets =+ [&](const std::string &path) -> std::vector<std::pair<std::size_t, std::string>> {+ std::vector<std::pair<std::size_t, std::string>> out;+ for (std::size_t i = 0; i < maps.size(); ++i) {+ auto dest = rename_lookup(maps[i], path);+ if (!dest)+ continue;+ bool exists = false;+ for (const auto &item : out) {+ if (item.second == *dest) {+ exists = true;+ break;+ }+ }+ if (!exists)+ out.emplace_back(i, *dest);+ }+ return out;+ };++ auto find_orig = [&](std::size_t term,+ const std::string &path) -> const OrigEntry * {+ for (const auto &entry : orig) {+ if (entry.term == term && entry.path == path)+ return &entry;+ }+ return nullptr;+ };++ std::vector<OrigEntry> canon;+ std::vector<std::string> special;+ std::vector<std::string> consumed;+ auto mark_consumed = [&](const std::string &path) {+ for (const auto &item : consumed) {+ if (item == path)+ return;+ }+ consumed.push_back(path);+ };+ for (const auto &entry : orig) {+ auto targets = canonical_targets(entry.path);+ if (targets.size() > 1) {+ bool seen = false;+ for (const auto &item : special) {+ if (item == entry.path) {+ seen = true;+ break;+ }+ }+ if (!seen)+ special.push_back(entry.path);+ }+ const std::string &canonical =+ targets.size() == 1 ? targets[0].second : entry.path;+ canon.push_back(OrigEntry{entry.term, canonical, entry.kind, entry.target});+ }++ std::vector<OutEntry> out;+ std::size_t rerere = 0;++ for (const auto &sp : special) {+ auto targets = canonical_targets(sp);+ std::vector<EntryTerm> ets;+ for (const auto &target : targets) {+ EntryTerm term;+ term.positive = true;+ if (const OrigEntry *found = find_orig(target.first, target.second)) {+ term.present = true;+ term.kind = found->kind;+ term.target = found->target;+ }+ ets.push_back(term);+ mark_consumed(target.second);+ }+ std::ptrdiff_t base_term = -1;+ for (std::size_t ti = 0; ti < terms.size(); ++ti) {+ if (!terms[ti].positive) {+ base_term = static_cast<std::ptrdiff_t>(ti);+ break;+ }+ }+ if (base_term >= 0) {+ EntryTerm term;+ term.positive = false;+ if (const OrigEntry *found =+ find_orig(static_cast<std::size_t>(base_term), sp)) {+ term.present = true;+ term.kind = found->kind;+ term.target = found->target;+ }+ ets.push_back(term);+ }+ if (auto merged = merge_entry(repo, tx, store, sp, ets, adjacent, rerere))+ out.push_back(std::move(*merged));+ mark_consumed(sp);+ }++ auto find_canon = [&](std::size_t term,+ const std::string &path) -> const OrigEntry * {+ for (const auto &entry : canon) {+ if (entry.term == term && entry.path == path)+ return &entry;+ }+ return nullptr;+ };++ std::vector<std::string> paths;+ for (const auto &entry : canon) {+ bool seen = false;+ for (const auto &path : paths) {+ if (path == entry.path) {+ seen = true;+ break;+ }+ }+ if (!seen)+ paths.push_back(entry.path);+ }+ std::sort(paths.begin(), paths.end(),+ [](const std::string &a, const std::string &b) {+ return compare(bytes_of(a), bytes_of(b)) < 0;+ });++ auto is_consumed = [&](const std::string &path) {+ for (const auto &item : consumed) {+ if (item == path)+ return true;+ }+ return false;+ };++ for (const auto &path : paths) {+ if (is_consumed(path))+ continue;+ bool any_exact = false;+ bool any_children = false;+ for (std::size_t t = 0; t < terms.size(); ++t) {+ if (find_canon(t, path))+ any_exact = true;+ for (const auto &entry : canon) {+ if (entry.term == t && has_prefix(entry.path, path)) {+ any_children = true;+ break;+ }+ }+ }+ if (!any_exact)+ continue;+ const bool mixed = any_children;+ std::vector<EntryTerm> ets;+ for (std::size_t t = 0; t < terms.size(); ++t) {+ EntryTerm term;+ term.positive = terms[t].positive;+ if (const OrigEntry *exact = find_canon(t, path)) {+ term.present = true;+ term.kind = exact->kind;+ term.target = exact->target;+ } else if (mixed) {+ bool children = false;+ for (const auto &entry : canon) {+ if (entry.term == t && has_prefix(entry.path, path)) {+ children = true;+ break;+ }+ }+ if (children) {+ term.present = true;+ term.kind = KIND_SUBTREE;+ term.target = build_subtree(tx, canon, t, path);+ }+ }+ ets.push_back(term);+ }+ if (auto merged = merge_entry(repo, tx, store, path, ets, adjacent, rerere))+ out.push_back(std::move(*merged));+ if (mixed) {+ for (const auto &entry : canon) {+ if (has_prefix(entry.path, path))+ mark_consumed(entry.path);+ }+ }+ }++ return MergeOutcome{build_from_entries(tx, out), rerere};+}++// ---------------------------------------------------------------------------+// Commit-level merge helpers+// ---------------------------------------------------------------------------++bool contains_id_vec(const std::vector<Id> &ids, const Id &id) {+ for (const auto &candidate : ids) {+ if (same_id(candidate, id))+ return true;+ }+ return false;+}++std::vector<Id> merge_bases(Store &store, const Id &a, const Id &b) {+ const std::vector<Id> aa = collect_commits(store, std::vector<Id>{a});+ const std::vector<Id> bb = collect_commits(store, std::vector<Id>{b});+ std::vector<Id> common;+ for (const auto &x : aa) {+ if (contains_id_vec(bb, x))+ common.push_back(x);+ }+ std::vector<Id> out;+ for (const auto &c : common) {+ bool dominated = false;+ for (const auto &d : common) {+ if (same_id(c, d))+ continue;+ const auto descendants = collect_commits(store, std::vector<Id>{c});+ if (contains_id_vec(descendants, d)) {+ dominated = true;+ break;+ }+ }+ if (!dominated)+ out.push_back(c);+ }+ return out;+}++bool is_ancestor(Store &store, const Id &ancestor, const Id &descendant) {+ if (same_id(ancestor, descendant))+ return true;+ return contains_id_vec(collect_commits(store, std::vector<Id>{descendant}),+ ancestor);+}++std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,+ const std::vector<Id> &bases, bool adjacent);++std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,+ const std::vector<Id> &bases, bool adjacent) {+ if (bases.empty())+ return std::nullopt;+ if (bases.size() == 1)+ return tree_of(store, bases.front());+ auto t0 = tree_of(store, bases[0]);+ auto t1 = tree_of(store, bases[1]);+ const auto lcas = merge_bases(store, bases[0], bases[1]);+ std::vector<TreeTerm> terms;+ terms.push_back(TreeTerm{true, t0.has_value(), t0.value_or(Id{})});+ terms.push_back(TreeTerm{true, t1.has_value(), t1.value_or(Id{})});+ if (!lcas.empty()) {+ auto lt = tree_of(store, lcas.front());+ terms.push_back(TreeTerm{false, lt.has_value(), lt.value_or(Id{})});+ } else {+ terms.push_back(TreeTerm{false, false, Id{}});+ }+ std::vector<RenameMap> maps(3);+ return treemerge(repo, tx, store, terms, maps, adjacent).tree;+}++MergeOutcome merge_many(const fs::path &repo, Txn &tx, Store &store,+ const std::vector<Id> &heads, bool adjacent) {+ if (heads.size() == 1) {+ auto t = tree_of(store, heads.front());+ std::vector<TreeTerm> terms{+ TreeTerm{true, t.has_value(), t.value_or(Id{})}};+ return treemerge(repo, tx, store, terms, {RenameMap{}}, adjacent);+ }+ std::vector<TreeTerm> terms;+ std::vector<RenameMap> maps;+ std::optional<Id> map_base;+ if (heads.size() > 1) {+ const auto bases = merge_bases(store, heads[0], heads[1]);+ if (!bases.empty())+ map_base = bases.front();+ }+ for (const auto &head : heads) {+ auto t = tree_of(store, head);+ terms.push_back(TreeTerm{true, t.has_value(), t.value_or(Id{})});+ if (map_base)+ maps.push_back(map_from(store, *map_base, head));+ else+ maps.push_back(RenameMap{});+ }+ for (std::size_t i = 1; i < heads.size(); ++i) {+ const auto bases = merge_bases(store, heads[0], heads[i]);+ auto bt = base_tree(repo, tx, store, bases, adjacent);+ if (bt)+ terms.push_back(TreeTerm{false, true, *bt});+ else+ terms.push_back(TreeTerm{false, false, Id{}});+ maps.push_back(RenameMap{});+ }+ return treemerge(repo, tx, store, terms, maps, adjacent);+}++MergeOutcome rewrite_tree(const fs::path &repo, Txn &tx, Store &store,+ const Id &old_commit, const Id &commit_tree,+ const std::vector<Id> &old_parents,+ const std::vector<Id> &new_parents,+ const std::vector<Id> &new_parent_trees,+ bool adjacent) {+ std::vector<TreeTerm> terms;+ std::vector<RenameMap> maps;+ terms.push_back(TreeTerm{true, true, commit_tree});+ if (!old_parents.empty())+ maps.push_back(map_from(store, old_parents.front(), old_commit));+ else+ maps.push_back(RenameMap{});++ if (old_parents.empty()) {+ for (const auto &tree : new_parent_trees) {+ terms.push_back(TreeTerm{true, true, tree});+ maps.push_back(RenameMap{});+ }+ terms.push_back(TreeTerm{false, false, Id{}});+ maps.push_back(RenameMap{});+ } else {+ for (std::size_t i = 0; i < old_parents.size(); ++i) {+ auto old_tree = tree_of(store, old_parents[i]);+ const Id new_tree =+ i < new_parent_trees.size() ? new_parent_trees[i] : Id{};+ terms.push_back(TreeTerm{true, true, new_tree});+ terms.push_back(+ TreeTerm{false, old_tree.has_value(), old_tree.value_or(Id{})});+ if (i < new_parents.size())+ maps.push_back(map_from(store, old_parents[i], new_parents[i]));+ else+ maps.push_back(RenameMap{});+ maps.push_back(RenameMap{});+ }+ }+ return treemerge(repo, tx, store, terms, maps, adjacent);+}++Id make_commit(Txn &tx, Store &store, const fs::path &repo,+ const std::vector<Id> &parents, const Id &root,+ const ChangeId &change, const Sig &author,+ const std::string &message, std::uint8_t renames_state,+ const std::vector<KeyValue> &extra) {+ Commit commit;+ commit.version = 1;+ commit.parents = parents;+ commit.root_tree = root;+ commit.change_id = change;+ commit.author = author;+ commit.committer = identity_signature(repo);+ commit.message = message;+ commit.renames_state = renames_state;+ commit.extra = extra;+ if (renames_state == RENAMES_RECORDED) {+ for (std::size_t i = 0; i < parents.size(); ++i) {+ auto parent_tree = tree_of(store, parents[i]);+ auto detected =+ detect_renames(store, &tx, parent_tree, std::optional<Id>{root}, 0, i);+ for (auto &rename : detected)+ commit.renames.push_back(std::move(rename));+ }+ }+ return tx.add_object(TYPE_COMMIT, encode_commit(commit));+}++std::string rerere_suffix(std::size_t count) {+ if (count == 0)+ return std::string();+ return " (rerere " + std::to_string(count) + ")";+}++std::string join_revs(const std::vector<std::string> &revs) {+ std::string out;+ for (std::size_t i = 0; i < revs.size(); ++i) {+ if (i != 0)+ out.push_back(' ');+ out += revs[i];+ }+ return out;+}++bool adjacent_config(const fs::path &root) {+ auto value = repo_config_value(root, "merge.adjacent");+ return value && *value == "merge";+}++// ---------------------------------------------------------------------------+// Tree editing+// ---------------------------------------------------------------------------++std::optional<Id> tree_edit_into(Txn &tx, Store &store, const Id &tree_id,+ std::string_view path, bool present,+ std::uint8_t kind, const Id &target,+ std::size_t depth) {+ if (depth > 4096)+ return std::nullopt;+ auto body = read_body_any(store, &tx, TYPE_TREE, tree_id);+ if (!body)+ return std::nullopt;+ auto tree = decode_tree(bytes_of(*body));+ if (!tree)+ return std::nullopt;+ const std::size_t cut = path.find('/');+ const std::size_t cut_pos = cut == std::string_view::npos ? path.size() : cut;+ const std::string_view name = path.substr(0, cut_pos);+ std::vector<TreeEntry> entries;+ bool found = false;+ for (const auto &entry : tree->entries) {+ if (entry.name != name) {+ entries.push_back(entry);+ continue;+ }+ found = true;+ if (cut_pos == path.size()) {+ if (present)+ entries.push_back(TreeEntry{entry.name, kind, target});+ } else if (entry.kind == KIND_SUBTREE) {+ auto child = tree_edit_into(tx, store, entry.target,+ path.substr(cut_pos + 1), present, kind,+ target, depth + 1);+ if (child && !tree_empty_any(store, &tx, *child))+ entries.push_back(TreeEntry{entry.name, KIND_SUBTREE, *child});+ } else {+ entries.push_back(entry);+ }+ }+ if (!found && cut_pos == path.size() && present)+ entries.push_back(TreeEntry{std::string(name), kind, target});+ return add_tree(tx, entries);+}++std::optional<Id> tree_edit_replace(Txn &tx, Store &store, const Id &root,+ std::string_view path, bool present,+ std::uint8_t kind, const Id &target) {+ auto edited =+ tree_edit_into(tx, store, root, path, present, kind, target, 0);+ if (!edited)+ return std::nullopt;+ return edited;+}++// ---------------------------------------------------------------------------+// Conflicts+// ---------------------------------------------------------------------------++std::string conflict_kind_label(const Conflict &conflict) {+ for (const auto &value : conflict.adds) {+ if (value.kind == KIND_SUBTREE)+ return "tree";+ }+ for (const auto &value : conflict.removes) {+ if (value.kind == KIND_SUBTREE)+ return "tree";+ }+ for (const auto &value : conflict.adds) {+ if (value.kind == 0)+ return "delete/modify";+ }+ for (const auto &value : conflict.removes) {+ if (value.kind == 0)+ return "delete/modify";+ }+ return "text";+}++void print_range(std::size_t a, std::size_t b) {+ if (a == b)+ std::cout << a + 1;+ else+ std::cout << a + 1 << "-" << b;+}++std::optional<EditResult> conflict_ranges(Store &store, const Conflict &conflict,+ bool adjacent) {+ if (conflict.adds.size() != 2 || conflict.removes.size() != 1)+ return std::nullopt;+ const auto &ours = conflict.adds[0];+ const auto &theirs = conflict.adds[1];+ const auto &base = conflict.removes[0];+ if (ours.kind == 0 || theirs.kind == 0 || base.kind == 0)+ return std::nullopt;+ if (ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE ||+ base.kind == KIND_SUBTREE)+ return std::nullopt;+ return merge_blobs(store, nullptr, *base.target, *ours.target,+ *theirs.target, adjacent);+}++std::vector<FlatEntry> flatten_store(Store &store, const Id &tree) {+ return flatten_any_sorted(store, nullptr, std::optional<Id>{tree});+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++int merge_command(const std::vector<std::string> &revs) {+ if (revs.empty()) {+ error_prefix();+ std::cout << "merge requires at least one revision\n";+ return 1;+ }+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ 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());+ if (!wc) {+ error_prefix();+ std::cout << "no working-copy commit to merge into\n";+ return 1;+ }++ std::vector<Id> parents{*wc};+ bool failed = false;+ for (const auto &rev : revs) {+ auto resolved = resolve_revision(store, tx->view(), rev);+ if (!resolved) {+ failed = true;+ continue;+ }+ if (same_id(*resolved, *wc)) {+ error_prefix();+ std::cout << "cannot merge a commit with itself\n";+ failed = true;+ continue;+ }+ parents.push_back(*resolved);+ }+ if (failed) {+ error_prefix();+ std::cout << "unknown revision\n";+ return 1;+ }++ const auto old_root = tree_of(store, *wc);+ const bool adjacent = adjacent_config(*root);+ MergeOutcome outcome =+ merge_many(*root, *tx, store, parents, adjacent);+ const Sig author = identity_signature(*root);+ const Id new_id = make_commit(+ *tx, store, *root, parents, outcome.tree, random_change_id(), author, "",+ RENAMES_RECORDED, {});++ remove_head(tx->view(), *wc);+ move_bookmarks(tx->view(), *wc, new_id);+ set_workspace(tx->view(), new_id);+ rebuild_heads(tx->view());+ const std::string description =+ "merge " + join_revs(revs) + rerere_suffix(outcome.rerere);+ const auto status = tx->finish(description);+ if (!status)+ return 1;+ store.refresh(*root);+ (void)mark_native(*root, new_id);+ if (old_root)+ return checkout_materialize_commit(*root, store, old_root, outcome.tree);+ return 0;+}++int rebase_command(const std::string &source, const std::string &dest) {+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ 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 src = resolve_revision(store, tx->view(), source);+ auto dst = resolve_revision(store, tx->view(), dest);+ if (!src || !dst) {+ error_prefix();+ std::cout << "unknown revision\n";+ return 1;+ }+ const auto wc = working_copy_id(tx->view());+ std::optional<Id> old_wc_root;+ if (wc)+ old_wc_root = tree_of(store, *wc);++ std::vector<Id> set;+ for (const auto &commit : all_commits(store, tx->view())) {+ if (is_ancestor(store, *src, commit))+ set.push_back(commit);+ }++ std::vector<Id> old_ids;+ std::vector<Id> new_ids;+ std::vector<Id> new_tree_ids;+ std::vector<Id> remaining = set;+ std::size_t rerere_total = 0;+ const bool adjacent = adjacent_config(*root);+ const Sig fallback_sig = identity_signature(*root);+ (void)fallback_sig;++ while (!remaining.empty()) {+ std::ptrdiff_t ready_idx = -1;+ for (std::size_t i = 0; i < remaining.size(); ++i) {+ bool ready = true;+ auto loaded = load_commit(store, remaining[i]);+ if (!loaded)+ continue;+ for (const auto &parent : loaded->commit.parents) {+ if (contains_id_vec(set, parent) && !contains_id_vec(old_ids, parent) &&+ !same_id(remaining[i], *src))+ ready = false;+ }+ if (ready) {+ ready_idx = static_cast<std::ptrdiff_t>(i);+ break;+ }+ }+ if (ready_idx < 0) {+ error_prefix();+ std::cout << "rebase could not order commits\n";+ break;+ }+ const Id chosen = remaining[static_cast<std::size_t>(ready_idx)];+ auto loaded = load_commit(store, chosen);+ if (!loaded)+ break;++ std::vector<Id> new_parents;+ std::vector<Id> new_parent_trees;+ for (std::size_t pi = 0; pi < loaded->commit.parents.size(); ++pi) {+ const Id parent = loaded->commit.parents[pi];+ if (pi == 0 && same_id(chosen, *src)) {+ new_parents.push_back(*dst);+ new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));+ continue;+ }+ bool mapped = false;+ for (std::size_t mi = 0; mi < old_ids.size(); ++mi) {+ if (same_id(old_ids[mi], parent)) {+ new_parents.push_back(new_ids[mi]);+ new_parent_trees.push_back(new_tree_ids[mi]);+ mapped = true;+ break;+ }+ }+ if (!mapped) {+ new_parents.push_back(parent);+ new_parent_trees.push_back(tree_of(store, parent).value_or(Id{}));+ }+ }+ if (loaded->commit.parents.empty()) {+ new_parents.push_back(*dst);+ new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));+ }++ MergeOutcome outcome =+ rewrite_tree(*root, *tx, store, chosen, loaded->commit.root_tree,+ loaded->commit.parents, new_parents, new_parent_trees,+ adjacent);+ rerere_total += outcome.rerere;+ const Id new_id =+ make_commit(*tx, store, *root, new_parents, outcome.tree,+ loaded->commit.change_id, loaded->commit.author,+ loaded->commit.message, loaded->commit.renames_state,+ loaded->commit.extra);+ old_ids.push_back(chosen);+ new_ids.push_back(new_id);+ new_tree_ids.push_back(outcome.tree);+ remaining.erase(remaining.begin() ++ static_cast<std::ptrdiff_t>(ready_idx));+ }++ auto remap = [&](std::optional<Id> &id) {+ if (!id)+ return;+ for (std::size_t i = 0; i < old_ids.size(); ++i) {+ if (same_id(old_ids[i], *id)) {+ id = new_ids[i];+ return;+ }+ }+ };+ for (auto &bookmark : tx->view().bookmarks) {+ for (auto &id : bookmark.targets.adds)+ remap(id);+ for (auto &id : bookmark.targets.removes)+ remap(id);+ }+ for (auto &tag : tx->view().tags) {+ std::optional<Id> target = tag.target;+ remap(target);+ if (target)+ tag.target = *target;+ }+ for (auto &workspace : tx->view().working_copies) {+ std::optional<Id> target = workspace.target;+ remap(target);+ if (target)+ workspace.target = *target;+ }+ rebuild_heads(tx->view());+ const auto status =+ tx->finish("rebase " + source + " onto " + dest ++ rerere_suffix(rerere_total));+ if (!status)+ return 1;+ for (const auto &id : new_ids)+ (void)mark_native(*root, id);+ if (wc) {+ for (std::size_t i = 0; i < old_ids.size(); ++i) {+ if (same_id(old_ids[i], *wc)) {+ Store refreshed = Store::open_all(*root);+ return checkout_materialize_commit(*root, refreshed, old_wc_root,+ new_tree_ids[i]);+ }+ }+ }+ return 0;+}++int xs_command(bool porcelain) {+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ 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::vector<std::pair<std::string, Conflict>> items;+ if (const auto wc = working_copy_id(*view)) {+ auto loaded = load_commit(store, *wc);+ if (loaded) {+ for (const auto &entry : flatten_store(store, loaded->commit.root_tree)) {+ if (entry.kind != KIND_CONFLICT)+ continue;+ auto body = store.read_body(entry.target, TYPE_CONFLICT);+ if (!body)+ continue;+ auto conflict = decode_conflict(bytes_of(*body));+ if (!conflict)+ continue;+ items.emplace_back(entry.path, std::move(*conflict));+ }+ }+ }+ const bool adjacent = adjacent_config(*root);+ bool first = true;+ for (const auto &[path, conflict] : items) {+ const std::string kind = conflict_kind_label(conflict);+ auto ranges = conflict_ranges(store, conflict, adjacent);+ if (porcelain) {+ std::cout << path << "\t" << kind << "\t";+ if (ranges) {+ for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+ if (i > 0)+ std::cout << ",";+ print_range(ranges->ranges[i].base_start,+ ranges->ranges[i].base_end);+ }+ std::cout << "\t";+ for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+ if (i > 0)+ std::cout << ",";+ print_range(ranges->ranges[i].ours_start,+ ranges->ranges[i].ours_end);+ }+ std::cout << "\t";+ for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+ if (i > 0)+ std::cout << ",";+ print_range(ranges->ranges[i].theirs_start,+ ranges->ranges[i].theirs_end);+ }+ } else {+ std::cout << "\t\t";+ }+ std::cout << "\n";+ } else {+ std::cout << path << ": " << kind << " conflict";+ if (ranges && !ranges->ranges.empty()) {+ std::cout << " (";+ for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+ if (i > 0)+ std::cout << ", ";+ std::cout << "base ";+ print_range(ranges->ranges[i].base_start,+ ranges->ranges[i].base_end);+ std::cout << ", ours ";+ print_range(ranges->ranges[i].ours_start,+ ranges->ranges[i].ours_end);+ std::cout << ", theirs ";+ print_range(ranges->ranges[i].theirs_start,+ ranges->ranges[i].theirs_end);+ }+ std::cout << ")";+ }+ std::cout << "\n";+ }+ first = false;+ }+ if (first) {+ info_prefix();+ std::cout << "no conflicts\n";+ }+ return 0;+}++std::string shell_replace(std::string_view command, std::string_view key,+ const std::string &value) {+ std::string out;+ std::size_t i = 0;+ while (i < command.size()) {+ if (i + key.size() <= command.size() &&+ command.compare(i, key.size(), key) == 0) {+ out.push_back('\'');+ out += value;+ out.push_back('\'');+ i += key.size();+ } else {+ out.push_back(command[i]);+ ++i;+ }+ }+ return out;+}++bool run_tool(const fs::path &root, std::string_view command,+ std::string_view path) {+ const std::string base = path_to_bytes(root / path_from_bytes(path));+ std::string expanded(command);+ expanded = shell_replace(expanded, "$BASE", base + ".base");+ expanded = shell_replace(expanded, "$OURS", base + ".ours");+ expanded = shell_replace(expanded, "$THEIRS", base + ".theirs");+ expanded = shell_replace(expanded, "$OUTPUT", base);+ return std::system(expanded.c_str()) == 0;+}++void delete_sidecar(const fs::path &root, std::string_view path,+ std::string_view suffix) {+ std::string full(path);+ full += suffix;+ (void)remove_file(root / path_from_bytes(full));+}++void delete_sidecars(const fs::path &root, std::string_view path) {+ delete_sidecar(root, path, ".base");+ delete_sidecar(root, path, ".ours");+ delete_sidecar(root, path, ".theirs");+ for (int n = 2; n <= 64; ++n) {+ delete_sidecar(root, path, ".base" + std::to_string(n));+ delete_sidecar(root, path, ".theirs" + std::to_string(n));+ }+}++std::optional<ConflictValue> choose_value(const Conflict &conflict,+ std::string_view take) {+ if (take == "ours" && !conflict.adds.empty())+ return conflict.adds[0];+ if (take == "theirs" && conflict.adds.size() > 1)+ return conflict.adds[1];+ if (take == "base" && !conflict.removes.empty())+ return conflict.removes[0];+ return std::nullopt;+}++int resolve_command(std::string_view take, std::string_view tool,+ const std::vector<std::string> &paths) {+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ 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());+ 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 Id old_root = loaded->commit.root_tree;+ Id mut_root = old_root;+ bool resolved_any = false;+ std::vector<std::string> normalized_paths;++ const auto cwd = cwd_relative(*root);+ for (const auto &arg : paths) {+ auto norm = cwd ? pathspec_normalize(*root, *cwd, arg) : std::nullopt;+ if (!norm || norm->empty()) {+ error_prefix();+ std::cout << "invalid path\n";+ continue;+ }+ normalized_paths.push_back(*norm);+ auto flat = flatten_store(store, mut_root);+ const FlatEntry *entry = find_flat_entry(flat, *norm);+ if (!entry || entry->kind != KIND_CONFLICT) {+ error_prefix();+ std::cout << "not a conflicted path: " << *norm << "\n";+ continue;+ }+ auto body = store.read_body(entry->target, TYPE_CONFLICT);+ if (!body)+ continue;+ auto conflict = decode_conflict(bytes_of(*body));+ if (!conflict)+ continue;++ bool present = false;+ std::uint8_t new_kind = KIND_FILE;+ std::optional<Id> new_target;+ if (auto chosen = choose_value(*conflict, take)) {+ if (chosen->kind != 0) {+ present = true;+ new_kind = chosen->kind;+ new_target = chosen->target;+ }+ } else if (!tool.empty()) {+ if (run_tool(*root, tool, *norm)) {+ if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {+ new_target = add_blob(*tx, bytes_of(*data));+ present = true;+ new_kind = KIND_FILE;+ }+ }+ } else {+ if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {+ new_target = add_blob(*tx, bytes_of(*data));+ present = true;+ new_kind = KIND_FILE;+ }+ }+ if (present) {+ if (auto info = stat_path(*root / path_from_bytes(*norm))) {+ if (info->executable)+ new_kind = KIND_EXECUTABLE;+ }+ if (new_kind == KIND_FILE || new_kind == KIND_EXECUTABLE) {+ if (auto conflict_body =+ store.read_body(entry->target, TYPE_CONFLICT)) {+ resolution_record(*root, bytes_of(*conflict_body),+ *new_target);+ }+ }+ }+ auto replaced = tree_edit_replace(*tx, store, mut_root, *norm, present,+ new_kind, new_target.value_or(Id{}));+ if (replaced) {+ mut_root = *replaced;+ resolved_any = true;+ }+ }++ if (!resolved_any) {+ return 1;+ }++ Commit commit = loaded->commit;+ commit.root_tree = mut_root;+ commit.committer = identity_signature(*root);+ const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));+ 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("resolve");+ if (!status)+ return 1;+ Store refreshed = Store::open_all(*root);+ const int materialized =+ checkout_materialize_commit(*root, refreshed, old_root, mut_root);+ if (materialized != 0)+ return materialized;+ for (const auto &path : normalized_paths)+ delete_sidecars(*root, path);+ return 0;+}++} // namespace++// ---------------------------------------------------------------------------+// Argument parsing+// ---------------------------------------------------------------------------++int merge_run(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.empty() && arg.front() == '-') {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ revs.push_back(arg);+ }+ }+ return merge_command(revs);+}++int rebase_run(const std::vector<std::string> &args) {+ std::string source;+ std::string dest;+ 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 == "-s" || arg == "-source")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a revision\n";+ return 1;+ }+ source = args[++i];+ } else if (!end_flags && (arg == "-d" || arg == "-destination")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a revision\n";+ return 1;+ }+ dest = args[++i];+ } else if (!end_flags && !arg.empty() && arg.front() == '-') {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ error_prefix();+ std::cout << "unexpected argument: " << arg << "\n";+ return 1;+ }+ }+ if (source.empty() || dest.empty()) {+ error_prefix();+ std::cout << "rebase requires -s <rev> and -d <rev>\n";+ return 1;+ }+ return rebase_command(source, dest);+}++int xs_run(const std::vector<std::string> &args) {+ bool porcelain = 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 == "-porcelain" || arg == "-p")) {+ porcelain = true;+ } else if (!end_flags && !arg.empty() && arg.front() == '-') {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ error_prefix();+ std::cout << "unexpected argument: " << arg << "\n";+ return 1;+ }+ }+ return xs_command(porcelain);+}++int resolve_run(const std::vector<std::string> &args) {+ std::string take;+ std::string tool;+ bool list_only = false;+ std::vector<std::string> paths;+ 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 == "-list" || arg == "-l")) {+ list_only = true;+ } else if (!end_flags && (arg == "-take" || arg == "-t")) {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires ours, theirs, or base\n";+ return 1;+ }+ take = args[++i];+ } else if (!end_flags && arg == "-tool") {+ if (i + 1 >= args.size()) {+ error_prefix();+ std::cout << arg << " requires a command\n";+ return 1;+ }+ tool = args[++i];+ } else if (!end_flags && !arg.empty() && arg.front() == '-') {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ paths.push_back(arg);+ }+ }+ if (list_only)+ return xs_command(false);+ if (paths.empty()) {+ error_prefix();+ std::cout << "resolve requires at least one path\n";+ return 1;+ }+ return resolve_command(take, tool, paths);+}++} // namespace vn--- /dev/null+++ b/xveins/src/merge.h@@ -0,0 +1,27 @@+#pragma once++#include "store.h"++#include <optional>+#include <string>+#include <vector>++namespace vn {++// Detect renames between two trees. `tx` may be provided so trees and blobs that+// have only been added to the pending transaction are visible. Results are+// sorted by (parent_index, to_path).+std::vector<Rename> detect_renames(Store &store, Txn *tx,+ std::optional<Id> old_tree,+ std::optional<Id> new_tree, int similar_pct,+ std::uint64_t parent_index);++// Configured rename similarity threshold (0 disables detection).+int rename_similar_pct(const fs::path &root);++int merge_run(const std::vector<std::string> &args);+int rebase_run(const std::vector<std::string> &args);+int xs_run(const std::vector<std::string> &args);+int resolve_run(const std::vector<std::string> &args);++} // namespace vn--- /dev/null+++ b/xveins/src/net.cpp@@ -0,0 +1,753 @@+#include "net.h"++#include <algorithm>+#include <cerrno>+#include <climits>+#include <cstring>++#if defined(_WIN32)+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <winsock2.h>+#include <ws2tcpip.h>+#include <windows.h>+#include <io.h>+#endif++#include <openssl/err.h>+#include <openssl/ssl.h>+#include <openssl/x509.h>+#include <openssl/x509_vfy.h>++#if !defined(_WIN32)+#include <arpa/inet.h>+#include <fcntl.h>+#include <limits.h>+#include <netdb.h>+#include <netinet/in.h>+#include <signal.h>+#include <sys/socket.h>+#include <sys/types.h>+#include <sys/wait.h>+#include <unistd.h>+#if defined(__APPLE__)+#include <mach-o/dyld.h>+#endif+#endif++namespace vn::net {++namespace {++#if defined(_WIN32)+void ensure_winsock() {+ static const bool initialized = [] {+ WSADATA data{};+ return WSAStartup(MAKEWORD(2, 2), &data) == 0;+ }();+ (void)initialized;+}++std::wstring widen_utf8(std::string_view text) {+ if (text.empty())+ return {};+ const int len = MultiByteToWideChar(CP_UTF8, 0, text.data(),+ static_cast<int>(text.size()), nullptr, 0);+ std::wstring out(static_cast<std::size_t>(len), L'\0');+ MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()),+ out.data(), len);+ return out;+}++// Quote one argument for CreateProcessW's command line.+std::wstring quote_windows_arg(std::wstring_view arg) {+ if (!arg.empty() &&+ arg.find_first_of(L" \t\n\v\"") == std::wstring_view::npos)+ return std::wstring(arg);+ std::wstring out = L"\"";+ for (std::size_t i = 0; i < arg.size(); ++i) {+ std::size_t backslashes = 0;+ while (i < arg.size() && arg[i] == L'\\') {+ ++backslashes;+ ++i;+ }+ if (i == arg.size()) {+ out.append(backslashes * 2, L'\\');+ break;+ }+ if (arg[i] == L'"') {+ out.append(backslashes * 2 + 1, L'\\');+ out.push_back(L'"');+ } else {+ out.append(backslashes, L'\\');+ out.push_back(arg[i]);+ }+ }+ out.push_back(L'"');+ return out;+}++std::wstring build_windows_command_line(+ const std::vector<std::string> &argv) {+ std::wstring out;+ for (std::size_t i = 0; i < argv.size(); ++i) {+ if (i != 0)+ out.push_back(L' ');+ out += quote_windows_arg(widen_utf8(argv[i]));+ }+ return out;+}+#endif++std::string ssl_error_string() {+ unsigned long code = ERR_get_error();+ if (code == 0)+ return {};+ char buffer[256];+ ERR_error_string_n(code, buffer, sizeof(buffer));+ return std::string(buffer);+}++} // namespace++// ---------------------------------------------------------------------------+// Stream+// ---------------------------------------------------------------------------++Stream::Stream(Stream &&other) noexcept { *this = std::move(other); }++Stream &Stream::operator=(Stream &&other) noexcept {+ if (this == &other)+ return *this;+ close();+ kind_ = other.kind_;+ fd_in_ = other.fd_in_;+ fd_out_ = other.fd_out_;+ ssl_ = other.ssl_;+#if defined(_WIN32)+ process_ = other.process_;+ process_id_ = other.process_id_;+#else+ pid_ = other.pid_;+#endif+ open_ = other.open_;+ other.open_ = false;+ other.ssl_ = nullptr;+ other.fd_in_ = 0;+ other.fd_out_ = 0;+#if defined(_WIN32)+ other.process_ = nullptr;+ other.process_id_ = 0;+#else+ other.pid_ = 0;+#endif+ return *this;+}++Stream::~Stream() { close(); }++Stream Stream::stdio_stream() {+ Stream stream;+ stream.kind_ = Kind::Stdio;+#if defined(_WIN32)+ stream.fd_in_ =+ reinterpret_cast<Socket>(GetStdHandle(STD_INPUT_HANDLE));+ stream.fd_out_ =+ reinterpret_cast<Socket>(GetStdHandle(STD_OUTPUT_HANDLE));+#else+ stream.fd_in_ = 0;+ stream.fd_out_ = 1;+#endif+ stream.open_ = true;+ return stream;+}++Stream Stream::fd_stream(Socket fd) {+ Stream stream;+ stream.kind_ = Kind::Fd;+ stream.fd_in_ = fd;+ stream.fd_out_ = fd;+ stream.open_ = true;+ return stream;+}++Stream Stream::tls_stream(Socket fd, void *ssl) {+ Stream stream;+ stream.kind_ = Kind::Tls;+ stream.fd_in_ = fd;+ stream.fd_out_ = fd;+ stream.ssl_ = ssl;+ stream.open_ = true;+ return stream;+}++std::optional<Stream> Stream::spawn_argv(const std::vector<std::string> &argv) {+ return vn::net::spawn_argv(argv);+}++std::int64_t Stream::read(void *buffer, std::size_t count) {+ if (!open_ || count == 0)+ return count == 0 ? 0 : -1;+ if (kind_ == Kind::Tls) {+ const int n = SSL_read(static_cast<SSL *>(ssl_), buffer,+ static_cast<int>(std::min<std::size_t>(+ count, static_cast<std::size_t>(INT_MAX))));+ if (n > 0)+ return n;+ if (n == 0)+ return 0;+ return -1;+ }+#if defined(_WIN32)+ if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {+ DWORD got = 0;+ if (!ReadFile(reinterpret_cast<HANDLE>(fd_in_), buffer,+ static_cast<DWORD>(std::min<std::size_t>(+ count, static_cast<std::size_t>(MAXDWORD))),+ &got, nullptr))+ return -1;+ return static_cast<std::int64_t>(got);+ }+ const int n = recv(static_cast<SOCKET>(fd_in_),+ static_cast<char *>(buffer),+ static_cast<int>(std::min<std::size_t>(+ count, static_cast<std::size_t>(INT_MAX))),+ 0);+ return n;+#else+ const int fd = kind_ == Kind::Stdio ? 0 : static_cast<int>(fd_in_);+ ssize_t n = 0;+ do {+ n = ::read(fd, buffer, count);+ } while (n < 0 && errno == EINTR);+ return n;+#endif+}++bool Stream::write_all(Bytes data) {+ if (!open_)+ return false;+ std::size_t offset = 0;+ while (offset < data.size()) {+ const std::size_t remaining = data.size() - offset;+ std::int64_t written = -1;+ if (kind_ == Kind::Tls) {+ const int n = SSL_write(+ static_cast<SSL *>(ssl_), data.data() + offset,+ static_cast<int>(std::min<std::size_t>(remaining,+ static_cast<std::size_t>(+ INT_MAX))));+ written = n;+ }+#if defined(_WIN32)+ else if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {+ DWORD count = 0;+ if (!WriteFile(reinterpret_cast<HANDLE>(fd_out_), data.data() + offset,+ static_cast<DWORD>(std::min<std::size_t>(+ remaining, static_cast<std::size_t>(MAXDWORD))),+ &count, nullptr))+ return false;+ written = static_cast<std::int64_t>(count);+ } else {+ const int n = send(+ static_cast<SOCKET>(fd_out_),+ reinterpret_cast<const char *>(data.data() + offset),+ static_cast<int>(std::min<std::size_t>(+ remaining, static_cast<std::size_t>(INT_MAX))),+ 0);+ written = n;+ }+#else+ else {+ ssize_t n = 0;+ do {+ n = ::write(kind_ == Kind::Stdio ? 1 : static_cast<int>(fd_out_),+ data.data() + offset, remaining);+ } while (n < 0 && errno == EINTR);+ written = n;+ }+#endif+ if (written <= 0)+ return false;+ offset += static_cast<std::size_t>(written);+ }+ return true;+}++void Stream::close() {+ if (!open_)+ return;+ open_ = false;+ if (kind_ == Kind::Tls) {+ if (ssl_)+ tls_free(ssl_);+ ssl_ = nullptr;+#if defined(_WIN32)+ closesocket(static_cast<SOCKET>(fd_in_));+#else+ if (static_cast<int>(fd_in_) > 2)+ ::close(static_cast<int>(fd_in_));+#endif+ return;+ }+ if (kind_ == Kind::Proc) {+#if defined(_WIN32)+ if (fd_in_ != 0)+ CloseHandle(reinterpret_cast<HANDLE>(fd_in_));+ if (fd_out_ != 0)+ CloseHandle(reinterpret_cast<HANDLE>(fd_out_));+ if (process_) {+ WaitForSingleObject(reinterpret_cast<HANDLE>(process_), INFINITE);+ CloseHandle(reinterpret_cast<HANDLE>(process_));+ process_ = nullptr;+ }+#else+ if (static_cast<int>(fd_in_) > 2)+ ::close(static_cast<int>(fd_in_));+ if (static_cast<int>(fd_out_) > 2)+ ::close(static_cast<int>(fd_out_));+ if (pid_ > 0) {+ int status = 0;+ while (waitpid(pid_, &status, 0) < 0 && errno == EINTR) {+ }+ pid_ = 0;+ }+#endif+ return;+ }+ if (kind_ == Kind::Fd) {+#if defined(_WIN32)+ closesocket(static_cast<SOCKET>(fd_in_));+#else+ if (static_cast<int>(fd_in_) > 2)+ ::close(static_cast<int>(fd_in_));+#endif+ }+}++// ---------------------------------------------------------------------------+// Process spawning+// ---------------------------------------------------------------------------++#if defined(_WIN32)+std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {+ if (argv.empty())+ return std::nullopt;+ ensure_winsock();+ SECURITY_ATTRIBUTES attributes{};+ attributes.nLength = sizeof(attributes);+ attributes.bInheritHandle = TRUE;+ HANDLE child_stdin_read = nullptr;+ HANDLE child_stdin_write = nullptr;+ HANDLE child_stdout_read = nullptr;+ HANDLE child_stdout_write = nullptr;+ if (!CreatePipe(&child_stdin_read, &child_stdin_write, &attributes, 0) ||+ !CreatePipe(&child_stdout_read, &child_stdout_write, &attributes, 0)) {+ if (child_stdin_read)+ CloseHandle(child_stdin_read);+ if (child_stdin_write)+ CloseHandle(child_stdin_write);+ return std::nullopt;+ }+ SetHandleInformation(child_stdin_write, HANDLE_FLAG_INHERIT, 0);+ SetHandleInformation(child_stdout_read, HANDLE_FLAG_INHERIT, 0);+ STARTUPINFOW startup{};+ startup.cb = sizeof(startup);+ startup.dwFlags = STARTF_USESTDHANDLES;+ startup.hStdInput = child_stdin_read;+ startup.hStdOutput = child_stdout_write;+ startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);+ PROCESS_INFORMATION process{};+ std::wstring command_line = build_windows_command_line(argv);+ const BOOL started =+ CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0,+ nullptr, nullptr, &startup, &process);+ CloseHandle(child_stdin_read);+ CloseHandle(child_stdout_write);+ if (!started) {+ CloseHandle(child_stdin_write);+ CloseHandle(child_stdout_read);+ return std::nullopt;+ }+ CloseHandle(process.hThread);+ Stream stream;+ stream.kind_ = Stream::Kind::Proc;+ stream.fd_in_ = reinterpret_cast<Socket>(child_stdout_read);+ stream.fd_out_ = reinterpret_cast<Socket>(child_stdin_write);+ stream.process_ = process.hProcess;+ stream.process_id_ = process.dwProcessId;+ stream.open_ = true;+ return stream;+}+#else+std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {+ if (argv.empty())+ return std::nullopt;+ int in_pipe[2];+ int out_pipe[2];+ if (::pipe(in_pipe) != 0)+ return std::nullopt;+ if (::pipe(out_pipe) != 0) {+ ::close(in_pipe[0]);+ ::close(in_pipe[1]);+ return std::nullopt;+ }+ std::vector<char *> raw;+ raw.reserve(argv.size() + 1);+ for (const auto &item : argv)+ raw.push_back(const_cast<char *>(item.c_str()));+ raw.push_back(nullptr);+ const pid_t pid = ::fork();+ if (pid == 0) {+ (void)::dup2(in_pipe[0], 0);+ (void)::dup2(out_pipe[1], 1);+ ::close(in_pipe[0]);+ ::close(in_pipe[1]);+ ::close(out_pipe[0]);+ ::close(out_pipe[1]);+ ::execvp(raw[0], raw.data());+ ::_exit(127);+ }+ ::close(in_pipe[0]);+ ::close(out_pipe[1]);+ if (pid < 0) {+ ::close(in_pipe[1]);+ ::close(out_pipe[0]);+ return std::nullopt;+ }+ Stream stream;+ stream.kind_ = Stream::Kind::Proc;+ stream.fd_in_ = out_pipe[0];+ stream.fd_out_ = in_pipe[1];+ stream.pid_ = pid;+ stream.open_ = true;+ return stream;+}+#endif++// ---------------------------------------------------------------------------+// TCP+// ---------------------------------------------------------------------------++std::optional<Socket> tcp_connect(std::string_view host, int port) {+ if (host.empty())+ return std::nullopt;+#if defined(_WIN32)+ ensure_winsock();+#endif+ addrinfo hints{};+ hints.ai_family = AF_UNSPEC;+ hints.ai_socktype = SOCK_STREAM;+ const std::string service = std::to_string(port);+ const std::string host_text(host);+ addrinfo *results = nullptr;+ if (getaddrinfo(host_text.c_str(), service.c_str(), &hints, &results) != 0)+ return std::nullopt;+ Socket connected = INVALID_SOCKET_VALUE;+ for (addrinfo *it = results; it != nullptr; it = it->ai_next) {+#if defined(_WIN32)+ SOCKET socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);+ if (socket == INVALID_SOCKET)+ continue;+ if (::connect(socket, it->ai_addr, static_cast<int>(it->ai_addrlen)) == 0) {+ connected = static_cast<Socket>(socket);+ break;+ }+ closesocket(socket);+#else+ const int socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);+ if (socket < 0)+ continue;+ if (::connect(socket, it->ai_addr, it->ai_addrlen) == 0) {+ connected = socket;+ break;+ }+ ::close(socket);+#endif+ }+ freeaddrinfo(results);+ return connected == INVALID_SOCKET_VALUE+ ? std::nullopt+ : std::optional<Socket>(connected);+}++Socket tcp_listen(int port, int backlog) {+#if defined(_WIN32)+ ensure_winsock();+ SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+ if (listener == INVALID_SOCKET)+ return INVALID_SOCKET_VALUE;+ BOOL reuse = TRUE;+ setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,+ reinterpret_cast<const char *>(&reuse), sizeof(reuse));+ sockaddr_in address{};+ address.sin_family = AF_INET;+ address.sin_addr.s_addr = htonl(INADDR_ANY);+ address.sin_port = htons(static_cast<u_short>(port));+ if (::bind(listener, reinterpret_cast<sockaddr *>(&address),+ sizeof(address)) == SOCKET_ERROR ||+ ::listen(listener, backlog) == SOCKET_ERROR) {+ closesocket(listener);+ return INVALID_SOCKET_VALUE;+ }+ return static_cast<Socket>(listener);+#else+ const int listener = ::socket(AF_INET, SOCK_STREAM, 0);+ if (listener < 0)+ return INVALID_SOCKET_VALUE;+ int reuse = 1;+ (void)setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));+ sockaddr_in address{};+ address.sin_family = AF_INET;+ address.sin_addr.s_addr = htonl(INADDR_ANY);+ address.sin_port = htons(static_cast<std::uint16_t>(port));+ if (::bind(listener, reinterpret_cast<sockaddr *>(&address),+ sizeof(address)) != 0 ||+ ::listen(listener, backlog) != 0) {+ ::close(listener);+ return INVALID_SOCKET_VALUE;+ }+ return listener;+#endif+}++std::optional<Socket> tcp_accept(Socket listener) {+#if defined(_WIN32)+ const SOCKET accepted = ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);+ if (accepted == INVALID_SOCKET)+ return std::nullopt;+ return static_cast<Socket>(accepted);+#else+ const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);+ if (accepted < 0)+ return std::nullopt;+ return accepted;+#endif+}++void close_socket(Socket socket) {+ if (socket == INVALID_SOCKET_VALUE)+ return;+#if defined(_WIN32)+ closesocket(static_cast<SOCKET>(socket));+#else+ if (static_cast<int>(socket) > 2)+ ::close(static_cast<int>(socket));+#endif+}++// ---------------------------------------------------------------------------+// Process/platform helpers+// ---------------------------------------------------------------------------++void ignore_sigpipe() {+#if !defined(_WIN32)+ (void)::signal(SIGPIPE, SIG_IGN);+#endif+}++fs::path self_exe() {+#if defined(_WIN32)+ std::wstring buffer(32768, L'\0');+ const DWORD len =+ GetModuleFileNameW(nullptr, buffer.data(),+ static_cast<DWORD>(buffer.size()));+ if (len > 0) {+ buffer.resize(len);+ return fs::path(buffer);+ }+ return fs::path("vn.exe");+#elif defined(__APPLE__)+ std::uint32_t size = 0;+ _NSGetExecutablePath(nullptr, &size);+ std::string buffer(size, '\0');+ if (_NSGetExecutablePath(buffer.data(), &size) == 0) {+ char resolved[PATH_MAX];+ if (::realpath(buffer.c_str(), resolved))+ return fs::path(resolved);+ buffer.resize(std::strlen(buffer.c_str()));+ return fs::path(buffer);+ }+ return fs::path("vn");+#else+ std::string buffer(4096, '\0');+ const ssize_t len = ::readlink("/proc/self/exe", buffer.data(),+ buffer.size() - 1);+ if (len > 0) {+ buffer.resize(static_cast<std::size_t>(len));+ return fs::path(buffer);+ }+ return fs::path("vn");+#endif+}++std::string quote_shell(std::string_view word) {+ std::string out;+ out.reserve(word.size() + 2);+ out.push_back('\'');+ for (char c : word) {+ if (c == '\'')+ out += "'\\''";+ else+ out.push_back(c);+ }+ out.push_back('\'');+ return out;+}++std::string build_shell_command(const std::vector<std::string> &parts) {+ std::string out;+ for (const auto &part : parts) {+ if (!out.empty())+ out.push_back(' ');+ out += quote_shell(part);+ }+ return out;+}++// ---------------------------------------------------------------------------+// TLS+// ---------------------------------------------------------------------------++void *tls_server_ctx(std::string_view cert_path, std::string_view key_path) {+ SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());+ if (!ctx)+ return nullptr;+ if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1)+ goto fail;+ if (SSL_CTX_use_certificate_chain_file(ctx,+ std::string(cert_path).c_str()) != 1)+ goto fail;+ if (SSL_CTX_use_PrivateKey_file(ctx, std::string(key_path).c_str(),+ SSL_FILETYPE_PEM) != 1)+ goto fail;+ if (SSL_CTX_check_private_key(ctx) != 1)+ goto fail;+ return ctx;+fail:+ SSL_CTX_free(ctx);+ return nullptr;+}++void *tls_client_ctx(bool pinned) {+ SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());+ if (!ctx)+ return nullptr;+ if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {+ SSL_CTX_free(ctx);+ return nullptr;+ }+ if (pinned) {+ SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);+ return ctx;+ }+ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);+ if (SSL_CTX_set_default_verify_paths(ctx) != 1) {+ SSL_CTX_free(ctx);+ return nullptr;+ }+ return ctx;+}++void *tls_accept(void *ctx, Socket fd) {+ SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));+ if (!ssl)+ return nullptr;+ if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1 ||+ SSL_accept(ssl) != 1) {+ SSL_free(ssl);+ return nullptr;+ }+ return ssl;+}++void *tls_connect(void *ctx, Socket fd, std::string_view host) {+ SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));+ if (!ssl)+ return nullptr;+ if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1) {+ SSL_free(ssl);+ return nullptr;+ }+ if (!host.empty()) {+ const std::string text(host);+ SSL_set_tlsext_host_name(ssl, text.c_str());+ X509_VERIFY_PARAM *param = SSL_get0_param(ssl);+ X509_VERIFY_PARAM_set1_host(param, text.c_str(), 0);+ }+ if (SSL_connect(ssl) != 1) {+ SSL_free(ssl);+ return nullptr;+ }+ return ssl;+}++bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len) {+ static constexpr char label[] = "EXPORTER-veins-auth/1";+ return SSL_export_keying_material(static_cast<SSL *>(ssl), out, len, label,+ sizeof(label) - 1, nullptr, 0, 0) == 1;+}++bool tls_peer_sha256(void *ssl, std::uint8_t *out) {+ X509 *cert = SSL_get1_peer_certificate(static_cast<SSL *>(ssl));+ if (!cert)+ return false;+ unsigned int len = 0;+ const bool ok =+ X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;+ X509_free(cert);+ return ok;+}++void tls_free(void *ssl) {+ if (!ssl)+ return;+ SSL_shutdown(static_cast<SSL *>(ssl));+ SSL_free(static_cast<SSL *>(ssl));+}++void tls_ctx_free(void *ctx) {+ if (ctx)+ SSL_CTX_free(static_cast<SSL_CTX *>(ctx));+}++std::string tls_error() { return ssl_error_string(); }++std::string to_hex(Bytes data) {+ static constexpr char digits[] = "0123456789abcdef";+ std::string out;+ out.reserve(data.size() * 2);+ for (std::uint8_t byte : data) {+ out.push_back(digits[byte >> 4]);+ out.push_back(digits[byte & 15]);+ }+ return out;+}++bool hex_equal(std::string_view a, std::string_view b) {+ auto skip = [](std::string_view text, std::size_t &index) {+ while (index < text.size() && text[index] == ':')+ ++index;+ };+ std::size_t ai = 0;+ std::size_t bi = 0;+ for (;;) {+ skip(a, ai);+ skip(b, bi);+ if (ai >= a.size() || bi >= b.size())+ return ai >= a.size() && bi >= b.size();+ auto lower = [](char c) {+ return static_cast<char>((c >= 'A' && c <= 'Z') ? c + 32 : c);+ };+ if (lower(a[ai]) != lower(b[bi]))+ return false;+ ++ai;+ ++bi;+ }+}++} // namespace vn::net--- /dev/null+++ b/xveins/src/net.h@@ -0,0 +1,102 @@+#pragma once++#include "common.h"++#include <cstdint>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn::net {++#if defined(_WIN32)+using Socket = std::uintptr_t;+constexpr Socket INVALID_SOCKET_VALUE = static_cast<Socket>(~0ull);+#else+using Socket = int;+constexpr Socket INVALID_SOCKET_VALUE = -1;+#endif++// A reliable, ordered byte stream over stdio, a file descriptor/socket, TLS,+// or a child process.+class Stream {+public:+ enum class Kind : std::uint8_t { Stdio, Fd, Tls, Proc };++ Stream() = default;+ ~Stream();++ Stream(Stream &&other) noexcept;+ Stream &operator=(Stream &&other) noexcept;+ Stream(const Stream &) = delete;+ Stream &operator=(const Stream &) = delete;++ static Stream stdio_stream();+ static Stream fd_stream(Socket fd);+ static Stream tls_stream(Socket fd, void *ssl);+ static std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);++ friend std::optional<Stream>+ spawn_argv(const std::vector<std::string> &argv);++ [[nodiscard]] Kind kind() const { return kind_; }+ [[nodiscard]] void *ssl() const { return ssl_; }+ [[nodiscard]] Socket fd() const { return fd_in_; }+ [[nodiscard]] bool valid() const { return open_; }++ // Returns the number of bytes read, 0 at clean end of stream, -1 on error.+ std::int64_t read(void *buffer, std::size_t count);+ bool write_all(Bytes data);+ bool write_all(std::string_view text) {+ return write_all(Bytes(reinterpret_cast<const std::uint8_t *>(text.data()),+ text.size()));+ }+ void close();++private:+ Kind kind_ = Kind::Stdio;+ Socket fd_in_ = 0;+ Socket fd_out_ = 0;+ void *ssl_ = nullptr;+#if defined(_WIN32)+ void *process_ = nullptr;+ std::uint32_t process_id_ = 0;+#else+ int pid_ = 0;+#endif+ bool open_ = false;+};++// Run argv[0] with the given arguments. stdin/stdout are connected to the+// stream; stderr is inherited.+std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);++std::optional<Socket> tcp_connect(std::string_view host, int port);+Socket tcp_listen(int port, int backlog = 64);+std::optional<Socket> tcp_accept(Socket listener);+void close_socket(Socket socket);++void ignore_sigpipe();+fs::path self_exe();+std::string quote_shell(std::string_view word);+std::string build_shell_command(const std::vector<std::string> &parts);++// ---------------------------------------------------------------------------+// TLS 1.3+// ---------------------------------------------------------------------------++void *tls_server_ctx(std::string_view cert_path, std::string_view key_path);+void *tls_client_ctx(bool pinned);+void *tls_accept(void *ctx, Socket fd);+void *tls_connect(void *ctx, Socket fd, std::string_view host);+bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len);+bool tls_peer_sha256(void *ssl, std::uint8_t *out);+void tls_free(void *ssl);+void tls_ctx_free(void *ctx);+std::string tls_error();++std::string to_hex(Bytes data);+bool hex_equal(std::string_view a, std::string_view b);++} // namespace vn::net--- /dev/null+++ b/xveins/src/net_commands.cpp@@ -0,0 +1,1296 @@+#include "net_commands.h"++#include "auth.h"+#include "crypto.h"+#include "promisor.h"+#include "protocol.h"+#include "server.h"+#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <cstddef>+#include <cstring>+#include <iostream>+#include <optional>+#include <set>+#include <string>+#include <vector>++namespace vn {++namespace {++bool starts_with(std::string_view text, std::string_view prefix) {+ return text.size() >= prefix.size() && text.substr(0, prefix.size()) == prefix;+}++bool is_flag(std::string_view arg) { return !arg.empty() && arg.front() == '-'; }++std::string arg_at(const std::vector<std::string> &args, std::size_t index) {+ return index < args.size() ? args[index] : std::string();+}++std::string trim_text(std::string_view text) {+ std::size_t start = 0;+ std::size_t end = text.size();+ auto blank = [](char c) {+ return c == ' ' || c == '\t' || c == '\r' || c == '\n';+ };+ while (start < end && blank(text[start]))+ ++start;+ while (end > start && blank(text[end - 1]))+ --end;+ return std::string(text.substr(start, end - start));+}++std::string remote_key(std::string_view remote, std::string_view field) {+ std::string out = "remote.";+ out += remote;+ out.push_back('.');+ out += field;+ return out;+}++std::string last_segment(std::string_view path) {+ while (path.size() > 1 && path.back() == '/')+ path.remove_suffix(1);+ const auto slash = path.rfind('/');+ if (slash != std::string_view::npos && slash + 1 < path.size())+ return std::string(path.substr(slash + 1));+ if (!path.empty() && path != "/")+ return std::string(path);+ return "repo";+}++bool same_id(const Id &a, const Id &b) {+ return std::memcmp(a.data(), b.data(), ID_LEN) == 0;+}++void report_client_error(const proto::Client &client,+ std::string_view context) {+ error_prefix();+ if (!client.error().empty())+ std::cout << context << ": " << client.error() << "\n";+ else+ std::cout << context << "\n";+}++std::optional<Id> default_target(const std::vector<proto::RefInfo> &refs) {+ for (const auto &ref : refs) {+ if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))+ return ref.target;+ }+ for (const auto &ref : refs) {+ if (ref.kind == 0)+ return ref.target;+ }+ return std::nullopt;+}++std::vector<Id> selected_commits(const std::vector<proto::RefInfo> &refs,+ std::string_view policy) {+ std::vector<Id> out;+ if (policy == "none")+ return out;+ if (policy == "head") {+ if (auto target = default_target(refs))+ out.push_back(*target);+ return out;+ }+ for (const auto &ref : refs)+ out.push_back(ref.target);+ return out;+}++bool set_bookmark(View &view, std::string_view name, const Id &target) {+ if (auto index = find_bookmark(view, name)) {+ view.bookmarks[*index].targets.adds = {target};+ view.bookmarks[*index].targets.removes.clear();+ return true;+ }+ Bookmark bookmark;+ bookmark.name = std::string(name);+ bookmark.targets.adds = {target};+ view.bookmarks.push_back(std::move(bookmark));+ return true;+}++bool set_tag(View &view, std::string_view name, const Id &target) {+ if (auto index = find_tag(view, name)) {+ view.tags[*index].target = target;+ return true;+ }+ view.tags.push_back(TagRef{std::string(name), target});+ return true;+}++bool set_remote_ref(View &view, std::string_view remote, std::string_view name,+ const Id &target) {+ for (auto &ref : view.remote_refs) {+ if (ref.remote == remote && ref.name == name) {+ ref.target = target;+ return true;+ }+ }+ view.remote_refs.push_back(+ RemoteRef{std::string(remote), std::string(name), target});+ return true;+}++bool apply_refs(const fs::path &root, const std::vector<proto::RefInfo> &refs,+ std::string_view remote, bool clone) {+ Store store = Store::open_all(root);+ auto tx = Txn::begin(root, store);+ if (!tx)+ return false;+ for (const auto &ref : refs) {+ if (ref.kind == 1) {+ set_tag(tx->view(), ref.name, ref.target);+ } else if (clone) {+ set_bookmark(tx->view(), ref.name, ref.target);+ } else {+ set_remote_ref(tx->view(), remote, ref.name, ref.target);+ if (!find_bookmark(tx->view(), ref.name))+ set_bookmark(tx->view(), ref.name, ref.target);+ }+ }+ rebuild_heads(tx->view());+ if (clone) {+ if (auto target = default_target(refs))+ set_workspace(tx->view(), *target);+ }+ return tx->finish("clone").has_value();+}++struct Walker {+ Walker(Store &store, bool want_objects)+ : store(store), want_objects(want_objects) {}++ Store &store;+ bool want_objects = false;+ std::set<Id> blobs;+ std::set<Id> conflicts;+ std::set<Id> chunks;+ std::set<Id> objects;+ std::vector<Id> chunk_out;+ std::vector<Id> object_out;++ void add_object(const Id &id) {+ if (want_objects && objects.insert(id).second)+ object_out.push_back(id);+ }++ void walk_blob(const Id &id) {+ if (!blobs.insert(id).second)+ return;+ add_object(id);+ auto body = store.read_body(id, TYPE_BLOB);+ if (!body)+ return;+ auto blob = decode_blob(bytes_of(*body));+ if (!blob)+ return;+ if (blob->form == BlobForm::Leaf) {+ for (const auto &entry : blob->entries) {+ if (chunks.insert(entry.id).second)+ chunk_out.push_back(entry.id);+ add_object(entry.id);+ }+ } else if (blob->form == BlobForm::Interior) {+ for (const auto &entry : blob->entries)+ walk_blob(entry.id);+ }+ }++ void walk_conflict(const Id &id) {+ if (!conflicts.insert(id).second)+ return;+ add_object(id);+ auto body = store.read_body(id, TYPE_CONFLICT);+ if (!body)+ return;+ auto conflict = decode_conflict(bytes_of(*body));+ if (!conflict)+ return;+ for (const auto &value : conflict->adds) {+ if (value.target)+ walk_value(value.kind, *value.target);+ }+ for (const auto &value : conflict->removes) {+ if (value.target)+ walk_value(value.kind, *value.target);+ }+ }++ void walk_value(std::uint8_t kind, const Id &id) {+ if (kind == KIND_SUBTREE)+ walk_tree(id);+ else if (kind == KIND_CONFLICT)+ walk_conflict(id);+ else+ walk_blob(id);+ }++ void walk_tree(const Id &id) {+ add_object(id);+ auto body = store.read_body(id, TYPE_TREE);+ if (!body)+ return;+ auto tree = decode_tree(bytes_of(*body));+ if (!tree)+ return;+ for (const auto &entry : tree->entries) {+ if (entry.kind == KIND_SUBTREE)+ walk_tree(entry.target);+ else if (entry.kind == KIND_CONFLICT)+ walk_conflict(entry.target);+ else if (entry.kind != KIND_SUBMODULE)+ walk_blob(entry.target);+ }+ }+};++std::vector<Id> chunks_for_commits(Store &store,+ const std::vector<Id> &commits) {+ Walker walker{store, false};+ for (const auto &id : commits) {+ auto loaded = load_commit(store, id);+ if (loaded)+ walker.walk_tree(loaded->commit.root_tree);+ }+ return std::move(walker.chunk_out);+}++std::vector<Id> objects_for_commits(Store &store,+ const std::vector<Id> &commits) {+ Walker walker{store, true};+ for (const auto &id : commits) {+ walker.add_object(id);+ auto loaded = load_commit(store, id);+ if (loaded)+ walker.walk_tree(loaded->commit.root_tree);+ }+ return std::move(walker.object_out);+}++bool send_chunks(proto::Client &client, const fs::path &root,+ const std::vector<Id> &chunks) {+ constexpr std::size_t BATCH = 4096;+ for (std::size_t offset = 0; offset < chunks.size(); offset += BATCH) {+ const std::size_t end = std::min(offset + BATCH, chunks.size());+ std::vector<Id> batch(chunks.begin() + static_cast<std::ptrdiff_t>(offset),+ chunks.begin() + static_cast<std::ptrdiff_t>(end));+ if (!client.get_chunks(root, batch))+ return false;+ }+ return true;+}++bool send_missing_chunks(proto::Client &client, const fs::path &root,+ const std::vector<Id> &chunks) {+ Store store = Store::open_all(root);+ std::vector<Id> missing;+ for (const auto &id : chunks) {+ if (!store.find(id))+ missing.push_back(id);+ }+ return send_chunks(client, root, missing);+}++std::optional<std::string> config_value(const fs::path &root,+ std::string_view key) {+ return repo_config_value(root, key);+}++std::vector<std::string> list_remote_names(const fs::path &root) {+ std::vector<std::string> out;+ auto data = read_file_opt(config_path(root));+ if (!data)+ return out;+ const std::string_view text(reinterpret_cast<const char *>(data->data()),+ data->size());+ std::size_t start = 0;+ for (std::size_t i = 0; i <= text.size(); ++i) {+ if (i != text.size() && text[i] != '\n')+ continue;+ const std::string_view line = text.substr(start, i - start);+ if (starts_with(line, "remote.")) {+ const auto dot = line.find(".url", 7);+ if (dot != std::string_view::npos && dot > 7)+ out.emplace_back(line.substr(7, dot - 7));+ }+ start = i + 1;+ }+ return out;+}++std::string role_text(std::uint8_t role) {+ if (role == 2)+ return "write";+ if (role == 1)+ return "read";+ return "anonymous";+}++void print_key(const auth::Key &key) {+ std::cout << "name: " << key.name << "\n";+ std::cout << "public key: " << format_public_key(key.public_key) << "\n";+ std::cout << "fingerprint: " << key.fingerprint << "\n";+}++void auth_usage() {+ std::cout << "usage: vn auth <use|list|remove> ...\n";+ std::cout << " vn auth use <key> [<host|url>] set the default or host key\n";+ std::cout << " vn auth list show stored key mappings\n";+ std::cout << " vn auth remove [<host|url>] remove a mapping (default if "+ "omitted)\n";+}++std::optional<PublicKey> read_public_key(std::string_view arg) {+ if (starts_with(arg, "ed25519:"))+ return parse_public_key(arg);+ auto data = read_file_opt(path_from_bytes(arg));+ if (!data)+ return std::nullopt;+ const std::string text = trim_text(+ std::string_view(reinterpret_cast<const char *>(data->data()),+ data->size()));+ return parse_public_key(text);+}++} // namespace++// ---------------------------------------------------------------------------+// remote+// ---------------------------------------------------------------------------++int remote_run(const std::vector<std::string> &args) {+ const std::string sub = arg_at(args, 2);+ if (sub.empty()) {+ error_prefix();+ std::cout << "expected a remote subcommand (add, set-url, list, remove)\n";+ return 1;+ }+ auto repo = discover_repo(".");+ if (!repo) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const fs::path root = *repo;++ if (sub == "add" || sub == "set-url") {+ const bool replace = sub == "set-url";+ std::string name;+ std::string url;+ std::optional<std::string> key;+ std::optional<std::string> pin;+ for (std::size_t i = 3; i < args.size(); ++i) {+ const std::string &arg = args[i];+ if (starts_with(arg, "-key:")) {+ key = arg.substr(5);+ } else if (starts_with(arg, "-tls-pin:")) {+ pin = arg.substr(9);+ } else if (is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (name.empty()) {+ name = arg;+ } else if (url.empty()) {+ url = arg;+ } else {+ error_prefix();+ std::cout << "too many arguments\n";+ return 1;+ }+ }+ if (name.empty() || url.empty()) {+ error_prefix();+ std::cout << (replace ? "remote set-url requires a name and URL\n"+ : "remote add requires a name and URL\n");+ return 1;+ }+ const std::string url_key = remote_key(name, "url");+ const auto existing = config_value(root, url_key);+ if (existing && !replace) {+ error_prefix();+ std::cout << "remote already exists: " << name << "\n";+ return 1;+ }+ if (!existing && replace) {+ error_prefix();+ std::cout << "unknown remote: " << name << "\n";+ return 1;+ }+ if (!repo_config_set(root, url_key, url)) {+ error_prefix();+ std::cout << "cannot write repository config\n";+ return 1;+ }+ if (key) {+ const std::string field = remote_key(name, "key");+ const bool ok = key->empty() ? repo_config_remove(root, field)+ : repo_config_set(root, field, *key);+ if (!ok) {+ error_prefix();+ std::cout << "cannot write repository config\n";+ return 1;+ }+ }+ if (pin) {+ const std::string field = remote_key(name, "tls-pin");+ const bool ok = pin->empty() ? repo_config_remove(root, field)+ : repo_config_set(root, field, *pin);+ if (!ok) {+ error_prefix();+ std::cout << "cannot write repository config\n";+ return 1;+ }+ }+ return 0;+ }++ if (sub == "list" || sub == "ls") {+ for (const auto &name : list_remote_names(root)) {+ const auto url = config_value(root, remote_key(name, "url"));+ std::cout << name << "\t" << (url ? *url : std::string()) << "\n";+ }+ return 0;+ }++ if (sub == "remove" || sub == "rm") {+ const std::string name = arg_at(args, 3);+ if (name.empty()) {+ error_prefix();+ std::cout << "remote remove requires a name\n";+ return 1;+ }+ if (!config_value(root, remote_key(name, "url"))) {+ error_prefix();+ std::cout << "unknown remote: " << name << "\n";+ return 1;+ }+ (void)repo_config_remove(root, remote_key(name, "url"));+ (void)repo_config_remove(root, remote_key(name, "key"));+ (void)repo_config_remove(root, remote_key(name, "tls-pin"));+ return 0;+ }++ error_prefix();+ std::cout << "unknown remote subcommand: " << sub << "\n";+ return 1;+}++// ---------------------------------------------------------------------------+// clone+// ---------------------------------------------------------------------------++int clone_run(const std::vector<std::string> &args) {+ std::string url;+ std::string path;+ std::string policy = "head";+ std::string key_name;+ bool key_explicit = false;+ std::string tls_pin;+ for (std::size_t i = 2; i < args.size(); ++i) {+ const std::string &arg = args[i];+ if (starts_with(arg, "-blobs:")) {+ policy = arg.substr(7);+ } else if (starts_with(arg, "-key:")) {+ key_name = arg.substr(5);+ if (starts_with(key_name, "ed25519:")) {+ error_prefix();+ std::cout << "-key: expects a local key name, not a public key\n";+ return 1;+ }+ key_explicit = true;+ } else if (starts_with(arg, "-pin:")) {+ tls_pin = arg.substr(5);+ } else if (is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (url.empty()) {+ url = arg;+ } else {+ path = arg;+ }+ }+ if (url.empty()) {+ error_prefix();+ std::cout << "clone requires a URL\n";+ return 1;+ }+ const auto parsed = proto::parse_url(url);+ if (!parsed) {+ error_prefix();+ std::cout << "unsupported URL\n";+ return 1;+ }+ if (path.empty())+ path = last_segment(parsed->path);+ auto repo = init_repo(path_from_bytes(path));+ if (!repo) {+ error_prefix();+ std::cout << "cannot create repository\n";+ return 1;+ }+ const fs::path root = *repo;++ if (key_name.empty()) {+ if (auto fallback = auth::key_for_url(url))+ key_name = *fallback;+ }+ (void)repo_config_set(root, remote_key("origin", "url"), url);+ if (key_explicit && !key_name.empty())+ (void)repo_config_set(root, remote_key("origin", "key"), key_name);+ if (!tls_pin.empty())+ (void)repo_config_set(root, remote_key("origin", "tls-pin"), tls_pin);++ const std::string repo_name = proto::url_repo_name(url);+ auto client = proto::Client::connect(url, key_name, repo_name, tls_pin);+ if (!client) {+ error_prefix();+ std::cout << "cannot connect or authenticate\n";+ return 1;+ }+ std::vector<proto::RefInfo> refs;+ if (!client->list_refs(refs)) {+ report_client_error(*client, "cannot list remote refs");+ return 1;+ }+ std::vector<Id> wants;+ for (const auto &ref : refs)+ wants.push_back(ref.target);+ if (wants.empty()) {+ info_prefix();+ std::cout << "cloned empty repository into " << path << "\n";+ return 0;+ }+ if (!client->negotiate(wants, {})) {+ report_client_error(*client, "negotiation failed");+ return 1;+ }+ if (!client->fetch_skeleton(root, wants)) {+ report_client_error(*client, "fetch failed");+ return 1;+ }+ {+ Store store = Store::open_all(root);+ const auto commits = selected_commits(refs, policy);+ const auto chunks = chunks_for_commits(store, commits);+ if (!send_chunks(*client, root, chunks)) {+ report_client_error(*client, "chunk fetch failed");+ return 1;+ }+ }+ if (!apply_refs(root, refs, "origin", true)) {+ error_prefix();+ std::cout << "cannot write repository state\n";+ return 1;+ }+ (void)repo_config_set(root, "promisor", "origin");+ install_promisor_fetcher();+ if (policy == "none") {+ info_prefix();+ std::cout << "cloned metadata only; blobs are promised\n";+ }++ int checkout_status = 1;+ {+ Store store = Store::open_all(root);+ auto view = current_view(root, store);+ if (view) {+ if (auto wc = working_copy_id(*view)) {+ auto body = store.read_body(*wc, TYPE_COMMIT);+ if (body) {+ auto commit = decode_commit(bytes_of(*body));+ if (commit) {+ checkout_status = checkout_materialize_commit(+ root, store, std::nullopt, commit->root_tree);+ }+ }+ }+ }+ }+ if (checkout_status != 0) {+ info_prefix();+ std::cout << "cloned; checkout reported " << checkout_status << "\n";+ }+ info_prefix();+ std::cout << "cloned into " << path << "\n";+ return 0;+}++// ---------------------------------------------------------------------------+// fetch+// ---------------------------------------------------------------------------++int fetch_run(const std::vector<std::string> &args) {+ std::string remote_name = "origin";+ std::string path = ".";+ std::string explicit_key;+ std::string explicit_pin;+ bool have_remote = false;+ for (std::size_t i = 2; i < args.size(); ++i) {+ const std::string &arg = args[i];+ if (starts_with(arg, "-key:")) {+ explicit_key = arg.substr(5);+ if (starts_with(explicit_key, "ed25519:")) {+ error_prefix();+ std::cout << "-key: expects a local key name, not a public key\n";+ return 1;+ }+ } else if (starts_with(arg, "-pin:")) {+ explicit_pin = arg.substr(5);+ } else if (is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (!have_remote) {+ remote_name = arg;+ have_remote = true;+ } else {+ path = arg;+ }+ }+ auto repo = discover_repo(path_from_bytes(path));+ if (!repo) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const fs::path root = *repo;+ auto url = config_value(root, remote_key(remote_name, "url"));+ if (!url) {+ error_prefix();+ std::cout << "unknown remote\n";+ return 1;+ }+ std::string key;+ if (!explicit_key.empty()) {+ key = explicit_key;+ } else {+ auto configured = config_value(root, remote_key(remote_name, "key"));+ if (configured && auth::local_key_exists(*configured))+ key = *configured;+ if (key.empty()) {+ if (auto fallback = auth::key_for_url(*url))+ key = *fallback;+ }+ }+ std::string pin;+ if (!explicit_pin.empty()) {+ pin = explicit_pin;+ } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {+ pin = *configured;+ }+ const std::string repo_name = proto::url_repo_name(*url);+ auto client = proto::Client::connect(*url, key, repo_name, pin);+ if (!client) {+ error_prefix();+ std::cout << "cannot connect or authenticate\n";+ return 1;+ }+ std::vector<proto::RefInfo> refs;+ if (!client->list_refs(refs)) {+ report_client_error(*client, "cannot list remote refs");+ return 1;+ }+ std::vector<Id> haves = read_heads(root);+ std::vector<Id> wants;+ for (const auto &ref : refs)+ wants.push_back(ref.target);+ if (wants.empty()) {+ info_prefix();+ std::cout << "no refs to fetch\n";+ return 0;+ }+ if (!client->negotiate(wants, haves)) {+ report_client_error(*client, "negotiation failed");+ return 1;+ }+ if (!client->fetch_skeleton(root, wants)) {+ report_client_error(*client, "fetch failed");+ return 1;+ }+ {+ Store store = Store::open_all(root);+ const auto chunks = chunks_for_commits(store, wants);+ if (!send_missing_chunks(*client, root, chunks)) {+ report_client_error(*client, "chunk fetch failed");+ return 1;+ }+ }+ if (!apply_refs(root, refs, remote_name, false)) {+ error_prefix();+ std::cout << "cannot write repository state\n";+ return 1;+ }+ info_prefix();+ std::cout << "fetched from " << remote_name << "\n";+ return 0;+}++// ---------------------------------------------------------------------------+// push+// ---------------------------------------------------------------------------++int push_run(const std::vector<std::string> &args) {+ std::string remote_name = "origin";+ std::string bookmark;+ std::string explicit_key;+ std::string explicit_pin;+ std::string path = ".";+ bool have_remote = false;+ for (std::size_t i = 2; i < args.size(); ++i) {+ const std::string &arg = args[i];+ if (starts_with(arg, "-key:")) {+ explicit_key = arg.substr(5);+ if (starts_with(explicit_key, "ed25519:")) {+ error_prefix();+ std::cout << "-key: expects a local key name, not a public key\n";+ return 1;+ }+ } else if (starts_with(arg, "-pin:")) {+ explicit_pin = arg.substr(5);+ } else if (is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else if (!have_remote) {+ remote_name = arg;+ have_remote = true;+ } else if (bookmark.empty()) {+ bookmark = arg;+ } else {+ path = arg;+ }+ }+ if (bookmark.empty()) {+ error_prefix();+ std::cout << "push requires a bookmark name\n";+ return 1;+ }+ auto repo = discover_repo(path_from_bytes(path));+ if (!repo) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const fs::path root = *repo;+ auto url = config_value(root, remote_key(remote_name, "url"));+ if (!url) {+ error_prefix();+ std::cout << "unknown remote\n";+ return 1;+ }+ std::string key;+ if (!explicit_key.empty()) {+ key = explicit_key;+ } else {+ auto configured = config_value(root, remote_key(remote_name, "key"));+ if (configured && auth::local_key_exists(*configured))+ key = *configured;+ if (key.empty()) {+ if (auto fallback = auth::key_for_url(*url))+ key = *fallback;+ }+ }+ std::string pin;+ if (!explicit_pin.empty()) {+ pin = explicit_pin;+ } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {+ pin = *configured;+ }++ std::optional<Id> target;+ std::vector<Id> commits;+ std::vector<Id> objects;+ {+ Store store = Store::open_all(root);+ auto view = current_view(root, store);+ View empty;+ const View ¤t = view ? *view : empty;+ target = resolve_revision(store, current, bookmark);+ if (!target) {+ error_prefix();+ std::cout << "unknown bookmark: " << bookmark << "\n";+ return 1;+ }+ const std::array<Id, 1> roots{*target};+ commits = collect_commits(store, roots);+ objects = objects_for_commits(store, commits);+ }+ const std::string repo_name = proto::url_repo_name(*url);+ auto client = proto::Client::connect(*url, key, repo_name, pin);+ if (!client) {+ error_prefix();+ std::cout << "cannot connect or authenticate\n";+ return 1;+ }+ std::vector<proto::RefInfo> refs;+ if (!client->list_refs(refs)) {+ report_client_error(*client, "cannot list remote refs");+ return 1;+ }+ std::optional<Id> old;+ for (const auto &ref : refs) {+ if (ref.name == bookmark)+ old = ref.target;+ }+ if (old && same_id(*old, *target)) {+ info_prefix();+ std::cout << "nothing to push, everything is up to date\n";+ return 0;+ }+ if (!client->push_objects(root, objects)) {+ report_client_error(*client, "push failed");+ return 1;+ }+ std::vector<proto::UpdateRef> updates;+ updates.push_back(proto::UpdateRef{bookmark, old, target});+ if (!client->update_refs(updates)) {+ report_client_error(*client, "ref update rejected");+ return 1;+ }+ info_prefix();+ std::cout << "pushed " << bookmark << " to " << remote_name << "\n";+ return 0;+}++// ---------------------------------------------------------------------------+// serve+// ---------------------------------------------------------------------------++int serve_run(const std::vector<std::string> &args) {+ bool stdio_mode = false;+ std::string listen;+ std::string root = ".";+ std::string cert;+ std::string key;+ std::string repo_path = ".";+ for (std::size_t i = 2; i < args.size(); ++i) {+ const std::string &arg = args[i];+ if (arg == "-stdio") {+ stdio_mode = true;+ if (i + 1 < args.size())+ repo_path = args[++i];+ } else if (arg == "-listen") {+ if (i + 1 < args.size())+ listen = args[++i];+ } else if (arg == "-root") {+ if (i + 1 < args.size())+ root = args[++i];+ } else if (arg == "-tls-cert") {+ if (i + 1 < args.size())+ cert = args[++i];+ } else if (arg == "-tls-key") {+ if (i + 1 < args.size())+ key = args[++i];+ } else {+ error_prefix();+ std::cout << "unknown serve option: " << arg << "\n";+ return 1;+ }+ }+ if (stdio_mode) {+ auto repo = discover_repo(path_from_bytes(repo_path));+ if (!repo) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ return server::serve_stdio(*repo);+ }+ if (listen.empty()) {+ error_prefix();+ std::cout << "serve requires -stdio or -listen\n";+ return 1;+ }+ if (cert.empty() || key.empty()) {+ error_prefix();+ std::cout << "TLS requires -tls-cert and -tls-key\n";+ return 1;+ }+ return server::serve_listen(listen, path_from_bytes(root), cert, key);+}++// ---------------------------------------------------------------------------+// key+// ---------------------------------------------------------------------------++int key_run(const std::vector<std::string> &args) {+ const std::string sub = arg_at(args, 2);+ if (sub.empty()) {+ error_prefix();+ std::cout+ << "expected key subcommand (generate, list, show, import)\n";+ return 1;+ }+ if (sub == "generate") {+ const std::string name = arg_at(args, 3);+ if (name.empty()) {+ error_prefix();+ std::cout << "key generate requires a name\n";+ return 1;+ }+ auto key = auth::generate_key(name);+ if (!key) {+ error_prefix();+ std::cout << "cannot create key\n";+ return 1;+ }+ print_key(*key);+ return 0;+ }+ if (sub == "list") {+ for (const auto &name : auth::list_key_names()) {+ if (auto key = auth::load_key(name))+ print_key(*key);+ }+ return 0;+ }+ if (sub == "show") {+ const std::string name = arg_at(args, 3);+ if (name.empty()) {+ error_prefix();+ std::cout << "key show requires a name\n";+ return 1;+ }+ auto key = auth::load_key(name);+ if (!key) {+ error_prefix();+ std::cout << "key not found or has unsafe permissions\n";+ return 1;+ }+ print_key(*key);+ return 0;+ }+ if (sub == "import") {+ error_prefix();+ std::cout << "OpenSSH key import is not supported\n";+ return 1;+ }+ error_prefix();+ std::cout << "unknown key subcommand: " << sub << "\n";+ return 1;+}++// ---------------------------------------------------------------------------+// auth+// ---------------------------------------------------------------------------++int auth_run(const std::vector<std::string> &args) {+ const std::string sub = arg_at(args, 2);+ if (sub.empty()) {+ auth_usage();+ return 1;+ }+ if (sub == "use") {+ const std::string name = arg_at(args, 3);+ if (name.empty()) {+ auth_usage();+ return 1;+ }+ if (!auth::load_key(name)) {+ error_prefix();+ std::cout << "key not found or has unsafe permissions: " << name+ << "\n";+ return 1;+ }+ const std::string target = auth::normalize_target(arg_at(args, 4));+ if (!auth::set_key(target, name)) {+ error_prefix();+ std::cout << "cannot write auth configuration\n";+ return 1;+ }+ if (target == "default")+ std::cout << "default key set to " << name << "\n";+ else+ std::cout << "key for " << target << " set to " << name << "\n";+ return 0;+ }+ if (sub == "list") {+ const auto lines = auth::list_credential_lines();+ if (lines.empty())+ std::cout << "no stored credentials\n";+ for (const auto &line : lines)+ std::cout << line;+ return 0;+ }+ if (sub == "remove") {+ const std::string target = auth::normalize_target(arg_at(args, 3));+ if (auth::remove_key(target)) {+ std::cout << "removed " << target << "\n";+ return 0;+ }+ error_prefix();+ std::cout << "no credential for " << target << "\n";+ return 1;+ }+ error_prefix();+ std::cout << "unknown auth subcommand: " << sub << "\n";+ auth_usage();+ return 1;+}++// ---------------------------------------------------------------------------+// access+// ---------------------------------------------------------------------------++int access_run(const std::vector<std::string> &args) {+ const std::string sub = arg_at(args, 2);+ if (sub.empty()) {+ error_prefix();+ std::cout << "expected access subcommand\n";+ return 1;+ }+ auto repo = discover_repo(".");+ if (!repo) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const fs::path root = *repo;+ if (sub == "add") {+ std::string role;+ std::string key_arg;+ std::string name;+ for (std::size_t i = 3; i < args.size(); ++i) {+ const std::string &arg = args[i];+ if (arg == "-role" && i + 1 < args.size()) {+ role = args[++i];+ } else if (arg == "-key" && i + 1 < args.size()) {+ key_arg = args[++i];+ } else if (arg == "-name" && i + 1 < args.size()) {+ name = args[++i];+ } else {+ error_prefix();+ std::cout << "unknown access add option: " << arg << "\n";+ return 1;+ }+ }+ if (role.empty() || key_arg.empty()) {+ error_prefix();+ std::cout << "access add requires -role and -key\n";+ return 1;+ }+ std::uint8_t role_code = auth::ROLE_READ;+ if (role == "write") {+ role_code = auth::ROLE_WRITE;+ } else if (role != "read") {+ error_prefix();+ std::cout << "role must be read or write\n";+ return 1;+ }+ auto public_key = read_public_key(key_arg);+ if (!public_key) {+ error_prefix();+ std::cout << "invalid public key\n";+ return 1;+ }+ if (!auth::add_access(root, role_code, *public_key, name)) {+ error_prefix();+ std::cout << "cannot add key\n";+ return 1;+ }+ info_prefix();+ std::cout << "access granted\n";+ return 0;+ }+ if (sub == "list") {+ const auth::Access access = auth::load_access(root);+ if (!access.valid) {+ error_prefix();+ std::cout << "invalid access file at line " << access.error_line << "\n";+ return 1;+ }+ std::cout << "anonymous: " << (access.anonymous_read ? "read" : "off")+ << "\n";+ for (const auto &entry : access.entries) {+ std::cout << (entry.role == auth::ROLE_WRITE ? "write" : "read") << " "+ << key_fingerprint(entry.public_key) << " " << entry.name+ << "\n";+ }+ return 0;+ }+ if (sub == "remove") {+ const std::string arg = arg_at(args, 3);+ if (arg.empty()) {+ error_prefix();+ std::cout << "access remove requires a fingerprint or name\n";+ return 1;+ }+ const bool is_fingerprint = arg.size() == 26;+ const std::string fingerprint = is_fingerprint ? arg : std::string();+ const std::string name = is_fingerprint ? std::string() : arg;+ if (!auth::remove_access(root, fingerprint, name)) {+ error_prefix();+ std::cout << "key not found or cannot write access file\n";+ return 1;+ }+ info_prefix();+ std::cout << "access removed\n";+ return 0;+ }+ if (sub == "anonymous") {+ const bool on = arg_at(args, 3) == "on";+ if (!auth::set_anonymous(root, on)) {+ error_prefix();+ std::cout << "cannot update access file\n";+ return 1;+ }+ return 0;+ }+ error_prefix();+ std::cout << "unknown access subcommand: " << sub << "\n";+ return 1;+}++// ---------------------------------------------------------------------------+// whoami+// ---------------------------------------------------------------------------++int whoami_run(const std::vector<std::string> &args) {+ std::string remote = "origin";+ std::string url;+ std::string key;+ std::string repo_name;+ std::string pin;+ const std::string arg = arg_at(args, 2);+ if (!arg.empty()) {+ if (starts_with(arg, "file://") || starts_with(arg, "ssh://") ||+ starts_with(arg, "veins://")) {+ url = arg;+ repo_name = proto::url_repo_name(url);+ } else {+ remote = arg;+ }+ }+ if (url.empty()) {+ auto repo = discover_repo(".");+ if (!repo) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const fs::path root = *repo;+ auto configured = config_value(root, remote_key(remote, "url"));+ if (!configured) {+ error_prefix();+ std::cout << "unknown remote\n";+ return 1;+ }+ url = *configured;+ if (auto k = config_value(root, remote_key(remote, "key"))) {+ if (auth::local_key_exists(*k))+ key = *k;+ }+ if (auto p = config_value(root, remote_key(remote, "tls-pin")))+ pin = *p;+ repo_name = proto::url_repo_name(url);+ }+ if (key.empty()) {+ if (auto fallback = auth::key_for_url(url))+ key = *fallback;+ }+ auto client = proto::Client::connect(url, key, repo_name, pin);+ if (!client) {+ error_prefix();+ std::cout << "cannot authenticate\n";+ return 1;+ }+ std::uint8_t role = 0;+ std::string fingerprint;+ if (!client->whoami(role, fingerprint)) {+ error_prefix();+ std::cout << "cannot authenticate\n";+ return 1;+ }+ std::cout << "role: " << role_text(role) << "\n";+ std::cout << "fingerprint: " << base32_text(bytes_of(fingerprint)) << "\n";+ return 0;+}++// ---------------------------------------------------------------------------+// Help+// ---------------------------------------------------------------------------++bool net_help(std::string_view command) {+ if (command == "remote") {+ std::cout << "usage: vn remote <add|set-url|list|remove> ...\n\n";+ std::cout << "manage native remotes stored in .veins/config\n\n";+ std::cout << "subcommands:\n";+ std::cout << " add <name> <url> [-key:<name>] [-tls-pin:<hash>]\n";+ std::cout << " add a remote\n";+ std::cout << " set-url <name> <url> [-key:<name>] [-tls-pin:<hash>]\n";+ std::cout << " change a remote URL (and "+ "optionally key/pin)\n";+ std::cout << " list list remotes\n";+ std::cout << " remove <name> remove a remote\n\n";+ std::cout << "an empty -key: or -tls-pin: value clears that setting\n\n";+ std::cout << "examples:\n";+ std::cout << " vn remote add origin veins://127.0.0.1:7419/navid-m/veins2\n";+ std::cout << " vn remote set-url origin veins://example/repo -key:my-key\n";+ return true;+ }+ if (command == "clone") {+ std::cout << "usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] "+ "[-pin:<sha256>] [path]\n\n";+ std::cout << "clone a repository over file://, ssh://, or veins://\n\n";+ std::cout << "without -key, the key stored by 'vn auth use' is used when "+ "available\n";+ return true;+ }+ if (command == "fetch") {+ std::cout << "usage: vn fetch [-key:<name>] [<remote>] [path]\n\n";+ std::cout << "fetch new history and chunks from a configured native "+ "remote\n\n";+ std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";+ return true;+ }+ if (command == "push") {+ std::cout << "usage: vn push [-key:<name>] [<remote>] <bookmark> [path]\n\n";+ std::cout << "push a bookmark to a configured native remote\n\n";+ std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";+ return true;+ }+ if (command == "serve") {+ std::cout << "usage: vn serve -stdio <repo>\n";+ std::cout << " vn serve -listen <addr:port> -root <dir> -tls-cert "+ "<file> -tls-key <file>\n\n";+ std::cout << "run the native server over standard input/output or TLS 1.3\n";+ return true;+ }+ if (command == "key") {+ std::cout << "usage: vn key <generate|list|show> [name]\n\n";+ std::cout << "manage local Ed25519 keys in the user key directory\n";+ return true;+ }+ if (command == "auth") {+ std::cout << "usage: vn auth <use|list|remove> ...\n\n";+ std::cout << "remember which key clone/fetch/push should use\n\n";+ std::cout << " vn auth use <key> [<host|url>] set the default or host "+ "key\n";+ std::cout << " vn auth list show stored key mappings\n";+ std::cout << " vn auth remove [<host|url>] remove a mapping\n";+ return true;+ }+ if (command == "access") {+ std::cout << "usage: vn access <add|list|remove|anonymous> ...\n\n";+ std::cout << "manage a served repository's .veins/access policy\n";+ return true;+ }+ if (command == "whoami") {+ std::cout << "usage: vn whoami [<remote>|<url>]\n\n";+ std::cout << "connect to a server and report the granted role and key "+ "fingerprint\n";+ return true;+ }+ return false;+}++} // namespace vn--- /dev/null+++ b/xveins/src/net_commands.h@@ -0,0 +1,23 @@+#pragma once++#include <string>+#include <string_view>+#include <vector>++namespace vn {++int remote_run(const std::vector<std::string> &args);+int clone_run(const std::vector<std::string> &args);+int fetch_run(const std::vector<std::string> &args);+int push_run(const std::vector<std::string> &args);+int serve_run(const std::vector<std::string> &args);+int key_run(const std::vector<std::string> &args);+int auth_run(const std::vector<std::string> &args);+int access_run(const std::vector<std::string> &args);+int whoami_run(const std::vector<std::string> &args);++// Print help for a network command. Returns false when `command` is not one of+// them.+bool net_help(std::string_view command);++} // namespace vn--- /dev/null+++ b/xveins/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/xveins/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/xveins/src/oplog.cpp@@ -0,0 +1,246 @@+#include "local_commands.h"++#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <iostream>++namespace vn {++namespace {++struct OpRec {+ Id id{};+ Operation op;+};++std::vector<OpRec> collect_operations(Store &store,+ const std::vector<Id> &heads) {+ std::vector<OpRec> out;+ std::vector<Id> seen;+ std::vector<Id> stack(heads.rbegin(), heads.rend());+ while (!stack.empty()) {+ const Id id = stack.back();+ stack.pop_back();+ if (contains_id(seen, id))+ continue;+ seen.push_back(id);+ auto op = store.read_operation(id);+ if (!op)+ continue;+ for (const auto &parent : op->parents) {+ if (!contains_id(seen, parent))+ stack.push_back(parent);+ }+ out.push_back(OpRec{id, std::move(*op)});+ }+ return out;+}++void sort_operations(std::vector<OpRec> &recs) {+ std::stable_sort(recs.begin(), recs.end(), [](const OpRec &a, const OpRec &b) {+ return a.op.end.ms > b.op.end.ms;+ });+}++std::optional<std::size_t> resolve_operation(+ const std::vector<OpRec> &recs, std::string_view text) {+ std::optional<std::size_t> found;+ std::size_t count = 0;+ for (std::size_t i = 0; i < recs.size(); ++i) {+ const std::string full = hex_encode(recs[i].id);+ if (full.size() >= text.size() && full.compare(0, text.size(), text) == 0) {+ found = i;+ ++count;+ }+ }+ if (count == 1)+ return found;+ return std::nullopt;+}++std::optional<Id> wc_tree(Store &store, const View &view) {+ const auto wc = working_copy_id(view);+ if (!wc)+ return std::nullopt;+ auto loaded = load_commit(store, *wc);+ if (!loaded)+ return std::nullopt;+ return loaded->commit.root_tree;+}++int write_view(const fs::path &root, Store &store, const View &next,+ std::string_view description) {+ auto tx = Txn::begin(root, store);+ if (!tx) {+ error_prefix();+ std::cout << "cannot load repository state\n";+ return 1;+ }+ const auto old_tree = wc_tree(store, tx->view());+ const auto new_tree = wc_tree(store, next);+ tx->view() = next;+ if (!tx->finish(description))+ return 1;+ return checkout_materialize_optional(root, store, old_tree, new_tree);+}++int op_log(const std::vector<std::string> &) {+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ Store store = Store::open_all(*root);+ const auto heads = read_heads(*root);+ auto recs = collect_operations(store, heads);+ sort_operations(recs);+ for (const auto &rec : recs) {+ const std::string marker = contains_id(heads, rec.id) ? "@" : " ";+ const std::string stamp =+ format_utc(rec.op.end.ms / 1000);+ std::cout << marker << " " << hex_encode(rec.id).substr(0, 12) << " "+ << stamp << " " << rec.op.description << "\n";+ }+ return 0;+}++int op_restore(const std::vector<std::string> &args, std::size_t start) {+ if (start >= args.size()) {+ error_prefix();+ std::cout << "op restore requires an operation id\n";+ return 1;+ }+ const std::string &text = args[start];+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ const auto heads = read_heads(*root);+ auto recs = collect_operations(store, heads);+ const auto target = resolve_operation(recs, text);+ if (!target) {+ error_prefix();+ std::cout << "unknown operation\n";+ return 1;+ }+ auto target_view = store.read_view(recs[*target].op.view);+ if (!target_view) {+ error_prefix();+ std::cout << "cannot read operation view\n";+ return 1;+ }+ return write_view(*root, store, *target_view, "op restore");+}++int op_revert(const std::vector<std::string> &args, std::size_t start) {+ if (start >= args.size()) {+ error_prefix();+ std::cout << "op revert requires an operation id\n";+ return 1;+ }+ const std::string &text = args[start];+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ const auto heads = read_heads(*root);+ auto recs = collect_operations(store, heads);+ const auto target = resolve_operation(recs, text);+ if (!target) {+ error_prefix();+ std::cout << "unknown operation\n";+ return 1;+ }+ const auto &op = recs[*target].op;+ View view;+ if (!op.parents.empty()) {+ auto parent = store.read_operation(op.parents.front());+ if (parent) {+ auto parent_view = store.read_view(parent->view);+ if (parent_view)+ view = std::move(*parent_view);+ }+ }+ return write_view(*root, store, view, "op revert");+}++} // namespace++int op_run(const std::vector<std::string> &args) {+ if (args.size() <= 2) {+ error_prefix();+ std::cout << "expected an op subcommand (log, restore, revert)\n";+ return 1;+ }+ const std::string &sub = args[2];+ if (sub == "log")+ return op_log(args);+ if (sub == "restore")+ return op_restore(args, 3);+ if (sub == "revert")+ return op_revert(args, 3);+ error_prefix();+ std::cout << "unknown op subcommand: " << sub << "\n";+ return 1;+}++int undo_run(const std::vector<std::string> &) {+ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;+ Store store = Store::open_all(*root);+ const auto heads = read_heads(*root);+ if (heads.empty()) {+ error_prefix();+ std::cout << "no operations to undo\n";+ return 1;+ }+ auto recs = collect_operations(store, heads);+ sort_operations(recs);+ if (recs.empty()) {+ error_prefix();+ std::cout << "cannot resolve undo target\n";+ return 1;+ }+ const auto &latest = recs.front().op;+ View view;+ if (!latest.parents.empty()) {+ auto parent = store.read_operation(latest.parents.front());+ if (!parent) {+ error_prefix();+ std::cout << "cannot resolve undo target\n";+ return 1;+ }+ auto parent_view = store.read_view(parent->view);+ if (!parent_view) {+ error_prefix();+ std::cout << "cannot resolve undo target\n";+ return 1;+ }+ view = std::move(*parent_view);+ }+ return write_view(*root, store, view, "undo");+}++} // namespace vn--- /dev/null+++ b/xveins/src/pathspec.cpp@@ -0,0 +1,96 @@+#include "pathspec.h"++#include <vector>++namespace vn {++namespace {++// Collapse "." and ".." components and drop empty components.+std::optional<std::string> normalize_components(std::string_view input) {+ std::vector<std::string_view> comps;+ std::size_t start = 0;+ for (std::size_t i = 0; i <= input.size(); ++i) {+ const bool at_end = i == input.size();+ if (!at_end && input[i] != '/')+ continue;+ const std::string_view comp = input.substr(start, i - start);+ if (!comp.empty() && comp != ".") {+ if (comp == "..") {+ if (comps.empty())+ return std::nullopt;+ comps.pop_back();+ } else {+ comps.push_back(comp);+ }+ }+ start = i + 1;+ }+ std::string out;+ for (std::size_t i = 0; i < comps.size(); ++i) {+ if (i != 0)+ out.push_back('/');+ out.append(comps[i]);+ }+ return out;+}++std::string join_relative(std::string_view base, std::string_view arg) {+ if (base.empty())+ return std::string(arg);+ if (arg.empty())+ return std::string(base);+ std::string out(base);+ out.push_back('/');+ out.append(arg);+ return out;+}++} // namespace++std::optional<std::string> cwd_relative(const fs::path &root) {+ std::error_code ec;+ fs::path cwd = fs::current_path(ec);+ if (ec)+ return std::nullopt;+ cwd = fs::weakly_canonical(cwd, ec);+ if (ec)+ return std::nullopt;+ const std::string canon = path_to_bytes(cwd);+ const std::string root_bytes = path_to_bytes(root);+ if (canon == root_bytes)+ return std::string();+ if (canon.size() > root_bytes.size() &&+ canon.compare(0, root_bytes.size(), root_bytes) == 0 &&+ canon[root_bytes.size()] == '/')+ return canon.substr(root_bytes.size() + 1);+ return std::nullopt;+}++std::optional<std::string> pathspec_normalize(const fs::path &root,+ std::string_view cwd_rel,+ std::string_view arg) {+ if (arg.empty())+ return std::nullopt;+ if (arg.front() == '/') {+ auto norm = normalize_components(arg);+ if (!norm)+ return std::nullopt;+ std::string root_view = path_to_bytes(root);+ if (!root_view.empty() && root_view.front() == '/')+ root_view.erase(0, 1);+ if (norm->size() > root_view.size() &&+ norm->compare(0, root_view.size(), root_view) == 0 &&+ (*norm)[root_view.size()] == '/')+ return norm->substr(root_view.size() + 1);+ return std::nullopt;+ }+ return normalize_components(join_relative(cwd_rel, arg));+}++bool pathspec_has_glob(std::string_view value) {+ return value.find('*') != std::string_view::npos ||+ value.find('?') != std::string_view::npos;+}++} // namespace vn--- /dev/null+++ b/xveins/src/pathspec.h@@ -0,0 +1,23 @@+#pragma once++#include "common.h"++#include <optional>+#include <string>++namespace vn {++// Current directory relative to the repository root, or nullopt when the+// process is outside the repository.+std::optional<std::string> cwd_relative(const fs::path &root);++// Normalize one command-line operand into a repository-relative path. Relative+// operands are resolved against `cwd_rel`; absolute operands must live inside+// `root`. Glob metacharacters are preserved.+std::optional<std::string> pathspec_normalize(const fs::path &root,+ std::string_view cwd_rel,+ std::string_view arg);++bool pathspec_has_glob(std::string_view value);++} // namespace vn--- /dev/null+++ b/xveins/src/promisor.cpp@@ -0,0 +1,57 @@+#include "promisor.h"++#include "protocol.h"+#include "store.h"++#include <optional>+#include <string>+#include <vector>++namespace vn {++namespace {++std::string remote_field(std::string_view remote, std::string_view field) {+ std::string out = "remote.";+ out += remote;+ out.push_back('.');+ out += field;+ return out;+}++bool fetch_missing_chunk(const fs::path &root, const Id &id) {+ static thread_local bool active = false;+ if (active)+ return false;+ active = true;+ struct Guard {+ bool &flag;+ ~Guard() { flag = false; }+ } guard{active};++ auto promisor = repo_config_value(root, "promisor");+ if (!promisor || promisor->empty())+ return false;+ auto url = repo_config_value(root, remote_field(*promisor, "url"));+ if (!url || url->empty())+ return false;+ auto key = repo_config_value(root, remote_field(*promisor, "key"));+ auto pin = repo_config_value(root, remote_field(*promisor, "tls-pin"));+ const std::string repo_name = proto::url_repo_name(*url);+ auto client = proto::Client::connect(*url, key ? *key : std::string(),+ repo_name, pin ? *pin : std::string());+ if (!client)+ return false;+ const std::vector<Id> ids = {id};+ return client->get_chunks(root, ids);+}++} // namespace++void install_promisor_fetcher() {+ set_promisor_fetcher([](const fs::path &root, const Id &id) {+ return fetch_missing_chunk(root, id);+ });+}++} // namespace vn--- /dev/null+++ b/xveins/src/promisor.h@@ -0,0 +1,9 @@+#pragma once++namespace vn {++// Register the lazy-chunk fetch hook used by the store. Safe to call more than+// once; the last registration wins.+void install_promisor_fetcher();++} // namespace vn--- /dev/null+++ b/xveins/src/protocol.cpp@@ -0,0 +1,901 @@+#include "protocol.h"++#include "auth.h"+#include "store.h"++#include <blake3.h>++#include <algorithm>+#include <array>+#include <cstring>++namespace vn::proto {++namespace {++void put_u16_be(ByteWriter &writer, std::uint16_t value) {+ writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));+ writer.u8(static_cast<std::uint8_t>(value & 255u));+}++std::optional<std::uint16_t> read_u16_be(Reader &reader) {+ const auto high = reader.u8();+ if (!high)+ return std::nullopt;+ const auto low = reader.u8();+ if (!low)+ return std::nullopt;+ return static_cast<std::uint16_t>((static_cast<std::uint16_t>(*high) << 8) |+ *low);+}++std::vector<std::uint8_t>+encode_string_list(const std::vector<std::string> &items) {+ ByteWriter writer(128);+ writer.varint(items.size());+ for (const auto &item : items)+ writer.length_prefixed(item);+ return writer.take();+}++std::optional<std::vector<std::string>> decode_string_list(Reader &reader,+ std::size_t max) {+ const auto count = reader.list_len(max);+ if (!count)+ return std::nullopt;+ std::vector<std::string> out;+ out.reserve(*count);+ for (std::size_t i = 0; i < *count; ++i) {+ const auto value = reader.bytes(4096);+ if (!value)+ return std::nullopt;+ out.emplace_back(str_of(*value));+ }+ return out;+}++std::string bytes_to_string(Bytes data) { return std::string(str_of(data)); }++void append_id(ByteWriter &writer, const Id &id) {+ writer.raw(Bytes(id.data(), id.size()));+}++std::optional<Id> read_id(Reader &reader) {+ const auto id = reader.id();+ if (!id)+ return std::nullopt;+ return *id;+}++std::size_t find_char(std::string_view text, char needle) {+ const auto at = text.find(needle);+ return at == std::string_view::npos ? std::string_view::npos : at;+}++struct Authority {+ std::string host;+ int port = 0;+};++Authority parse_authority(std::string_view authority, int default_port,+ bool strip_user) {+ if (strip_user) {+ const auto at = find_char(authority, '@');+ if (at != std::string_view::npos)+ authority.remove_prefix(at + 1);+ }+ Authority out;+ out.host = std::string(authority);+ out.port = default_port;+ const auto colon = find_char(authority, ':');+ if (colon != std::string_view::npos) {+ out.host = std::string(authority.substr(0, colon));+ const std::string_view port_text = authority.substr(colon + 1);+ if (!port_text.empty()) {+ int port = 0;+ bool numeric = true;+ for (char c : port_text) {+ if (c < '0' || c > '9') {+ numeric = false;+ break;+ }+ if (port > 1000000)+ port = 1000000;+ port = port * 10 + (c - '0');+ }+ if (numeric)+ out.port = port;+ }+ }+ return out;+}++std::optional<net::Stream> connect_stream(const Url &url,+ std::string_view tls_pin,+ std::string &binding) {+ if (url.ssh) {+ std::vector<std::string> remote = {"vn", "serve", "-stdio", url.path};+ const std::string remote_command = net::build_shell_command(remote);+ std::vector<std::string> argv = {"ssh"};+ if (url.port != 22) {+ argv.push_back("-p");+ argv.push_back(std::to_string(url.port));+ }+ argv.push_back(url.host);+ argv.push_back(remote_command);+ return net::Stream::spawn_argv(argv);+ }+ if (url.tls) {+ auto fd = net::tcp_connect(url.host, url.port);+ if (!fd)+ return std::nullopt;+ void *ctx = net::tls_client_ctx(!tls_pin.empty());+ if (!ctx) {+ net::close_socket(*fd);+ return std::nullopt;+ }+ void *ssl = net::tls_connect(ctx, *fd, url.host);+ net::tls_ctx_free(ctx);+ if (!ssl) {+ net::close_socket(*fd);+ return std::nullopt;+ }+ std::array<std::uint8_t, 32> exported{};+ if (net::tls_exporter(ssl, exported.data(), exported.size()))+ binding.assign(reinterpret_cast<const char *>(exported.data()),+ exported.size());+ if (!tls_pin.empty()) {+ std::array<std::uint8_t, 32> digest{};+ const bool got = net::tls_peer_sha256(ssl, digest.data());+ const std::string hex = net::to_hex(Bytes(digest.data(), digest.size()));+ if (!got || !net::hex_equal(hex, tls_pin)) {+ net::close_socket(*fd);+ net::tls_free(ssl);+ return std::nullopt;+ }+ }+ return net::Stream::tls_stream(*fd, ssl);+ }+ std::vector<std::string> argv = {path_to_bytes(net::self_exe()), "serve",+ "-stdio", url.path};+ return net::Stream::spawn_argv(argv);+}++std::string id_text(const Id &id) { return hex_encode(id); }++} // namespace++// ---------------------------------------------------------------------------+// Message codecs+// ---------------------------------------------------------------------------++std::vector<std::uint8_t> encode_hello(const Hello &hello) {+ ByteWriter writer(128);+ put_u16_be(writer, hello.min_version);+ put_u16_be(writer, hello.max_version);+ writer.raw(Bytes(encode_string_list(hello.capabilities)));+ writer.length_prefixed(hello.repo);+ writer.length_prefixed(hello.client_nonce);+ return writer.take();+}++std::optional<Hello> decode_hello(Bytes data) {+ Reader reader(data);+ const auto min_version = read_u16_be(reader);+ if (!min_version)+ return std::nullopt;+ const auto max_version = read_u16_be(reader);+ if (!max_version)+ return std::nullopt;+ auto capabilities = decode_string_list(reader, 64);+ if (!capabilities)+ return std::nullopt;+ const auto repo = reader.bytes(4096);+ if (!repo)+ return std::nullopt;+ const auto nonce = reader.bytes(64);+ if (!nonce)+ return std::nullopt;+ if (!reader.finish())+ return std::nullopt;+ Hello out;+ out.min_version = *min_version;+ out.max_version = *max_version;+ out.capabilities = std::move(*capabilities);+ out.repo = bytes_to_string(*repo);+ out.client_nonce = bytes_to_string(*nonce);+ return out;+}++std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello) {+ ByteWriter writer(128);+ put_u16_be(writer, hello.version);+ writer.raw(Bytes(encode_string_list(hello.capabilities)));+ writer.length_prefixed(hello.server_nonce);+ writer.u8(hello.auth_required);+ return writer.take();+}++std::optional<HelloOk> decode_hello_ok(Bytes data) {+ Reader reader(data);+ const auto version = read_u16_be(reader);+ if (!version)+ return std::nullopt;+ auto capabilities = decode_string_list(reader, 64);+ if (!capabilities)+ return std::nullopt;+ const auto nonce = reader.bytes(64);+ if (!nonce)+ return std::nullopt;+ const auto auth = reader.u8();+ if (!auth)+ return std::nullopt;+ if (!reader.finish())+ return std::nullopt;+ HelloOk out;+ out.version = *version;+ out.capabilities = std::move(*capabilities);+ out.server_nonce = bytes_to_string(*nonce);+ out.auth_required = *auth;+ return out;+}++std::vector<std::uint8_t> encode_auth(const Auth &auth) {+ ByteWriter writer(128);+ writer.length_prefixed(auth.public_key);+ writer.length_prefixed(auth.signature);+ return writer.take();+}++std::optional<Auth> decode_auth(Bytes data) {+ Reader reader(data);+ const auto public_key = reader.bytes(64);+ if (!public_key)+ return std::nullopt;+ const auto signature = reader.bytes(128);+ if (!signature)+ return std::nullopt;+ if (!reader.finish())+ return std::nullopt;+ return Auth{bytes_to_string(*public_key), bytes_to_string(*signature)};+}++std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth) {+ ByteWriter writer(64);+ writer.u8(auth.role);+ writer.length_prefixed(auth.fingerprint);+ return writer.take();+}++std::optional<AuthOk> decode_auth_ok(Bytes data) {+ Reader reader(data);+ const auto role = reader.u8();+ if (!role)+ return std::nullopt;+ const auto fingerprint = reader.bytes(64);+ if (!fingerprint)+ return std::nullopt;+ if (!reader.finish())+ return std::nullopt;+ return AuthOk{*role, bytes_to_string(*fingerprint)};+}++std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs) {+ ByteWriter writer(256);+ writer.varint(refs.size());+ for (const auto &ref : refs) {+ writer.length_prefixed(ref.name);+ append_id(writer, ref.target);+ writer.length_prefixed(ref.change_id);+ writer.u8(ref.kind);+ }+ return writer.take();+}++std::optional<std::vector<RefInfo>> decode_refs(Bytes data) {+ Reader reader(data);+ const auto count = reader.list_len(1000000);+ if (!count)+ return std::nullopt;+ std::vector<RefInfo> out;+ out.reserve(*count);+ for (std::size_t i = 0; i < *count; ++i) {+ const auto name = reader.bytes(4096);+ if (!name)+ return std::nullopt;+ const auto target = read_id(reader);+ if (!target)+ return std::nullopt;+ const auto change_id = reader.bytes(64);+ if (!change_id)+ return std::nullopt;+ const auto kind = reader.u8();+ if (!kind)+ return std::nullopt;+ RefInfo ref;+ ref.name = bytes_to_string(*name);+ ref.target = *target;+ ref.change_id = bytes_to_string(*change_id);+ ref.kind = *kind;+ out.push_back(std::move(ref));+ }+ if (!reader.finish())+ return std::nullopt;+ return out;+}++std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids) {+ ByteWriter writer(ids.size() * 32 + 8);+ writer.varint(ids.size());+ for (const auto &id : ids)+ append_id(writer, id);+ return writer.take();+}++std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max) {+ Reader reader(data);+ const auto count = reader.list_len(max);+ if (!count)+ return std::nullopt;+ std::vector<Id> out;+ out.reserve(*count);+ for (std::size_t i = 0; i < *count; ++i) {+ const auto id = read_id(reader);+ if (!id)+ return std::nullopt;+ out.push_back(*id);+ }+ if (!reader.finish())+ return std::nullopt;+ return out;+}++std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,+ const std::vector<Id> &haves) {+ ByteWriter writer(256);+ writer.varint(wants.size());+ for (const auto &id : wants)+ append_id(writer, id);+ writer.varint(haves.size());+ for (const auto &id : haves)+ append_id(writer, id);+ return writer.take();+}++std::optional<Negotiate> decode_negotiate(Bytes data) {+ Reader reader(data);+ const auto want_count = reader.list_len(1000000);+ if (!want_count)+ return std::nullopt;+ Negotiate out;+ out.wants.reserve(*want_count);+ for (std::size_t i = 0; i < *want_count; ++i) {+ const auto id = read_id(reader);+ if (!id)+ return std::nullopt;+ out.wants.push_back(*id);+ }+ const auto have_count = reader.list_len(1000000);+ if (!have_count)+ return std::nullopt;+ out.haves.reserve(*have_count);+ for (std::size_t i = 0; i < *have_count; ++i) {+ const auto id = read_id(reader);+ if (!id)+ return std::nullopt;+ out.haves.push_back(*id);+ }+ if (!reader.finish())+ return std::nullopt;+ return out;+}++std::vector<std::uint8_t>+encode_negotiate_ok(const std::vector<std::uint8_t> &known,+ std::uint8_t enough) {+ ByteWriter writer(known.size() + 16);+ writer.u8(enough);+ writer.varint(known.size());+ for (std::uint8_t bit : known)+ writer.u8(bit);+ return writer.take();+}++std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data) {+ Reader reader(data);+ const auto enough = reader.u8();+ if (!enough)+ return std::nullopt;+ const auto count = reader.list_len(1000000);+ if (!count)+ return std::nullopt;+ std::vector<std::uint8_t> out;+ out.reserve(*count);+ for (std::size_t i = 0; i < *count; ++i) {+ const auto bit = reader.u8();+ if (!bit)+ return std::nullopt;+ out.push_back(*bit);+ }+ if (!reader.finish())+ return std::nullopt;+ return out;+}++std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits) {+ ByteWriter writer(bits.size() + 8);+ writer.varint(bits.size());+ for (std::uint8_t bit : bits)+ writer.u8(bit);+ return writer.take();+}++std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data) {+ Reader reader(data);+ const auto count = reader.list_len(1000000);+ if (!count)+ return std::nullopt;+ std::vector<std::uint8_t> out;+ out.reserve(*count);+ for (std::size_t i = 0; i < *count; ++i) {+ const auto bit = reader.u8();+ if (!bit)+ return std::nullopt;+ out.push_back(*bit);+ }+ if (!reader.finish())+ return std::nullopt;+ return out;+}++std::vector<std::uint8_t>+encode_update_refs(const std::vector<UpdateRef> &updates) {+ ByteWriter writer(256);+ writer.varint(updates.size());+ for (const auto &update : updates) {+ writer.length_prefixed(update.name);+ writer.opt_id(update.expected);+ writer.opt_id(update.target);+ }+ return writer.take();+}++std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data) {+ Reader reader(data);+ const auto count = reader.list_len(1000000);+ if (!count)+ return std::nullopt;+ std::vector<UpdateRef> out;+ out.reserve(*count);+ for (std::size_t i = 0; i < *count; ++i) {+ const auto name = reader.bytes(4096);+ if (!name)+ return std::nullopt;+ const auto expected = reader.opt_id();+ if (!expected)+ return std::nullopt;+ const auto target = reader.opt_id();+ if (!target)+ return std::nullopt;+ UpdateRef update;+ update.name = bytes_to_string(*name);+ update.expected = *expected;+ update.target = *target;+ out.push_back(std::move(update));+ }+ if (!reader.finish())+ return std::nullopt;+ return out;+}++std::string auth_message(std::uint16_t version, std::string_view repo,+ Bytes server_nonce, Bytes client_nonce, Bytes binding) {+ ByteWriter writer(128);+ writer.raw(std::string_view("veins-auth/1"));+ writer.u8(0);+ writer.u8(static_cast<std::uint8_t>((version >> 8) & 255u));+ writer.u8(static_cast<std::uint8_t>(version & 255u));+ writer.length_prefixed(repo);+ writer.raw(server_nonce);+ writer.raw(client_nonce);+ writer.raw(binding);+ return std::string(str_of(writer.view()));+}++std::string_view role_name(std::uint8_t role) {+ if (role == 2)+ return "write";+ if (role == 1)+ return "read";+ return "anonymous";+}++// ---------------------------------------------------------------------------+// URLs+// ---------------------------------------------------------------------------++std::optional<Url> parse_url(std::string_view url) {+ constexpr std::string_view file_prefix = "file://";+ constexpr std::string_view ssh_prefix = "ssh://";+ constexpr std::string_view veins_prefix = "veins://";+ if (url.starts_with(file_prefix))+ return Url{false, false, {}, 0, std::string(url.substr(file_prefix.size()))};+ if (url.starts_with(ssh_prefix)) {+ std::string_view rest = url.substr(ssh_prefix.size());+ const auto slash = rest.find('/');+ if (slash == std::string_view::npos)+ return std::nullopt;+ const auto authority = parse_authority(rest.substr(0, slash), 22, true);+ return Url{false, true, authority.host, authority.port,+ std::string(rest.substr(slash + 1))};+ }+ if (url.starts_with(veins_prefix)) {+ std::string_view rest = url.substr(veins_prefix.size());+ const auto slash = rest.find('/');+ if (slash == std::string_view::npos)+ return std::nullopt;+ const auto authority = parse_authority(rest.substr(0, slash), 7419, false);+ return Url{true, false, authority.host, authority.port,+ std::string(rest.substr(slash + 1))};+ }+ return std::nullopt;+}++std::string url_repo_name(std::string_view url) {+ auto parsed = parse_url(url);+ if (!parsed || !parsed->tls)+ return {};+ return parsed->path;+}++// ---------------------------------------------------------------------------+// Client+// ---------------------------------------------------------------------------++void Client::set_error(std::string text) { last_error_ = std::move(text); }++void Client::set_error_frame(const wire::Frame &frame) {+ const std::uint8_t code = wire::read_error(frame.payload);+ const std::string_view name = wire::error_code_name(code);+ const std::string message = wire::error_message(frame.payload);+ std::string text = "server error: ";+ text += name;+ if (!message.empty()) {+ text += ": ";+ text += message;+ }+ set_error(std::move(text));+}++std::optional<wire::Frame> Client::request(std::uint8_t kind, Bytes payload) {+ const std::uint32_t rid =+ static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+ if (!wire::write_frame(stream_, kind, rid, payload)) {+ set_error("connection closed while sending request");+ return std::nullopt;+ }+ auto frame = wire::read_frame(stream_);+ if (!frame) {+ set_error("connection closed while waiting for server response");+ return std::nullopt;+ }+ if (frame->kind == wire::ERROR) {+ set_error_frame(*frame);+ return std::nullopt;+ }+ return frame;+}++std::optional<Client> Client::connect(std::string_view url,+ std::string_view key_name,+ std::string_view repo_name,+ std::string_view tls_pin) {+ auto parsed = parse_url(url);+ if (!parsed)+ return std::nullopt;+ std::string binding;+ auto stream = connect_stream(*parsed, tls_pin, binding);+ if (!stream)+ return std::nullopt;++ const auto nonce_bytes = secure_random(32);+ if (nonce_bytes.size() != 32) {+ stream->close();+ return std::nullopt;+ }+ const std::string client_nonce(reinterpret_cast<const char *>(+ nonce_bytes.data()),+ nonce_bytes.size());++ Hello hello;+ hello.capabilities = {"zstd-records", "lazy-chunks", "push", "auth-ed25519"};+ hello.repo = std::string(repo_name);+ hello.client_nonce = client_nonce;+ const auto hello_body = encode_hello(hello);+ if (!wire::write_frame(*stream, wire::HELLO, 1, hello_body)) {+ stream->close();+ return std::nullopt;+ }+ auto hello_frame = wire::read_frame(*stream);+ if (!hello_frame || hello_frame->kind != wire::HELLO_OK) {+ stream->close();+ return std::nullopt;+ }+ auto hello_ok = decode_hello_ok(hello_frame->payload);+ if (!hello_ok) {+ stream->close();+ return std::nullopt;+ }++ Client client;+ client.stream_ = std::move(*stream);+ client.binding_ = std::move(binding);+ client.version_ = hello_ok->version;++ std::string selected_key(key_name);+ if (selected_key.empty() && hello_ok->auth_required != 0)+ selected_key = "default";++ if (!selected_key.empty()) {+ auto key = auth::load_key(selected_key);+ if (key) {+ const std::string message = auth_message(+ hello_ok->version, repo_name,+ Bytes(reinterpret_cast<const std::uint8_t *>(+ hello_ok->server_nonce.data()),+ hello_ok->server_nonce.size()),+ Bytes(reinterpret_cast<const std::uint8_t *>(client_nonce.data()),+ client_nonce.size()),+ Bytes(reinterpret_cast<const std::uint8_t *>(client.binding_.data()),+ client.binding_.size()));+ auto signature = ed25519_sign(Bytes(key->seed.data(), key->seed.size()),+ Bytes(reinterpret_cast<const std::uint8_t *>(+ message.data()),+ message.size()));+ if (signature) {+ Auth auth;+ auth.public_key.assign(+ reinterpret_cast<const char *>(key->public_key.data()),+ key->public_key.size());+ auth.signature.assign(+ reinterpret_cast<const char *>(signature->data()),+ signature->size());+ const auto body = encode_auth(auth);+ if (wire::write_frame(client.stream_, wire::AUTH, 2, body)) {+ auto reply = wire::read_frame(client.stream_);+ if (reply && reply->kind == wire::AUTH_OK) {+ auto ok = decode_auth_ok(reply->payload);+ if (ok) {+ client.role_ = ok->role;+ client.authed_ = true;+ client.fingerprint_ = std::move(ok->fingerprint);+ }+ }+ }+ }+ }+ }++ if (hello_ok->auth_required != 0 && !client.authed_) {+ client.stream_.close();+ return std::nullopt;+ }+ return client;+}++bool Client::list_refs(std::vector<RefInfo> &refs) {+ auto frame = request(wire::LIST_REFS, Bytes{});+ if (!frame)+ return false;+ if (frame->kind != wire::REFS) {+ set_error("unexpected response to ref listing (message kind " ++ std::to_string(frame->kind) + ")");+ return false;+ }+ auto decoded = decode_refs(frame->payload);+ if (!decoded)+ return false;+ refs = std::move(*decoded);+ return true;+}++bool Client::negotiate(const std::vector<Id> &wants,+ const std::vector<Id> &haves) {+ const auto body = encode_negotiate(wants, haves);+ auto frame = request(wire::NEGOTIATE, body);+ if (!frame)+ return false;+ if (frame->kind != wire::NEGOTIATE_OK) {+ set_error("unexpected response to negotiation (message kind " ++ std::to_string(frame->kind) + ")");+ return false;+ }+ return true;+}++bool Client::receive_stream(const fs::path &repo) {+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ Writer writer;+ bool good = true;++ for (;;) {+ auto frame = wire::read_frame(stream_);+ if (!frame) {+ set_error("connection closed while receiving data");+ return false;+ }+ if (frame->kind == wire::END) {+ std::array<std::uint8_t, 32> digest{};+ blake3_hasher_finalize(&hasher, digest.data(), digest.size());+ if (frame->payload.size() != digest.size() ||+ std::memcmp(frame->payload.data(), digest.data(), digest.size()) !=+ 0) {+ set_error("server sent a corrupt transfer checksum");+ return false;+ }+ break;+ }+ if (frame->kind == wire::ERROR) {+ set_error_frame(*frame);+ return false;+ }+ if (frame->kind != wire::RECORDS) {+ set_error("unexpected message while receiving data (message kind " ++ std::to_string(frame->kind) + ")");+ return false;+ }+ blake3_hasher_update(&hasher, frame->payload.data(), frame->payload.size());+ auto record = wire::parse_record(bytes_of(frame->payload));+ if (!record) {+ good = false;+ } else {+ const Id computed =+ object_id(record->kind, bytes_of(record->body));+ if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {+ good = false;+ } else {+ writer.add_known(record->kind, record->id, std::move(record->body));+ }+ }+ if (!good)+ return false;+ }++ if (!writer.finish(repo)) {+ set_error("cannot write incoming objects to the store");+ return false;+ }+ return true;+}++bool Client::fetch_skeleton(const fs::path &repo,+ const std::vector<Id> &wants) {+ const auto body = encode_ids(wants);+ const std::uint32_t rid =+ static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+ if (!wire::write_frame(stream_, wire::FETCH_SKELETON, rid, body)) {+ set_error("connection closed while requesting objects");+ return false;+ }+ return receive_stream(repo);+}++bool Client::get_chunks(const fs::path &repo, const std::vector<Id> &ids) {+ if (ids.empty())+ return true;+ const auto body = encode_ids(ids);+ const std::uint32_t rid =+ static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+ if (!wire::write_frame(stream_, wire::GET_CHUNKS, rid, body)) {+ set_error("connection closed while requesting chunks");+ return false;+ }+ return receive_stream(repo);+}++bool Client::have_query(const std::vector<Id> &ids,+ std::vector<std::uint8_t> &bits) {+ const auto body = encode_ids(ids);+ auto frame = request(wire::HAVE_QUERY, body);+ if (!frame)+ return false;+ if (frame->kind != wire::HAVE_BITMAP)+ return false;+ auto decoded = decode_bitmap(frame->payload);+ if (!decoded)+ return false;+ bits = std::move(*decoded);+ return true;+}++bool Client::push_objects(const fs::path &repo, const std::vector<Id> &ids) {+ const std::uint32_t rid =+ static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+ if (!wire::write_frame(stream_, wire::PUT_RECORDS, rid, Bytes{})) {+ set_error("connection closed while starting push");+ return false;+ }+ Store store = Store::open_all(repo);+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ bool good = true;+ for (const auto &id : ids) {+ const auto loc = store.find(id);+ if (!loc) {+ set_error("local object is missing from the store: " + id_text(id));+ good = false;+ break;+ }+ auto body = store.read_body(id, loc->kind);+ if (!body) {+ set_error("cannot read local object from the store: " + id_text(id));+ good = false;+ break;+ }+ const auto record = wire::make_record(id, loc->kind, bytes_of(*body));+ blake3_hasher_update(&hasher, record.data(), record.size());+ if (!wire::write_frame(stream_, wire::RECORDS, rid,+ Bytes(record.data(), record.size()))) {+ set_error("connection closed while sending object: " + id_text(id));+ good = false;+ break;+ }+ }+ std::array<std::uint8_t, 32> digest{};+ blake3_hasher_finalize(&hasher, digest.data(), digest.size());+ if (!good)+ return false;+ if (!wire::write_frame(stream_, wire::END, rid,+ Bytes(digest.data(), digest.size()))) {+ set_error("connection closed while finishing push");+ return false;+ }+ auto ack = wire::read_frame(stream_);+ if (!ack) {+ set_error("server closed the connection before acknowledging the push");+ return false;+ }+ if (ack->kind == wire::END)+ return true;+ if (ack->kind == wire::ERROR) {+ set_error_frame(*ack);+ return false;+ }+ set_error("unexpected response to object push (message kind " ++ std::to_string(ack->kind) + ")");+ return false;+}++bool Client::update_refs(const std::vector<UpdateRef> &updates) {+ const auto body = encode_update_refs(updates);+ auto frame = request(wire::UPDATE_REFS, body);+ if (!frame)+ return false;+ if (frame->kind != wire::UPDATE_REFS_OK) {+ set_error("unexpected response to ref update (message kind " ++ std::to_string(frame->kind) + ")");+ return false;+ }+ return true;+}++bool Client::whoami(std::uint8_t &role, std::string &fingerprint) {+ auto frame = request(wire::WHOAMI, Bytes{});+ if (!frame)+ return false;+ if (frame->kind != wire::WHOAMI_OK)+ return false;+ Reader reader(frame->payload);+ const auto role_value = reader.u8();+ if (!role_value)+ return false;+ const auto fp = reader.bytes(64);+ if (!fp)+ return false;+ role = *role_value;+ fingerprint = bytes_to_string(*fp);+ return true;+}++} // namespace vn::proto--- /dev/null+++ b/xveins/src/protocol.h@@ -0,0 +1,162 @@+#pragma once++#include "crypto.h"+#include "net.h"+#include "wire.h"++#include <cstdint>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace vn::proto {++constexpr std::uint16_t PROTOCOL_VERSION = 1;++struct Hello {+ std::uint16_t min_version = PROTOCOL_VERSION;+ std::uint16_t max_version = PROTOCOL_VERSION;+ std::vector<std::string> capabilities;+ std::string repo;+ std::string client_nonce;+};++struct HelloOk {+ std::uint16_t version = 0;+ std::vector<std::string> capabilities;+ std::string server_nonce;+ std::uint8_t auth_required = 0;+};++struct Auth {+ std::string public_key;+ std::string signature;+};++struct AuthOk {+ std::uint8_t role = 0;+ std::string fingerprint;+};++struct RefInfo {+ std::string name;+ Id target{};+ std::string change_id;+ std::uint8_t kind = 0; // 0 bookmark, 1 tag+};++struct Negotiate {+ std::vector<Id> wants;+ std::vector<Id> haves;+};++struct UpdateRef {+ std::string name;+ std::optional<Id> expected;+ std::optional<Id> target;+};++std::vector<std::uint8_t> encode_hello(const Hello &hello);+std::optional<Hello> decode_hello(Bytes data);++std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello);+std::optional<HelloOk> decode_hello_ok(Bytes data);++std::vector<std::uint8_t> encode_auth(const Auth &auth);+std::optional<Auth> decode_auth(Bytes data);++std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth);+std::optional<AuthOk> decode_auth_ok(Bytes data);++std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs);+std::optional<std::vector<RefInfo>> decode_refs(Bytes data);++std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids);+std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max);++std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,+ const std::vector<Id> &haves);+std::optional<Negotiate> decode_negotiate(Bytes data);++std::vector<std::uint8_t> encode_negotiate_ok(const std::vector<std::uint8_t> &known,+ std::uint8_t enough);+std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data);++std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits);+std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data);++std::vector<std::uint8_t> encode_update_refs(const std::vector<UpdateRef> &updates);+std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data);++// The bytes signed in AUTH.+std::string auth_message(std::uint16_t version, std::string_view repo,+ Bytes server_nonce, Bytes client_nonce, Bytes binding);+std::string_view role_name(std::uint8_t role);++// ---------------------------------------------------------------------------+// URLs+// ---------------------------------------------------------------------------++struct Url {+ bool tls = false;+ bool ssh = false;+ std::string host;+ int port = 0;+ std::string path;+};++std::optional<Url> parse_url(std::string_view url);+std::string url_repo_name(std::string_view url);++// ---------------------------------------------------------------------------+// Client+// ---------------------------------------------------------------------------++class Client {+public:+ Client() = default;+ ~Client() = default;+ Client(Client &&) noexcept = default;+ Client &operator=(Client &&) noexcept = default;+ Client(const Client &) = delete;+ Client &operator=(const Client &) = delete;++ // Connect and authenticate. An empty key name means anonymous unless the+ // server requires authentication, in which case "default" is used.+ static std::optional<Client> connect(std::string_view url,+ std::string_view key_name,+ std::string_view repo_name,+ std::string_view tls_pin = {});++ bool list_refs(std::vector<RefInfo> &refs);+ bool negotiate(const std::vector<Id> &wants, const std::vector<Id> &haves);+ bool fetch_skeleton(const fs::path &repo, const std::vector<Id> &wants);+ bool get_chunks(const fs::path &repo, const std::vector<Id> &ids);+ bool have_query(const std::vector<Id> &ids, std::vector<std::uint8_t> &bits);+ bool push_objects(const fs::path &repo, const std::vector<Id> &ids);+ bool update_refs(const std::vector<UpdateRef> &updates);+ bool whoami(std::uint8_t &role, std::string &fingerprint);++ [[nodiscard]] const std::string &error() const { return last_error_; }+ [[nodiscard]] std::uint8_t role() const { return role_; }+ [[nodiscard]] bool authenticated() const { return authed_; }+ [[nodiscard]] const std::string &fingerprint() const { return fingerprint_; }+ [[nodiscard]] bool has_connection() const { return stream_.valid(); }++private:+ std::optional<wire::Frame> request(std::uint8_t kind, Bytes payload);+ bool receive_stream(const fs::path &repo);+ void set_error(std::string text);+ void set_error_frame(const wire::Frame &frame);++ net::Stream stream_;+ std::string binding_;+ std::uint16_t version_ = PROTOCOL_VERSION;+ std::uint8_t role_ = 0;+ bool authed_ = false;+ std::string fingerprint_;+ std::string last_error_;+};++} // namespace vn::proto--- /dev/null+++ b/xveins/src/remove.cpp@@ -0,0 +1,415 @@+#include "local_commands.h"++#include "pathspec.h"+#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <iostream>+#include <set>+#include <system_error>++namespace vn {++namespace {++bool rm_is_flag(std::string_view arg) {+ return !arg.empty() && arg.front() == '-';+}++bool starts_with_child(std::string_view path, std::string_view parent) {+ return path.size() > parent.size() &&+ path.compare(0, parent.size(), parent) == 0 &&+ path[parent.size()] == '/';+}++bool literal_matches(std::string_view operand, std::string_view path) {+ return path == operand || starts_with_child(path, operand);+}++bool glob_matches(std::string_view operand, std::string_view path) {+ if (glob_match(operand, path))+ return true;+ for (std::size_t i = 0; i < path.size(); ++i) {+ if (path[i] == '/' && glob_match(operand, path.substr(0, i)))+ return true;+ }+ return false;+}++bool operand_matches(std::string_view operand, std::string_view path) {+ if (pathspec_has_glob(operand))+ return glob_matches(operand, path);+ return literal_matches(operand, path);+}++bool subtree_affected(std::string_view prefix,+ const std::vector<std::string> &removes) {+ if (prefix.empty())+ return !removes.empty();+ for (const auto &r : removes) {+ if (prefix == r || starts_with_child(r, prefix) ||+ starts_with_child(prefix, r))+ return true;+ }+ return false;+}++bool path_removed(std::string_view path,+ const std::vector<std::string> &removes) {+ for (const auto &r : removes) {+ if (path == r || starts_with_child(path, r))+ return true;+ }+ return false;+}++std::string join_path(std::string_view prefix, std::string_view name) {+ if (prefix.empty())+ return std::string(name);+ std::string out(prefix);+ out.push_back('/');+ out.append(name);+ return out;+}++Id empty_tree_id(Txn &tx) {+ auto body = encode_tree({});+ if (!body)+ return Id{};+ return tx.add_object(TYPE_TREE, *body);+}++std::optional<Id> filter_tree(Txn &tx, Store &store, const Id &tree_id,+ std::string_view prefix,+ const std::vector<std::string> &removes,+ std::size_t depth) {+ if (depth > 4096)+ return tree_id;+ if (!subtree_affected(prefix, removes))+ return tree_id;+ auto body = store.read_body(tree_id, TYPE_TREE);+ if (!body)+ return tree_id;+ auto tree = decode_tree(bytes_of(*body));+ if (!tree)+ return tree_id;++ std::vector<TreeEntry> entries;+ entries.reserve(tree->entries.size());+ for (const auto &entry : tree->entries) {+ const std::string full = join_path(prefix, entry.name);+ if (path_removed(full, removes))+ continue;+ if (entry.kind == KIND_SUBTREE && subtree_affected(full, removes)) {+ auto child = filter_tree(tx, store, entry.target, full, removes, depth + 1);+ if (child)+ entries.push_back(TreeEntry{entry.name, entry.kind, *child});+ } else {+ entries.push_back(entry);+ }+ }+ if (entries.empty())+ return std::nullopt;+ auto encoded = encode_tree(entries);+ if (!encoded)+ return std::nullopt;+ return tx.add_object(TYPE_TREE, *encoded);+}++std::optional<std::string> parent_of(std::string_view path) {+ const auto slash = path.rfind('/');+ if (slash == std::string_view::npos)+ return std::nullopt;+ return std::string(path.substr(0, slash));+}++bool delete_one(const fs::path &root, std::string_view rel) {+ std::error_code ec;+ const fs::path full = root / path_from_bytes(rel);+ const bool removed = fs::remove(full, ec);+ return removed && !ec;+}++void prune_empty_parents(const fs::path &root, std::string_view rel) {+ std::string current(rel);+ for (;;) {+ const auto slash = current.rfind('/');+ if (slash == std::string::npos)+ break;+ current.resize(slash);+ std::error_code ec;+ const fs::path dir = root / path_from_bytes(current);+ if (!fs::is_directory(dir, ec))+ break;+ if (!fs::remove(dir, ec) || ec)+ break;+ }+}++int delete_paths(const fs::path &root, const std::vector<std::string> &removes) {+ std::size_t failed = 0;+ for (const auto &rel : removes) {+ if (!delete_one(root, rel))+ ++failed;+ else+ prune_empty_parents(root, rel);+ }+ if (failed > 0) {+ warning_prefix();+ std::cout << "could not delete " << failed << " path(s) from disk\n";+ return 1;+ }+ return 0;+}++int run_removal(const fs::path &root, const std::vector<std::string> &operands,+ bool delete_mode) {+ 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());+ 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;+ }++ std::vector<bool> matched(operands.size(), false);+ std::vector<std::string> removes;+ std::set<std::string> seen;+ for (const auto &entry : flatten_tree(store, loaded->commit.root_tree)) {+ for (std::size_t i = 0; i < operands.size(); ++i) {+ if (operand_matches(operands[i], entry.path)) {+ matched[i] = true;+ if (seen.insert(entry.path).second)+ removes.push_back(entry.path);+ }+ }+ }++ bool unmatched = false;+ for (std::size_t i = 0; i < operands.size(); ++i) {+ if (!matched[i]) {+ error_prefix();+ std::cout << "path is not tracked: " << operands[i] << "\n";+ unmatched = true;+ }+ }+ if (unmatched)+ return 1;++ if (!delete_mode) {+ for (const auto &rel : removes) {+ if (!ignore_path_ignored(root, rel)) {+ warning_prefix();+ std::cout << rel+ << " is not ignored and will be re-added on the next snapshot\n";+ }+ }+ }++ auto new_root = filter_tree(*tx, store, loaded->commit.root_tree, "", removes, 0);+ Id root_id{};+ if (new_root)+ root_id = *new_root;+ else+ root_id = empty_tree_id(*tx);+ if (std::memcmp(root_id.data(), loaded->commit.root_tree.data(), ID_LEN) == 0) {+ error_prefix();+ std::cout << "no tracked paths to remove\n";+ return 1;+ }++ const Sig sig = identity_signature(root);+ Commit commit = loaded->commit;+ commit.root_tree = root_id;+ commit.committer = sig;+ commit.renames_state = RENAMES_RECORDED;+ commit.renames.clear();+ const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));++ remove_head(tx->view(), *wc);+ move_bookmarks(tx->view(), *wc, new_id);+ set_workspace(tx->view(), new_id);+ rebuild_heads(tx->view());++ int status = 0;+ const auto finished = tx->finish("rm");+ if (!finished)+ status = 1;+ if (status == 0)+ (void)mark_native(root, new_id);++ if (status == 0) {+ if (delete_mode) {+ const int del = delete_paths(root, removes);+ if (del != 0)+ status = del;+ }+ info_prefix();+ std::cout << "untracked " << removes.size() << " path(s)\n";+ }+ return status;+}++int rm_command(const std::vector<std::string> &args, std::size_t start) {+ bool delete_mode = false;+ std::vector<std::string> operands;+ 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 == "-delete") {+ delete_mode = true;+ } else if (!end_flags && rm_is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ operands.push_back(arg);+ }+ }+ if (operands.empty()) {+ error_prefix();+ std::cout << "rm requires at least one path\n";+ return 1;+ }++ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;++ const auto cwd_rel = cwd_relative(*root);+ if (!cwd_rel) {+ error_prefix();+ std::cout << "cannot determine current directory\n";+ return 1;+ }++ std::vector<std::string> normalized;+ for (const auto &arg : operands) {+ auto norm = pathspec_normalize(*root, *cwd_rel, arg);+ if (!norm) {+ error_prefix();+ std::cout << "path is outside the repository: " << arg << "\n";+ return 1;+ }+ if (norm->empty() || !valid_path(*norm)) {+ error_prefix();+ std::cout << "invalid path: " << arg << "\n";+ return 1;+ }+ normalized.push_back(std::move(*norm));+ }+ if (normalized.empty()) {+ error_prefix();+ std::cout << "rm requires at least one path\n";+ return 1;+ }+ return run_removal(*root, normalized, delete_mode);+}++} // namespace++int rm_run(const std::vector<std::string> &args) { return rm_command(args, 2); }++int mv_run(const std::vector<std::string> &args) {+ std::vector<std::string> operands;+ 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 && rm_is_flag(arg)) {+ error_prefix();+ std::cout << "unknown flag: " << arg << "\n";+ return 1;+ } else {+ operands.push_back(arg);+ }+ }++ const auto root = discover_repo(".");+ if (!root) {+ error_prefix();+ std::cout << "not a veins repository\n";+ return 1;+ }+ const int snap = snapshot_run(*root);+ if (snap != 0)+ return snap;++ if (operands.size() != 2) {+ error_prefix();+ std::cout << "mv requires a source and a destination\n";+ return 1;+ }++ const auto cwd_rel = cwd_relative(*root);+ if (!cwd_rel) {+ error_prefix();+ std::cout << "cannot determine current directory\n";+ return 1;+ }+ auto src = pathspec_normalize(*root, *cwd_rel, operands[0]);+ if (!src) {+ error_prefix();+ std::cout << "invalid path\n";+ return 1;+ }+ auto dst = pathspec_normalize(*root, *cwd_rel, operands[1]);+ if (!dst) {+ error_prefix();+ std::cout << "invalid path\n";+ return 1;+ }++ const fs::path src_abs = *root / path_from_bytes(*src);+ const fs::path dst_abs = *root / path_from_bytes(*dst);+ if (!stat_path(src_abs)) {+ error_prefix();+ std::cout << "not a tracked path: " << *src << "\n";+ return 1;+ }+ if (stat_path(dst_abs)) {+ error_prefix();+ std::cout << "destination already exists: " << *dst << "\n";+ return 1;+ }++ if (const auto parent = parent_of(*dst)) {+ if (!ensure_directory(*root / path_from_bytes(*parent))) {+ error_prefix();+ std::cout << "cannot create destination directory\n";+ return 1;+ }+ }+ std::error_code ec;+ fs::rename(src_abs, dst_abs, ec);+ if (ec) {+ error_prefix();+ std::cout << "cannot move path\n";+ return 1;+ }+ return snapshot_run(*root);+}++} // namespace vn--- /dev/null+++ b/xveins/src/server.cpp@@ -0,0 +1,912 @@+#include "server.h"++#include "auth.h"+#include "crypto.h"+#include "net.h"+#include "protocol.h"+#include "store.h"+#include "wire.h"++#include <blake3.h>++#include <algorithm>+#include <cstddef>+#include <cstring>+#include <iostream>+#include <optional>+#include <set>+#include <string>++namespace vn::server {++namespace {++constexpr std::size_t MAX_CHUNKS_PER_REQUEST = 4096;++struct Session {+ net::Stream stream;+ fs::path repo_root;+ bool repo_present = false;+ Store store;+ bool store_open = false;+ auth::Access access;+ std::string hello_repo;+ std::string server_nonce;+ std::string client_nonce;+ std::string binding;+ std::uint16_t version = proto::PROTOCOL_VERSION;+ bool authed = false;+ std::uint8_t role = auth::ROLE_ANONYMOUS;+ PublicKey public_key{};+ bool has_public_key = false;+ std::string fingerprint;+ std::vector<Id> haves;+ int failed_auth = 0;+ bool closing = false;+ fs::path root;+};++std::uint8_t effective_role(const Session &session) {+ if (session.authed)+ return session.role;+ if (session.access.valid && session.access.anonymous_read &&+ session.repo_present)+ return auth::ROLE_READ;+ return auth::ROLE_ANONYMOUS;+}++bool deny(Session &session, std::uint32_t request_id, bool write) {+ const std::uint8_t role = effective_role(session);+ if (write) {+ if (role == auth::ROLE_WRITE)+ return false;+ if (!session.authed) {+ wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,+ "authentication required");+ } else {+ wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,+ "write role required");+ }+ return true;+ }+ if (role == auth::ROLE_READ || role == auth::ROLE_WRITE)+ return false;+ if (!session.authed) {+ wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,+ "authentication required");+ } else {+ wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,+ "read role required");+ }+ return true;+}++void log_line(Session &session, std::string_view text) {+ if (!session.repo_present)+ return;+ (void)append_file(veins_dir(session.repo_root) / "server.log",+ bytes_of(text));+}++void log_outcome(Session &session, std::string_view outcome) {+ if (!session.repo_present)+ return;+ const std::string line =+ std::to_string(unix_now_millis()) + " " ++ std::string(proto::role_name(effective_role(session))) + " " ++ std::string(outcome) + " " + session.hello_repo + "\n";+ log_line(session, line);+}++bool safe_repo_name(std::string_view name) {+ if (name.empty() || name.size() > 4096)+ return false;+ if (name.front() == '/')+ return false;+ if (name.find('\0') != std::string_view::npos ||+ name.find('\\') != std::string_view::npos)+ return false;+ std::size_t start = 0;+ for (std::size_t i = 0; i <= name.size(); ++i) {+ if (i == name.size() || name[i] == '/') {+ if (i - start == 2 && name[start] == '.' && name[start + 1] == '.')+ return false;+ start = i + 1;+ }+ }+ return true;+}++void open_session_store(Session &session) {+ if (session.store_open)+ return;+ session.store = Store::open_all(session.repo_root);+ session.store_open = true;+}++void select_repo(Session &session, bool has_root) {+ if (session.repo_present || !has_root)+ return;+ if (!safe_repo_name(session.hello_repo))+ return;+ const fs::path joined = session.root / path_from_bytes(session.hello_repo);+ if (auto found = discover_repo(joined)) {+ session.repo_root = *found;+ session.repo_present = true;+ }+}++std::string change_id_of(Session &session, const Id &id) {+ auto loaded = load_commit(session.store, id);+ if (!loaded)+ return {};+ return std::string(reinterpret_cast<const char *>(loaded->commit.change_id.data()),+ loaded->commit.change_id.size());+}++bool send_record(Session &session, std::uint32_t request_id,+ blake3_hasher &hasher, const Id &id, std::uint8_t kind,+ Bytes body) {+ const auto record = wire::make_record(id, kind, body);+ blake3_hasher_update(&hasher, record.data(), record.size());+ return wire::write_frame(session.stream, wire::RECORDS, request_id,+ Bytes(record.data(), record.size()));+}++bool send_end(Session &session, std::uint32_t request_id,+ blake3_hasher &hasher) {+ std::array<std::uint8_t, 32> digest{};+ blake3_hasher_finalize(&hasher, digest.data(), digest.size());+ return wire::write_frame(session.stream, wire::END, request_id,+ Bytes(digest.data(), digest.size()));+}++std::uint8_t value_kind_to_type(std::uint8_t kind) {+ if (kind == KIND_SUBTREE)+ return TYPE_TREE;+ if (kind == KIND_CONFLICT)+ return TYPE_CONFLICT;+ if (kind == KIND_FILE || kind == KIND_EXECUTABLE || kind == KIND_SYMLINK)+ return TYPE_BLOB;+ return 0;+}++void collect_object(Session &session, std::uint32_t request_id,+ blake3_hasher &hasher, const Id &id, std::uint8_t kind,+ std::set<Id> &seen, bool send, bool &failed);++void collect_tree(Session &session, std::uint32_t request_id,+ blake3_hasher &hasher, const Id &id, std::set<Id> &seen,+ bool send, bool &failed) {+ if (!seen.insert(id).second)+ return;+ auto body = session.store.read_body(id, TYPE_TREE);+ if (!body) {+ failed = true;+ return;+ }+ if (send && !send_record(session, request_id, hasher, id, TYPE_TREE,+ bytes_of(*body))) {+ failed = true;+ }+ auto tree = decode_tree(bytes_of(*body));+ if (!tree) {+ failed = true;+ return;+ }+ for (const auto &entry : tree->entries) {+ if (entry.kind == KIND_SUBTREE) {+ collect_tree(session, request_id, hasher, entry.target, seen, send,+ failed);+ } else if (entry.kind == KIND_CONFLICT) {+ collect_object(session, request_id, hasher, entry.target, TYPE_CONFLICT,+ seen, send, failed);+ } else if (entry.kind != KIND_SUBMODULE) {+ collect_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen,+ send, failed);+ }+ if (failed)+ return;+ }+}++void collect_object(Session &session, std::uint32_t request_id,+ blake3_hasher &hasher, const Id &id, std::uint8_t kind,+ std::set<Id> &seen, bool send, bool &failed) {+ if (!seen.insert(id).second)+ return;+ auto body = session.store.read_body(id, kind);+ if (!body) {+ failed = true;+ return;+ }+ if (send && !send_record(session, request_id, hasher, id, kind,+ bytes_of(*body))) {+ failed = true;+ }+ if (kind == TYPE_BLOB) {+ auto blob = decode_blob(bytes_of(*body));+ if (!blob) {+ failed = true;+ return;+ }+ if (blob->form == BlobForm::Interior) {+ for (const auto &entry : blob->entries) {+ collect_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen,+ send, failed);+ if (failed)+ return;+ }+ }+ } else if (kind == TYPE_CONFLICT) {+ auto conflict = decode_conflict(bytes_of(*body));+ if (!conflict) {+ failed = true;+ return;+ }+ for (const auto &value : conflict->adds) {+ if (!value.target)+ continue;+ const std::uint8_t child = value_kind_to_type(value.kind);+ if (child != 0)+ collect_object(session, request_id, hasher, *value.target, child, seen,+ send, failed);+ if (failed)+ return;+ }+ for (const auto &value : conflict->removes) {+ if (!value.target)+ continue;+ const std::uint8_t child = value_kind_to_type(value.kind);+ if (child != 0)+ collect_object(session, request_id, hasher, *value.target, child, seen,+ send, failed);+ if (failed)+ return;+ }+ }+}++bool handle_hello(Session &session, const wire::Frame &frame, bool has_root) {+ auto hello = proto::decode_hello(bytes_of(frame.payload));+ if (!hello) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "bad HELLO");+ return false;+ }+ if (hello->min_version > proto::PROTOCOL_VERSION ||+ hello->max_version < proto::PROTOCOL_VERSION) {+ wire::write_error(session.stream, frame.request_id,+ wire::ERR_UNSUPPORTED_VERSION, "no common version");+ return false;+ }+ session.version = proto::PROTOCOL_VERSION;+ session.hello_repo = std::move(hello->repo);+ session.client_nonce = std::move(hello->client_nonce);+ select_repo(session, has_root);+ if (!session.repo_present && !session.hello_repo.empty()) {+ error_prefix();+ std::cout << "repository not found: " << session.hello_repo << "\n";+ wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,+ "repository not found");+ return false;+ }+ if (session.repo_present) {+ session.access = auth::load_access(session.repo_root);+ if (!session.access.valid) {+ error_prefix();+ std::cout << "access file error at line " << session.access.error_line+ << " in " << path_display(session.repo_root) << "\n";+ wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+ "invalid access file");+ return false;+ }+ open_session_store(session);+ }+ log_outcome(session, "hello");++ const auto nonce = secure_random(32);+ if (nonce.size() != 32) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+ "cannot generate nonce");+ return false;+ }+ session.server_nonce.assign(reinterpret_cast<const char *>(nonce.data()),+ nonce.size());++ proto::HelloOk hello_ok;+ hello_ok.version = session.version;+ hello_ok.capabilities = {"zstd-records", "lazy-chunks", "push",+ "auth-ed25519"};+ hello_ok.server_nonce = session.server_nonce;+ hello_ok.auth_required =+ (session.repo_present && session.access.anonymous_read) ? 0 : 1;+ const auto body = proto::encode_hello_ok(hello_ok);+ return wire::write_frame(session.stream, wire::HELLO_OK, frame.request_id,+ body);+}++bool handle_auth(Session &session, const wire::Frame &frame) {+ if (session.authed) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "repeated AUTH");+ session.closing = true;+ return false;+ }+ auto auth = proto::decode_auth(bytes_of(frame.payload));+ if (!auth) {+ ++session.failed_auth;+ wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,+ "authentication failed");+ return false;+ }+ PublicKey public_key{};+ const bool key_well_formed = auth->public_key.size() == public_key.size();+ if (key_well_formed) {+ std::memcpy(public_key.data(), auth->public_key.data(),+ public_key.size());+ }+ std::uint8_t role = auth::ROLE_UNKNOWN;+ if (key_well_formed && session.repo_present && session.access.valid)+ role = auth::role_for(session.access, &public_key);++ const std::string message = proto::auth_message(+ session.version, session.hello_repo, bytes_of(session.server_nonce),+ bytes_of(session.client_nonce), bytes_of(session.binding));+ const bool signature_ok =+ role != auth::ROLE_UNKNOWN &&+ ed25519_verify(public_key, bytes_of(message), bytes_of(auth->signature));+ if (!signature_ok) {+ ++session.failed_auth;+ wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,+ "authentication failed");+ if (session.failed_auth >= 3)+ session.closing = true;+ return false;+ }++ session.authed = true;+ session.role = role;+ session.public_key = public_key;+ session.has_public_key = true;+ const auto raw_fingerprint = key_fingerprint_bytes(public_key);+ session.fingerprint.assign(+ reinterpret_cast<const char *>(raw_fingerprint.data()),+ raw_fingerprint.size());++ proto::AuthOk auth_ok;+ auth_ok.role = role;+ auth_ok.fingerprint = session.fingerprint;+ const auto body = proto::encode_auth_ok(auth_ok);+ const bool wrote = wire::write_frame(session.stream, wire::AUTH_OK,+ frame.request_id, body);+ log_outcome(session, "auth-ok");+ return wrote;+}++bool handle_whoami(Session &session, const wire::Frame &frame) {+ ByteWriter writer(64);+ writer.u8(effective_role(session));+ writer.length_prefixed(session.fingerprint);+ return wire::write_frame(session.stream, wire::WHOAMI_OK, frame.request_id,+ writer.view());+}++bool handle_list_refs(Session &session, const wire::Frame &frame) {+ if (deny(session, frame.request_id, false))+ return true;+ log_outcome(session, "list-refs");+ std::optional<View> view = current_view(session.repo_root, session.store);+ if (!view) {+ const auto heads = read_heads(session.repo_root);+ if (!heads.empty()) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+ "cannot read operation state");+ log_outcome(session, "list-refs-error");+ return true;+ }+ view = empty_view();+ }+ std::vector<proto::RefInfo> refs;+ for (const auto &bookmark : view->bookmarks) {+ if (bookmark.targets.adds.size() != 1 || !bookmark.targets.adds.front())+ continue;+ proto::RefInfo ref;+ ref.name = bookmark.name;+ ref.target = *bookmark.targets.adds.front();+ ref.change_id = change_id_of(session, ref.target);+ ref.kind = 0;+ refs.push_back(std::move(ref));+ }+ for (const auto &tag : view->tags) {+ proto::RefInfo ref;+ ref.name = tag.name;+ ref.target = tag.target;+ ref.change_id = change_id_of(session, tag.target);+ ref.kind = 1;+ refs.push_back(std::move(ref));+ }+ const auto body = proto::encode_refs(refs);+ const bool wrote =+ wire::write_frame(session.stream, wire::REFS, frame.request_id, body);+ if (!wrote)+ log_outcome(session, "list-refs-write-error");+ return wrote;+}++bool handle_negotiate(Session &session, const wire::Frame &frame) {+ if (deny(session, frame.request_id, false))+ return true;+ auto negotiate = proto::decode_negotiate(bytes_of(frame.payload));+ if (!negotiate) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "bad NEGOTIATE");+ return true;+ }+ session.haves = std::move(negotiate->haves);+ std::vector<std::uint8_t> known;+ known.reserve(session.haves.size());+ bool any_known = false;+ for (const auto &id : session.haves) {+ const bool found = session.store.find(id).has_value();+ known.push_back(found ? 1 : 0);+ any_known = any_known || found;+ }+ const std::uint8_t enough =+ (session.haves.empty() || any_known) ? 1 : 0;+ const auto body = proto::encode_negotiate_ok(known, enough);+ return wire::write_frame(session.stream, wire::NEGOTIATE_OK,+ frame.request_id, body);+}++bool handle_fetch(Session &session, const wire::Frame &frame) {+ if (deny(session, frame.request_id, false))+ return true;+ auto wants = proto::decode_ids(bytes_of(frame.payload), 1000000);+ if (!wants) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "bad wants");+ return true;+ }+ if (wants->empty()) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "empty wants");+ return true;+ }+ const auto all = collect_commits(session.store, *wants);+ std::set<Id> exclude;+ for (const auto &have : session.haves) {+ const std::array<Id, 1> roots{have};+ for (const auto &id : collect_commits(session.store, roots))+ exclude.insert(id);+ }++ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ bool failed = false;+ std::set<Id> seen;+ for (const auto &id : all) {+ if (exclude.contains(id))+ continue;+ auto loaded = load_commit(session.store, id);+ if (!loaded) {+ failed = true;+ break;+ }+ if (!send_record(session, frame.request_id, hasher, id, TYPE_COMMIT,+ bytes_of(loaded->body))) {+ failed = true;+ break;+ }+ collect_tree(session, frame.request_id, hasher, loaded->commit.root_tree,+ seen, true, failed);+ if (failed)+ break;+ }+ if (!failed)+ (void)send_end(session, frame.request_id, hasher);+ log_outcome(session, "fetch");+ return !failed;+}++bool handle_get_chunks(Session &session, const wire::Frame &frame) {+ if (deny(session, frame.request_id, false))+ return true;+ auto ids = proto::decode_ids(bytes_of(frame.payload),+ MAX_CHUNKS_PER_REQUEST);+ if (!ids) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "bad chunk list");+ return true;+ }+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ bool failed = false;+ for (const auto &id : *ids) {+ const auto loc = session.store.find(id);+ if (!loc || loc->kind != TYPE_CHUNK) {+ failed = true;+ break;+ }+ auto body = session.store.get(*loc);+ if (!body) {+ failed = true;+ break;+ }+ if (!send_record(session, frame.request_id, hasher, id, TYPE_CHUNK,+ bytes_of(*body))) {+ failed = true;+ break;+ }+ }+ if (failed) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,+ "chunk not found");+ } else {+ (void)send_end(session, frame.request_id, hasher);+ }+ return !failed;+}++bool handle_have_query(Session &session, const wire::Frame &frame) {+ if (deny(session, frame.request_id, true))+ return true;+ auto ids = proto::decode_ids(bytes_of(frame.payload), 1000000);+ if (!ids) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "bad HAVE_QUERY");+ return true;+ }+ std::vector<std::uint8_t> bits;+ bits.reserve(ids->size());+ for (const auto &id : *ids)+ bits.push_back(session.store.find(id).has_value() ? 1 : 0);+ const auto body = proto::encode_bitmap(bits);+ return wire::write_frame(session.stream, wire::HAVE_BITMAP,+ frame.request_id, body);+}++bool object_exists(Session &session, const Id &id) {+ return session.store.find(id).has_value();+}++bool check_closure(Session &session, const Id &id, std::uint8_t kind) {+ auto body = session.store.read_body(id, kind);+ if (!body)+ return false;+ bool fine = true;+ if (kind == TYPE_COMMIT) {+ auto commit = decode_commit(bytes_of(*body));+ if (!commit)+ return false;+ if (!object_exists(session, commit->root_tree))+ fine = false;+ for (const auto &parent : commit->parents) {+ if (!object_exists(session, parent))+ fine = false;+ }+ } else if (kind == TYPE_TREE) {+ auto tree = decode_tree(bytes_of(*body));+ if (!tree)+ return false;+ for (const auto &entry : tree->entries) {+ if (entry.kind != KIND_SUBMODULE && !object_exists(session, entry.target))+ fine = false;+ }+ } else if (kind == TYPE_BLOB) {+ auto blob = decode_blob(bytes_of(*body));+ if (!blob)+ return false;+ for (const auto &entry : blob->entries) {+ if (!object_exists(session, entry.id))+ fine = false;+ }+ } else if (kind == TYPE_CONFLICT) {+ auto conflict = decode_conflict(bytes_of(*body));+ if (!conflict)+ return false;+ for (const auto &value : conflict->adds) {+ if (value.target && !object_exists(session, *value.target))+ fine = false;+ }+ for (const auto &value : conflict->removes) {+ if (value.target && !object_exists(session, *value.target))+ fine = false;+ }+ }+ return fine;+}++bool handle_put_records(Session &session, const wire::Frame &frame) {+ if (deny(session, frame.request_id, true))+ return true;+ Writer writer;+ blake3_hasher hasher;+ blake3_hasher_init(&hasher);+ bool failed = false;+ std::vector<Id> accepted;++ for (;;) {+ auto frame_opt = wire::read_frame(session.stream);+ if (!frame_opt) {+ failed = true;+ break;+ }+ const auto &incoming = *frame_opt;+ if (incoming.kind == wire::END) {+ std::array<std::uint8_t, 32> digest{};+ blake3_hasher_finalize(&hasher, digest.data(), digest.size());+ if (incoming.payload.size() != digest.size() ||+ std::memcmp(incoming.payload.data(), digest.data(), digest.size()) !=+ 0) {+ failed = true;+ }+ break;+ }+ if (incoming.kind != wire::RECORDS) {+ failed = true;+ break;+ }+ blake3_hasher_update(&hasher, incoming.payload.data(),+ incoming.payload.size());+ auto record = wire::parse_record(bytes_of(incoming.payload));+ if (!record) {+ failed = true;+ break;+ }+ const Id computed = object_id(record->kind, bytes_of(record->body));+ if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {+ failed = true;+ break;+ }+ writer.add_known(record->kind, record->id, std::move(record->body));+ accepted.push_back(record->id);+ }++ if (failed) {+ wire::write_error(session.stream, frame.request_id,+ wire::ERR_HASH_MISMATCH, "record rejected");+ return true;+ }+ if (!writer.finish(session.repo_root)) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+ "pack write failed");+ return true;+ }+ open_session_store(session);+ session.store.refresh(session.repo_root);++ bool closure_ok = true;+ for (const auto &id : accepted) {+ const auto loc = session.store.find(id);+ if (!loc)+ continue;+ if (!check_closure(session, id, loc->kind)) {+ closure_ok = false;+ break;+ }+ }+ if (!closure_ok) {+ wire::write_error(session.stream, frame.request_id,+ wire::ERR_MISSING_CLOSURE, "missing object closure");+ return true;+ }+ return wire::write_frame(session.stream, wire::END, frame.request_id,+ Bytes{});+}++std::optional<Id> first_target(const TargetSet &targets) {+ if (targets.adds.empty())+ return std::nullopt;+ return targets.adds.front();+}++bool ref_matches(const View &view, std::string_view name,+ const std::optional<Id> &expected) {+ std::optional<Id> current;+ if (auto index = find_bookmark(view, name)) {+ current = first_target(view.bookmarks[*index].targets);+ } else if (auto index = find_tag(view, name)) {+ current = view.tags[*index].target;+ }+ if (!expected)+ return !current.has_value();+ if (!current)+ return false;+ return std::memcmp(current->data(), expected->data(), ID_LEN) == 0;+}++void apply_ref(View &view, std::string_view name,+ const std::optional<Id> &target) {+ if (!target) {+ if (auto index = find_bookmark(view, name))+ view.bookmarks.erase(view.bookmarks.begin() ++ static_cast<std::ptrdiff_t>(*index));+ if (auto index = find_tag(view, name))+ view.tags.erase(view.tags.begin() ++ static_cast<std::ptrdiff_t>(*index));+ return;+ }+ if (auto index = find_bookmark(view, name)) {+ auto &bookmark = view.bookmarks[*index];+ bookmark.targets.adds = {*target};+ bookmark.targets.removes.clear();+ return;+ }+ if (auto index = find_tag(view, name)) {+ view.tags[*index].target = *target;+ return;+ }+ Bookmark bookmark;+ bookmark.name = std::string(name);+ bookmark.targets.adds = {*target};+ view.bookmarks.push_back(std::move(bookmark));+}++bool handle_update_refs(Session &session, const wire::Frame &frame) {+ if (deny(session, frame.request_id, true))+ return true;+ auto updates = proto::decode_update_refs(bytes_of(frame.payload));+ if (!updates) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "bad UPDATE_REFS");+ return true;+ }+ auto tx = Txn::begin(session.repo_root, session.store);+ if (!tx) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+ "cannot update refs");+ return true;+ }+ for (const auto &update : *updates) {+ if (!ref_matches(tx->view(), update.name, update.expected)) {+ wire::write_error(session.stream, frame.request_id,+ wire::ERR_REF_CONFLICT, "ref changed");+ return true;+ }+ }+ for (const auto &update : *updates)+ apply_ref(tx->view(), update.name, update.target);+ rebuild_heads(tx->view());+ const auto status = tx->finish("remote push");+ if (!status) {+ wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+ "commit failed");+ return true;+ }+ session.store.refresh(session.repo_root);+ const std::string line = std::to_string(unix_now_millis()) + " " ++ base32_text(bytes_of(session.fingerprint)) ++ " update-refs\n";+ log_line(session, line);+ return wire::write_simple(session.stream, wire::UPDATE_REFS_OK,+ frame.request_id);+}++bool dispatch(Session &session, const wire::Frame &frame) {+ if (frame.kind == wire::HELLO)+ return handle_hello(session, frame, !session.root.empty());+ if (frame.kind == wire::AUTH)+ return handle_auth(session, frame);+ if (frame.kind == wire::WHOAMI)+ return handle_whoami(session, frame);+ if (!session.repo_present) {+ wire::write_error(session.stream, frame.request_id,+ wire::ERR_UNAUTHENTICATED, "authentication required");+ return true;+ }+ if (frame.kind == wire::LIST_REFS)+ return handle_list_refs(session, frame);+ if (frame.kind == wire::NEGOTIATE)+ return handle_negotiate(session, frame);+ if (frame.kind == wire::FETCH_SKELETON)+ return handle_fetch(session, frame);+ if (frame.kind == wire::GET_CHUNKS)+ return handle_get_chunks(session, frame);+ if (frame.kind == wire::HAVE_QUERY)+ return handle_have_query(session, frame);+ if (frame.kind == wire::PUT_RECORDS)+ return handle_put_records(session, frame);+ if (frame.kind == wire::UPDATE_REFS)+ return handle_update_refs(session, frame);+ wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,+ "unknown request");+ return true;+}++void run_session(net::Stream stream, std::optional<fs::path> fixed,+ std::optional<fs::path> root, std::string binding) {+ Session session;+ session.stream = std::move(stream);+ session.binding = std::move(binding);+ if (root)+ session.root = *root;+ if (fixed) {+ session.repo_root = *fixed;+ session.repo_present = true;+ session.access = auth::load_access(session.repo_root);+ if (session.access.valid)+ open_session_store(session);+ }+ while (!session.closing) {+ auto frame = wire::read_frame(session.stream);+ if (!frame)+ break;+ const bool keep = dispatch(session, *frame);+ if (!keep)+ break;+ }+ log_outcome(session, "close");+ session.stream.close();+}++std::optional<int> parse_port(std::string_view address) {+ const auto colon = address.rfind(':');+ if (colon == std::string_view::npos || colon + 1 >= address.size())+ return std::nullopt;+ int port = 0;+ for (char c : address.substr(colon + 1)) {+ if (c < '0' || c > '9')+ return std::nullopt;+ port = port * 10 + (c - '0');+ if (port > 65535)+ return std::nullopt;+ }+ return port;+}++} // namespace++int serve_stdio(const fs::path &repo) {+ run_session(net::Stream::stdio_stream(), repo, std::nullopt, {});+ return 0;+}++int serve_listen(std::string_view address, const fs::path &root,+ std::string_view cert_path, std::string_view key_path) {+ net::ignore_sigpipe();+ auto port = parse_port(address);+ if (!port) {+ error_prefix();+ std::cout << "invalid listen address\n";+ return 1;+ }+ void *ctx = net::tls_server_ctx(cert_path, key_path);+ if (!ctx) {+ error_prefix();+ std::cout << "cannot load TLS certificate or key\n";+ return 1;+ }+ const net::Socket listener = net::tcp_listen(*port);+ if (listener == net::INVALID_SOCKET_VALUE) {+ error_prefix();+ std::cout << "cannot listen on port " << *port << "\n";+ net::tls_ctx_free(ctx);+ return 1;+ }+ info_prefix();+ std::cout << "listening on " << address << "\n";+ for (;;) {+ auto accepted = net::tcp_accept(listener);+ if (!accepted)+ break;+ void *ssl = net::tls_accept(ctx, *accepted);+ if (!ssl) {+ net::close_socket(*accepted);+ continue;+ }+ std::array<std::uint8_t, 32> exported{};+ std::string binding;+ if (net::tls_exporter(ssl, exported.data(), exported.size())) {+ binding.assign(reinterpret_cast<const char *>(exported.data()),+ exported.size());+ }+ run_session(net::Stream::tls_stream(*accepted, ssl), std::nullopt, root,+ std::move(binding));+ }+ net::close_socket(listener);+ net::tls_ctx_free(ctx);+ return 0;+}++} // namespace vn::server--- /dev/null+++ b/xveins/src/server.h@@ -0,0 +1,13 @@+#pragma once++#include "common.h"++#include <string_view>++namespace vn::server {++int serve_stdio(const fs::path &repo);+int serve_listen(std::string_view address, const fs::path &root,+ std::string_view cert_path, std::string_view key_path);++} // namespace vn::server--- /dev/null+++ b/xveins/src/store.cpp@@ -0,0 +1,1939 @@+#include "store.h"++#include <algorithm>+#include <atomic>+#include <cstring>+#include <iostream>+#include <thread>+#include <unordered_set>++#include <zstd.h>++namespace vn {++namespace {+PromisorFetcher promisor_fetcher;+} // namespace++void set_promisor_fetcher(PromisorFetcher fetcher) {+ promisor_fetcher = std::move(fetcher);+}++// ---------------------------------------------------------------------------+// 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;+ store.root_ = 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;+ 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) {+ auto loc = find(id);+ if (!loc && expected == TYPE_CHUNK && promisor_fetcher && !root_.empty()) {+ if (promisor_fetcher(root_, id)) {+ refresh(root_);+ 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/xveins/src/store.h@@ -0,0 +1,241 @@+#pragma once++#include "object.h"++#include <functional>+#include <memory>+#include <optional>+#include <set>+#include <string>+#include <vector>++namespace vn {++// Called when a promised chunk is missing. Returns true when the object was+// fetched and written to a pack.+using PromisorFetcher = std::function<bool(const fs::path &, const Id &)>;+void set_promisor_fetcher(PromisorFetcher fetcher);++// ---------------------------------------------------------------------------+// 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_; }+ const fs::path &root() const { return root_; }+ void preload();++private:+ bool ensure_index(StoreHandle &handle);+ bool ensure_pack(StoreHandle &handle);+ fs::path root_;+ 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/xveins/src/wire.cpp@@ -0,0 +1,185 @@+#include "wire.h"++#include <zstd.h>++#include <array>+#include <cstring>++namespace vn::wire {++namespace {++bool read_exact(net::Stream &stream, std::uint8_t *out, std::size_t count) {+ std::size_t got = 0;+ while (got < count) {+ const std::int64_t n = stream.read(out + got, count - got);+ if (n <= 0)+ return false;+ got += static_cast<std::size_t>(n);+ }+ return true;+}++} // namespace++std::optional<Frame> read_frame(net::Stream &stream) {+ std::array<std::uint8_t, 4> head{};+ if (!read_exact(stream, head.data(), head.size()))+ return std::nullopt;+ const std::uint32_t length = (static_cast<std::uint32_t>(head[0]) << 24) |+ (static_cast<std::uint32_t>(head[1]) << 16) |+ (static_cast<std::uint32_t>(head[2]) << 8) |+ static_cast<std::uint32_t>(head[3]);+ if (length < 5 || length > MAX_FRAME)+ return std::nullopt;+ std::vector<std::uint8_t> body(length);+ if (!read_exact(stream, body.data(), body.size()))+ return std::nullopt;+ Frame frame;+ frame.kind = body[0];+ frame.request_id = (static_cast<std::uint32_t>(body[1]) << 24) |+ (static_cast<std::uint32_t>(body[2]) << 16) |+ (static_cast<std::uint32_t>(body[3]) << 8) |+ static_cast<std::uint32_t>(body[4]);+ frame.payload.assign(body.begin() + 5, body.end());+ return frame;+}++bool write_frame(net::Stream &stream, std::uint8_t kind,+ std::uint32_t request_id, Bytes payload) {+ if (payload.size() > MAX_FRAME - 5)+ return false;+ const std::uint32_t length = static_cast<std::uint32_t>(5 + payload.size());+ std::array<std::uint8_t, 9> head{};+ head[0] = static_cast<std::uint8_t>((length >> 24) & 255u);+ head[1] = static_cast<std::uint8_t>((length >> 16) & 255u);+ head[2] = static_cast<std::uint8_t>((length >> 8) & 255u);+ head[3] = static_cast<std::uint8_t>(length & 255u);+ head[4] = kind;+ head[5] = static_cast<std::uint8_t>((request_id >> 24) & 255u);+ head[6] = static_cast<std::uint8_t>((request_id >> 16) & 255u);+ head[7] = static_cast<std::uint8_t>((request_id >> 8) & 255u);+ head[8] = static_cast<std::uint8_t>(request_id & 255u);+ if (!stream.write_all(Bytes(head.data(), head.size())))+ return false;+ return payload.empty() || stream.write_all(payload);+}++bool write_simple(net::Stream &stream, std::uint8_t kind,+ std::uint32_t request_id) {+ return write_frame(stream, kind, request_id, Bytes{});+}++bool write_error(net::Stream &stream, std::uint32_t request_id,+ std::uint8_t code, std::string_view message) {+ ByteWriter writer(64);+ writer.u8(code);+ writer.length_prefixed(message);+ return write_frame(stream, ERROR, request_id, writer.view());+}++std::uint8_t read_error(Bytes payload) {+ if (payload.empty())+ return ERR_INTERNAL;+ return payload[0];+}++std::string error_message(Bytes payload) {+ if (payload.size() < 2)+ return {};+ Reader reader(payload.subspan(1));+ auto value = reader.bytes(4096);+ if (!value)+ return {};+ return std::string(str_of(*value));+}++std::string_view error_code_name(std::uint8_t code) {+ switch (code) {+ case ERR_UNSUPPORTED_VERSION:+ return "unsupported protocol version";+ case ERR_BAD_FRAME:+ return "bad frame";+ case ERR_NOT_FOUND:+ return "object not found";+ case ERR_HASH_MISMATCH:+ return "hash mismatch";+ case ERR_NON_CANONICAL:+ return "non-canonical object";+ case ERR_MISSING_CLOSURE:+ return "missing object closure";+ case ERR_REF_CONFLICT:+ return "ref conflict";+ case ERR_REJECTED:+ return "request rejected";+ case ERR_INTERNAL:+ return "server internal error";+ case ERR_UNAUTHENTICATED:+ return "authentication required";+ case ERR_FORBIDDEN:+ return "permission denied";+ case ERR_AUTH_FAILED:+ return "authentication failed";+ default:+ return "unknown server error";+ }+}++std::optional<IncomingRecord> parse_record(Bytes data) {+ if (data.size() < 35)+ return std::nullopt;+ Reader reader(data);+ const auto id = reader.id();+ if (!id)+ return std::nullopt;+ const auto kind = reader.u8();+ if (!kind)+ return std::nullopt;+ const auto compression = reader.u8();+ if (!compression)+ return std::nullopt;+ const auto raw_len = reader.varint();+ if (!raw_len)+ return std::nullopt;+ const auto stored_len = reader.varint();+ if (!stored_len)+ return std::nullopt;+ if (*raw_len == 0 || *raw_len > 64u * 1024u * 1024u ||+ *stored_len > MAX_FRAME)+ return std::nullopt;+ const auto stored = reader.raw(static_cast<std::size_t>(*stored_len));+ if (!stored)+ return std::nullopt;+ if (!reader.at_end())+ return std::nullopt;+ IncomingRecord record;+ record.id = *id;+ record.kind = *kind;+ if (*compression == 0) {+ if (stored->size() != static_cast<std::size_t>(*raw_len))+ return std::nullopt;+ record.body.assign(stored->begin(), stored->end());+ return record;+ }+ record.body.resize(static_cast<std::size_t>(*raw_len));+ const std::size_t result =+ ZSTD_decompress(record.body.data(), record.body.size(), stored->data(),+ stored->size());+ if (ZSTD_isError(result) || result != record.body.size())+ return std::nullopt;+ return record;+}++std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,+ Bytes body) {+ ByteWriter writer(body.size() + 64);+ writer.raw(Bytes(id.data(), id.size()));+ writer.u8(kind);+ writer.u8(0);+ writer.varint(body.size());+ writer.varint(body.size());+ writer.raw(body);+ return writer.take();+}++} // namespace vn::wire--- /dev/null+++ b/xveins/src/wire.h@@ -0,0 +1,80 @@+#pragma once++#include "net.h"++#include <cstdint>+#include <optional>+#include <string>+#include <vector>++namespace vn::wire {++constexpr std::size_t MAX_FRAME = 16u * 1024u * 1024u;++enum Kind : std::uint8_t {+ HELLO = 1,+ HELLO_OK = 2,+ AUTH = 3,+ AUTH_OK = 4,+ WHOAMI = 5,+ WHOAMI_OK = 6,+ LIST_REFS = 7,+ REFS = 8,+ NEGOTIATE = 9,+ NEGOTIATE_OK = 10,+ FETCH_SKELETON = 11,+ GET_CHUNKS = 12,+ HAVE_QUERY = 13,+ HAVE_BITMAP = 14,+ PUT_RECORDS = 15,+ UPDATE_REFS = 16,+ UPDATE_REFS_OK = 17,+ RECORDS = 18,+ END = 19,+ ERROR = 20,+};++enum ErrorCode : std::uint8_t {+ ERR_UNSUPPORTED_VERSION = 1,+ ERR_BAD_FRAME = 2,+ ERR_NOT_FOUND = 3,+ ERR_HASH_MISMATCH = 4,+ ERR_NON_CANONICAL = 5,+ ERR_MISSING_CLOSURE = 6,+ ERR_REF_CONFLICT = 7,+ ERR_REJECTED = 8,+ ERR_INTERNAL = 9,+ ERR_UNAUTHENTICATED = 10,+ ERR_FORBIDDEN = 11,+ ERR_AUTH_FAILED = 12,+};++struct Frame {+ std::uint8_t kind = 0;+ std::uint32_t request_id = 0;+ std::vector<std::uint8_t> payload;+};++std::optional<Frame> read_frame(net::Stream &stream);+bool write_frame(net::Stream &stream, std::uint8_t kind,+ std::uint32_t request_id, Bytes payload);+bool write_simple(net::Stream &stream, std::uint8_t kind,+ std::uint32_t request_id);+bool write_error(net::Stream &stream, std::uint32_t request_id,+ std::uint8_t code, std::string_view message);++std::uint8_t read_error(Bytes payload);+std::string error_message(Bytes payload);+std::string_view error_code_name(std::uint8_t code);++// Encode/decode the record layout shared by packs and RECORDS frames.+struct IncomingRecord {+ Id id{};+ std::uint8_t kind = 0;+ std::vector<std::uint8_t> body;+};+std::optional<IncomingRecord> parse_record(Bytes data);+std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,+ Bytes body);++} // namespace vn::wire--- /dev/null+++ b/xveins/src/worktree.cpp@@ -0,0 +1,990 @@+#include "worktree.h"++#include "merge.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;+ if (old_tree &&+ std::memcmp(old_tree->data(), new_root->data(), ID_LEN) != 0) {+ auto detected = detect_renames(+ tx->store(), &*tx, old_tree, std::optional<Id>{*new_root},+ rename_similar_pct(root), 0);+ for (auto &rename : detected)+ renames.push_back(std::move(rename));+ }+ std::stable_sort(renames.begin(), renames.end(),+ [](const Rename &a, const Rename &b) {+ if (a.parent_index != b.parent_index)+ return a.parent_index < b.parent_index;+ return compare(bytes_of(a.to_path), bytes_of(b.to_path)) <+ 0;+ });++ 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_materialize_optional(const fs::path &root, Store &store,+ std::optional<Id> old_root,+ std::optional<Id> new_root) {+ if (new_root)+ return checkout_materialize_commit(root, store, old_root, *new_root);+ const auto old_entries = flatten_or_empty(store, old_root);+ if (old_entries.empty()) {+ clear_stat_cache(root);+ return 0;+ }+ if (!delete_stale(store, root, old_entries, {})) {+ error_prefix();+ std::cout << "cannot remove files absent from the restored view\n";+ return 1;+ }+ clear_stat_cache(root);+ return 0;+}++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/xveins/src/worktree.h@@ -0,0 +1,21 @@+#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);+int checkout_materialize_optional(const fs::path &root, Store &store,+ std::optional<Id> old_root,+ std::optional<Id> new_root);+void clear_stat_cache(const fs::path &root);++} // namespace vn