navid/veins / 89aa02ed6b6660b6cf09e1a7700cf3b020a1b1e2bd33fd14dace8eb1a92db071 / xveins/src/worktree.cpp

worktree.cpp

← xveins/src · 32602 bytes · raw · download

#include "worktree.h"

#include "merge.h"

#include <algorithm>
#include <atomic>
#include <fstream>
#include <iostream>
#include <mutex>
#include <set>
#include <thread>

#if !defined(_WIN32)
#include <sys/stat.h>
#endif

namespace vn {

namespace {

struct CacheEntry {
  std::string path;
  std::uint64_t size = 0;
  std::uint64_t mtime_ns = 0;
  std::uint64_t inode = 0;
  std::uint8_t kind = 0;
  bool executable = false;
  Id target{};
};

struct Cache {
  std::vector<CacheEntry> entries;
  std::int64_t written_ms = 0;
};

std::string join_rel(std::string_view base, std::string_view name) {
  if (base.empty())
    return std::string(name);
  std::string out(base);
  out.push_back('/');
  out.append(name);
  return out;
}

bool name_ends_with(std::string_view name, std::string_view suffix) {
  return name.size() >= suffix.size() &&
         name.substr(name.size() - suffix.size()) == suffix;
}

std::optional<std::string> sidecar_base(std::string_view name) {
  if (name_ends_with(name, ".base") && name.size() > 5)
    return std::string(name.substr(0, name.size() - 5));
  if (name_ends_with(name, ".ours") && name.size() > 5)
    return std::string(name.substr(0, name.size() - 5));
  if (name_ends_with(name, ".theirs") && name.size() > 7)
    return std::string(name.substr(0, name.size() - 7));
  std::size_t digits = 0;
  while (digits < name.size() && name[name.size() - 1 - digits] >= '0' &&
         name[name.size() - 1 - digits] <= '9')
    ++digits;
  if (digits > 0) {
    const std::size_t stem_end = name.size() - digits;
    const std::string_view stem = name.substr(0, stem_end);
    if (stem_end > 5 && name_ends_with(stem, ".base"))
      return std::string(stem.substr(0, stem.size() - 5));
    if (stem_end > 7 && name_ends_with(stem, ".theirs"))
      return std::string(stem.substr(0, stem.size() - 7));
  }
  return std::nullopt;
}

bool is_meta_name(std::string_view name) {
  return name == ".veins" || name == ".git";
}

bool cache_matches(const CacheEntry &entry, const StatInfo &info,
                   bool executable, std::int64_t now_ms,
                   std::int64_t written_ms) {
  if (entry.size != info.size || entry.mtime_ns != info.mtime_ns ||
      entry.inode != info.inode)
    return false;
  if (entry.executable != executable || entry.kind != info.kind)
    return false;
  const std::int64_t now_ns = now_ms * 1'000'000;
  const std::int64_t written_ns = written_ms * 1'000'000;
  constexpr std::int64_t window = 2'000'000'000;
  if (static_cast<std::int64_t>(info.mtime_ns) >= written_ns - window)
    return false;
  if (now_ns - static_cast<std::int64_t>(info.mtime_ns) < window)
    return false;
  return true;
}

Cache load_cache(const fs::path &root) {
  Cache cache;
  auto data = read_file_opt(working_copy_dir(root) / "stat-cache");
  if (!data || data->size() < 13)
    return cache;
  if (std::memcmp(data->data(), "VST1", 4) != 0)
    return cache;
  Reader r(Bytes(data->data() + 4, data->size() - 4));
  const auto version = r.u8();
  if (!version || *version != 49)
    return cache;
  const auto written = r.u64le();
  if (!written)
    return cache;
  cache.written_ms = static_cast<std::int64_t>(*written);
  const auto count = r.varint();
  if (!count)
    return cache;
  for (std::uint64_t i = 0; i < *count; ++i) {
    auto path = r.string_bytes(65536);
    if (!path)
      break;
    const auto size = r.u64le();
    const auto mtime = r.u64le();
    const auto inode = r.u64le();
    const auto kind = r.u8();
    const auto executable = r.u8();
    const auto target = r.id();
    if (!size || !mtime || !inode || !kind || !executable || !target)
      break;
    cache.entries.push_back(CacheEntry{std::move(*path), *size, *mtime, *inode,
                                       *kind, *executable != 0, *target});
  }
  std::stable_sort(cache.entries.begin(), cache.entries.end(),
                   [](const CacheEntry &a, const CacheEntry &b) {
                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
                   });
  return cache;
}

bool save_cache(const fs::path &root, const std::vector<CacheEntry> &entries,
                std::int64_t written_ms) {
  ByteWriter w(4096);
  w.raw("VST1");
  w.u8(49);
  w.u64le(static_cast<std::uint64_t>(written_ms));
  w.varint(entries.size());
  for (const auto &entry : entries) {
    w.length_prefixed(entry.path);
    w.u64le(entry.size);
    w.u64le(entry.mtime_ns);
    w.u64le(entry.inode);
    w.u8(entry.kind);
    w.u8(entry.executable ? 1 : 0);
    w.id(entry.target);
  }
  const fs::path final_path = working_copy_dir(root) / "stat-cache";
  const fs::path tmp_path = tmp_dir(root) / "stat-cache.tmp";
  return write_atomic(tmp_path, final_path, w.view());
}

const CacheEntry *cache_lookup(const Cache &cache, std::string_view path) {
  std::size_t lo = 0;
  std::size_t hi = cache.entries.size();
  while (lo < hi) {
    const std::size_t mid = lo + (hi - lo) / 2;
    const int c = compare(bytes_of(cache.entries[mid].path), bytes_of(path));
    if (c == 0)
      return &cache.entries[mid];
    if (c < 0)
      lo = mid + 1;
    else
      hi = mid;
  }
  return nullptr;
}

Id add_blob_data(Txn &txn, Bytes data) {
  BlobBuild build = build_blob(data);
  for (auto &object : build.objects) {
    const Id id =
        object.id ? *object.id : object_id(object.type, bytes_of(object.body));
    (void)txn.add_known(object.type, id, std::move(object.body));
  }
  return build.root;
}

struct BuildState {
  bool failed = false;
};

std::optional<Id> empty_tree_id(Txn &txn) {
  static const std::vector<TreeEntry> empty;
  auto body = encode_tree(empty);
  if (!body)
    return std::nullopt;
  return txn.add_object(TYPE_TREE, std::move(*body));
}

std::optional<Id>
build_dir(Txn &txn, const fs::path &root, std::string_view base,
          std::optional<Id> old_tree_id, const IgnoreRules &base_rules,
          const Cache &cache, std::vector<CacheEntry> &new_cache,
          std::int64_t now_ms, BuildState &state, std::size_t depth) {
  if (depth > 4096) {
    state.failed = true;
    return std::nullopt;
  }

  IgnoreRules local = base_rules;
  ignore_load_file(local, root, base, ".vnexclude");
  ignore_load_file(local, root, base, ".gitignore");

  std::optional<Tree> old_tree;
  if (old_tree_id) {
    auto body = txn.store().read_body(*old_tree_id, TYPE_TREE);
    if (!body) {
      state.failed = true;
      return std::nullopt;
    }
    auto decoded = decode_tree(bytes_of(*body));
    if (!decoded) {
      state.failed = true;
      return std::nullopt;
    }
    old_tree = std::move(*decoded);
  }

  const fs::path dir = base.empty() ? root : root / path_from_bytes(base);
  if (!path_is_dir(dir)) {
    state.failed = true;
    return std::nullopt;
  }

  auto names = list_directory(dir);
  std::stable_sort(names.begin(), names.end(),
                   [](const std::string &a, const std::string &b) {
                     return compare(bytes_of(a), bytes_of(b)) < 0;
                   });

  std::vector<TreeEntry> entries;
  for (const auto &name : names) {
    if (is_meta_name(name))
      continue;
    if (old_tree) {
      if (auto base_name = sidecar_base(name)) {
        const int index = find_tree_name(*old_tree, *base_name);
        if (index >= 0 &&
            old_tree->entries[static_cast<std::size_t>(index)].kind ==
                KIND_CONFLICT)
          continue;
      }
    }

    const std::string rel = join_rel(base, name);
    const fs::path fs_path = dir / path_from_bytes(name);
    const auto info = stat_path(fs_path);
    if (!info)
      continue;
    const bool is_dir = info->kind == 2;
    const bool ignored = ignore_ignored(local, rel, is_dir);
    const int old_index = old_tree ? find_tree_name(*old_tree, name) : -1;
    if (old_index >= 0 &&
        old_tree->entries[static_cast<std::size_t>(old_index)].kind ==
            KIND_CONFLICT) {
      entries.push_back(TreeEntry{
          name, KIND_CONFLICT,
          old_tree->entries[static_cast<std::size_t>(old_index)].target});
      continue;
    }
    if (ignored && old_index < 0)
      continue;

    if (is_dir) {
      std::optional<Id> child_old;
      if (old_tree && old_index >= 0) {
        const auto &old_entry =
            old_tree->entries[static_cast<std::size_t>(old_index)];
        if (old_entry.kind == KIND_SUBTREE)
          child_old = old_entry.target;
      }
      auto child = build_dir(txn, root, rel, child_old, local, cache, new_cache,
                             now_ms, state, depth + 1);
      if (state.failed)
        return std::nullopt;
      if (child)
        entries.push_back(TreeEntry{name, KIND_SUBTREE, *child});
    } else if (info->kind == 3) {
      auto target = path_read_symlink(fs_path);
      if (!target) {
        state.failed = true;
        return std::nullopt;
      }
      const Id blob = add_blob_data(txn, bytes_of(*target));
      entries.push_back(TreeEntry{name, KIND_SYMLINK, blob});
      new_cache.push_back(CacheEntry{rel, info->size, info->mtime_ns,
                                     info->inode, info->kind, false, blob});
    } else if (info->kind == 1) {
      const bool executable = info->executable;
      std::optional<Id> target;
      if (const auto *cached = cache_lookup(cache, rel)) {
        if (cache_matches(*cached, *info, executable, now_ms,
                          cache.written_ms)) {
          target = cached->target;
        }
      }
      if (!target) {
        auto data = read_file_opt(fs_path);
        if (!data) {
          state.failed = true;
          return std::nullopt;
        }
        target = add_blob_data(txn, bytes_of(*data));
      }
      new_cache.push_back(CacheEntry{rel, info->size, info->mtime_ns,
                                     info->inode, info->kind, executable,
                                     *target});
      entries.push_back(
          TreeEntry{name, executable ? KIND_EXECUTABLE : KIND_FILE, *target});
    }
  }

  if (entries.empty())
    return std::nullopt;
  auto body = encode_tree(entries);
  if (!body) {
    state.failed = true;
    return std::nullopt;
  }
  return txn.add_object(TYPE_TREE, std::move(*body));
}

// ---------------------------------------------------------------------------
// Checkout helpers
// ---------------------------------------------------------------------------

struct WalkEntry {
  std::string path;
  std::uint8_t kind = 0;
  Id target{};
};

bool valid_checkout_component(std::string_view component) {
  if (!valid_name(component))
    return false;
  return !ascii_iequals(bytes_of(component), bytes_of(".git"));
}

bool valid_checkout_path(std::string_view path) {
  if (!valid_path(path))
    return false;
  std::size_t start = 0;
  for (std::size_t i = 0; i <= path.size(); ++i) {
    if (i == path.size() || path[i] == '/') {
      if (!valid_checkout_component(path.substr(start, i - start)))
        return false;
      start = i + 1;
    }
  }
  return true;
}

bool has_symlink_component(const fs::path &root, std::string_view rel) {
  fs::path current = root;
  std::size_t start = 0;
  for (std::size_t i = 0; i < rel.size(); ++i) {
    if (rel[i] == '/') {
      if (i == start)
        return true;
      current /= path_from_bytes(rel.substr(start, i - start));
      const auto info = stat_path(current);
      if (info && info->kind == 3)
        return true;
      start = i + 1;
    }
  }
  return false;
}

bool ensure_safe_dirs(const fs::path &root, std::string_view rel) {
  if (rel.empty())
    return true;
  fs::path current = root;
  std::size_t start = 0;
  for (std::size_t i = 0; i <= rel.size(); ++i) {
    const bool at_end = i == rel.size();
    if (!at_end && rel[i] != '/')
      continue;
    const std::string_view component = rel.substr(start, i - start);
    if (component.empty())
      return false;
    if (at_end)
      break; // final component is the file
    current /= path_from_bytes(component);
    const auto info = stat_path(current);
    if (info) {
      if (info->kind == 3 || info->kind != 2)
        return false;
    } else if (!ensure_directory(current)) {
      return false;
    }
    start = i + 1;
  }
  return true;
}

bool remove_any(const fs::path &path) {
  std::error_code ec;
  if (path_is_dir(path) && !path_is_symlink(path)) {
    fs::remove_all(path, ec);
    return !ec;
  }
  return remove_file(path);
}

bool write_bytes_to_path(const fs::path &root, std::string_view rel, Bytes data,
                         bool executable, std::string &error_path) {
  error_path = std::string(rel);
  if (!valid_checkout_path(rel) || has_symlink_component(root, rel))
    return false;
  if (!ensure_safe_dirs(root, rel))
    return false;
  const fs::path final_path = root / path_from_bytes(rel);
  if (path_is_dir(final_path) && !path_is_symlink(final_path))
    return false;
  if (path_is_symlink(final_path))
    (void)remove_file(final_path);
  if (!write_file(final_path, data))
    return false;
#if !defined(_WIN32)
  const mode_t mode = executable ? 0755 : 0644;
  (void)::chmod(final_path.c_str(), mode);
#else
  (void)executable;
#endif
  return true;
}

bool write_symlink_to_path(const fs::path &root, std::string_view rel,
                           std::string_view target, std::string &error_path) {
  error_path = std::string(rel);
  if (!valid_checkout_path(rel) || has_symlink_component(root, rel))
    return false;
  if (!ensure_safe_dirs(root, rel))
    return false;
  const fs::path final_path = root / path_from_bytes(rel);
  if (path_is_dir(final_path) && !path_is_symlink(final_path))
    return false;
  if (path_exists(final_path))
    (void)remove_any(final_path);
  std::error_code ec;
  fs::create_symlink(path_from_bytes(target), final_path, ec);
  return !ec;
}

bool write_entry(Store &store, const fs::path &root, const WalkEntry &entry,
                 std::string &error_path) {
  if (entry.kind == KIND_SYMLINK) {
    auto data = read_blob(store, entry.target);
    if (!data)
      return false;
    return write_symlink_to_path(root, entry.path, str_of(bytes_of(*data)),
                                 error_path);
  }
  auto data = read_blob(store, entry.target);
  if (!data)
    return false;
  return write_bytes_to_path(root, entry.path, bytes_of(*data),
                             entry.kind == KIND_EXECUTABLE, error_path);
}

bool prune_empty_parents(const fs::path &root, std::string_view rel) {
  std::size_t end = rel.size();
  while (end > 0) {
    const std::size_t slash = rel.rfind('/', end - 1);
    if (slash == std::string_view::npos)
      break;
    const std::string parent(rel.substr(0, slash));
    const fs::path abs = root / path_from_bytes(parent);
    std::error_code ec;
    if (!fs::remove(abs, ec) || ec)
      break;
    end = slash;
  }
  return true;
}

void remove_tracked_path(const fs::path &root, std::string_view rel) {
  const fs::path abs = root / path_from_bytes(rel);
  if (path_exists(abs) || path_is_symlink(abs)) {
    (void)remove_any(abs);
    (void)prune_empty_parents(root, rel);
  }
}

std::vector<std::string> sidecar_suffixes() {
  std::vector<std::string> out = {".base", ".ours", ".theirs"};
  for (int n = 2; n <= 64; ++n) {
    out.push_back(".base" + std::to_string(n));
    out.push_back(".theirs" + std::to_string(n));
  }
  return out;
}

void delete_sidecars(const fs::path &root, std::string_view path) {
  static const auto suffixes = sidecar_suffixes();
  for (const auto &suffix : suffixes) {
    std::string full(path);
    full += suffix;
    remove_tracked_path(root, full);
  }
}

bool delete_stale(Store &store, const fs::path &root,
                  const std::vector<FlatEntry> &old_entries,
                  const std::vector<FlatEntry> &new_entries) {
  bool ok = true;
  for (const auto &old_entry : old_entries) {
    if (old_entry.kind == KIND_SUBMODULE)
      continue;
    if (find_flat(new_entries, old_entry.path))
      continue;
    const fs::path abs = root / path_from_bytes(old_entry.path);
    if (path_exists(abs) || path_is_symlink(abs)) {
      if (!remove_any(abs))
        ok = false;
      else
        (void)prune_empty_parents(root, old_entry.path);
    }
    if (old_entry.kind == KIND_CONFLICT)
      delete_sidecars(root, old_entry.path);
  }
  (void)store;
  return ok;
}

std::optional<Conflict> load_conflict(Store &store, const Id &id) {
  auto body = store.read_body(id, TYPE_CONFLICT);
  if (!body)
    return std::nullopt;
  auto decoded = decode_conflict(bytes_of(*body));
  if (!decoded)
    return std::nullopt;
  return std::move(*decoded);
}

bool write_tree_side(Store &store, const fs::path &root, const Id &tree_id,
                     std::string_view prefix, std::string &error_path) {
  const auto entries = flatten_tree(store, tree_id);
  for (const auto &entry : entries) {
    if (entry.kind == KIND_CONFLICT)
      continue;
    if (entry.kind == KIND_SUBMODULE)
      continue;
    std::string path(prefix);
    if (!path.empty())
      path.push_back('/');
    path += entry.path;
    if (!write_entry(store, root, WalkEntry{path, entry.kind, entry.target},
                     error_path))
      return false;
  }
  return true;
}

bool materialize_value(Store &store, const fs::path &root,
                       std::string_view path, const ConflictValue &value,
                       std::string &error_path) {
  error_path = std::string(path);
  if (value.kind == 0) {
    remove_tracked_path(root, path);
    return true;
  }
  if (!value.target)
    return false;
  if (value.kind == KIND_SUBTREE) {
    remove_tracked_path(root, path);
    return write_tree_side(store, root, *value.target, path, error_path);
  }
  return write_entry(store, root,
                     WalkEntry{std::string(path), value.kind, *value.target},
                     error_path);
}

bool materialize_conflict(Store &store, const fs::path &root,
                          std::string_view path, const Id &target,
                          std::string &error_path) {
  auto conflict = load_conflict(store, target);
  if (!conflict) {
    error_path = std::string(path);
    return false;
  }
  bool ok = true;
  for (std::size_t i = 0; i < conflict->removes.size(); ++i) {
    std::string suffix = i == 0 ? ".base" : ".base" + std::to_string(i + 1);
    std::string full(path);
    full += suffix;
    if (!materialize_value(store, root, full, conflict->removes[i], error_path))
      ok = false;
  }
  for (std::size_t i = 0; i < conflict->adds.size(); ++i) {
    std::string suffix;
    if (i == 0)
      suffix = ".ours";
    else if (i == 1)
      suffix = ".theirs";
    else
      suffix = ".theirs" + std::to_string(i + 1);
    std::string full(path);
    full += suffix;
    if (!materialize_value(store, root, full, conflict->adds[i], error_path))
      ok = false;
  }
  if (!conflict->adds.empty()) {
    if (!materialize_value(store, root, path, conflict->adds.front(),
                           error_path))
      ok = false;
  } else {
    remove_tracked_path(root, path);
  }
  return ok;
}

int materialize_tree(Store &store, const fs::path &root,
                     const std::vector<FlatEntry> &old_entries,
                     const Id &new_root) {
  auto checked_entries = flatten_tree_checked(store, new_root);
  if (!checked_entries) {
    error_prefix();
    std::cout << "checkout tree validation failed\n";
    return 1;
  }
  const auto &new_entries = *checked_entries;
  std::set<std::string> dirs;
  std::vector<WalkEntry> files;
  std::vector<FlatEntry> conflicts;
  for (const auto &entry : new_entries) {
    if (!valid_checkout_path(entry.path)) {
      error_prefix();
      std::cout << "checkout tree validation failed at: " << entry.path << "\n";
      return 1;
    }
    std::string dir_path;
    std::size_t start = 0;
    for (std::size_t i = 0; i < entry.path.size(); ++i) {
      if (entry.path[i] == '/') {
        dir_path.append(entry.path.substr(start, i - start));
        dirs.insert(dir_path);
        dir_path.push_back('/');
        start = i + 1;
      }
    }
    if (entry.kind == KIND_CONFLICT) {
      conflicts.push_back(entry);
    } else if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||
               entry.kind == KIND_SYMLINK) {
      files.push_back(WalkEntry{entry.path, entry.kind, entry.target});
    }
  }

  // Sidecar collision check.
  const auto suffixes = sidecar_suffixes();
  for (const auto &conflict : conflicts) {
    for (const auto &suffix : suffixes) {
      std::string full = conflict.path;
      full += suffix;
      if (find_flat(old_entries, full)) {
        error_prefix();
        std::cout << "conflict sidecar would overwrite a tracked path: " << full
                  << "\n";
        return 1;
      }
    }
  }

  // Remove sidecars left by a previous materialization.
  for (const auto &entry : old_entries) {
    if (entry.kind == KIND_CONFLICT)
      delete_sidecars(root, entry.path);
  }

  if (!delete_stale(store, root, old_entries, new_entries)) {
    error_prefix();
    std::cout << "cannot remove files that are absent from the target tree\n";
    return 1;
  }

  for (const auto &dir : dirs) {
    if (!ensure_safe_dirs(root, dir + "/x")) {
      error_prefix();
      std::cout << "cannot create directory: " << dir << "\n";
      return 1;
    }
  }

  std::string error_path;
  if (!files.empty()) {
    std::size_t workers = available_cpu_count();
    if (workers == 0)
      workers = 1;
    workers = std::min<std::size_t>(workers, files.size());
    workers = std::min<std::size_t>(workers, 16);
    if (workers > 1)
      store.preload();
    std::atomic<std::size_t> next{0};
    std::atomic<bool> failed{false};
    std::mutex error_mutex;
    std::vector<std::thread> threads;
    threads.reserve(workers);
    for (std::size_t w = 0; w < workers; ++w) {
      threads.emplace_back([&]() {
        for (;;) {
          const std::size_t index = next.fetch_add(1);
          if (index >= files.size() || failed.load(std::memory_order_relaxed))
            return;
          std::string local_error;
          if (!write_entry(store, root, files[index], local_error)) {
            std::lock_guard<std::mutex> lock(error_mutex);
            if (!failed.exchange(true))
              error_path = std::move(local_error);
            return;
          }
        }
      });
    }
    for (auto &thread : threads)
      thread.join();
    if (failed.load()) {
      error_prefix();
      std::cout << "checkout failed at: " << error_path << "\n";
      return 1;
    }
  }
  for (const auto &conflict : conflicts) {
    if (!materialize_conflict(store, root, conflict.path, conflict.target,
                              error_path)) {
      error_prefix();
      std::cout << "checkout failed at: " << error_path << "\n";
      return 1;
    }
  }

  info_prefix();
  std::cout << "checked out " << files.size() << " files\n";
  return 0;
}

} // namespace

// ---------------------------------------------------------------------------
// Snapshot
// ---------------------------------------------------------------------------

int snapshot_run(const fs::path &root) {
  Store store = Store::open_all(root);
  const int status = snapshot_run(root, store);
  return status;
}

int snapshot_run(const fs::path &root, Store &store) {
  auto tx = Txn::begin(root, store);
  if (!tx) {
    error_prefix();
    std::cout << "cannot load repository state\n";
    return 1;
  }

  const auto wc = working_copy_id(tx->view());
  std::optional<Commit> old_commit;
  std::optional<Id> old_tree;
  bool old_empty = false;
  bool have_wc = false;
  if (wc) {
    have_wc = true;
    auto body = tx->store().read_body(*wc, TYPE_COMMIT);
    if (!body) {
      error_prefix();
      std::cout << "missing working-copy commit\n";
      return 1;
    }
    auto decoded = decode_commit(bytes_of(*body));
    if (!decoded) {
      error_prefix();
      std::cout << "corrupt working-copy commit\n";
      return 1;
    }
    old_commit = std::move(*decoded);
    old_tree = old_commit->root_tree;
    if (old_commit->parents.size() == 1) {
      auto parent_body =
          tx->store().read_body(old_commit->parents.front(), TYPE_COMMIT);
      if (parent_body) {
        auto parent_commit = decode_commit(bytes_of(*parent_body));
        if (parent_commit)
          old_empty = std::memcmp(parent_commit->root_tree.data(),
                                  old_commit->root_tree.data(), ID_LEN) == 0;
      }
    }
  }

  IgnoreRules rules = ignore_empty();
  ignore_load_root(rules, root);
  const Cache cache = load_cache(root);
  std::vector<CacheEntry> new_cache;
  const std::int64_t now_ms = unix_now_millis();
  BuildState state;
  auto built = build_dir(*tx, root, "", old_tree, rules, cache, new_cache,
                         now_ms, state, 0);

  std::optional<Id> new_root;
  if (!state.failed && built) {
    new_root = built;
  } else if (!state.failed) {
    new_root = empty_tree_id(*tx);
  }
  if (!new_root || state.failed) {
    error_prefix();
    std::cout << "failed to build working-copy tree\n";
    return 1;
  }

  const bool unchanged =
      old_tree && std::memcmp(old_tree->data(), new_root->data(), ID_LEN) == 0;
  if (unchanged) {
    std::vector<CacheEntry> sorted = new_cache;
    std::stable_sort(sorted.begin(), sorted.end(),
                     [](const CacheEntry &a, const CacheEntry &b) {
                       return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
                     });
    (void)save_cache(root, sorted, now_ms);
    return 0;
  }

  const Sig committer = identity_signature(root);
  Sig author = committer;
  std::vector<Id> parents;
  ChangeId change_id{};
  std::string message;
  if (old_commit) {
    if (!old_empty)
      author = old_commit->author;
    parents = old_commit->parents;
    change_id = old_commit->change_id;
    message = old_commit->message;
  } else {
    change_id = random_change_id();
  }

  std::vector<Rename> renames;
  if (old_commit)
    renames = old_commit->renames;
  if (old_tree &&
      std::memcmp(old_tree->data(), new_root->data(), ID_LEN) != 0) {
    auto detected = detect_renames(
        tx->store(), &*tx, old_tree, std::optional<Id>{*new_root},
        rename_similar_pct(root), 0);
    for (auto &rename : detected)
      renames.push_back(std::move(rename));
  }
  std::stable_sort(renames.begin(), renames.end(),
                   [](const Rename &a, const Rename &b) {
                     if (a.parent_index != b.parent_index)
                       return a.parent_index < b.parent_index;
                     return compare(bytes_of(a.to_path), bytes_of(b.to_path)) <
                            0;
                   });

  Commit commit;
  commit.version = 1;
  commit.parents = parents;
  commit.root_tree = *new_root;
  commit.change_id = change_id;
  commit.author = author;
  commit.committer = committer;
  commit.message = message;
  commit.renames_state = RENAMES_RECORDED;
  commit.renames = std::move(renames);
  commit.extra = old_commit ? old_commit->extra : std::vector<KeyValue>{};
  const auto encoded = encode_commit(commit);
  const Id new_commit = tx->add_object(TYPE_COMMIT, encoded);

  if (have_wc) {
    remove_head(tx->view(), *wc);
    move_bookmarks(tx->view(), *wc, new_commit);
  }
  if (auto current = current_bookmark_name(root)) {
    if (find_bookmark(tx->view(), *current))
      set_bookmark_target(tx->view(), *current, new_commit);
  }
  set_workspace(tx->view(), new_commit);
  rebuild_heads(tx->view());

  const auto status = tx->finish("snapshot");
  if (!status)
    return 1;
  store.refresh(root);
  (void)mark_native(root, new_commit);

  std::vector<CacheEntry> sorted = new_cache;
  std::stable_sort(sorted.begin(), sorted.end(),
                   [](const CacheEntry &a, const CacheEntry &b) {
                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
                   });
  (void)save_cache(root, sorted, now_ms);
  return 0;
}

// ---------------------------------------------------------------------------
// Checkout
// ---------------------------------------------------------------------------

int checkout_materialize_commit(const fs::path &root, Store &store,
                                std::optional<Id> old_root,
                                const Id &new_root) {
  if (old_root && std::memcmp(old_root->data(), new_root.data(), ID_LEN) == 0)
    return 0;
  const auto old_entries = flatten_or_empty(store, old_root);
  const int status = materialize_tree(store, root, old_entries, new_root);
  if (status == 0)
    clear_stat_cache(root);
  return status;
}

void clear_stat_cache(const fs::path &root) {
  (void)remove_file(working_copy_dir(root) / "stat-cache");
}

int checkout_materialize_optional(const fs::path &root, Store &store,
                                  std::optional<Id> old_root,
                                  std::optional<Id> new_root) {
  if (new_root)
    return checkout_materialize_commit(root, store, old_root, *new_root);
  const auto old_entries = flatten_or_empty(store, old_root);
  if (old_entries.empty()) {
    clear_stat_cache(root);
    return 0;
  }
  if (!delete_stale(store, root, old_entries, {})) {
    error_prefix();
    std::cout << "cannot remove files absent from the restored view\n";
    return 1;
  }
  clear_stat_cache(root);
  return 0;
}

std::optional<Id> create_working_copy_commit(Txn &tx, const Id &parent) {
  auto loaded = load_commit(tx.store(), parent);
  if (!loaded)
    return std::nullopt;
  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(tx.store().root());
  commit.committer = commit.author;
  commit.renames_state = RENAMES_RECORDED;
  return tx.add_object(TYPE_COMMIT, encode_commit(commit));
}

int checkout_run(const fs::path &root, std::string_view rev) {
  const int snap = snapshot_run(root);
  if (snap != 0)
    return snap;

  Store store = Store::open_all(root);
  auto view = current_view(root, store);
  if (!view) {
    error_prefix();
    std::cout << "no operation state; import a repository first\n";
    return 1;
  }

  const auto target = resolve_revision(store, *view, rev);
  if (!target) {
    error_prefix();
    std::cout << "unknown revision: " << rev << "\n";
    return 1;
  }
  bool bookmark_checkout = false;
  bool detach_bookmark = false;
  if (!rev.empty() && rev != "@") {
    bookmark_checkout = find_bookmark(*view, rev).has_value();
    detach_bookmark = !bookmark_checkout;
  }
  auto commit_body = store.read_body(*target, TYPE_COMMIT);
  if (!commit_body) {
    error_prefix();
    std::cout << "cannot read commit\n";
    return 1;
  }
  auto commit = decode_commit(bytes_of(*commit_body));
  if (!commit) {
    error_prefix();
    std::cout << "cannot read commit\n";
    return 1;
  }

  const auto wc = working_copy_id(*view);
  std::optional<Id> old_root;
  if (wc) {
    auto old_body = store.read_body(*wc, TYPE_COMMIT);
    if (old_body) {
      auto old_commit = decode_commit(bytes_of(*old_body));
      if (old_commit)
        old_root = old_commit->root_tree;
    }
  }

  const int materialized =
      checkout_materialize_commit(root, store, old_root, commit->root_tree);
  if (materialized != 0)
    return materialized;

  if (!wc || std::memcmp(wc->data(), target->data(), ID_LEN) != 0) {
    bool already_empty_child = false;
    if (wc) {
      auto wc_loaded = load_commit(store, *wc);
      if (wc_loaded && wc_loaded->commit.parents.size() == 1 &&
          std::memcmp(wc_loaded->commit.parents.front().data(), target->data(),
                      ID_LEN) == 0 &&
          std::memcmp(wc_loaded->commit.root_tree.data(),
                      commit->root_tree.data(), ID_LEN) == 0 &&
          wc_loaded->commit.message.empty()) {
        already_empty_child = true;
      }
    }
    if (!already_empty_child) {
      auto tx = Txn::begin(root, store);
      if (!tx) {
        error_prefix();
        std::cout << "cannot load repository state\n";
        return 1;
      }
      if (wc)
        remove_head(tx->view(), *wc);
      auto child = create_working_copy_commit(*tx, *target);
      if (!child)
        return 1;
      set_workspace(tx->view(), *child);
      rebuild_heads(tx->view());
      const auto status = tx->finish("checkout");
      if (!status)
        return 1;
    }
  }
  if (bookmark_checkout)
    (void)set_current_bookmark(root, rev);
  else if (detach_bookmark)
    (void)clear_current_bookmark(root);
  return 0;
}

} // namespace vn