navid/veins / commit

46f2c49a7517

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

parents: 206319a7536d

Browse files at this commit · Download source

all: add materialize subcommand to alternate implementation
--- a/xveins/CMakeLists.txt+++ b/xveins/CMakeLists.txt@@ -47,6 +47,7 @@     endif() endif() find_package(OpenSSL REQUIRED)+find_package(ZLIB REQUIRED)  # --------------------------------------------------------------------------- # zstd: prefer an installed package, otherwise a system library, otherwise@@ -143,6 +144,8 @@     src/server.cpp     src/promisor.cpp     src/net_commands.cpp+    src/git_object.cpp+    src/git.cpp )  target_include_directories(vn PRIVATE src)@@ -151,6 +154,7 @@     ${VN_ZSTD_TARGET}     OpenSSL::SSL     OpenSSL::Crypto+    ZLIB::ZLIB     Threads::Threads ) if(WIN32)--- a/xveins/src/cli.cpp+++ b/xveins/src/cli.cpp@@ -1,5 +1,6 @@ #include "cli.h" +#include "git.h" #include "local_commands.h" #include "merge.h" #include "net_commands.h"@@ -474,9 +475,20 @@   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;+    const int prepared = git_prepare_mirror(*initialized, *source);+    if (prepared != 0) {+      error_prefix();+      if (prepared == 2) {+        std::cout << "-git-import: " << *source+                  << " is not a git repository root (expected the directory "+                     "containing .git)\n";+      } else {+        std::cout << "cannot prepare git mirror from " << *source << " (code "+                  << prepared << ")\n";+      }+      return 1;+    }+    return git_import(*initialized);   }   return 0; }@@ -2146,6 +2158,35 @@   std::cout << "and $OUTPUT in the command.\n"; } +void show_git() {+  std::cout << "usage: vn git <subcommand> [arguments]\n\n";+  std::cout << "git bridge commands:\n";+  std::cout << "  import [-source:<gitdir>] [path]\n";+  std::cout << "                            import reachable git commits and refs\n";+  std::cout << "  export [path]             export commits into the git mirror\n";+  std::cout << "  fetch [<remote>] [path]   git fetch into the mirror, then import\n";+  std::cout << "  push [<remote>] <bookmark> [path]\n";+  std::cout << "                            export and git push a bookmark\n";+  std::cout << "  remote <add|list|remove>  manage git remotes\n\n";+  std::cout << "run 'vn help git <subcommand>' for details\n";+}++void show_git_import() {+  std::cout << "usage: vn git import [-source:<gitdir>] [path]\n\n";+  std::cout << "import commits and refs reachable from a git repository\n\n";+  std::cout << "an empty working tree is checked out to the imported head\n\n";+  std::cout << "arguments:\n";+  std::cout << "  [path]                    veins repository (default: .)\n\n";+  std::cout << "options:\n";+  std::cout << "  -source:<gitdir>          source git root to mirror (a directory "+               "containing .git)\n";+}++void show_git_export() {+  std::cout << "usage: vn git export [path]\n\n";+  std::cout << "export commits reachable from bookmarks and tags into .veins/git\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";@@ -2213,7 +2254,28 @@   else if (cmd == "help")     show_help();   else if (net_help(cmd)) {-  } else if (cmd == "git" || cmd == "bench-import")+  } else if (cmd == "git") {+    if (args.size() > 3) {+      const std::string &sub = args[3];+      if (sub == "import")+        show_git_import();+      else if (sub == "export")+        show_git_export();+      else if (sub == "fetch")+        std::cout << "usage: vn git fetch [<remote>] [path]\n";+      else if (sub == "push")+        std::cout << "usage: vn git push [<remote>] <bookmark> [path]\n";+      else if (sub == "remote")+        std::cout << "usage: vn git remote <add|list|remove> ...\n";+      else {+        error_prefix();+        std::cout << "unknown git subcommand: " << sub << "\n";+        return 1;+      }+    } else {+      show_git();+    }+  } else if (cmd == "bench-import")     show_unimplemented(cmd);   else {     usage();@@ -2309,7 +2371,9 @@   if (cmd == "whoami")     return whoami_run(args); -  if (cmd == "git" || cmd == "bench-import") {+  if (cmd == "git")+    return git_cli_run(args);+  if (cmd == "bench-import") {     error_prefix();     std::cout << "command '" << cmd << "' is not available in this stage\n";     return 1;--- /dev/null+++ b/xveins/src/git.cpp@@ -0,0 +1,1181 @@+#include "git.h"++#include "git_internal.h"++#include "worktree.h"++#include <algorithm>+#include <cstdlib>+#include <iostream>+#include <map>+#include <set>+#include <string_view>++#if !defined(_WIN32)+#include <sys/wait.h>+#endif++namespace vn {++namespace {++using git::IdMap;+using git::Kind;+using git::Oid;+using git::OidLess;+using git::ParsedCommit;++struct OidHash {+  std::size_t operator()(const Oid &oid) const {+    std::size_t h = 1469598103934665603ull;+    for (auto b : oid) {+      h ^= b;+      h *= 1099511628211ull;+    }+    return h;+  }+};++struct NamedTarget {+  std::string name;+  Oid oid{};+};++struct CommitRecord {+  Oid oid{};+  std::vector<std::uint8_t> body;+  ParsedCommit parsed;+};++bool working_tree_empty(const fs::path &root) {+  for (const auto &name : list_directory(root)) {+    if (name != ".veins")+      return false;+  }+  return true;+}++ChangeId derive_change_id(const Oid &oid) {+  std::string input = "veins/change";+  input.append(reinterpret_cast<const char *>(oid.data()), oid.size());+  const auto hash = blake3_hash(bytes_of(input));+  ChangeId out{};+  std::memcpy(out.data(), hash.data(), out.size());+  return out;+}++std::optional<Oid> peel_to_commit(git::Repo &repo, const Oid &start) {+  Oid current = start;+  for (std::size_t i = 0; i < 4096; ++i) {+    auto object = git::read_object(repo, current);+    if (!object)+      return std::nullopt;+    if (object->kind == git::KIND_COMMIT)+      return current;+    if (object->kind != git::KIND_TAG)+      return std::nullopt;+    auto tag = git::parse_tag(Bytes(object->body.data(), object->body.size()));+    if (!tag)+      return std::nullopt;+    current = tag->target;+  }+  return std::nullopt;+}++void set_bookmark(View &view, std::string_view name, const Id &id) {+  for (auto &bookmark : view.bookmarks) {+    if (bookmark.name == name) {+      bookmark.targets.adds = {id};+      bookmark.targets.removes.clear();+      return;+    }+  }+  Bookmark bookmark;+  bookmark.name = std::string(name);+  bookmark.targets.adds = {id};+  view.bookmarks.push_back(std::move(bookmark));+}++void set_tag(View &view, std::string_view name, const Id &id) {+  for (auto &tag : view.tags) {+    if (tag.name == name) {+      tag.target = id;+      return;+    }+  }+  view.tags.push_back(TagRef{std::string(name), id});+}++void set_remote_ref(View &view, std::string_view remote, std::string_view name,+                    const Id &id) {+  for (auto &ref : view.remote_refs) {+    if (ref.remote == remote && ref.name == name) {+      ref.target = id;+      return;+    }+  }+  view.remote_refs.push_back(+      RemoteRef{std::string(remote), std::string(name), id});+}++std::pair<std::string, std::string> split_remote(std::string_view full) {+  const std::size_t slash = full.find('/');+  if (slash == std::string_view::npos)+    return {std::string(full), "main"};+  return {std::string(full.substr(0, slash)),+          std::string(full.substr(slash + 1))};+}++int create_working_copy(const fs::path &root, const Id &parent) {+  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 loaded = load_commit(tx->store(), parent);+  if (!loaded) {+    error_prefix();+    std::cout << "cannot read imported commit\n";+    return 1;+  }+  Commit commit;+  commit.version = 1;+  commit.parents = {parent};+  commit.root_tree = loaded->commit.root_tree;+  commit.change_id = random_change_id();+  commit.author = identity_signature(root);+  commit.committer = commit.author;+  commit.renames_state = RENAMES_RECORDED;+  const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));+  remove_head(tx->view(), parent);+  set_workspace(tx->view(), new_id);+  rebuild_heads(tx->view());+  auto status = tx->finish("import");+  if (!status)+    return 1;+  store.refresh(root);+  return 0;+}++int materialize_working_copy(const fs::path &root, Store &store) {+  store.refresh(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)+    return 0;+  auto body = store.read_body(*wc, TYPE_COMMIT);+  if (!body)+    return 1;+  auto commit = decode_commit(bytes_of(*body));+  if (!commit)+    return 1;+  return checkout_materialize_commit(root, store, std::nullopt,+                                     commit->root_tree);+}++std::vector<Id> ordered_commits(Store &store,+                                const std::vector<Id> &roots) {+  struct Mark {+    Id id{};+    bool expanded = false;+  };+  std::vector<Mark> stack;+  for (const auto &id : roots)+    stack.push_back(Mark{id, false});+  std::set<Id> visited;+  std::vector<Id> ordered;+  while (!stack.empty()) {+    Mark mark = stack.back();+    stack.pop_back();+    if (visited.count(mark.id))+      continue;+    if (!mark.expanded) {+      mark.expanded = true;+      stack.push_back(mark);+      if (auto loaded = load_commit(store, mark.id)) {+        for (auto it = loaded->commit.parents.rbegin();+             it != loaded->commit.parents.rend(); ++it) {+          if (!visited.count(*it))+            stack.push_back(Mark{*it, false});+        }+      }+    } else {+      visited.insert(mark.id);+      ordered.push_back(mark.id);+    }+  }+  return ordered;+}++std::optional<Id> exportable_target(Store &store, const Id &start) {+  Id current = start;+  for (std::size_t steps = 0; steps < 100000; ++steps) {+    auto loaded = load_commit(store, current);+    if (!loaded)+      return std::nullopt;+    if (!tree_conflicted(store, loaded->commit.root_tree))+      return current;+    if (loaded->commit.parents.empty())+      return std::nullopt;+    current = loaded->commit.parents.front();+  }+  return std::nullopt;+}++std::string shell_quote(std::string_view value) {+  std::string out;+  out.push_back('\'');+  for (char c : value) {+    if (c == '\'')+      out += "'\\''";+    else+      out.push_back(c);+  }+  out.push_back('\'');+  return out;+}++int run_git(const fs::path &dir, const std::vector<std::string> &args) {+  std::string command = "git -C ";+  command += shell_quote(path_to_bytes(dir));+  for (const auto &arg : args) {+    command.push_back(' ');+    command += shell_quote(arg);+  }+  const int rc = std::system(command.c_str());+  if (rc == -1)+    return -1;+#if !defined(_WIN32)+  if (WIFEXITED(rc))+    return WEXITSTATUS(rc);+  return 1;+#else+  return rc;+#endif+}++bool configure_mirror(const fs::path &root, std::string_view remote,+                      std::string_view url) {+  const fs::path dir = git_dir(root);+  if (!path_is_dir(dir))+    return false;+  (void)run_git(dir, {"remote", "remove", std::string(remote)});+  return run_git(dir, {"remote", "add", std::string(remote), std::string(url)}) ==+         0;+}++void add_unique(std::vector<Id> &ids, const Id &id) {+  if (!contains_id(ids, id))+    ids.push_back(id);+}++int import_tree_impl(+    Writer &writer, git::Repo &repo, IdMap &trees, IdMap &blobs, const Oid &oid,+    std::vector<std::pair<Id, std::vector<std::uint8_t>>> &raw_saves,+    std::size_t &new_trees, std::size_t &new_blobs, std::size_t depth) {+  if (depth > 4096)+    return 1;+  if (auto existing = trees.get(oid)) {+    (void)existing;+    return 0;+  }+  auto object = git::read_object(repo, oid);+  if (!object || object->kind != git::KIND_TREE)+    return 1;+  auto parsed = git::parse_tree(Bytes(object->body.data(), object->body.size()));+  if (!parsed)+    return 1;+  std::stable_sort(parsed->entries.begin(), parsed->entries.end(),+                   [](const git::RawTreeEntry &a,+                      const git::RawTreeEntry &b) {+                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+                   });+  std::vector<TreeEntry> entries;+  entries.reserve(parsed->entries.size());+  for (const auto &raw : parsed->entries) {+    const std::uint8_t kind = git::mode_kind(raw.mode);+    Id target{};+    if (kind == KIND_SUBTREE) {+      if (import_tree_impl(writer, repo, trees, blobs, raw.oid, raw_saves,+                           new_trees, new_blobs, depth + 1) != 0)+        return 1;+      auto child = trees.get(raw.oid);+      if (!child)+        return 1;+      target = *child;+    } else if (kind == KIND_SUBMODULE) {+      std::memcpy(target.data(), raw.oid.data(), 20);+    } else {+      auto existing = blobs.get(raw.oid);+      if (existing) {+        target = *existing;+      } else {+        target = git::lazy_blob_id(raw.oid);+        blobs.put(raw.oid, target);+        ++new_blobs;+      }+    }+    entries.push_back(TreeEntry{raw.name, kind, target});+  }+  auto body = encode_tree(entries);+  if (!body)+    return 1;+  const Id id = writer.add(TYPE_TREE, *body);+  trees.put(oid, id);+  ++new_trees;+  if (!parsed->canonical)+    raw_saves.emplace_back(id, object->body);+  return 0;+}++} // namespace++namespace git {++std::optional<Id> import_tree(+    Writer &writer, Repo &repo, IdMap &trees, IdMap &blobs, const Oid &oid,+    std::vector<std::pair<Id, std::vector<std::uint8_t>>> &raw_saves,+    std::size_t &new_trees, std::size_t &new_blobs, std::size_t depth) {+  if (import_tree_impl(writer, repo, trees, blobs, oid, raw_saves, new_trees,+                       new_blobs, depth) != 0)+    return std::nullopt;+  return trees.get(oid);+}++bool export_tree(const fs::path &root, Store &store, IdMap &trees,+                 IdMap &blobs, const Id &id, Oid &out, std::size_t depth) {+  if (depth > 4096)+    return false;+  if (auto existing = trees.reverse(id)) {+    out = *existing;+    return true;+  }+  const fs::path mirror = git_dir(root);+  if (auto raw = load_raw(root, id)) {+    auto oid = object_hash(git::KIND_TREE, Bytes(raw->data(), raw->size()));+    if (!oid || !write_loose(mirror, git::KIND_TREE, *oid,+                             Bytes(raw->data(), raw->size())))+      return false;+    trees.put(*oid, id);+    out = *oid;+    return true;+  }+  auto body = store.read_body(id, TYPE_TREE);+  if (!body)+    return false;+  auto tree = decode_tree(bytes_of(*body));+  if (!tree)+    return false;++  struct GitEntry {+    std::string mode;+    std::string name;+    Oid oid{};+    bool dir = false;+  };+  std::vector<GitEntry> entries;+  entries.reserve(tree->entries.size());+  for (const auto &entry : tree->entries) {+    GitEntry out_entry;+    out_entry.name = entry.name;+    out_entry.mode = mode_for_kind(entry.kind);+    out_entry.dir = entry.kind == KIND_SUBTREE;+    if (entry.kind == KIND_SUBTREE) {+      if (!export_tree(root, store, trees, blobs, entry.target, out_entry.oid,+                       depth + 1))+        return false;+    } else if (entry.kind == KIND_SUBMODULE) {+      std::memcpy(out_entry.oid.data(), entry.target.data(), 20);+    } else if (entry.kind == KIND_CONFLICT) {+      return false;+    } else {+      Oid oid{};+      if (auto lazy = lazy_blob_oid(entry.target)) {+        oid = *lazy;+        blobs.put(oid, entry.target);+      } else if (auto existing = blobs.reverse(entry.target)) {+        oid = *existing;+      } else {+        auto data = read_blob(store, entry.target);+        if (!data)+          return false;+        auto hash = object_hash(git::KIND_BLOB,+                                Bytes(data->data(), data->size()));+        if (!hash || !write_loose(mirror, git::KIND_BLOB, *hash,+                                  Bytes(data->data(), data->size())))+          return false;+        oid = *hash;+        blobs.put(oid, entry.target);+      }+      out_entry.oid = oid;+    }+    entries.push_back(std::move(out_entry));+  }+  std::stable_sort(entries.begin(), entries.end(),+                   [](const GitEntry &a, const GitEntry &b) {+                     std::string ak = a.name;+                     std::string bk = b.name;+                     if (a.dir)+                       ak.push_back('/');+                     if (b.dir)+                       bk.push_back('/');+                     return compare(bytes_of(ak), bytes_of(bk)) < 0;+                   });+  std::vector<std::uint8_t> git_body;+  for (const auto &entry : entries) {+    git_body.insert(git_body.end(), entry.mode.begin(), entry.mode.end());+    git_body.push_back(' ');+    git_body.insert(git_body.end(), entry.name.begin(), entry.name.end());+    git_body.push_back(0);+    git_body.insert(git_body.end(), entry.oid.begin(), entry.oid.end());+  }+  auto oid = object_hash(git::KIND_TREE, Bytes(git_body.data(), git_body.size()));+  if (!oid ||+      !write_loose(mirror, git::KIND_TREE, *oid,+                   Bytes(git_body.data(), git_body.size())))+    return false;+  trees.put(*oid, id);+  out = *oid;+  return true;+}++bool export_commit(const fs::path &root, Store &store, IdMap &commits,+                   IdMap &trees, IdMap &blobs,+                   const std::vector<Id> &native, const Id &id, Oid &out,+                   std::size_t depth) {+  if (depth > 4096)+    return false;+  if (auto existing = commits.reverse(id)) {+    out = *existing;+    return true;+  }+  auto loaded = load_commit(store, id);+  if (!loaded)+    return false;+  Oid tree_oid{};+  if (!export_tree(root, store, trees, blobs, loaded->commit.root_tree,+                   tree_oid, 0))+    return false;+  std::vector<Oid> parents;+  for (const auto &parent : loaded->commit.parents) {+    auto oid = commits.reverse(parent);+    if (!oid)+      return false;+    parents.push_back(*oid);+  }+  const fs::path mirror = git_dir(root);++  std::vector<std::uint8_t> body;+  bool used_raw = false;+  if (auto raw = load_raw(root, id)) {+    if (auto parsed =+            parse_commit(Bytes(raw->data(), raw->size()))) {+      bool matches = std::memcmp(parsed->tree.data(), tree_oid.data(),+                                 tree_oid.size()) == 0 &&+                     parsed->parents.size() == parents.size();+      for (std::size_t i = 0; matches && i < parents.size(); ++i)+        matches = std::memcmp(parsed->parents[i].data(), parents[i].data(),+                              parents[i].size()) == 0;+      if (matches) {+        body = *raw;+        used_raw = true;+      }+    }+  }+  if (!used_raw) {+    ParsedCommit parsed;+    parsed.tree = tree_oid;+    parsed.parents = parents;+    parsed.author = loaded->commit.author;+    parsed.committer = loaded->commit.committer;+    parsed.message = loaded->commit.message;+    parsed.extras = loaded->commit.extra;+    if (is_native(native, id)) {+      parsed.extras.push_back(KeyValue{+          "veins-change-id",+          hex_encode(Bytes(loaded->commit.change_id.data(),+                           loaded->commit.change_id.size()))});+    }+    body = serialize_commit(parsed);+  }+  auto oid = object_hash(git::KIND_COMMIT, Bytes(body.data(), body.size()));+  if (!oid || !write_loose(mirror, git::KIND_COMMIT, *oid,+                           Bytes(body.data(), body.size())))+    return false;+  commits.put(*oid, id);+  out = *oid;+  return true;+}++} // namespace git++int git_import(const fs::path &root) {+  const bool checkout_after = working_tree_empty(root);+  const bool view_from_store = !read_heads(root).empty();+  const fs::path mirror = git_dir(root);+  auto repo = git::open_repo(mirror);+  if (!repo) {+    error_prefix();+    std::cout << "cannot open git mirror: " << path_display(mirror) << "\n";+    return 1;+  }+  IdMap commits_map;+  IdMap trees_map;+  IdMap blobs_map;+  if (!git::load_map(root, "commits", commits_map) ||+      !git::load_map(root, "trees", trees_map) ||+      !git::load_map(root, "blobs", blobs_map)) {+    error_prefix();+    std::cout << "corrupt git mapping table\n";+    return 1;+  }++  const auto refset = git::read_refs(mirror);+  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;+  }+  View before = tx->view();+  Writer &writer = tx->writer();+  std::vector<std::pair<Id, std::vector<std::uint8_t>>> raw_saves;+  std::size_t new_commits = 0;+  std::size_t new_trees = 0;+  std::size_t new_blobs = 0;++  std::vector<NamedTarget> branches;+  std::vector<NamedTarget> tags;+  std::vector<NamedTarget> remotes;+  std::vector<Oid> tips;+  for (const auto &ref : refset.branches) {+    auto peeled = peel_to_commit(*repo, ref.oid);+    if (peeled) {+      branches.push_back(NamedTarget{ref.name, *peeled});+      tips.push_back(*peeled);+    }+  }+  for (const auto &ref : refset.tags) {+    auto peeled = peel_to_commit(*repo, ref.oid);+    if (peeled) {+      tags.push_back(NamedTarget{ref.name, *peeled});+      tips.push_back(*peeled);+    }+  }+  for (const auto &ref : refset.remotes) {+    auto peeled = peel_to_commit(*repo, ref.oid);+    if (peeled) {+      remotes.push_back(NamedTarget{ref.name, *peeled});+      tips.push_back(*peeled);+    }+  }+  std::optional<Oid> head_commit;+  if (refset.head) {+    head_commit = peel_to_commit(*repo, *refset.head);+    if (head_commit)+      tips.push_back(*head_commit);+  }++  std::vector<CommitRecord> records;+  std::set<Oid, OidLess> seen;+  std::vector<Oid> stack(tips.rbegin(), tips.rend());+  while (!stack.empty()) {+    const Oid oid = stack.back();+    stack.pop_back();+    if (commits_map.get(oid) || seen.count(oid))+      continue;+    seen.insert(oid);+    auto object = git::read_object(*repo, oid);+    if (!object)+      continue;+    if (object->kind != git::KIND_COMMIT)+      continue;+    auto parsed =+        git::parse_commit(Bytes(object->body.data(), object->body.size()));+    if (!parsed)+      continue;+    records.push_back(CommitRecord{oid, std::move(object->body),+                                   std::move(*parsed)});+    for (const auto &parent : records.back().parsed.parents)+      stack.push_back(parent);+  }++  const std::size_t n = records.size();+  std::map<Oid, std::size_t, OidLess> index;+  for (std::size_t i = 0; i < n; ++i)+    index[records[i].oid] = i;+  std::vector<std::size_t> indegree(n, 0);+  std::vector<std::vector<std::size_t>> children(n);+  bool topo_failed = false;+  for (std::size_t i = 0; i < n; ++i) {+    for (const auto &parent : records[i].parsed.parents) {+      if (commits_map.get(parent))+        continue;+      auto it = index.find(parent);+      if (it == index.end()) {+        topo_failed = true;+        continue;+      }+      ++indegree[i];+      children[it->second].push_back(i);+    }+  }+  std::vector<std::size_t> queue;+  for (std::size_t i = 0; i < n; ++i) {+    if (indegree[i] == 0)+      queue.push_back(i);+  }+  std::vector<std::size_t> order;+  for (std::size_t head = 0; head < queue.size(); ++head) {+    const std::size_t current = queue[head];+    order.push_back(current);+    for (std::size_t child : children[current]) {+      if (indegree[child] > 0 && --indegree[child] == 0)+        queue.push_back(child);+    }+  }+  if (topo_failed || order.size() != n) {+    error_prefix();+    std::cout << "git commit graph is incomplete or cyclic\n";+    return 1;+  }++  bool build_failed = false;+  for (std::size_t idx : order) {+    auto imported = git::import_tree(writer, *repo, trees_map, blobs_map,+                                     records[idx].parsed.tree, raw_saves,+                                     new_trees, new_blobs);+    if (!imported) {+      build_failed = true;+      break;+    }+  }+  if (!build_failed) {+    for (std::size_t idx : order) {+      const auto &record = records[idx];+      auto tree = trees_map.get(record.parsed.tree);+      if (!tree) {+        build_failed = true;+        break;+      }+      Commit commit;+      commit.version = 1;+      for (const auto &parent : record.parsed.parents) {+        auto mapped = commits_map.get(parent);+        if (!mapped) {+          build_failed = true;+          break;+        }+        commit.parents.push_back(*mapped);+      }+      if (build_failed)+        break;+      commit.root_tree = *tree;+      commit.change_id = record.parsed.change_id+                             ? *record.parsed.change_id+                             : derive_change_id(record.oid);+      commit.author = record.parsed.author;+      commit.committer = record.parsed.committer;+      commit.message = record.parsed.message;+      commit.renames_state = RENAMES_UNKNOWN;+      commit.extra = record.parsed.extras;+      const Id id = writer.add(TYPE_COMMIT, encode_commit(commit));+      commits_map.put(record.oid, id);+      ++new_commits;+      const auto canonical = git::serialize_commit(record.parsed);+      const bool is_canonical =+          record.parsed.canonical &&+          equals(Bytes(canonical.data(), canonical.size()),+                 Bytes(record.body.data(), record.body.size()));+      if (!is_canonical)+        raw_saves.emplace_back(id, record.body);+    }+  }+  if (build_failed) {+    error_prefix();+    std::cout << "referenced git object is missing\n";+    return 1;+  }++  View &view = tx->view();+  for (const auto &branch : branches) {+    if (auto id = commits_map.get(branch.oid))+      set_bookmark(view, branch.name, *id);+  }+  for (const auto &tag : tags) {+    if (auto id = commits_map.get(tag.oid))+      set_tag(view, tag.name, *id);+  }+  for (const auto &remote : remotes) {+    if (auto id = commits_map.get(remote.oid)) {+      const auto parts = split_remote(remote.name);+      set_remote_ref(view, parts.first, parts.second, *id);+      if (!find_bookmark(view, parts.second))+        set_bookmark(view, parts.second, *id);+    }+  }++  view.heads.clear();+  for (const auto &branch : branches) {+    if (auto id = commits_map.get(branch.oid))+      add_unique(view.heads, *id);+  }+  for (const auto &remote : remotes) {+    if (auto id = commits_map.get(remote.oid))+      add_unique(view.heads, *id);+  }+  if (view.heads.empty()) {+    for (const auto &tag : tags) {+      if (auto id = commits_map.get(tag.oid))+        add_unique(view.heads, *id);+    }+  }+  std::optional<Id> head_id;+  if (head_commit) {+    if (auto id = commits_map.get(*head_commit))+      head_id = *id;+  }+  if (view.heads.empty() && head_id)+    add_unique(view.heads, *head_id);+  sort_ids(view.heads);+  if (checkout_after || !view_from_store) {+    if (head_id)+      set_workspace(view, *head_id);+    else if (!view.heads.empty())+      set_workspace(view, view.heads.front());+  }++  const auto old_encoded = encode_view(before);+  const auto new_encoded = encode_view(view);+  const bool unchanged = equals(bytes_of(old_encoded), bytes_of(new_encoded));+  const bool has_new_objects =+      new_commits > 0 || new_trees > 0 || new_blobs > 0;+  if (unchanged && !has_new_objects) {+    info_prefix();+    std::cout << "already up to date\n";+    return 0;+  }+  auto status = tx->finish("git import");+  if (!status) {+    error_prefix();+    std::cout << "failed to write object pack\n";+    return 1;+  }+  for (const auto &raw : raw_saves)+    (void)git::save_raw(root, raw.first,+                        Bytes(raw.second.data(), raw.second.size()));+  if (!git::save_map(root, "commits", commits_map) ||+      !git::save_map(root, "trees", trees_map) ||+      !git::save_map(root, "blobs", blobs_map)) {+    error_prefix();+    std::cout << "failed to write git mapping tables\n";+  }+  info_prefix();+  std::cout << "imported " << new_commits << " commits, " << new_trees+            << " trees, " << new_blobs << " blobs\n";++  if (checkout_after && head_id) {+    const int wc_status = create_working_copy(root, *head_id);+    if (wc_status != 0) {+      error_prefix();+      std::cout << "imported history; cannot create working copy (code "+                << wc_status << ")\n";+      return 1;+    }+    const int checkout_status = materialize_working_copy(root, store);+    if (checkout_status != 0) {+      error_prefix();+      std::cout << "imported history; checkout failed (code "+                << checkout_status << ")\n";+      return 1;+    }+  }+  return 0;+}++int git_export(const fs::path &root) {+  if (!git::ensure_mirror(root)) {+    error_prefix();+    std::cout << "cannot create git mirror\n";+    return 1;+  }+  IdMap commits;+  IdMap trees;+  IdMap blobs;+  (void)git::load_map(root, "commits", commits);+  (void)git::load_map(root, "trees", trees);+  (void)git::load_map(root, "blobs", blobs);+  const auto native = load_native(root);+  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<Id> roots;+  struct ResolvedBookmark {+    Bookmark bookmark;+  };+  std::vector<ResolvedBookmark> resolved_bookmarks;+  struct ResolvedTag {+    TagRef tag;+  };+  std::vector<ResolvedTag> resolved_tags;+  std::size_t skipped = 0;+  for (const auto &bookmark : view->bookmarks) {+    if (bookmark.targets.adds.empty() || !bookmark.targets.adds.front())+      continue;+    auto target = exportable_target(store, *bookmark.targets.adds.front());+    if (!target) {+      ++skipped;+      continue;+    }+    add_unique(roots, *target);+    Bookmark resolved;+    resolved.name = bookmark.name;+    resolved.targets.adds = {*target};+    resolved_bookmarks.push_back(ResolvedBookmark{std::move(resolved)});+  }+  for (const auto &tag : view->tags) {+    auto target = exportable_target(store, tag.target);+    if (!target) {+      ++skipped;+      continue;+    }+    add_unique(roots, *target);+    resolved_tags.push_back(ResolvedTag{TagRef{tag.name, *target}});+  }++  const auto ordered = ordered_commits(store, roots);+  std::size_t exported = 0;+  bool failed = false;+  for (const auto &id : ordered) {+    if (commits.reverse(id))+      continue;+    Oid oid{};+    if (!git::export_commit(root, store, commits, trees, blobs, native, id,+                            oid)) {+      failed = true;+      break;+    }+    ++exported;+  }+  int status = 0;+  if (failed) {+    error_prefix();+    std::cout << "git export failed\n";+    status = 1;+  } else {+    for (const auto &item : resolved_bookmarks) {+      if (item.bookmark.targets.adds.empty())+        continue;+      auto oid = commits.reverse(*item.bookmark.targets.adds.front());+      if (oid &&+          !git::write_ref(git_dir(root), "refs/heads/" + item.bookmark.name,+                          *oid))+        status = 1;+    }+    for (const auto &item : resolved_tags) {+      auto oid = commits.reverse(item.tag.target);+      if (oid &&+          !git::write_ref(git_dir(root), "refs/tags/" + item.tag.name, *oid))+        status = 1;+    }+    if (skipped > 0) {+      warning_prefix();+      std::cout << "skipped " << skipped << " conflicted ref(s)\n";+    }+  }+  if (status == 0) {+    if (!git::save_map(root, "commits", commits) ||+        !git::save_map(root, "trees", trees) ||+        !git::save_map(root, "blobs", blobs)) {+      error_prefix();+      std::cout << "failed to write git mapping tables\n";+      status = 1;+    }+  }+  info_prefix();+  std::cout << "exported " << exported << " commits\n";+  return status;+}++int git_fetch(const fs::path &root, std::string_view remote) {+  const auto url = repo_config_value(root, git::remote_key(remote, "url"));+  if (!url) {+    error_prefix();+    std::cout << "unknown remote: " << remote << "\n";+    return 1;+  }+  if (!configure_mirror(root, remote, *url)) {+    error_prefix();+    std::cout << "cannot configure git mirror\n";+    return 1;+  }+  if (run_git(git_dir(root), {"fetch", "--prune", std::string(remote)}) != 0) {+    error_prefix();+    std::cout << "git fetch failed\n";+    return 1;+  }+  return git_import(root);+}++int git_push(const fs::path &root, std::string_view remote,+             std::string_view bookmark) {+  const auto url = repo_config_value(root, git::remote_key(remote, "url"));+  if (!url) {+    error_prefix();+    std::cout << "unknown remote: " << remote << "\n";+    return 1;+  }+  if (!configure_mirror(root, remote, *url)) {+    error_prefix();+    std::cout << "cannot configure git mirror\n";+    return 1;+  }+  const int exported = git_export(root);+  if (exported != 0)+    return exported;+  const std::string refspec = "refs/heads/" + std::string(bookmark) ++                              ":refs/heads/" + std::string(bookmark);+  if (run_git(git_dir(root),+              {"push", std::string(remote), refspec}) != 0) {+    error_prefix();+    std::cout << "git push failed\n";+    return 1;+  }+  std::cout << "pushed " << bookmark << " to " << remote << "\n";+  return 0;+}++int git_prepare_mirror(const fs::path &root, std::string_view source) {+  return git::prepare_mirror(root, path_from_bytes(source));+}++std::optional<std::vector<std::uint8_t>> git_read_lazy_blob(const fs::path &root,+                                                            const Id &id) {+  const auto oid = git::lazy_blob_oid(id);+  if (!oid)+    return std::nullopt;+  auto repo = git::cached_repo(git_dir(root));+  if (!repo)+    return std::nullopt;+  auto object = git::read_object(*repo, *oid);+  if (!object || object->kind != git::KIND_BLOB)+    return std::nullopt;+  return std::move(object->body);+}++namespace {++int git_import_cli(const std::vector<std::string> &args) {+  std::string repo_path = ".";+  std::optional<std::string> source;+  for (std::size_t i = 3; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (arg.starts_with("-source:")) {+      if (arg.size() == 8) {+        error_prefix();+        std::cout << "-source: requires a path\n";+        return 1;+      }+      source = arg.substr(8);+    } else if (!arg.empty() && arg.front() == '-') {+      error_prefix();+      std::cout << "unknown flag: " << arg << "\n";+      return 1;+    } else {+      repo_path = arg;+    }+  }+  const auto root = discover_repo(path_from_bytes(repo_path));+  if (!root) {+    error_prefix();+    std::cout << "not a veins repository: " << repo_path << "\n";+    return 1;+  }+  if (source) {+    const int prepared = git_prepare_mirror(*root, *source);+    if (prepared != 0) {+      error_prefix();+      if (prepared == 2) {+        std::cout << "-source: " << *source+                  << " is not a git repository root (expected the directory "+                     "containing .git)\n";+      } else {+        std::cout << "cannot prepare git mirror from " << *source+                  << " (code " << prepared << ")\n";+      }+      return 1;+    }+  }+  return git_import(*root);+}++int git_export_cli(const std::vector<std::string> &args) {+  std::string repo_path = ".";+  for (std::size_t i = 3; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (!arg.empty() && arg.front() == '-') {+      error_prefix();+      std::cout << "unknown flag: " << arg << "\n";+      return 1;+    }+    repo_path = arg;+  }+  const auto root = discover_repo(path_from_bytes(repo_path));+  if (!root) {+    error_prefix();+    std::cout << "not a veins repository: " << repo_path << "\n";+    return 1;+  }+  return git_export(*root);+}++int git_fetch_cli(const std::vector<std::string> &args) {+  std::string remote = "origin";+  std::string repo_path = ".";+  bool have_remote = false;+  for (std::size_t i = 3; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (!arg.empty() && arg.front() == '-') {+      error_prefix();+      std::cout << "unknown flag: " << arg << "\n";+      return 1;+    }+    if (!have_remote) {+      remote = arg;+      have_remote = true;+    } else {+      repo_path = arg;+    }+  }+  const auto root = discover_repo(path_from_bytes(repo_path));+  if (!root) {+    error_prefix();+    std::cout << "not a veins repository\n";+    return 1;+  }+  return git_fetch(*root, remote);+}++int git_push_cli(const std::vector<std::string> &args) {+  std::string remote = "origin";+  std::optional<std::string> bookmark;+  std::string repo_path = ".";+  bool have_remote = false;+  for (std::size_t i = 3; i < args.size(); ++i) {+    const std::string &arg = args[i];+    if (!arg.empty() && arg.front() == '-') {+      error_prefix();+      std::cout << "unknown flag: " << arg << "\n";+      return 1;+    }+    if (!have_remote) {+      remote = arg;+      have_remote = true;+    } else if (!bookmark) {+      bookmark = arg;+    } else {+      repo_path = arg;+    }+  }+  if (!bookmark) {+    error_prefix();+    std::cout << "git push requires a bookmark\n";+    return 1;+  }+  const auto root = discover_repo(path_from_bytes(repo_path));+  if (!root) {+    error_prefix();+    std::cout << "not a veins repository\n";+    return 1;+  }+  return git_push(*root, remote, *bookmark);+}++int git_remote_cli(const std::vector<std::string> &args) {+  if (args.size() < 4) {+    error_prefix();+    std::cout << "expected remote subcommand (add, list, remove)\n";+    return 1;+  }+  const std::string &sub = args[3];+  const auto root = discover_repo(".");+  if (!root) {+    error_prefix();+    std::cout << "not a veins repository\n";+    return 1;+  }+  if (sub == "add") {+    if (args.size() < 6) {+      error_prefix();+      std::cout << "remote add requires a name and URL\n";+      return 1;+    }+    if (!repo_config_set(*root, git::remote_key(args[4], "url"), args[5])) {+      error_prefix();+      std::cout << "cannot write repository config\n";+      return 1;+    }+    return 0;+  }+  if (sub == "list" || sub == "ls") {+    for (const auto &name : git::list_remotes(*root)) {+      const auto url = repo_config_value(*root, git::remote_key(name, "url"));+      std::cout << name << '\t' << (url ? *url : std::string()) << '\n';+    }+    return 0;+  }+  if (sub == "remove" || sub == "rm") {+    if (args.size() < 5) {+      error_prefix();+      std::cout << "remote remove requires a name\n";+      return 1;+    }+    const std::string &name = args[4];+    (void)repo_config_remove(*root, git::remote_key(name, "url"));+    (void)repo_config_remove(*root, git::remote_key(name, "key"));+    (void)repo_config_remove(*root, git::remote_key(name, "tls-pin"));+    return 0;+  }+  error_prefix();+  std::cout << "unknown remote subcommand: " << sub << "\n";+  return 1;+}++} // namespace++int git_cli_run(const std::vector<std::string> &args) {+  if (args.size() < 3) {+    error_prefix();+    std::cout << "expected a git subcommand (import)\n";+    return 1;+  }+  const std::string &sub = args[2];+  if (sub == "import")+    return git_import_cli(args);+  if (sub == "export")+    return git_export_cli(args);+  if (sub == "fetch")+    return git_fetch_cli(args);+  if (sub == "push")+    return git_push_cli(args);+  if (sub == "remote")+    return git_remote_cli(args);+  error_prefix();+  std::cout << "unknown git subcommand: " << sub << "\n";+  return 1;+}++} // namespace vn--- /dev/null+++ b/xveins/src/git.h@@ -0,0 +1,22 @@+#pragma once++#include "common.h"+#include "object.h"++#include <optional>+#include <string>+#include <vector>++namespace vn {++int git_import(const fs::path &root);+int git_export(const fs::path &root);+int git_fetch(const fs::path &root, std::string_view remote);+int git_push(const fs::path &root, std::string_view remote,+             std::string_view bookmark);+int git_prepare_mirror(const fs::path &root, std::string_view source);+std::optional<std::vector<std::uint8_t>> git_read_lazy_blob(const fs::path &root,+                                                            const Id &id);+int git_cli_run(const std::vector<std::string> &args);++} // namespace vn--- /dev/null+++ b/xveins/src/git_internal.h@@ -0,0 +1,148 @@+#pragma once++#include "common.h"+#include "object.h"+#include "store.h"++#include <array>+#include <map>+#include <memory>+#include <optional>+#include <string>+#include <vector>++namespace vn::git {++using Oid = std::array<std::uint8_t, 20>;++struct OidLess {+  bool operator()(const Oid &a, const Oid &b) const {+    return std::memcmp(a.data(), b.data(), a.size()) < 0;+  }+};++enum Kind : std::uint8_t {+  KIND_NONE = 0,+  KIND_COMMIT = 1,+  KIND_TREE = 2,+  KIND_BLOB = 3,+  KIND_TAG = 4,+  KIND_OFS_DELTA = 6,+  KIND_REF_DELTA = 7,+};++struct Object {+  std::uint8_t kind = 0;+  std::vector<std::uint8_t> body;+};++struct Pack {+  fs::path path;+  std::vector<std::uint8_t> data;+  std::vector<Oid> oids;+  std::vector<std::uint64_t> offsets;+};++struct Repo {+  fs::path git_dir;+  std::vector<Pack> packs;+};++std::string oid_hex(const Oid &oid);+std::optional<Oid> oid_from_hex(std::string_view hex);+std::optional<Oid> object_hash(std::uint8_t kind, Bytes body);+std::optional<Repo> open_repo(const fs::path &git_dir);+std::optional<Object> read_object(Repo &repo, const Oid &oid,+                                  bool verify = false);+std::shared_ptr<Repo> cached_repo(const fs::path &git_dir);++struct RawTreeEntry {+  std::string mode;+  std::string name;+  Oid oid{};+};++struct ParsedTree {+  std::vector<RawTreeEntry> entries;+  bool canonical = true;+};++struct ParsedTag {+  Oid target{};+  std::uint8_t target_kind = 0;+};++struct ParsedCommit {+  Oid tree{};+  std::vector<Oid> parents;+  Sig author;+  Sig committer;+  std::string message;+  std::vector<KeyValue> extras;+  std::optional<ChangeId> change_id;+  bool canonical = true;+};++std::optional<Sig> parse_sig(std::string_view value);+std::optional<ParsedCommit> parse_commit(Bytes body);+std::vector<std::uint8_t> serialize_commit(const ParsedCommit &commit);+std::optional<ParsedTree> parse_tree(Bytes body);+std::string mode_for_kind(std::uint8_t kind);+std::uint8_t mode_kind(std::string_view mode);+std::optional<ParsedTag> parse_tag(Bytes body);++struct IdMap {+  std::map<Oid, Id, OidLess> items;++  std::optional<Id> get(const Oid &oid) const;+  void put(const Oid &oid, const Id &id);+  std::optional<Oid> reverse(const Id &id) const;+};++bool load_map(const fs::path &root, std::string_view name, IdMap &out);+bool save_map(const fs::path &root, std::string_view name, const IdMap &map);+bool save_raw(const fs::path &root, const Id &id, Bytes body);+std::optional<std::vector<std::uint8_t>> load_raw(const fs::path &root,+                                                  const Id &id);++struct Ref {+  std::string name;+  Oid oid{};+};++struct RefSet {+  std::vector<Ref> branches;+  std::vector<Ref> tags;+  std::vector<Ref> remotes;+  std::optional<Oid> head;+};++RefSet read_refs(const fs::path &git_dir);++Id lazy_blob_id(const Oid &oid);+std::optional<Oid> lazy_blob_oid(const Id &id);++bool ensure_mirror(const fs::path &root);+int prepare_mirror(const fs::path &root, const fs::path &source);+bool write_loose(const fs::path &git_dir, std::uint8_t kind, const Oid &oid,+                 Bytes body);+bool write_ref(const fs::path &git_dir, std::string_view name, const Oid &oid);++std::string remote_key(std::string_view remote, std::string_view field);+std::vector<std::string> list_remotes(const fs::path &root);++std::optional<Id> import_tree(Writer &writer, Repo &repo, IdMap &trees,+                              IdMap &blobs, const Oid &oid,+                              std::vector<std::pair<Id, std::vector<std::uint8_t>>>+                                  &raw_saves,+                              std::size_t &new_trees, std::size_t &new_blobs,+                              std::size_t depth = 0);++bool export_tree(const fs::path &root, Store &store, IdMap &trees,+                 IdMap &blobs, const Id &id, Oid &out, std::size_t depth = 0);+bool export_commit(const fs::path &root, Store &store, IdMap &commits,+                   IdMap &trees, IdMap &blobs,+                   const std::vector<Id> &native, const Id &id, Oid &out,+                   std::size_t depth = 0);++} // namespace vn::git--- /dev/null+++ b/xveins/src/git_object.cpp@@ -0,0 +1,1145 @@+#include "git_internal.h"++#include <openssl/evp.h>+#include <zlib.h>++#include <algorithm>+#include <cstring>+#include <map>+#include <mutex>+#include <string_view>++namespace vn::git {++namespace {++std::uint32_t be32(Bytes data, std::size_t off) {+  return (static_cast<std::uint32_t>(data[off]) << 24) |+         (static_cast<std::uint32_t>(data[off + 1]) << 16) |+         (static_cast<std::uint32_t>(data[off + 2]) << 8) |+         static_cast<std::uint32_t>(data[off + 3]);+}++std::uint64_t be64(Bytes data, std::size_t off) {+  return (static_cast<std::uint64_t>(be32(data, off)) << 32) |+         static_cast<std::uint64_t>(be32(data, off + 4));+}++Oid sha1(Bytes data) {+  Oid out{};+  unsigned int len = 0;+  static const std::uint8_t empty = 0;+  const std::uint8_t *ptr = data.empty() ? &empty : data.data();+  EVP_Digest(ptr, data.size(), out.data(), &len, EVP_sha1(), nullptr);+  return out;+}++bool bytes_equal(const Oid &a, Bytes b) {+  return b.size() == a.size() && std::memcmp(a.data(), b.data(), a.size()) == 0;+}++std::string kind_name(std::uint8_t kind) {+  switch (kind) {+  case KIND_COMMIT:+    return "commit";+  case KIND_TREE:+    return "tree";+  case KIND_BLOB:+    return "blob";+  case KIND_TAG:+    return "tag";+  default:+    return "unknown";+  }+}++std::uint8_t kind_from_name(std::string_view name) {+  if (name == "commit")+    return KIND_COMMIT;+  if (name == "tree")+    return KIND_TREE;+  if (name == "blob")+    return KIND_BLOB;+  if (name == "tag")+    return KIND_TAG;+  return 0;+}++std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input);++std::optional<std::vector<std::uint8_t>> inflate_exact(Bytes input,+                                                       std::size_t expected) {+  if (expected == 0) {+    auto result = inflate_unknown(input);+    if (!result || !result->empty())+      return std::nullopt;+    return result;+  }+  std::vector<std::uint8_t> out(expected);+  uLongf dest_len = static_cast<uLongf>(expected);+  const int rc = uncompress(out.data(), &dest_len, input.data(),+                            static_cast<uLong>(input.size()));+  if (rc != Z_OK || dest_len != expected)+    return std::nullopt;+  out.resize(expected);+  return out;+}++std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input) {+  z_stream zs{};+  if (inflateInit(&zs) != Z_OK)+    return std::nullopt;+  std::vector<std::uint8_t> out(4096);+  zs.next_in = const_cast<Bytef *>(input.data());+  zs.avail_in = static_cast<uInt>(input.size());+  int rc = Z_OK;+  for (;;) {+    if (zs.total_out == out.size())+      out.resize(out.size() * 2);+    zs.next_out = out.data() + zs.total_out;+    zs.avail_out = static_cast<uInt>(out.size() - zs.total_out);+    rc = inflate(&zs, Z_NO_FLUSH);+    if (rc == Z_STREAM_END)+      break;+    if (rc != Z_OK) {+      inflateEnd(&zs);+      return std::nullopt;+    }+  }+  const std::size_t written = zs.total_out;+  inflateEnd(&zs);+  out.resize(written);+  return out;+}++struct Varint {+  std::uint64_t value = 0;+  std::size_t next = 0;+};++std::optional<Varint> read_be_varint(Bytes data, std::size_t start) {+  if (start >= data.size())+    return std::nullopt;+  const std::uint8_t c0 = data[start];+  std::uint64_t value = c0 & 0x0f;+  std::uint64_t shift = 4;+  std::size_t pos = start + 1;+  bool more = (c0 & 0x80) != 0;+  while (more) {+    if (pos >= data.size())+      return std::nullopt;+    const std::uint8_t c = data[pos++];+    value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);+    shift += 7;+    more = (c & 0x80) != 0;+  }+  return Varint{value, pos};+}++std::optional<Varint> read_delta_varint(Bytes data, std::size_t start) {+  std::uint64_t value = 0;+  std::uint64_t shift = 0;+  std::size_t pos = start;+  for (;;) {+    if (pos >= data.size() || shift > 63)+      return std::nullopt;+    const std::uint8_t c = data[pos++];+    value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);+    shift += 7;+    if ((c & 0x80) == 0)+      return Varint{value, pos};+  }+}++std::optional<std::vector<std::uint8_t>> apply_delta(Bytes base,+                                                     Bytes delta) {+  const auto src_size = read_delta_varint(delta, 0);+  if (!src_size || src_size->value != base.size())+    return std::nullopt;+  const auto dst_size = read_delta_varint(delta, src_size->next);+  if (!dst_size || dst_size->value > 2147483648ull)+    return std::nullopt;+  const std::size_t cap = static_cast<std::size_t>(dst_size->value);+  std::vector<std::uint8_t> out(cap);+  std::size_t written = 0;+  std::size_t pos = dst_size->next;+  while (pos < delta.size()) {+    const std::uint8_t op = delta[pos++];+    if ((op & 0x80) != 0) {+      std::uint64_t off = 0;+      std::uint64_t size = 0;+      for (int bit = 0; bit < 4; ++bit) {+        if ((op & (1u << bit)) != 0) {+          if (pos >= delta.size())+            return std::nullopt;+          off |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);+        }+      }+      for (int bit = 0; bit < 3; ++bit) {+        if ((op & (1u << (4 + bit))) != 0) {+          if (pos >= delta.size())+            return std::nullopt;+          size |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);+        }+      }+      if (size == 0)+        size = 65536;+      if (off > base.size() || size > base.size() - off)+        return std::nullopt;+      if (size > cap - written)+        return std::nullopt;+      if (size > 0)+        std::memcpy(out.data() + written, base.data() + off,+                    static_cast<std::size_t>(size));+      written += static_cast<std::size_t>(size);+    } else {+      if (op == 0)+        return std::nullopt;+      const std::size_t n = op;+      if (pos + n > delta.size() || n > cap - written)+        return std::nullopt;+      std::memcpy(out.data() + written, delta.data() + pos, n);+      pos += n;+      written += n;+    }+  }+  if (written != cap)+    return std::nullopt;+  return out;+}++std::optional<std::size_t> find_oid(const Pack &pack, const Oid &oid) {+  auto it = std::lower_bound(pack.oids.begin(), pack.oids.end(), oid, OidLess{});+  if (it == pack.oids.end() || std::memcmp(it->data(), oid.data(), oid.size()) != 0)+    return std::nullopt;+  return static_cast<std::size_t>(it - pack.oids.begin());+}++std::optional<Object> read_at(Repo &repo, Pack &pack, std::uint64_t start,+                              bool verify, std::size_t depth) {+  if (depth > 4096 || start >= pack.data.size())+    return std::nullopt;+  Bytes data(pack.data.data(), pack.data.size());+  const std::size_t begin = static_cast<std::size_t>(start);+  const std::uint8_t c0 = data[begin];+  const std::uint8_t kind = static_cast<std::uint8_t>((c0 >> 4) & 7);+  const auto header = read_be_varint(data, begin);+  if (!header || header->value > 2147483648ull)+    return std::nullopt;+  const std::size_t size = static_cast<std::size_t>(header->value);+  std::size_t pos = header->next;++  Oid base_oid{};+  bool has_base_oid = false;+  std::uint64_t base_off = 0;+  bool has_base_off = false;+  if (kind == KIND_OFS_DELTA) {+    if (pos >= data.size())+      return std::nullopt;+    std::uint8_t c = data[pos++];+    std::uint64_t acc = c & 0x7f;+    bool more = (c & 0x80) != 0;+    while (more) {+      if (pos >= data.size())+        return std::nullopt;+      c = data[pos++];+      acc = ((acc + 1) << 7) | (c & 0x7f);+      more = (c & 0x80) != 0;+    }+    has_base_off = true;+    base_off = start - acc;+  } else if (kind == KIND_REF_DELTA) {+    if (pos + 20 > data.size())+      return std::nullopt;+    std::memcpy(base_oid.data(), data.data() + pos, 20);+    has_base_oid = true;+    pos += 20;+  }++  if (pos > data.size())+    return std::nullopt;+  auto inflated = inflate_exact(data.subspan(pos), size);+  if (!inflated)+    return std::nullopt;+  if (kind >= KIND_COMMIT && kind <= KIND_TAG)+    return Object{kind, std::move(*inflated)};+  if (kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA)+    return std::nullopt;++  std::optional<Object> base;+  if (has_base_off) {+    if (base_off >= start)+      return std::nullopt;+    base = read_at(repo, pack, base_off, verify, depth + 1);+  } else if (has_base_oid) {+    base = read_object(repo, base_oid, verify);+  }+  if (!base)+    return std::nullopt;+  auto merged = apply_delta(Bytes(base->body.data(), base->body.size()),+                            Bytes(inflated->data(), inflated->size()));+  if (!merged)+    return std::nullopt;+  return Object{base->kind, std::move(*merged)};+}++std::optional<Pack> parse_idx(Bytes data, std::size_t pack_count,+                              Bytes pack_trailer) {+  if (data.size() < 40)+    return std::nullopt;+  const std::size_t trailer_off = data.size() - 20;+  const Oid check = sha1(data.first(trailer_off));+  if (!bytes_equal(check, data.subspan(trailer_off, 20)))+    return std::nullopt;+  if (pack_trailer.size() != 20 ||+      std::memcmp(data.data() + data.size() - 40, pack_trailer.data(), 20) != 0)+    return std::nullopt;++  const bool is_v2 = data.size() >= 4 && data[0] == 0xff &&+                     data[1] == 0x74 && data[2] == 0x4f && data[3] == 0x63;+  const std::size_t fanout_off = is_v2 ? 8 : 0;+  if (is_v2 && be32(data, 4) != 2)+    return std::nullopt;+  if (data.size() < fanout_off + 1024 + 40)+    return std::nullopt;+  const std::size_t n = be32(data, fanout_off + 255 * 4);+  if (n != pack_count)+    return std::nullopt;++  Pack pack;+  pack.oids.resize(n);+  pack.offsets.resize(n);+  if (is_v2) {+    const std::size_t names_off = fanout_off + 1024;+    const std::size_t crcs_off = names_off + n * 20;+    const std::size_t offs_off = crcs_off + n * 4;+    const std::size_t large_off = offs_off + n * 4;+    if (large_off + 40 > data.size())+      return std::nullopt;+    const std::size_t large_bytes = data.size() - 40 - large_off;+    if (large_bytes % 8 != 0)+      return std::nullopt;+    for (std::size_t i = 0; i < n; ++i) {+      std::memcpy(pack.oids[i].data(), data.data() + names_off + i * 20, 20);+      const std::uint32_t raw_off = be32(data, offs_off + i * 4);+      std::uint64_t resolved = raw_off;+      if ((raw_off & 0x80000000u) != 0) {+        const std::size_t idx = raw_off & 0x7fffffffu;+        if (idx * 8 + 8 > large_bytes)+          return std::nullopt;+        resolved = be64(data, large_off + idx * 8);+      }+      pack.offsets[i] = resolved;+    }+  } else {+    const std::size_t records_off = 1024;+    if (records_off + n * 24 + 40 > data.size())+      return std::nullopt;+    for (std::size_t i = 0; i < n; ++i) {+      const std::size_t rec = records_off + i * 24;+      pack.offsets[i] = be32(data, rec);+      std::memcpy(pack.oids[i].data(), data.data() + rec + 4, 20);+    }+  }+  return pack;+}++std::optional<Pack> open_pack(const fs::path &pack_path,+                              const fs::path &idx_path) {+  auto pdata = read_file_opt(pack_path);+  if (!pdata || pdata->size() < 32)+    return std::nullopt;+  if (std::memcmp(pdata->data(), "PACK", 4) != 0)+    return std::nullopt;+  const std::uint32_t version = be32(bytes_of(*pdata), 4);+  if (version != 2 && version != 3)+    return std::nullopt;+  const std::size_t count = be32(bytes_of(*pdata), 8);+  const std::size_t trailer_off = pdata->size() - 20;+  const Oid pack_trailer = sha1(Bytes(pdata->data(), trailer_off));+  if (std::memcmp(pack_trailer.data(), pdata->data() + trailer_off, 20) != 0)+    return std::nullopt;++  auto idata = read_file_opt(idx_path);+  if (!idata)+    return std::nullopt;+  auto parsed = parse_idx(bytes_of(*idata),+                          count,+                          Bytes(pdata->data() + trailer_off, 20));+  if (!parsed)+    return std::nullopt;+  parsed->path = pack_path;+  parsed->data = std::move(*pdata);+  return parsed;+}++std::optional<Object> read_loose(const Repo &repo, const Oid &oid,+                                 bool verify) {+  const std::string hex = oid_hex(oid);+  const fs::path path =+      repo.git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) /+      path_from_bytes(hex.substr(2));+  auto compressed = read_file_opt(path);+  if (!compressed)+    return std::nullopt;+  auto inflated = inflate_unknown(bytes_of(*compressed));+  if (!inflated)+    return std::nullopt;+  Bytes data(inflated->data(), inflated->size());+  const std::size_t space = static_cast<std::size_t>(+      std::find(data.begin(), data.end(), ' ') - data.begin());+  std::size_t nul = space;+  while (nul < data.size() && data[nul] != 0)+    ++nul;+  if (space == 0 || nul >= data.size())+    return std::nullopt;+  const std::uint8_t kind =+      kind_from_name(str_of(data.first(space)));+  if (kind == 0)+    return std::nullopt;+  std::uint64_t declared = 0;+  for (std::size_t i = space + 1; i < nul; ++i) {+    const std::uint8_t c = data[i];+    if (c < '0' || c > '9')+      return std::nullopt;+    declared = declared * 10 + (c - '0');+  }+  Bytes body = data.subspan(nul + 1);+  if (body.size() != declared)+    return std::nullopt;+  Object object{kind, std::vector<std::uint8_t>(body.begin(), body.end())};+  if (verify) {+    auto hash = object_hash(kind, body);+    if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)+      return std::nullopt;+  }+  return object;+}++std::string trim_line(std::string_view text) {+  while (!text.empty() && (text.back() == '\n' || text.back() == '\r'))+    text.remove_suffix(1);+  return std::string(text);+}++void replace_ref(std::vector<Ref> &refs, std::string name, const Oid &oid) {+  for (auto &ref : refs) {+    if (ref.name == name) {+      ref.oid = oid;+      return;+    }+  }+  refs.push_back(Ref{std::move(name), oid});+}++std::optional<Oid> find_ref(const std::vector<Ref> &refs,+                            std::string_view name) {+  for (const auto &ref : refs) {+    if (ref.name == name)+      return ref.oid;+  }+  return std::nullopt;+}++void read_packed_refs(const fs::path &git_dir, std::vector<Ref> &branches,+                      std::vector<Ref> &tags) {+  auto data = read_file_opt(git_dir / "packed-refs");+  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();+    std::string_view line = text.substr(start, end - start);+    if (!line.empty() && line.front() != '#' && line.front() != '^') {+      const std::size_t space = line.find(' ');+      if (space != std::string_view::npos && space != 0) {+        auto oid = oid_from_hex(line.substr(0, space));+        std::string_view name = line.substr(space + 1);+        if (oid) {+          if (name.starts_with("refs/heads/"))+            replace_ref(branches, std::string(name.substr(11)), *oid);+          else if (name.starts_with("refs/tags/"))+            replace_ref(tags, std::string(name.substr(10)), *oid);+        }+      }+    }+    if (end == text.size())+      break;+    start = end + 1;+  }+}++void read_ref_dir(const fs::path &base, std::string_view rel,+                  std::vector<Ref> &refs) {+  const fs::path dir = rel.empty() ? base : base / path_from_bytes(rel);+  for (const auto &name : list_directory(dir)) {+    std::string child_rel(rel);+    if (!child_rel.empty())+      child_rel.push_back('/');+    child_rel += name;+    const fs::path child = base / path_from_bytes(child_rel);+    std::error_code ec;+    if (fs::is_directory(child, ec)) {+      read_ref_dir(base, child_rel, refs);+    } else {+      auto content = read_file_opt(child);+      if (!content)+        continue;+      const std::string line =+          trim_line(std::string_view(reinterpret_cast<const char *>(content->data()),+                                     content->size()));+      if (auto oid = oid_from_hex(line))+        replace_ref(refs, child_rel, *oid);+    }+  }+}++std::optional<Oid> resolve_head(const fs::path &git_dir,+                                const std::vector<Ref> &branches,+                                const std::vector<Ref> &tags) {+  auto data = read_file_opt(git_dir / "HEAD");+  if (!data)+    return std::nullopt;+  const std::string line =+      trim_line(std::string_view(reinterpret_cast<const char *>(data->data()),+                                 data->size()));+  if (line.starts_with("ref: ")) {+    std::string_view name(line.data() + 5, line.size() - 5);+    if (name.starts_with("refs/heads/"))+      return find_ref(branches, name.substr(11));+    if (name.starts_with("refs/tags/"))+      return find_ref(tags, name.substr(10));+    return std::nullopt;+  }+  return oid_from_hex(line);+}++std::optional<fs::path> resolve_source(const fs::path &source) {+  std::error_code ec;+  const fs::path dotgit = source / ".git";+  if (fs::is_directory(dotgit, ec))+    return dotgit;+  if (fs::is_regular_file(source / "HEAD", ec) &&+      fs::is_directory(source / "objects", ec))+    return source;+  return std::nullopt;+}++bool copy_tree(const fs::path &src, const fs::path &dst) {+  std::error_code ec;+  fs::create_directories(dst, ec);+  if (ec)+    return false;+  for (const auto &name : list_directory(src)) {+    const fs::path s = src / path_from_bytes(name);+    const fs::path d = dst / path_from_bytes(name);+    if (fs::is_directory(s, ec)) {+      if (!copy_tree(s, d))+        return false;+    } else if (fs::is_regular_file(s, ec)) {+      fs::create_hard_link(s, d, ec);+      if (ec) {+        ec.clear();+        fs::copy_file(s, d, fs::copy_options::overwrite_existing, ec);+        if (ec)+          return false;+      }+    }+  }+  return true;+}++} // namespace++std::string oid_hex(const Oid &oid) {+  return hex_encode(Bytes(oid.data(), oid.size()));+}++std::optional<Oid> oid_from_hex(std::string_view hex) {+  Oid out{};+  if (!hex_decode(hex, MutBytes(out.data(), out.size())))+    return std::nullopt;+  return out;+}++std::optional<Oid> object_hash(std::uint8_t kind, Bytes body) {+  const std::string name = kind_name(kind);+  if (name == "unknown")+    return std::nullopt;+  std::string header = name;+  header.push_back(' ');+  header += std::to_string(body.size());+  header.push_back('\0');+  std::vector<std::uint8_t> data;+  data.reserve(header.size() + body.size());+  data.insert(data.end(), header.begin(), header.end());+  data.insert(data.end(), body.begin(), body.end());+  return sha1(Bytes(data.data(), data.size()));+}++std::optional<Repo> open_repo(const fs::path &git_dir) {+  Repo repo;+  repo.git_dir = git_dir;+  const fs::path pack_dir = git_dir / "objects" / "pack";+  std::error_code ec;+  if (fs::is_directory(pack_dir, ec)) {+    std::vector<std::string> names = list_directory(pack_dir);+    std::sort(names.begin(), names.end());+    for (const auto &name : names) {+      if (name.size() <= 4 || name.compare(name.size() - 4, 4, ".idx") != 0)+        continue;+      const std::string base = name.substr(0, name.size() - 4);+      const fs::path pack_path = pack_dir / path_from_bytes(base + ".pack");+      const fs::path idx_path = pack_dir / path_from_bytes(name);+      if (!path_is_file(pack_path))+        continue;+      auto pack = open_pack(pack_path, idx_path);+      if (!pack)+        return std::nullopt;+      repo.packs.push_back(std::move(*pack));+    }+  }+  return repo;+}++std::optional<Object> read_object(Repo &repo, const Oid &oid, bool verify) {+  for (auto &pack : repo.packs) {+    auto idx = find_oid(pack, oid);+    if (!idx)+      continue;+    auto object = read_at(repo, pack, pack.offsets[*idx], verify, 0);+    if (!object)+      return std::nullopt;+    if (verify) {+      auto hash = object_hash(object->kind,+                              Bytes(object->body.data(), object->body.size()));+      if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)+        return std::nullopt;+    }+    return object;+  }+  return read_loose(repo, oid, verify);+}++std::shared_ptr<Repo> cached_repo(const fs::path &git_dir) {+  static std::mutex mutex;+  static std::map<std::string, std::pair<fs::file_time_type,+                                         std::shared_ptr<Repo>>>+      cache;+  std::error_code ec;+  const fs::path pack_dir = git_dir / "objects" / "pack";+  const fs::file_time_type stamp = fs::last_write_time(pack_dir, ec);+  const std::string key = path_to_bytes(git_dir);+  std::lock_guard<std::mutex> lock(mutex);+  auto it = cache.find(key);+  if (it != cache.end() && !ec && it->second.first == stamp)+    return it->second.second;+  auto repo = open_repo(git_dir);+  if (!repo)+    return nullptr;+  auto shared = std::make_shared<Repo>(std::move(*repo));+  cache[key] = {stamp, shared};+  return shared;+}++std::optional<Sig> parse_sig(std::string_view value) {+  const std::size_t tz_space = value.rfind(' ');+  if (tz_space == std::string_view::npos || tz_space == 0)+    return std::nullopt;+  const std::size_t sec_space = value.rfind(' ', tz_space - 1);+  if (sec_space == std::string_view::npos)+    return std::nullopt;+  const std::string_view sec_text =+      value.substr(sec_space + 1, tz_space - sec_space - 1);+  const std::string_view tz_text = value.substr(tz_space + 1);+  if (sec_text.empty() || tz_text.size() != 5 ||+      (tz_text[0] != '+' && tz_text[0] != '-'))+    return std::nullopt;+  std::int64_t seconds = 0;+  bool negative = false;+  std::size_t i = 0;+  if (sec_text[0] == '-') {+    negative = true;+    i = 1;+  }+  if (i >= sec_text.size())+    return std::nullopt;+  for (; i < sec_text.size(); ++i) {+    if (sec_text[i] < '0' || sec_text[i] > '9')+      return std::nullopt;+    seconds = seconds * 10 + (sec_text[i] - '0');+  }+  if (negative)+    seconds = -seconds;+  std::int64_t hh = 0;+  std::int64_t mm = 0;+  for (std::size_t j = 1; j < 3; ++j) {+    if (tz_text[j] < '0' || tz_text[j] > '9')+      return std::nullopt;+    hh = hh * 10 + (tz_text[j] - '0');+  }+  for (std::size_t j = 3; j < 5; ++j) {+    if (tz_text[j] < '0' || tz_text[j] > '9')+      return std::nullopt;+    mm = mm * 10 + (tz_text[j] - '0');+  }+  std::int64_t tz = hh * 60 + mm;+  if (tz_text[0] == '-')+    tz = -tz;+  if (tz > 32767 || tz < -32768)+    return std::nullopt;++  const std::string_view ident = value.substr(0, sec_space);+  const std::size_t lt = ident.rfind('<');+  const std::size_t gt = ident.rfind('>');+  if (lt == std::string_view::npos || gt == std::string_view::npos || gt <= lt)+    return std::nullopt;+  std::string_view name = ident.substr(0, lt);+  if (!name.empty() && name.back() == ' ')+    name.remove_suffix(1);+  Sig sig;+  sig.name = std::string(name);+  sig.email = std::string(ident.substr(lt + 1, gt - lt - 1));+  sig.seconds = seconds;+  sig.tz_min = static_cast<std::int16_t>(tz);+  return sig;+}++namespace {++void append_sig(std::vector<std::uint8_t> &out, const Sig &sig) {+  auto append = [&](std::string_view text) {+    out.insert(out.end(), text.begin(), text.end());+  };+  append(sig.name);+  append(" <");+  append(sig.email);+  append("> ");+  append(std::to_string(sig.seconds));+  out.push_back(' ');+  const std::int64_t minutes = sig.tz_min;+  const std::int64_t abs_min = minutes < 0 ? -minutes : minutes;+  out.push_back(minutes < 0 ? '-' : '+');+  const std::int64_t hh = abs_min / 60;+  const std::int64_t mm = abs_min % 60;+  out.push_back(static_cast<std::uint8_t>('0' + hh / 10));+  out.push_back(static_cast<std::uint8_t>('0' + hh % 10));+  out.push_back(static_cast<std::uint8_t>('0' + mm / 10));+  out.push_back(static_cast<std::uint8_t>('0' + mm % 10));+}++std::optional<ChangeId> parse_change_id(std::string_view text) {+  if (text.size() != 32)+    return std::nullopt;+  ChangeId id{};+  if (!hex_decode(text, MutBytes(id.data(), id.size())))+    return std::nullopt;+  return id;+}++bool canonical_mode(std::string_view mode) {+  return mode == "100644" || mode == "100755" || mode == "120000" ||+         mode == "40000" || mode == "160000";+}++} // namespace++std::optional<ParsedCommit> parse_commit(Bytes body) {+  const std::string_view text(reinterpret_cast<const char *>(body.data()),+                              body.size());+  const std::size_t blank = text.find("\n\n");+  if (blank == std::string_view::npos)+    return std::nullopt;+  ParsedCommit out;+  out.message = std::string(text.substr(blank + 2));+  const std::size_t header_end = blank;+  std::size_t pos = 0;+  int last_extra = -1;+  std::size_t last_extra_start = 0;+  while (pos < header_end) {+    std::size_t line_end = text.find('\n', pos);+    if (line_end == std::string_view::npos || line_end > header_end)+      line_end = header_end;+    const std::string_view line = text.substr(pos, line_end - pos);+    if (!line.empty() && line.front() == ' ') {+      if (last_extra < 0) {+        out.canonical = false;+      } else {+        out.extras[static_cast<std::size_t>(last_extra)].value =+            std::string(text.substr(last_extra_start, line_end - last_extra_start));+      }+    } else {+      last_extra = -1;+      const std::size_t space = line.find(' ');+      if (space == std::string_view::npos || space == 0) {+        out.canonical = false;+      } else {+        const std::string_view key = line.substr(0, space);+        const std::string_view value = line.substr(space + 1);+        if (key == "tree") {+          if (auto oid = oid_from_hex(value))+            out.tree = *oid;+          else+            out.canonical = false;+        } else if (key == "parent") {+          if (auto oid = oid_from_hex(value))+            out.parents.push_back(*oid);+          else+            out.canonical = false;+        } else if (key == "author") {+          if (auto sig = parse_sig(value))+            out.author = *sig;+          else+            out.canonical = false;+        } else if (key == "committer") {+          if (auto sig = parse_sig(value))+            out.committer = *sig;+          else+            out.canonical = false;+        } else if (key == "veins-change-id") {+          if (auto change = parse_change_id(value))+            out.change_id = *change;+          else+            out.canonical = false;+        } else {+          out.extras.push_back(KeyValue{std::string(key), std::string(value)});+          last_extra = static_cast<int>(out.extras.size() - 1);+          last_extra_start = pos + key.size() + 1;+        }+      }+    }+    pos = line_end + 1;+  }+  return out;+}++std::vector<std::uint8_t> serialize_commit(const ParsedCommit &commit) {+  std::vector<std::uint8_t> out;+  auto append = [&](std::string_view text) {+    out.insert(out.end(), text.begin(), text.end());+  };+  append("tree ");+  append(oid_hex(commit.tree));+  out.push_back('\n');+  for (const auto &parent : commit.parents) {+    append("parent ");+    append(oid_hex(parent));+    out.push_back('\n');+  }+  append("author ");+  append_sig(out, commit.author);+  out.push_back('\n');+  append("committer ");+  append_sig(out, commit.committer);+  out.push_back('\n');+  for (const auto &kv : commit.extras) {+    append(kv.key);+    out.push_back(' ');+    append(kv.value);+    out.push_back('\n');+  }+  out.push_back('\n');+  append(commit.message);+  return out;+}++std::optional<ParsedTree> parse_tree(Bytes body) {+  ParsedTree out;+  std::size_t pos = 0;+  while (pos < body.size()) {+    const std::size_t mode_start = pos;+    while (pos < body.size() && body[pos] != ' ')+      ++pos;+    if (pos >= body.size()) {+      out.canonical = false;+      break;+    }+    const std::string mode(reinterpret_cast<const char *>(body.data() + mode_start),+                           pos - mode_start);+    ++pos;+    const std::size_t name_start = pos;+    while (pos < body.size() && body[pos] != 0)+      ++pos;+    if (pos >= body.size()) {+      out.canonical = false;+      break;+    }+    const std::string name(+        reinterpret_cast<const char *>(body.data() + name_start),+        pos - name_start);+    ++pos;+    if (pos + 20 > body.size()) {+      out.canonical = false;+      break;+    }+    RawTreeEntry entry;+    entry.mode = mode;+    entry.name = name;+    std::memcpy(entry.oid.data(), body.data() + pos, 20);+    pos += 20;+    if (!canonical_mode(mode))+      out.canonical = false;+    out.entries.push_back(std::move(entry));+  }+  if (pos != body.size())+    out.canonical = false;+  return out;+}++std::string mode_for_kind(std::uint8_t kind) {+  if (kind == KIND_EXECUTABLE)+    return "100755";+  if (kind == KIND_SYMLINK)+    return "120000";+  if (kind == KIND_SUBTREE)+    return "40000";+  if (kind == KIND_SUBMODULE)+    return "160000";+  return "100644";+}++std::uint8_t mode_kind(std::string_view mode) {+  if (mode == "40000" || mode == "040000")+    return KIND_SUBTREE;+  if (mode == "120000")+    return KIND_SYMLINK;+  if (mode == "160000")+    return KIND_SUBMODULE;+  if (mode == "100755")+    return KIND_EXECUTABLE;+  return KIND_FILE;+}++std::optional<ParsedTag> parse_tag(Bytes body) {+  ParsedTag out;+  const std::string_view text(reinterpret_cast<const char *>(body.data()),+                              body.size());+  std::size_t pos = 0;+  while (pos < text.size()) {+    std::size_t end = text.find('\n', pos);+    if (end == std::string_view::npos)+      end = text.size();+    const std::string_view line = text.substr(pos, end - pos);+    if (line.empty())+      break;+    const std::size_t space = line.find(' ');+    if (space != std::string_view::npos && space != 0) {+      const std::string_view key = line.substr(0, space);+      const std::string_view value = line.substr(space + 1);+      if (key == "object") {+        if (auto oid = oid_from_hex(value))+          out.target = *oid;+      } else if (key == "type") {+        out.target_kind = kind_from_name(value);+      }+    }+    pos = end + 1;+  }+  return out;+}++std::optional<Id> IdMap::get(const Oid &oid) const {+  auto it = items.find(oid);+  if (it == items.end())+    return std::nullopt;+  return it->second;+}++void IdMap::put(const Oid &oid, const Id &id) { items[oid] = id; }++std::optional<Oid> IdMap::reverse(const Id &id) const {+  for (const auto &item : items) {+    if (item.second == id)+      return item.first;+  }+  return std::nullopt;+}++namespace {++fs::path map_path(const fs::path &root, std::string_view name) {+  return git_map_dir(root) / path_from_bytes(std::string(name) + ".map");+}++} // namespace++bool load_map(const fs::path &root, std::string_view name, IdMap &out) {+  out.items.clear();+  auto data = read_file_opt(map_path(root, name));+  if (!data)+    return true;+  if (data->size() < 9 ||+      std::memcmp(data->data(), "VMAP1", 5) != 0)+    return false;+  const std::uint32_t count = static_cast<std::uint32_t>((*data)[5]) |+                              (static_cast<std::uint32_t>((*data)[6]) << 8) |+                              (static_cast<std::uint32_t>((*data)[7]) << 16) |+                              (static_cast<std::uint32_t>((*data)[8]) << 24);+  if (data->size() != 9 + static_cast<std::size_t>(count) * 52)+    return false;+  for (std::size_t i = 0; i < count; ++i) {+    const std::size_t off = 9 + i * 52;+    Oid oid{};+    std::memcpy(oid.data(), data->data() + off, 20);+    Id id{};+    std::memcpy(id.data(), data->data() + off + 20, 32);+    out.put(oid, id);+  }+  return true;+}++bool save_map(const fs::path &root, std::string_view name, const IdMap &map) {+  std::vector<std::uint8_t> data;+  data.insert(data.end(), {'V', 'M', 'A', 'P', '1'});+  const std::uint32_t count = static_cast<std::uint32_t>(map.items.size());+  data.push_back(static_cast<std::uint8_t>(count & 0xff));+  data.push_back(static_cast<std::uint8_t>((count >> 8) & 0xff));+  data.push_back(static_cast<std::uint8_t>((count >> 16) & 0xff));+  data.push_back(static_cast<std::uint8_t>((count >> 24) & 0xff));+  for (const auto &item : map.items) {+    data.insert(data.end(), item.first.begin(), item.first.end());+    data.insert(data.end(), item.second.begin(), item.second.end());+  }+  return write_atomic(map_path(root, name), Bytes(data.data(), data.size()));+}++bool save_raw(const fs::path &root, const Id &id, Bytes body) {+  const fs::path path = git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id));+  return write_atomic(path, body);+}++std::optional<std::vector<std::uint8_t>> load_raw(const fs::path &root,+                                                  const Id &id) {+  return read_file_opt(git_map_dir(root) / "raw" /+                       path_from_bytes(hex_encode(id)));+}++RefSet read_refs(const fs::path &git_dir) {+  RefSet out;+  read_packed_refs(git_dir, out.branches, out.tags);+  read_ref_dir(git_dir / "refs" / "heads", "", out.branches);+  read_ref_dir(git_dir / "refs" / "tags", "", out.tags);+  read_ref_dir(git_dir / "refs" / "remotes", "", out.remotes);+  out.head = resolve_head(git_dir, out.branches, out.tags);+  return out;+}++Id lazy_blob_id(const Oid &oid) {+  Id id{};+  std::memcpy(id.data(), "veins-gitoid", 12);+  std::memcpy(id.data() + 12, oid.data(), 20);+  return id;+}++std::optional<Oid> lazy_blob_oid(const Id &id) {+  if (!is_lazy_blob(id))+    return std::nullopt;+  Oid out{};+  std::memcpy(out.data(), id.data() + 12, 20);+  return out;+}++bool ensure_mirror(const fs::path &root) {+  const fs::path dir = git_dir(root);+  if (!ensure_directory(dir) ||+      !ensure_directory(dir / "objects") ||+      !ensure_directory(dir / "refs" / "heads") ||+      !ensure_directory(dir / "refs" / "tags"))+    return false;+  if (!path_is_file(dir / "HEAD")) {+    const std::string body = "ref: refs/heads/main\n";+    if (!write_file(dir / "HEAD", bytes_of(body)))+      return false;+  }+  if (!path_is_file(dir / "config")) {+    const std::string body =+        "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = true\n";+    if (!write_file(dir / "config", bytes_of(body)))+      return false;+  }+  return true;+}++int prepare_mirror(const fs::path &root, const fs::path &source) {+  const fs::path target = git_dir(root);+  if (path_is_file(target / "HEAD"))+    return 0;+  const auto resolved = resolve_source(source);+  if (!resolved)+    return 2;+  if (!copy_tree(*resolved, target))+    return 3;+  return 0;+}++bool write_loose(const fs::path &git_dir, std::uint8_t kind, const Oid &oid,+                 Bytes body) {+  const std::string hex = oid_hex(oid);+  const fs::path final_path =+      git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) /+      path_from_bytes(hex.substr(2));+  if (path_is_file(final_path))+    return true;+  std::string header = kind_name(kind);+  header.push_back(' ');+  header += std::to_string(body.size());+  header.push_back('\0');+  uLongf bound = compressBound(static_cast<uLong>(header.size() + body.size()));+  std::vector<std::uint8_t> compressed(bound);+  uLongf dest_len = bound;+  std::vector<std::uint8_t> raw;+  raw.reserve(header.size() + body.size());+  raw.insert(raw.end(), header.begin(), header.end());+  raw.insert(raw.end(), body.begin(), body.end());+  const int rc = compress2(compressed.data(), &dest_len, raw.data(),+                           static_cast<uLong>(raw.size()), 6);+  if (rc != Z_OK)+    return false;+  compressed.resize(dest_len);+  return write_atomic(final_path,+                      Bytes(compressed.data(), compressed.size()));+}++bool write_ref(const fs::path &git_dir, std::string_view name, const Oid &oid) {+  const std::string line = oid_hex(oid) + "\n";+  return write_atomic(git_dir / path_from_bytes(name), bytes_of(line));+}++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::vector<std::string> list_remotes(const fs::path &root) {+  std::vector<std::string> out;+  auto data = read_file_opt(root / ".veins" / "config");+  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();+    const std::string_view line = text.substr(start, end - start);+    if (line.starts_with("remote.")) {+      const std::size_t dot = line.find(".url", 7);+      if (dot != std::string_view::npos && dot > 7)+        out.emplace_back(line.substr(7, dot - 7));+    }+    if (end == text.size())+      break;+    start = end + 1;+  }+  return out;+}++} // namespace vn::git--- a/xveins/src/store.cpp+++ b/xveins/src/store.cpp@@ -1,4 +1,6 @@ #include "store.h"++#include "git.h"  #include <algorithm> #include <atomic>@@ -1465,9 +1467,14 @@                              std::vector<std::uint8_t> &out,                              std::size_t depth) {   if (depth > 64)-    return false;-  if (is_lazy_blob(id))     return false;+  if (is_lazy_blob(id)) {+    auto data = git_read_lazy_blob(store.root(), id);+    if (!data)+      return false;+    out.insert(out.end(), data->begin(), data->end());+    return true;+  }   auto body = store.read_body(id, TYPE_BLOB);   if (!body)     return false;