navid/veins / d99aa6ed5a2d4f8921aead1368a2665623a5d2c1b652fccc8890f852649a42df / xveins/src/git.cpp

git.cpp

← xveins/src · 45607 bytes · raw · download

#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;
}

struct MaterializeCtx {
  const fs::path &root;
  Store &store;
  Writer &writer;
  std::map<Id, Id> trees;
  std::map<Id, Id> blobs;
  std::map<Id, Id> commits;
  std::map<Id, Id> conflicts;
  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;
  bool changed = false;
};

std::optional<Id> materialize_blob(MaterializeCtx &ctx, const Id &old_id) {
  auto existing = ctx.blobs.find(old_id);
  if (existing != ctx.blobs.end())
    return existing->second;
  const auto oid = git::lazy_blob_oid(old_id);
  if (!oid) {
    ctx.blobs[old_id] = old_id;
    return old_id;
  }
  auto data = git_read_lazy_blob(ctx.root, old_id);
  if (!data)
    return std::nullopt;
  BlobBuild build = build_blob(bytes_of(*data));
  if (build.root == Id{})
    return std::nullopt;
  for (auto &object : build.objects) {
    const Id id = object.id ? *object.id
                            : object_id(object.type, bytes_of(object.body));
    (void)ctx.writer.add_known(object.type, id, std::move(object.body));
  }
  ctx.blobs[old_id] = build.root;
  ++ctx.new_blobs;
  ctx.changed = true;
  return build.root;
}

std::optional<Id> materialize_tree(MaterializeCtx &ctx, const Id &old_id,
                                   std::size_t depth);

std::optional<Id> materialize_conflict(MaterializeCtx &ctx, const Id &old_id,
                                       std::size_t depth) {
  if (depth > 4096)
    return std::nullopt;
  auto existing = ctx.conflicts.find(old_id);
  if (existing != ctx.conflicts.end())
    return existing->second;
  auto body = ctx.store.read_body(old_id, TYPE_CONFLICT);
  if (!body)
    return std::nullopt;
  auto conflict = decode_conflict(bytes_of(*body));
  if (!conflict)
    return std::nullopt;
  bool changed = false;
  auto rewire = [&](ConflictValue &value) -> bool {
    if (!value.target)
      return true;
    if (value.kind == KIND_FILE || value.kind == KIND_EXECUTABLE ||
        value.kind == KIND_SYMLINK) {
      if (!is_lazy_blob(*value.target))
        return true;
      auto mapped = materialize_blob(ctx, *value.target);
      if (!mapped)
        return false;
      if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {
        value.target = *mapped;
        changed = true;
      }
      return true;
    }
    if (value.kind == KIND_SUBTREE) {
      auto mapped = materialize_tree(ctx, *value.target, depth + 1);
      if (!mapped)
        return false;
      if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {
        value.target = *mapped;
        changed = true;
      }
      return true;
    }
    if (value.kind == KIND_CONFLICT) {
      auto mapped = materialize_conflict(ctx, *value.target, depth + 1);
      if (!mapped)
        return false;
      if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {
        value.target = *mapped;
        changed = true;
      }
      return true;
    }
    return true;
  };
  for (auto &value : conflict->adds) {
    if (!rewire(value))
      return std::nullopt;
  }
  for (auto &value : conflict->removes) {
    if (!rewire(value))
      return std::nullopt;
  }
  if (!changed) {
    ctx.conflicts[old_id] = old_id;
    return old_id;
  }
  const Id new_id =
      ctx.writer.add(TYPE_CONFLICT, encode_conflict(*conflict));
  ctx.conflicts[old_id] = new_id;
  ctx.changed = true;
  return new_id;
}

std::optional<Id> materialize_tree(MaterializeCtx &ctx, const Id &old_id,
                                   std::size_t depth) {
  if (depth > 4096)
    return std::nullopt;
  auto existing = ctx.trees.find(old_id);
  if (existing != ctx.trees.end())
    return existing->second;
  auto body = ctx.store.read_body(old_id, TYPE_TREE);
  if (!body)
    return std::nullopt;
  auto tree = decode_tree(bytes_of(*body));
  if (!tree)
    return std::nullopt;
  bool changed = false;
  std::vector<TreeEntry> entries = tree->entries;
  for (auto &entry : entries) {
    std::optional<Id> mapped;
    if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||
        entry.kind == KIND_SYMLINK) {
      if (!is_lazy_blob(entry.target))
        continue;
      mapped = materialize_blob(ctx, entry.target);
    } else if (entry.kind == KIND_SUBTREE) {
      mapped = materialize_tree(ctx, entry.target, depth + 1);
    } else if (entry.kind == KIND_CONFLICT) {
      mapped = materialize_conflict(ctx, entry.target, depth + 1);
    } else if (entry.kind == KIND_SUBMODULE) {
      continue;
    } else {
      return std::nullopt;
    }
    if (!mapped)
      return std::nullopt;
    if (std::memcmp(mapped->data(), entry.target.data(), ID_LEN) != 0) {
      entry.target = *mapped;
      changed = true;
    }
  }
  if (!changed) {
    ctx.trees[old_id] = old_id;
    return old_id;
  }
  auto new_body = encode_tree(entries);
  if (!new_body)
    return std::nullopt;
  const Id new_id = ctx.writer.add(TYPE_TREE, *new_body);
  ctx.trees[old_id] = new_id;
  ++ctx.new_trees;
  ctx.changed = true;
  if (auto raw = git::load_raw(ctx.root, old_id))
    ctx.raw_saves.emplace_back(new_id, std::move(*raw));
  return new_id;
}

std::map<Id, git::Oid> reverse_git_map(const git::IdMap &map) {
  std::map<Id, git::Oid> out;
  for (const auto &item : map.items)
    out[item.second] = item.first;
  return out;
}

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_materialize(const fs::path &root) {
  git::IdMap commits_map;
  git::IdMap trees_map;
  git::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 reverse_commits = reverse_git_map(commits_map);
  const auto reverse_trees = reverse_git_map(trees_map);

  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 tx = Txn::begin(root, store);
  if (!tx) {
    error_prefix();
    std::cout << "cannot load repository state\n";
    return 1;
  }
  MaterializeCtx ctx{root, store, tx->writer(), {}, {}, {}, {}, {}, 0, 0, 0,
                     false};
  const auto roots = view_roots(*view);
  const auto ordered = ordered_commits(store, roots);
  for (const auto &old_id : ordered) {
    auto body = store.read_body(old_id, TYPE_COMMIT);
    if (!body)
      break;
    auto commit = decode_commit(bytes_of(*body));
    if (!commit)
      break;
    auto mapped_root = materialize_tree(ctx, commit->root_tree, 0);
    if (!mapped_root)
      break;
    bool changed =
        std::memcmp(mapped_root->data(), commit->root_tree.data(), ID_LEN) != 0;
    std::vector<Id> parents;
    parents.reserve(commit->parents.size());
    bool parents_ok = true;
    for (const auto &parent : commit->parents) {
      auto it = ctx.commits.find(parent);
      if (it == ctx.commits.end()) {
        parents_ok = false;
        break;
      }
      parents.push_back(it->second);
      if (std::memcmp(it->second.data(), parent.data(), ID_LEN) != 0)
        changed = true;
    }
    if (!parents_ok)
      break;
    if (!changed) {
      ctx.commits[old_id] = old_id;
      continue;
    }
    commit->root_tree = *mapped_root;
    commit->parents = std::move(parents);
    const Id new_id = ctx.writer.add(TYPE_COMMIT, encode_commit(*commit));
    ctx.commits[old_id] = new_id;
    ++ctx.new_commits;
    ctx.changed = true;
    if (auto raw = git::load_raw(root, old_id))
      ctx.raw_saves.emplace_back(new_id, std::move(*raw));
  }
  if (ctx.commits.size() != ordered.size()) {
    error_prefix();
    std::cout << "git materialize failed (missing or corrupt object)\n";
    return 1;
  }

  View &updated = tx->view();
  auto remap = [&](const Id &id) -> Id {
    auto it = ctx.commits.find(id);
    return it == ctx.commits.end() ? id : it->second;
  };
  for (auto &head : updated.heads)
    head = remap(head);
  for (auto &bookmark : updated.bookmarks) {
    for (auto &target : bookmark.targets.adds) {
      if (target)
        target = remap(*target);
    }
    for (auto &target : bookmark.targets.removes) {
      if (target)
        target = remap(*target);
    }
  }
  for (auto &tag : updated.tags)
    tag.target = remap(tag.target);
  for (auto &ref : updated.remote_refs)
    ref.target = remap(ref.target);
  for (auto &workspace : updated.working_copies)
    workspace.target = remap(workspace.target);
  sort_ids(updated.heads);

  if (!ctx.changed) {
    info_prefix();
    std::cout << "already materialized\n";
    return 0;
  }
  auto status = tx->finish("git materialize");
  if (!status) {
    error_prefix();
    std::cout << "failed to write object pack\n";
    return 1;
  }
  for (const auto &raw : ctx.raw_saves)
    (void)git::save_raw(root, raw.first,
                        Bytes(raw.second.data(), raw.second.size()));
  for (const auto &item : ctx.commits) {
    if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)
      continue;
    auto it = reverse_commits.find(item.first);
    if (it != reverse_commits.end())
      commits_map.put(it->second, item.second);
  }
  for (const auto &item : ctx.trees) {
    if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)
      continue;
    auto it = reverse_trees.find(item.first);
    if (it != reverse_trees.end())
      trees_map.put(it->second, item.second);
  }
  for (const auto &item : ctx.blobs) {
    if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)
      continue;
    if (auto oid = git::lazy_blob_oid(item.first))
      blobs_map.put(*oid, item.second);
  }
  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";
  }
  clear_stat_cache(root);
  info_prefix();
  std::cout << "materialized " << ctx.new_commits << " commits, "
            << ctx.new_trees << " trees, " << ctx.new_blobs << " blobs\n";
  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_materialize_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_materialize(*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, export, materialize, "
                 "fetch, push, remote)\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 == "materialize")
    return git_materialize_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