navid/veins / 9892cd4abd2cafaa2face537414206345988784d1f0f786b824d9e95b1ba1e7e / xveins/src/merge.cpp

merge.cpp

← xveins/src · 70549 bytes · raw · download

#include "merge.h"

#include "pathspec.h"
#include "worktree.h"

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <set>
#include <utility>

namespace vn {

namespace {

// ---------------------------------------------------------------------------
// Object access that also sees pending transaction objects
// ---------------------------------------------------------------------------

bool same_id(const Id &a, const Id &b) {
  return std::memcmp(a.data(), b.data(), ID_LEN) == 0;
}

std::optional<std::vector<std::uint8_t>> read_body_any(Store &store, Txn *tx,
                                                       std::uint8_t type,
                                                       const Id &id) {
  if (tx) {
    if (auto cached = tx->writer().find_cached(type, id))
      return cached;
  }
  return store.read_body(id, type);
}

bool append_blob_any(Store &store, Txn *tx, const Id &id,
                     std::vector<std::uint8_t> &out, std::size_t depth) {
  if (depth > 64)
    return false;
  auto body = read_body_any(store, tx, TYPE_BLOB, id);
  if (!body)
    return false;
  auto blob = decode_blob(bytes_of(*body));
  if (!blob)
    return false;
  if (blob->form == BlobForm::Inline) {
    out.insert(out.end(), blob->data.begin(), blob->data.end());
    return true;
  }
  for (const auto &entry : blob->entries) {
    if (blob->form == BlobForm::Leaf) {
      auto chunk = read_body_any(store, tx, TYPE_CHUNK, entry.id);
      if (!chunk)
        return false;
      out.insert(out.end(), chunk->begin(), chunk->end());
    } else if (!append_blob_any(store, tx, entry.id, out, depth + 1)) {
      return false;
    }
  }
  return true;
}

std::optional<std::vector<std::uint8_t>> read_blob_any(Store &store, Txn *tx,
                                                       const Id &id) {
  std::vector<std::uint8_t> out;
  if (!append_blob_any(store, tx, id, out, 0))
    return std::nullopt;
  return out;
}

bool collect_chunks_any(Store &store, Txn *tx, const Id &id,
                        std::vector<Id> &out, std::size_t depth) {
  if (depth > 64)
    return false;
  auto body = read_body_any(store, tx, TYPE_BLOB, id);
  if (!body)
    return false;
  auto blob = decode_blob(bytes_of(*body));
  if (!blob)
    return false;
  if (blob->form == BlobForm::Leaf) {
    for (const auto &entry : blob->entries)
      out.push_back(entry.id);
    return true;
  }
  if (blob->form == BlobForm::Interior) {
    for (const auto &entry : blob->entries) {
      if (!collect_chunks_any(store, tx, entry.id, out, depth + 1))
        return false;
    }
  }
  return true;
}

bool flatten_any(Store &store, Txn *tx, const Id &tree_id, std::string &prefix,
                 std::vector<FlatEntry> &out, std::size_t depth) {
  if (depth > 4096)
    return false;
  auto body = read_body_any(store, tx, TYPE_TREE, tree_id);
  if (!body)
    return false;
  auto tree = decode_tree(bytes_of(*body));
  if (!tree)
    return false;
  for (const auto &entry : tree->entries) {
    const std::size_t old_size = prefix.size();
    if (!prefix.empty())
      prefix.push_back('/');
    prefix.append(entry.name);
    if (entry.kind == KIND_SUBTREE) {
      if (!flatten_any(store, tx, entry.target, prefix, out, depth + 1)) {
        prefix.resize(old_size);
        return false;
      }
      prefix.resize(old_size);
    } else {
      out.push_back(FlatEntry{prefix, entry.kind, entry.target});
      prefix.resize(old_size);
    }
  }
  return true;
}

std::vector<FlatEntry> flatten_any_sorted(Store &store, Txn *tx,
                                          std::optional<Id> tree) {
  std::vector<FlatEntry> out;
  if (!tree)
    return out;
  std::string prefix;
  (void)flatten_any(store, tx, *tree, prefix, out, 0);
  std::stable_sort(out.begin(), out.end(),
                   [](const FlatEntry &a, const FlatEntry &b) {
                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
                   });
  return out;
}

const FlatEntry *find_flat_entry(const std::vector<FlatEntry> &entries,
                                 std::string_view path) {
  for (const auto &entry : entries) {
    if (entry.path == path)
      return &entry;
  }
  return nullptr;
}

bool tree_empty_any(Store &store, Txn *tx, const Id &id) {
  auto body = read_body_any(store, tx, TYPE_TREE, id);
  if (!body)
    return true;
  auto tree = decode_tree(bytes_of(*body));
  return !tree || tree->entries.empty();
}

Id add_tree(Txn &tx, const std::vector<TreeEntry> &entries) {
  auto encoded = encode_tree(entries);
  if (!encoded)
    return Id{};
  return tx.add_object(TYPE_TREE, *encoded);
}

Id add_empty_tree(Txn &tx) { return add_tree(tx, {}); }

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

// ---------------------------------------------------------------------------
// Three-way line merge
// ---------------------------------------------------------------------------

struct DiffOp {
  char tag = ' ';
  std::size_t ai = 0;
  std::size_t bi = 0;
};

std::vector<std::string> split_lines(Bytes data) {
  std::vector<std::string> out;
  std::size_t start = 0;
  for (std::size_t i = 0; i < data.size(); ++i) {
    if (data[i] == '\n') {
      out.emplace_back(reinterpret_cast<const char *>(data.data() + start),
                       i + 1 - start);
      start = i + 1;
    }
  }
  if (start < data.size())
    out.emplace_back(reinterpret_cast<const char *>(data.data() + start),
                     data.size() - start);
  return out;
}

std::vector<DiffOp> fallback_ops(const std::vector<std::string> &a,
                                 const std::vector<std::string> &b) {
  const std::size_t n = a.size();
  const std::size_t m = b.size();
  std::size_t prefix = 0;
  while (prefix < n && prefix < m && a[prefix] == b[prefix])
    ++prefix;
  std::size_t suffix = 0;
  while (suffix < n - prefix && suffix < m - prefix &&
         a[n - 1 - suffix] == b[m - 1 - suffix])
    ++suffix;
  std::vector<DiffOp> ops;
  for (std::size_t i = 0; i < prefix; ++i)
    ops.push_back(DiffOp{' ', i, i});
  for (std::size_t i = prefix; i < n - suffix; ++i)
    ops.push_back(DiffOp{'-', i, 0});
  for (std::size_t j = prefix; j < m - suffix; ++j)
    ops.push_back(DiffOp{'+', 0, j});
  for (std::size_t k = 0; k < suffix; ++k)
    ops.push_back(DiffOp{' ', n - suffix + k, m - suffix + k});
  return ops;
}

std::vector<DiffOp> build_ops(const std::vector<std::string> &a,
                              const std::vector<std::string> &b) {
  const std::size_t n = a.size();
  const std::size_t m = b.size();
  const std::uint64_t cells =
      static_cast<std::uint64_t>(n + 1) * static_cast<std::uint64_t>(m + 1);
  if (cells > 8000000)
    return fallback_ops(a, b);
  const std::size_t cols = m + 1;
  std::vector<std::uint32_t> dp(static_cast<std::size_t>(cells), 0);
  for (std::size_t i = 1; i <= n; ++i) {
    for (std::size_t j = 1; j <= m; ++j) {
      if (a[i - 1] == b[j - 1]) {
        dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;
      } else {
        dp[i * cols + j] =
            std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);
      }
    }
  }
  std::vector<DiffOp> ops;
  std::size_t oi = n;
  std::size_t oj = m;
  while (oi > 0 || oj > 0) {
    if (oi > 0 && oj > 0 && a[oi - 1] == b[oj - 1]) {
      ops.push_back(DiffOp{' ', oi - 1, oj - 1});
      --oi;
      --oj;
    } else if (oj > 0 &&
               (oi == 0 || dp[oi * cols + (oj - 1)] >=
                               dp[(oi - 1) * cols + oj])) {
      ops.push_back(DiffOp{'+', 0, oj - 1});
      --oj;
    } else {
      ops.push_back(DiffOp{'-', oi - 1, 0});
      --oi;
    }
  }
  std::reverse(ops.begin(), ops.end());
  return ops;
}

struct Hunk {
  std::size_t start = 0;
  std::size_t end = 0;
  std::vector<std::string> lines;
};

std::vector<Hunk> hunks_from_ops(const std::vector<std::string> &side,
                                 const std::vector<DiffOp> &ops) {
  std::vector<Hunk> out;
  std::size_t base_pos = 0;
  std::size_t i = 0;
  while (i < ops.size()) {
    if (ops[i].tag == ' ') {
      ++base_pos;
      ++i;
      continue;
    }
    Hunk hunk;
    hunk.start = base_pos;
    while (i < ops.size() && ops[i].tag != ' ') {
      if (ops[i].tag == '-') {
        ++base_pos;
      } else {
        hunk.lines.push_back(side[ops[i].bi]);
      }
      ++i;
    }
    hunk.end = base_pos;
    out.push_back(std::move(hunk));
  }
  return out;
}

std::vector<Hunk> diff_hunks(const std::vector<std::string> &base,
                             const std::vector<std::string> &side) {
  return hunks_from_ops(side, build_ops(base, side));
}

struct MergeRange {
  std::size_t base_start = 0;
  std::size_t base_end = 0;
  std::size_t ours_start = 0;
  std::size_t ours_end = 0;
  std::size_t theirs_start = 0;
  std::size_t theirs_end = 0;
};

struct EditResult {
  bool conflicted = false;
  std::vector<std::uint8_t> data;
  std::vector<MergeRange> ranges;
};

void append_lines(std::vector<std::uint8_t> &out,
                  const std::vector<std::string> &lines, std::size_t start,
                  std::size_t end) {
  for (std::size_t i = start; i < end && i < lines.size(); ++i)
    out.insert(out.end(), lines[i].begin(), lines[i].end());
}

void apply_hunks(std::vector<std::uint8_t> &out,
                 const std::vector<std::string> &base, std::size_t from,
                 std::size_t to, const std::vector<Hunk> &hunks,
                 std::size_t first, std::size_t last) {
  std::size_t pos = from;
  for (std::size_t k = first; k < last; ++k) {
    const Hunk &h = hunks[k];
    if (h.start > pos && h.start <= to)
      append_lines(out, base, pos, h.start);
    for (const auto &line : h.lines)
      out.insert(out.end(), line.begin(), line.end());
    if (h.end > pos)
      pos = h.end;
  }
  if (pos < to)
    append_lines(out, base, pos, to);
}

std::size_t map_pos(const std::vector<Hunk> &hunks, std::size_t pos) {
  std::ptrdiff_t out = static_cast<std::ptrdiff_t>(pos);
  for (const auto &h : hunks) {
    if (h.end <= pos) {
      const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(h.end - h.start);
      const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());
      out += fresh - old;
    } else if (h.start < pos) {
      const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(pos - h.start);
      const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());
      out += fresh - old;
      break;
    } else {
      break;
    }
  }
  return static_cast<std::size_t>(out);
}

bool same_hunks(const std::vector<Hunk> &ours, std::size_t of, std::size_t ol,
                const std::vector<Hunk> &theirs, std::size_t tf,
                std::size_t tl) {
  std::string a;
  std::string b;
  for (std::size_t k = of; k < ol; ++k)
    for (const auto &line : ours[k].lines)
      a += line;
  for (std::size_t j = tf; j < tl; ++j)
    for (const auto &line : theirs[j].lines)
      b += line;
  return a == b;
}

EditResult merge_lines(const std::vector<std::string> &base,
                       const std::vector<std::string> &ours,
                       const std::vector<std::string> &theirs,
                       bool adjacent_merge) {
  const auto ours_h = diff_hunks(base, ours);
  const auto theirs_h = diff_hunks(base, theirs);
  EditResult result;
  std::size_t oi = 0;
  std::size_t ti = 0;
  std::size_t pos = 0;
  while (oi < ours_h.size() || ti < theirs_h.size()) {
    const bool have_o = oi < ours_h.size();
    const bool have_t = ti < theirs_h.size();
    const std::size_t o_start = have_o ? ours_h[oi].start : 0;
    const std::size_t t_start = have_t ? theirs_h[ti].start : 0;
    const bool take_ours_cluster = have_o && (!have_t || o_start <= t_start);
    const std::size_t cluster_start = take_ours_cluster ? o_start : t_start;
    const std::size_t of = oi;
    const std::size_t tf = ti;
    std::size_t o_last = of;
    std::size_t t_last = tf;
    std::size_t end = cluster_start;
    bool seen_o = false;
    bool seen_t = false;
    for (;;) {
      bool progress = false;
      if (o_last < ours_h.size()) {
        const Hunk &h = ours_h[o_last];
        bool include = h.start <= end;
        if (o_last != of)
          include = adjacent_merge ? h.start < end : h.start <= end;
        if (include) {
          seen_o = true;
          ++o_last;
          if (h.end > end)
            end = h.end;
          progress = true;
        }
      }
      if (t_last < theirs_h.size()) {
        const Hunk &h = theirs_h[t_last];
        bool include = h.start <= end;
        if (t_last != tf)
          include = adjacent_merge ? h.start < end : h.start <= end;
        if (include) {
          seen_t = true;
          ++t_last;
          if (h.end > end)
            end = h.end;
          progress = true;
        }
      }
      if (!progress)
        break;
    }
    if (end < cluster_start)
      end = cluster_start;
    if (seen_o && !seen_t) {
      apply_hunks(result.data, base, pos, end, ours_h, of, o_last);
      pos = end;
      oi = o_last;
      ti = t_last;
    } else if (seen_t && !seen_o) {
      apply_hunks(result.data, base, pos, end, theirs_h, tf, t_last);
      pos = end;
      oi = o_last;
      ti = t_last;
    } else {
      if (same_hunks(ours_h, of, o_last, theirs_h, tf, t_last)) {
        apply_hunks(result.data, base, pos, end, ours_h, of, o_last);
        pos = end;
      } else {
        result.conflicted = true;
        apply_hunks(result.data, base, pos, end, ours_h, of, o_last);
        MergeRange range;
        range.base_start = cluster_start;
        range.base_end = end;
        range.ours_start = map_pos(ours_h, cluster_start);
        range.ours_end = map_pos(ours_h, end);
        range.theirs_start = map_pos(theirs_h, cluster_start);
        range.theirs_end = map_pos(theirs_h, end);
        result.ranges.push_back(range);
        pos = end;
      }
      oi = o_last;
      ti = t_last;
    }
  }
  if (pos < base.size())
    append_lines(result.data, base, pos, base.size());
  return result;
}

std::optional<EditResult> merge_blobs(Store &store, Txn *tx, const Id &base_id,
                                      const Id &ours_id, const Id &theirs_id,
                                      bool adjacent) {
  auto base = read_blob_any(store, tx, base_id);
  auto ours = read_blob_any(store, tx, ours_id);
  auto theirs = read_blob_any(store, tx, theirs_id);
  if (!base || !ours || !theirs)
    return std::nullopt;
  return merge_lines(split_lines(bytes_of(*base)), split_lines(bytes_of(*ours)),
                     split_lines(bytes_of(*theirs)), adjacent);
}

// ---------------------------------------------------------------------------
// Rename detection
// ---------------------------------------------------------------------------

struct RenamePair {
  std::string old_path;
  std::string new_path;
  std::size_t score = 0;
  bool old_used = false;
  bool new_used = false;
};

std::uint64_t hash_line(std::string_view line) {
  std::uint64_t h = 1469598103934665603ull;
  for (char raw : line) {
    const auto c = static_cast<unsigned char>(raw);
    h = (h ^ static_cast<std::uint64_t>(c)) * 1099511628211ull;
  }
  return h;
}

int line_similarity(Bytes a, Bytes b) {
  std::vector<std::uint64_t> la;
  std::vector<std::uint64_t> lb;
  std::size_t start = 0;
  for (std::size_t i = 0; i <= a.size(); ++i) {
    if (i == a.size() || a[i] == '\n') {
      la.push_back(hash_line(str_of(a.subspan(start, i - start))));
      start = i + 1;
    }
  }
  start = 0;
  for (std::size_t j = 0; j <= b.size(); ++j) {
    if (j == b.size() || b[j] == '\n') {
      lb.push_back(hash_line(str_of(b.subspan(start, j - start))));
      start = j + 1;
    }
  }
  std::sort(la.begin(), la.end());
  std::sort(lb.begin(), lb.end());
  std::size_t ia = 0;
  std::size_t ib = 0;
  std::size_t inter = 0;
  while (ia < la.size() && ib < lb.size()) {
    if (la[ia] == lb[ib]) {
      ++inter;
      ++ia;
      ++ib;
    } else if (la[ia] < lb[ib]) {
      ++ia;
    } else {
      ++ib;
    }
  }
  const std::size_t total = la.size() + lb.size() - inter;
  if (total == 0)
    return 100;
  return static_cast<int>((inter * 100) / total);
}

int chunk_similarity(Store &store, Txn *tx, const Id &a, const Id &b) {
  std::vector<Id> ca;
  std::vector<Id> cb;
  if (!collect_chunks_any(store, tx, a, ca, 0) ||
      !collect_chunks_any(store, tx, b, cb, 0))
    return 0;
  std::size_t inter = 0;
  for (const auto &x : ca) {
    for (const auto &y : cb) {
      if (same_id(x, y)) {
        ++inter;
        break;
      }
    }
  }
  const std::size_t total = ca.size() + cb.size() - inter;
  if (total == 0)
    return 0;
  return static_cast<int>((inter * 100) / total);
}

int similarity(Store &store, Txn *tx, const Id &a, const Id &b) {
  if (same_id(a, b))
    return 100;
  auto da = read_blob_any(store, tx, a);
  auto db = read_blob_any(store, tx, b);
  if (!da || !db)
    return 0;
  int result = 0;
  if (da->size() >= 131072 && db->size() >= 131072)
    result = chunk_similarity(store, tx, a, b);
  if (result == 0)
    result = line_similarity(bytes_of(*da), bytes_of(*db));
  return result;
}

} // namespace

std::vector<Rename> detect_renames(Store &store, Txn *tx,
                                   std::optional<Id> old_tree,
                                   std::optional<Id> new_tree, int similar_pct,
                                   std::uint64_t parent_index) {
  const auto old_entries = flatten_any_sorted(store, tx, old_tree);
  const auto new_entries = flatten_any_sorted(store, tx, new_tree);
  std::vector<FlatEntry> deleted;
  std::vector<FlatEntry> added;
  for (const auto &entry : old_entries) {
    if (!find_flat_entry(new_entries, entry.path))
      deleted.push_back(entry);
  }
  for (const auto &entry : new_entries) {
    if (!find_flat_entry(old_entries, entry.path))
      added.push_back(entry);
  }
  std::vector<char> used_old(deleted.size(), 0);
  std::vector<char> used_new(added.size(), 0);
  std::vector<Rename> out;
  for (std::size_t di = 0; di < deleted.size(); ++di) {
    if (used_old[di])
      continue;
    for (std::size_t ai = 0; ai < added.size(); ++ai) {
      if (used_new[ai])
        continue;
      if (same_id(deleted[di].target, added[ai].target)) {
        out.push_back(Rename{parent_index, 0, deleted[di].path, added[ai].path});
        used_old[di] = 1;
        used_new[ai] = 1;
        break;
      }
    }
  }
  if (similar_pct > 0) {
    std::vector<RenamePair> pairs;
    constexpr std::size_t candidate_limit = 5000;
    for (std::size_t di = 0; di < deleted.size(); ++di) {
      if (used_old[di] || (deleted[di].kind != KIND_FILE &&
                           deleted[di].kind != KIND_EXECUTABLE))
        continue;
      for (std::size_t ai = 0; ai < added.size() && pairs.size() < candidate_limit;
           ++ai) {
        if (used_new[ai] || (added[ai].kind != KIND_FILE &&
                             added[ai].kind != KIND_EXECUTABLE))
          continue;
        RenamePair pair;
        pair.old_path = deleted[di].path;
        pair.new_path = added[ai].path;
        pair.score = static_cast<std::size_t>(
            similarity(store, tx, deleted[di].target, added[ai].target));
        pairs.push_back(std::move(pair));
      }
    }
    for (;;) {
      std::ptrdiff_t best_i = -1;
      std::size_t best = 0;
      for (std::size_t i = 0; i < pairs.size(); ++i) {
        if (!pairs[i].old_used && !pairs[i].new_used &&
            pairs[i].score > best) {
          best = pairs[i].score;
          best_i = static_cast<std::ptrdiff_t>(i);
        }
      }
      if (best_i < 0 || best < static_cast<std::size_t>(similar_pct))
        break;
      auto &pair = pairs[static_cast<std::size_t>(best_i)];
      pair.old_used = true;
      pair.new_used = true;
      out.push_back(Rename{parent_index, 0, pair.old_path, pair.new_path});
    }
  }
  std::stable_sort(out.begin(), out.end(), [](const Rename &a, const Rename &b) {
    if (a.parent_index != b.parent_index)
      return a.parent_index < b.parent_index;
    return compare(bytes_of(a.to_path), bytes_of(b.to_path)) < 0;
  });
  return out;
}

int rename_similar_pct(const fs::path &root) {
  if (auto value = repo_config_value(root, "rename.autodetect")) {
    if (*value == "off")
      return 0;
    return 60;
  }
  return 60;
}

namespace {

// ---------------------------------------------------------------------------
// Rename maps
// ---------------------------------------------------------------------------

using RenameMap = std::vector<std::pair<std::string, std::string>>;

std::optional<std::string> rename_lookup(const RenameMap &map,
                                         std::string_view path) {
  for (const auto &entry : map) {
    if (entry.first == path)
      return entry.second;
  }
  return std::nullopt;
}

void rename_apply(RenameMap &map, const std::string &from,
                  const std::string &to) {
  for (auto &entry : map) {
    if (entry.second == from) {
      entry.second = to;
      return;
    }
  }
  for (auto &entry : map) {
    if (entry.first == from) {
      entry.second = to;
      return;
    }
  }
  map.emplace_back(from, to);
}

std::optional<Id> tree_of(Store &store, const Id &commit_id) {
  auto loaded = load_commit(store, commit_id);
  if (!loaded)
    return std::nullopt;
  return loaded->commit.root_tree;
}

std::optional<Id> first_parent(Store &store, const Id &commit_id) {
  auto loaded = load_commit(store, commit_id);
  if (!loaded || loaded->commit.parents.empty())
    return std::nullopt;
  return loaded->commit.parents.front();
}

RenameMap map_from(Store &store, const Id &base, const Id &side) {
  RenameMap map;
  if (same_id(base, side))
    return map;
  std::vector<Id> chain;
  Id current = side;
  bool reached = false;
  for (std::size_t depth = 0; depth < 100000; ++depth) {
    if (same_id(current, base)) {
      reached = true;
      break;
    }
    chain.push_back(current);
    auto parent = first_parent(store, current);
    if (!parent)
      break;
    current = *parent;
  }
  if (!reached)
    return map;
  for (std::size_t i = chain.size(); i > 0; --i) {
    auto loaded = load_commit(store, chain[i - 1]);
    if (!loaded)
      continue;
    if (loaded->commit.renames_state == RENAMES_RECORDED) {
      for (const auto &rename : loaded->commit.renames) {
        if (rename.parent_index == 0)
          rename_apply(map, rename.from_path, rename.to_path);
      }
    } else {
      auto parent = first_parent(store, chain[i - 1]);
      if (!parent)
        continue;
      auto old_tree = tree_of(store, *parent);
      auto new_tree = tree_of(store, chain[i - 1]);
      for (const auto &rename :
           detect_renames(store, nullptr, old_tree, new_tree, 50, 0))
        rename_apply(map, rename.from_path, rename.to_path);
    }
  }
  return map;
}

// ---------------------------------------------------------------------------
// Tree merge
// ---------------------------------------------------------------------------

struct TreeTerm {
  bool positive = true;
  bool present = false;
  Id id{};
};

struct EntryTerm {
  bool positive = true;
  bool present = false;
  std::uint8_t kind = 0;
  std::optional<Id> target;
};

struct OrigEntry {
  std::size_t term = 0;
  std::string path;
  std::uint8_t kind = 0;
  Id target{};
};

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

struct MergeOutcome {
  Id tree{};
  std::size_t rerere = 0;
};

bool value_equal(const ConflictValue &a, const ConflictValue &b) {
  if (a.kind != b.kind)
    return false;
  if (a.kind == 0)
    return true;
  return a.target && b.target && same_id(*a.target, *b.target);
}

void flatten_values(Store &store, const std::vector<ConflictValue> &values,
                    bool positive, std::vector<ConflictValue> &adds,
                    std::vector<ConflictValue> &removes, std::size_t depth) {
  for (const auto &value : values) {
    if (value.kind == KIND_CONFLICT && value.target && depth < 64) {
      auto body = store.read_body(*value.target, TYPE_CONFLICT);
      if (body) {
        auto child = decode_conflict(bytes_of(*body));
        if (child) {
          flatten_values(store, child->adds, positive, adds, removes,
                         depth + 1);
          flatten_values(store, child->removes, !positive, adds, removes,
                         depth + 1);
          continue;
        }
      }
    }
    if (positive)
      adds.push_back(value);
    else
      removes.push_back(value);
  }
}

Conflict simplify(Store &store, const std::vector<ConflictValue> &adds_in,
                  const std::vector<ConflictValue> &removes_in) {
  std::vector<ConflictValue> flat_adds;
  std::vector<ConflictValue> flat_removes;
  flatten_values(store, adds_in, true, flat_adds, flat_removes, 0);
  flatten_values(store, removes_in, false, flat_adds, flat_removes, 0);

  std::vector<char> used(flat_adds.size(), 0);
  std::vector<char> rem_used(flat_removes.size(), 0);
  for (std::size_t r = 0; r < flat_removes.size(); ++r) {
    for (std::size_t a = 0; a < flat_adds.size(); ++a) {
      if (!used[a] && value_equal(flat_adds[a], flat_removes[r])) {
        used[a] = 1;
        rem_used[r] = 1;
        break;
      }
    }
  }
  Conflict out;
  for (std::size_t a = 0; a < flat_adds.size(); ++a) {
    if (!used[a])
      out.adds.push_back(flat_adds[a]);
  }
  for (std::size_t r = 0; r < flat_removes.size(); ++r) {
    if (!rem_used[r])
      out.removes.push_back(flat_removes[r]);
  }
  return out;
}

std::optional<ConflictValue> resolved(const Conflict &conflict) {
  if (conflict.adds.empty())
    return std::nullopt;
  for (std::size_t i = 1; i < conflict.adds.size(); ++i) {
    if (!value_equal(conflict.adds[0], conflict.adds[i]))
      return std::nullopt;
  }
  return conflict.adds[0];
}

bool all_files(const Conflict &conflict) {
  for (const auto &value : conflict.adds) {
    if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&
        value.kind != 0)
      return false;
  }
  for (const auto &value : conflict.removes) {
    if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&
        value.kind != 0)
      return false;
  }
  return true;
}

int merge_mode(const Conflict &conflict) {
  if (conflict.adds.size() != 2 || conflict.removes.size() != 1)
    return -1;
  auto mode = [](const ConflictValue &value) -> int {
    if (value.kind == 0)
      return -1;
    return value.kind == KIND_EXECUTABLE ? 1 : 0;
  };
  const int m0 = mode(conflict.adds[0]);
  const int m1 = mode(conflict.adds[1]);
  const int mr = mode(conflict.removes[0]);
  if (m0 < 0 || m1 < 0)
    return -1;
  if (m0 == m1)
    return m0;
  if (mr >= 0 && m0 == mr)
    return m1;
  if (mr >= 0 && m1 == mr)
    return m0;
  return -1;
}

bool merge_binary(const fs::path &repo, std::string_view path) {
  auto data = read_file_opt(repo / ".veinsattributes");
  if (!data)
    return false;
  const std::string_view text(reinterpret_cast<const char *>(data->data()),
                              data->size());
  bool result = false;
  std::size_t start = 0;
  for (std::size_t pos = 0; pos <= text.size(); ++pos) {
    if (pos != text.size() && text[pos] != '\n')
      continue;
    std::string_view line = text.substr(start, pos - start);
    start = pos + 1;
    while (!line.empty() && (line.front() == ' ' || line.front() == '\t' ||
                             line.front() == '\r' || line.front() == '\n'))
      line.remove_prefix(1);
    while (!line.empty() && (line.back() == ' ' || line.back() == '\t' ||
                             line.back() == '\r' || line.back() == '\n'))
      line.remove_suffix(1);
    if (line.empty() || line.front() == '#')
      continue;
    std::size_t glob_end = 0;
    while (glob_end < line.size() && line[glob_end] != ' ' &&
           line[glob_end] != '\t')
      ++glob_end;
    const std::string_view glob = line.substr(0, glob_end);
    std::string_view base = glob;
    if (const auto slash = glob.rfind('/'); slash != std::string_view::npos)
      base = glob.substr(slash + 1);
    const bool matched =
        glob_match(glob, path) ||
        (glob.find('/') == std::string_view::npos && glob_match(base, path));
    if (!matched)
      continue;
    std::size_t t = glob_end;
    while (t < line.size()) {
      while (t < line.size() && (line[t] == ' ' || line[t] == '\t'))
        ++t;
      const std::size_t tok_start = t;
      while (t < line.size() && line[t] != ' ' && line[t] != '\t')
        ++t;
      const std::string_view token = line.substr(tok_start, t - tok_start);
      const auto eq = token.find('=');
      if (eq != std::string_view::npos) {
        const std::string_view key = token.substr(0, eq);
        const std::string_view value = token.substr(eq + 1);
        if (key == "merge") {
          if (value == "binary")
            result = true;
          else if (value == "text")
            result = false;
        }
      }
    }
  }
  return result;
}

std::optional<Id> resolution_lookup(const fs::path &repo, Bytes body) {
  const auto digest = blake3_hash(body);
  const std::string key = hex_encode(Bytes(digest.data(), digest.size()));
  auto data = read_file_opt(resolutions_dir(repo) / key);
  if (!data || data->size() < 64)
    return std::nullopt;
  const std::string_view text(reinterpret_cast<const char *>(data->data()), 64);
  Id id{};
  if (!hex_decode(text, MutBytes(id.data(), id.size())))
    return std::nullopt;
  return id;
}

void resolution_record(const fs::path &repo, Bytes body, const Id &blob) {
  const auto digest = blake3_hash(body);
  const std::string key = hex_encode(Bytes(digest.data(), digest.size()));
  (void)write_file(resolutions_dir(repo) / key, bytes_of(hex_encode(blob)));
}

Id build_level(Txn &tx, const std::vector<OutEntry> &entries,
               std::size_t start, std::size_t end, std::size_t prefix_len) {
  std::vector<TreeEntry> out;
  std::size_t i = start;
  while (i < end) {
    const OutEntry &entry = entries[i];
    const std::size_t name_end = entry.path.find('/', prefix_len);
    const std::size_t cut =
        name_end == std::string::npos ? entry.path.size() : name_end;
    const std::string name = entry.path.substr(prefix_len, cut - prefix_len);
    if (cut == entry.path.size()) {
      out.push_back(TreeEntry{name, entry.kind, entry.target});
      ++i;
    } else {
      std::size_t j = i + 1;
      while (j < end) {
        const std::size_t other_end = entries[j].path.find('/', prefix_len);
        const std::size_t other_cut = other_end == std::string::npos
                                          ? entries[j].path.size()
                                          : other_end;
        if (other_cut != cut ||
            entries[j].path.compare(prefix_len, cut - prefix_len, name) != 0)
          break;
        ++j;
      }
      const Id child = build_level(tx, entries, i, j, cut + 1);
      out.push_back(TreeEntry{name, KIND_SUBTREE, child});
      i = j;
    }
  }
  return add_tree(tx, out);
}

Id build_from_entries(Txn &tx, std::vector<OutEntry> &entries) {
  if (entries.empty())
    return add_empty_tree(tx);
  std::stable_sort(entries.begin(), entries.end(),
                   [](const OutEntry &a, const OutEntry &b) {
                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;
                   });
  return build_level(tx, entries, 0, entries.size(), 0);
}

Id build_subtree(Txn &tx, const std::vector<OrigEntry> &canon,
                 std::size_t term, std::string_view prefix) {
  std::vector<OutEntry> rels;
  for (const auto &entry : canon) {
    if (entry.term != term)
      continue;
    if (entry.path.size() > prefix.size() &&
        entry.path.compare(0, prefix.size(), prefix) == 0 &&
        entry.path[prefix.size()] == '/')
      rels.push_back(
          OutEntry{entry.path.substr(prefix.size() + 1), entry.kind,
                   entry.target});
  }
  return build_from_entries(tx, rels);
}

bool has_prefix(std::string_view path, std::string_view prefix) {
  return path.size() > prefix.size() &&
         path.compare(0, prefix.size(), prefix) == 0 &&
         path[prefix.size()] == '/';
}

std::optional<OutEntry> merge_entry(const fs::path &repo, Txn &tx,
                                    Store &store, const std::string &path,
                                    const std::vector<EntryTerm> &terms,
                                    bool adjacent, std::size_t &rerere) {
  std::vector<ConflictValue> adds;
  std::vector<ConflictValue> removes;
  for (const auto &term : terms) {
    ConflictValue value;
    if (term.present) {
      value.kind = term.kind;
      value.target = term.target;
    }
    if (term.positive)
      adds.push_back(value);
    else
      removes.push_back(value);
  }
  Conflict sum = simplify(store, adds, removes);
  if (auto value = resolved(sum)) {
    if (value->kind == 0)
      return std::nullopt;
    return OutEntry{path, value->kind, *value->target};
  }
  if (all_files(sum) && sum.adds.size() == 2 && sum.removes.size() == 1 &&
      sum.adds[0].kind != 0 && sum.adds[1].kind != 0 &&
      sum.removes[0].kind != 0 && !merge_binary(repo, path)) {
    auto merged = merge_blobs(store, &tx, *sum.removes[0].target,
                              *sum.adds[0].target, *sum.adds[1].target,
                              adjacent);
    if (merged && !merged->conflicted) {
      const Id blob = add_blob(tx, bytes_of(merged->data));
      const int mode = merge_mode(sum);
      if (mode >= 0)
        return OutEntry{path,
                        static_cast<std::uint8_t>(mode == 1 ? KIND_EXECUTABLE
                                                            : KIND_FILE),
                        blob};
    }
  }
  const auto body = encode_conflict(sum);
  if (all_files(sum)) {
    if (auto memo = resolution_lookup(repo, bytes_of(body))) {
      ++rerere;
      return OutEntry{path, KIND_FILE, *memo};
    }
  }
  const Id id = tx.add_object(TYPE_CONFLICT, body);
  return OutEntry{path, KIND_CONFLICT, id};
}

MergeOutcome treemerge(const fs::path &repo, Txn &tx, Store &store,
                       const std::vector<TreeTerm> &terms,
                       const std::vector<RenameMap> &maps, bool adjacent) {
  std::vector<OrigEntry> orig;
  for (std::size_t t = 0; t < terms.size(); ++t) {
    if (!terms[t].present)
      continue;
    for (const auto &entry : flatten_any_sorted(store, &tx, terms[t].id))
      orig.push_back(OrigEntry{t, entry.path, entry.kind, entry.target});
  }

  auto canonical_targets =
      [&](const std::string &path) -> std::vector<std::pair<std::size_t, std::string>> {
    std::vector<std::pair<std::size_t, std::string>> out;
    for (std::size_t i = 0; i < maps.size(); ++i) {
      auto dest = rename_lookup(maps[i], path);
      if (!dest)
        continue;
      bool exists = false;
      for (const auto &item : out) {
        if (item.second == *dest) {
          exists = true;
          break;
        }
      }
      if (!exists)
        out.emplace_back(i, *dest);
    }
    return out;
  };

  auto find_orig = [&](std::size_t term,
                       const std::string &path) -> const OrigEntry * {
    for (const auto &entry : orig) {
      if (entry.term == term && entry.path == path)
        return &entry;
    }
    return nullptr;
  };

  std::vector<OrigEntry> canon;
  std::vector<std::string> special;
  std::vector<std::string> consumed;
  auto mark_consumed = [&](const std::string &path) {
    for (const auto &item : consumed) {
      if (item == path)
        return;
    }
    consumed.push_back(path);
  };
  for (const auto &entry : orig) {
    auto targets = canonical_targets(entry.path);
    if (targets.size() > 1) {
      bool seen = false;
      for (const auto &item : special) {
        if (item == entry.path) {
          seen = true;
          break;
        }
      }
      if (!seen)
        special.push_back(entry.path);
    }
    const std::string &canonical =
        targets.size() == 1 ? targets[0].second : entry.path;
    canon.push_back(OrigEntry{entry.term, canonical, entry.kind, entry.target});
  }

  std::vector<OutEntry> out;
  std::size_t rerere = 0;

  for (const auto &sp : special) {
    auto targets = canonical_targets(sp);
    std::vector<EntryTerm> ets;
    for (const auto &target : targets) {
      EntryTerm term;
      term.positive = true;
      if (const OrigEntry *found = find_orig(target.first, target.second)) {
        term.present = true;
        term.kind = found->kind;
        term.target = found->target;
      }
      ets.push_back(term);
      mark_consumed(target.second);
    }
    std::ptrdiff_t base_term = -1;
    for (std::size_t ti = 0; ti < terms.size(); ++ti) {
      if (!terms[ti].positive) {
        base_term = static_cast<std::ptrdiff_t>(ti);
        break;
      }
    }
    if (base_term >= 0) {
      EntryTerm term;
      term.positive = false;
      if (const OrigEntry *found =
              find_orig(static_cast<std::size_t>(base_term), sp)) {
        term.present = true;
        term.kind = found->kind;
        term.target = found->target;
      }
      ets.push_back(term);
    }
    if (auto merged = merge_entry(repo, tx, store, sp, ets, adjacent, rerere))
      out.push_back(std::move(*merged));
    mark_consumed(sp);
  }

  auto find_canon = [&](std::size_t term,
                        const std::string &path) -> const OrigEntry * {
    for (const auto &entry : canon) {
      if (entry.term == term && entry.path == path)
        return &entry;
    }
    return nullptr;
  };

  std::vector<std::string> paths;
  for (const auto &entry : canon) {
    bool seen = false;
    for (const auto &path : paths) {
      if (path == entry.path) {
        seen = true;
        break;
      }
    }
    if (!seen)
      paths.push_back(entry.path);
  }
  std::sort(paths.begin(), paths.end(),
            [](const std::string &a, const std::string &b) {
              return compare(bytes_of(a), bytes_of(b)) < 0;
            });

  auto is_consumed = [&](const std::string &path) {
    for (const auto &item : consumed) {
      if (item == path)
        return true;
    }
    return false;
  };

  for (const auto &path : paths) {
    if (is_consumed(path))
      continue;
    bool any_exact = false;
    bool any_children = false;
    for (std::size_t t = 0; t < terms.size(); ++t) {
      if (find_canon(t, path))
        any_exact = true;
      for (const auto &entry : canon) {
        if (entry.term == t && has_prefix(entry.path, path)) {
          any_children = true;
          break;
        }
      }
    }
    if (!any_exact)
      continue;
    const bool mixed = any_children;
    std::vector<EntryTerm> ets;
    for (std::size_t t = 0; t < terms.size(); ++t) {
      EntryTerm term;
      term.positive = terms[t].positive;
      if (const OrigEntry *exact = find_canon(t, path)) {
        term.present = true;
        term.kind = exact->kind;
        term.target = exact->target;
      } else if (mixed) {
        bool children = false;
        for (const auto &entry : canon) {
          if (entry.term == t && has_prefix(entry.path, path)) {
            children = true;
            break;
          }
        }
        if (children) {
          term.present = true;
          term.kind = KIND_SUBTREE;
          term.target = build_subtree(tx, canon, t, path);
        }
      }
      ets.push_back(term);
    }
    if (auto merged = merge_entry(repo, tx, store, path, ets, adjacent, rerere))
      out.push_back(std::move(*merged));
    if (mixed) {
      for (const auto &entry : canon) {
        if (has_prefix(entry.path, path))
          mark_consumed(entry.path);
      }
    }
  }

  return MergeOutcome{build_from_entries(tx, out), rerere};
}

// ---------------------------------------------------------------------------
// Commit-level merge helpers
// ---------------------------------------------------------------------------

bool contains_id_vec(const std::vector<Id> &ids, const Id &id) {
  for (const auto &candidate : ids) {
    if (same_id(candidate, id))
      return true;
  }
  return false;
}

std::vector<Id> merge_bases(Store &store, const Id &a, const Id &b) {
  const std::vector<Id> aa = collect_commits(store, std::vector<Id>{a});
  const std::vector<Id> bb = collect_commits(store, std::vector<Id>{b});
  std::vector<Id> common;
  for (const auto &x : aa) {
    if (contains_id_vec(bb, x))
      common.push_back(x);
  }
  std::vector<Id> out;
  for (const auto &c : common) {
    bool dominated = false;
    for (const auto &d : common) {
      if (same_id(c, d))
        continue;
      const auto descendants = collect_commits(store, std::vector<Id>{c});
      if (contains_id_vec(descendants, d)) {
        dominated = true;
        break;
      }
    }
    if (!dominated)
      out.push_back(c);
  }
  return out;
}

bool is_ancestor(Store &store, const Id &ancestor, const Id &descendant) {
  if (same_id(ancestor, descendant))
    return true;
  return contains_id_vec(collect_commits(store, std::vector<Id>{descendant}),
                         ancestor);
}

std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,
                            const std::vector<Id> &bases, bool adjacent);

std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,
                            const std::vector<Id> &bases, bool adjacent) {
  if (bases.empty())
    return std::nullopt;
  if (bases.size() == 1)
    return tree_of(store, bases.front());
  auto t0 = tree_of(store, bases[0]);
  auto t1 = tree_of(store, bases[1]);
  const auto lcas = merge_bases(store, bases[0], bases[1]);
  std::vector<TreeTerm> terms;
  terms.push_back(TreeTerm{true, t0.has_value(), t0.value_or(Id{})});
  terms.push_back(TreeTerm{true, t1.has_value(), t1.value_or(Id{})});
  if (!lcas.empty()) {
    auto lt = tree_of(store, lcas.front());
    terms.push_back(TreeTerm{false, lt.has_value(), lt.value_or(Id{})});
  } else {
    terms.push_back(TreeTerm{false, false, Id{}});
  }
  std::vector<RenameMap> maps(3);
  return treemerge(repo, tx, store, terms, maps, adjacent).tree;
}

MergeOutcome merge_many(const fs::path &repo, Txn &tx, Store &store,
                        const std::vector<Id> &heads, bool adjacent) {
  if (heads.size() == 1) {
    auto t = tree_of(store, heads.front());
    std::vector<TreeTerm> terms{
        TreeTerm{true, t.has_value(), t.value_or(Id{})}};
    return treemerge(repo, tx, store, terms, {RenameMap{}}, adjacent);
  }
  std::vector<TreeTerm> terms;
  std::vector<RenameMap> maps;
  std::optional<Id> map_base;
  if (heads.size() > 1) {
    const auto bases = merge_bases(store, heads[0], heads[1]);
    if (!bases.empty())
      map_base = bases.front();
  }
  for (const auto &head : heads) {
    auto t = tree_of(store, head);
    terms.push_back(TreeTerm{true, t.has_value(), t.value_or(Id{})});
    if (map_base)
      maps.push_back(map_from(store, *map_base, head));
    else
      maps.push_back(RenameMap{});
  }
  for (std::size_t i = 1; i < heads.size(); ++i) {
    const auto bases = merge_bases(store, heads[0], heads[i]);
    auto bt = base_tree(repo, tx, store, bases, adjacent);
    if (bt)
      terms.push_back(TreeTerm{false, true, *bt});
    else
      terms.push_back(TreeTerm{false, false, Id{}});
    maps.push_back(RenameMap{});
  }
  return treemerge(repo, tx, store, terms, maps, adjacent);
}

MergeOutcome rewrite_tree(const fs::path &repo, Txn &tx, Store &store,
                          const Id &old_commit, const Id &commit_tree,
                          const std::vector<Id> &old_parents,
                          const std::vector<Id> &new_parents,
                          const std::vector<Id> &new_parent_trees,
                          bool adjacent) {
  std::vector<TreeTerm> terms;
  std::vector<RenameMap> maps;
  terms.push_back(TreeTerm{true, true, commit_tree});
  if (!old_parents.empty())
    maps.push_back(map_from(store, old_parents.front(), old_commit));
  else
    maps.push_back(RenameMap{});

  if (old_parents.empty()) {
    for (const auto &tree : new_parent_trees) {
      terms.push_back(TreeTerm{true, true, tree});
      maps.push_back(RenameMap{});
    }
    terms.push_back(TreeTerm{false, false, Id{}});
    maps.push_back(RenameMap{});
  } else {
    for (std::size_t i = 0; i < old_parents.size(); ++i) {
      auto old_tree = tree_of(store, old_parents[i]);
      const Id new_tree =
          i < new_parent_trees.size() ? new_parent_trees[i] : Id{};
      terms.push_back(TreeTerm{true, true, new_tree});
      terms.push_back(
          TreeTerm{false, old_tree.has_value(), old_tree.value_or(Id{})});
      if (i < new_parents.size())
        maps.push_back(map_from(store, old_parents[i], new_parents[i]));
      else
        maps.push_back(RenameMap{});
      maps.push_back(RenameMap{});
    }
  }
  return treemerge(repo, tx, store, terms, maps, adjacent);
}

Id make_commit(Txn &tx, Store &store, const fs::path &repo,
               const std::vector<Id> &parents, const Id &root,
               const ChangeId &change, const Sig &author,
               const std::string &message, std::uint8_t renames_state,
               const std::vector<KeyValue> &extra) {
  Commit commit;
  commit.version = 1;
  commit.parents = parents;
  commit.root_tree = root;
  commit.change_id = change;
  commit.author = author;
  commit.committer = identity_signature(repo);
  commit.message = message;
  commit.renames_state = renames_state;
  commit.extra = extra;
  if (renames_state == RENAMES_RECORDED) {
    for (std::size_t i = 0; i < parents.size(); ++i) {
      auto parent_tree = tree_of(store, parents[i]);
      auto detected =
          detect_renames(store, &tx, parent_tree, std::optional<Id>{root}, 0, i);
      for (auto &rename : detected)
        commit.renames.push_back(std::move(rename));
    }
  }
  return tx.add_object(TYPE_COMMIT, encode_commit(commit));
}

std::string rerere_suffix(std::size_t count) {
  if (count == 0)
    return std::string();
  return " (rerere " + std::to_string(count) + ")";
}

std::string join_revs(const std::vector<std::string> &revs) {
  std::string out;
  for (std::size_t i = 0; i < revs.size(); ++i) {
    if (i != 0)
      out.push_back(' ');
    out += revs[i];
  }
  return out;
}

bool adjacent_config(const fs::path &root) {
  auto value = repo_config_value(root, "merge.adjacent");
  return value && *value == "merge";
}

// ---------------------------------------------------------------------------
// Tree editing
// ---------------------------------------------------------------------------

std::optional<Id> tree_edit_into(Txn &tx, Store &store, const Id &tree_id,
                                 std::string_view path, bool present,
                                 std::uint8_t kind, const Id &target,
                                 std::size_t depth) {
  if (depth > 4096)
    return std::nullopt;
  auto body = read_body_any(store, &tx, TYPE_TREE, tree_id);
  if (!body)
    return std::nullopt;
  auto tree = decode_tree(bytes_of(*body));
  if (!tree)
    return std::nullopt;
  const std::size_t cut = path.find('/');
  const std::size_t cut_pos = cut == std::string_view::npos ? path.size() : cut;
  const std::string_view name = path.substr(0, cut_pos);
  std::vector<TreeEntry> entries;
  bool found = false;
  for (const auto &entry : tree->entries) {
    if (entry.name != name) {
      entries.push_back(entry);
      continue;
    }
    found = true;
    if (cut_pos == path.size()) {
      if (present)
        entries.push_back(TreeEntry{entry.name, kind, target});
    } else if (entry.kind == KIND_SUBTREE) {
      auto child = tree_edit_into(tx, store, entry.target,
                                  path.substr(cut_pos + 1), present, kind,
                                  target, depth + 1);
      if (child && !tree_empty_any(store, &tx, *child))
        entries.push_back(TreeEntry{entry.name, KIND_SUBTREE, *child});
    } else {
      entries.push_back(entry);
    }
  }
  if (!found && cut_pos == path.size() && present)
    entries.push_back(TreeEntry{std::string(name), kind, target});
  return add_tree(tx, entries);
}

std::optional<Id> tree_edit_replace(Txn &tx, Store &store, const Id &root,
                                    std::string_view path, bool present,
                                    std::uint8_t kind, const Id &target) {
  auto edited =
      tree_edit_into(tx, store, root, path, present, kind, target, 0);
  if (!edited)
    return std::nullopt;
  return edited;
}

// ---------------------------------------------------------------------------
// Conflicts
// ---------------------------------------------------------------------------

std::string conflict_kind_label(const Conflict &conflict) {
  for (const auto &value : conflict.adds) {
    if (value.kind == KIND_SUBTREE)
      return "tree";
  }
  for (const auto &value : conflict.removes) {
    if (value.kind == KIND_SUBTREE)
      return "tree";
  }
  for (const auto &value : conflict.adds) {
    if (value.kind == 0)
      return "delete/modify";
  }
  for (const auto &value : conflict.removes) {
    if (value.kind == 0)
      return "delete/modify";
  }
  return "text";
}

void print_range(std::size_t a, std::size_t b) {
  if (a == b)
    std::cout << a + 1;
  else
    std::cout << a + 1 << "-" << b;
}

std::optional<EditResult> conflict_ranges(Store &store, const Conflict &conflict,
                                          bool adjacent) {
  if (conflict.adds.size() != 2 || conflict.removes.size() != 1)
    return std::nullopt;
  const auto &ours = conflict.adds[0];
  const auto &theirs = conflict.adds[1];
  const auto &base = conflict.removes[0];
  if (ours.kind == 0 || theirs.kind == 0 || base.kind == 0)
    return std::nullopt;
  if (ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE ||
      base.kind == KIND_SUBTREE)
    return std::nullopt;
  return merge_blobs(store, nullptr, *base.target, *ours.target,
                     *theirs.target, adjacent);
}

std::vector<FlatEntry> flatten_store(Store &store, const Id &tree) {
  return flatten_any_sorted(store, nullptr, std::optional<Id>{tree});
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

int merge_command(const std::vector<std::string> &revs) {
  if (revs.empty()) {
    error_prefix();
    std::cout << "merge requires at least one revision\n";
    return 1;
  }
  const auto root = discover_repo(".");
  if (!root) {
    error_prefix();
    std::cout << "not a veins repository\n";
    return 1;
  }
  const int snap = snapshot_run(*root);
  if (snap != 0)
    return snap;

  Store store = Store::open_all(*root);
  auto tx = Txn::begin(*root, store);
  if (!tx) {
    error_prefix();
    std::cout << "cannot load repository state\n";
    return 1;
  }
  const auto wc = working_copy_id(tx->view());
  if (!wc) {
    error_prefix();
    std::cout << "no working-copy commit to merge into\n";
    return 1;
  }

  std::vector<Id> parents{*wc};
  bool failed = false;
  for (const auto &rev : revs) {
    auto resolved = resolve_revision(store, tx->view(), rev);
    if (!resolved) {
      failed = true;
      continue;
    }
    if (same_id(*resolved, *wc)) {
      error_prefix();
      std::cout << "cannot merge a commit with itself\n";
      failed = true;
      continue;
    }
    parents.push_back(*resolved);
  }
  if (failed) {
    error_prefix();
    std::cout << "unknown revision\n";
    return 1;
  }

  const auto old_root = tree_of(store, *wc);
  const bool adjacent = adjacent_config(*root);
  MergeOutcome outcome =
      merge_many(*root, *tx, store, parents, adjacent);
  const Sig author = identity_signature(*root);
  const Id new_id = make_commit(
      *tx, store, *root, parents, outcome.tree, random_change_id(), author, "",
      RENAMES_RECORDED, {});

  remove_head(tx->view(), *wc);
  move_bookmarks(tx->view(), *wc, new_id);
  set_workspace(tx->view(), new_id);
  rebuild_heads(tx->view());
  const std::string description =
      "merge " + join_revs(revs) + rerere_suffix(outcome.rerere);
  const auto status = tx->finish(description);
  if (!status)
    return 1;
  store.refresh(*root);
  (void)mark_native(*root, new_id);
  if (old_root)
    return checkout_materialize_commit(*root, store, old_root, outcome.tree);
  return 0;
}

int rebase_command(const std::string &source, const std::string &dest) {
  const auto root = discover_repo(".");
  if (!root) {
    error_prefix();
    std::cout << "not a veins repository\n";
    return 1;
  }
  const int snap = snapshot_run(*root);
  if (snap != 0)
    return snap;

  Store store = Store::open_all(*root);
  auto tx = Txn::begin(*root, store);
  if (!tx) {
    error_prefix();
    std::cout << "cannot load repository state\n";
    return 1;
  }
  auto src = resolve_revision(store, tx->view(), source);
  auto dst = resolve_revision(store, tx->view(), dest);
  if (!src || !dst) {
    error_prefix();
    std::cout << "unknown revision\n";
    return 1;
  }
  const auto wc = working_copy_id(tx->view());
  std::optional<Id> old_wc_root;
  if (wc)
    old_wc_root = tree_of(store, *wc);

  std::vector<Id> set;
  for (const auto &commit : all_commits(store, tx->view())) {
    if (is_ancestor(store, *src, commit))
      set.push_back(commit);
  }

  std::vector<Id> old_ids;
  std::vector<Id> new_ids;
  std::vector<Id> new_tree_ids;
  std::vector<Id> remaining = set;
  std::size_t rerere_total = 0;
  const bool adjacent = adjacent_config(*root);
  const Sig fallback_sig = identity_signature(*root);
  (void)fallback_sig;

  while (!remaining.empty()) {
    std::ptrdiff_t ready_idx = -1;
    for (std::size_t i = 0; i < remaining.size(); ++i) {
      bool ready = true;
      auto loaded = load_commit(store, remaining[i]);
      if (!loaded)
        continue;
      for (const auto &parent : loaded->commit.parents) {
        if (contains_id_vec(set, parent) && !contains_id_vec(old_ids, parent) &&
            !same_id(remaining[i], *src))
          ready = false;
      }
      if (ready) {
        ready_idx = static_cast<std::ptrdiff_t>(i);
        break;
      }
    }
    if (ready_idx < 0) {
      error_prefix();
      std::cout << "rebase could not order commits\n";
      break;
    }
    const Id chosen = remaining[static_cast<std::size_t>(ready_idx)];
    auto loaded = load_commit(store, chosen);
    if (!loaded)
      break;

    std::vector<Id> new_parents;
    std::vector<Id> new_parent_trees;
    for (std::size_t pi = 0; pi < loaded->commit.parents.size(); ++pi) {
      const Id parent = loaded->commit.parents[pi];
      if (pi == 0 && same_id(chosen, *src)) {
        new_parents.push_back(*dst);
        new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));
        continue;
      }
      bool mapped = false;
      for (std::size_t mi = 0; mi < old_ids.size(); ++mi) {
        if (same_id(old_ids[mi], parent)) {
          new_parents.push_back(new_ids[mi]);
          new_parent_trees.push_back(new_tree_ids[mi]);
          mapped = true;
          break;
        }
      }
      if (!mapped) {
        new_parents.push_back(parent);
        new_parent_trees.push_back(tree_of(store, parent).value_or(Id{}));
      }
    }
    if (loaded->commit.parents.empty()) {
      new_parents.push_back(*dst);
      new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));
    }

    MergeOutcome outcome =
        rewrite_tree(*root, *tx, store, chosen, loaded->commit.root_tree,
                     loaded->commit.parents, new_parents, new_parent_trees,
                     adjacent);
    rerere_total += outcome.rerere;
    const Id new_id =
        make_commit(*tx, store, *root, new_parents, outcome.tree,
                    loaded->commit.change_id, loaded->commit.author,
                    loaded->commit.message, loaded->commit.renames_state,
                    loaded->commit.extra);
    old_ids.push_back(chosen);
    new_ids.push_back(new_id);
    new_tree_ids.push_back(outcome.tree);
    remaining.erase(remaining.begin() +
                    static_cast<std::ptrdiff_t>(ready_idx));
  }

  auto remap = [&](std::optional<Id> &id) {
    if (!id)
      return;
    for (std::size_t i = 0; i < old_ids.size(); ++i) {
      if (same_id(old_ids[i], *id)) {
        id = new_ids[i];
        return;
      }
    }
  };
  for (auto &bookmark : tx->view().bookmarks) {
    for (auto &id : bookmark.targets.adds)
      remap(id);
    for (auto &id : bookmark.targets.removes)
      remap(id);
  }
  for (auto &tag : tx->view().tags) {
    std::optional<Id> target = tag.target;
    remap(target);
    if (target)
      tag.target = *target;
  }
  for (auto &workspace : tx->view().working_copies) {
    std::optional<Id> target = workspace.target;
    remap(target);
    if (target)
      workspace.target = *target;
  }
  rebuild_heads(tx->view());
  const auto status =
      tx->finish("rebase " + source + " onto " + dest +
                 rerere_suffix(rerere_total));
  if (!status)
    return 1;
  for (const auto &id : new_ids)
    (void)mark_native(*root, id);
  if (wc) {
    for (std::size_t i = 0; i < old_ids.size(); ++i) {
      if (same_id(old_ids[i], *wc)) {
        Store refreshed = Store::open_all(*root);
        return checkout_materialize_commit(*root, refreshed, old_wc_root,
                                           new_tree_ids[i]);
      }
    }
  }
  return 0;
}

int xs_command(bool porcelain) {
  const auto root = discover_repo(".");
  if (!root) {
    error_prefix();
    std::cout << "not a veins repository\n";
    return 1;
  }
  const int snap = snapshot_run(*root);
  if (snap != 0)
    return snap;
  Store store = Store::open_all(*root);
  auto view = current_view(*root, store);
  if (!view) {
    error_prefix();
    std::cout << "no operation state\n";
    return 1;
  }
  std::vector<std::pair<std::string, Conflict>> items;
  if (const auto wc = working_copy_id(*view)) {
    auto loaded = load_commit(store, *wc);
    if (loaded) {
      for (const auto &entry : flatten_store(store, loaded->commit.root_tree)) {
        if (entry.kind != KIND_CONFLICT)
          continue;
        auto body = store.read_body(entry.target, TYPE_CONFLICT);
        if (!body)
          continue;
        auto conflict = decode_conflict(bytes_of(*body));
        if (!conflict)
          continue;
        items.emplace_back(entry.path, std::move(*conflict));
      }
    }
  }
  const bool adjacent = adjacent_config(*root);
  bool first = true;
  for (const auto &[path, conflict] : items) {
    const std::string kind = conflict_kind_label(conflict);
    auto ranges = conflict_ranges(store, conflict, adjacent);
    if (porcelain) {
      std::cout << path << "\t" << kind << "\t";
      if (ranges) {
        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {
          if (i > 0)
            std::cout << ",";
          print_range(ranges->ranges[i].base_start,
                      ranges->ranges[i].base_end);
        }
        std::cout << "\t";
        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {
          if (i > 0)
            std::cout << ",";
          print_range(ranges->ranges[i].ours_start,
                      ranges->ranges[i].ours_end);
        }
        std::cout << "\t";
        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {
          if (i > 0)
            std::cout << ",";
          print_range(ranges->ranges[i].theirs_start,
                      ranges->ranges[i].theirs_end);
        }
      } else {
        std::cout << "\t\t";
      }
      std::cout << "\n";
    } else {
      std::cout << path << ": " << kind << " conflict";
      if (ranges && !ranges->ranges.empty()) {
        std::cout << " (";
        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {
          if (i > 0)
            std::cout << ", ";
          std::cout << "base ";
          print_range(ranges->ranges[i].base_start,
                      ranges->ranges[i].base_end);
          std::cout << ", ours ";
          print_range(ranges->ranges[i].ours_start,
                      ranges->ranges[i].ours_end);
          std::cout << ", theirs ";
          print_range(ranges->ranges[i].theirs_start,
                      ranges->ranges[i].theirs_end);
        }
        std::cout << ")";
      }
      std::cout << "\n";
    }
    first = false;
  }
  if (first) {
    info_prefix();
    std::cout << "no conflicts\n";
  }
  return 0;
}

std::string shell_replace(std::string_view command, std::string_view key,
                          const std::string &value) {
  std::string out;
  std::size_t i = 0;
  while (i < command.size()) {
    if (i + key.size() <= command.size() &&
        command.compare(i, key.size(), key) == 0) {
      out.push_back('\'');
      out += value;
      out.push_back('\'');
      i += key.size();
    } else {
      out.push_back(command[i]);
      ++i;
    }
  }
  return out;
}

bool run_tool(const fs::path &root, std::string_view command,
              std::string_view path) {
  const std::string base = path_to_bytes(root / path_from_bytes(path));
  std::string expanded(command);
  expanded = shell_replace(expanded, "$BASE", base + ".base");
  expanded = shell_replace(expanded, "$OURS", base + ".ours");
  expanded = shell_replace(expanded, "$THEIRS", base + ".theirs");
  expanded = shell_replace(expanded, "$OUTPUT", base);
  return std::system(expanded.c_str()) == 0;
}

void delete_sidecar(const fs::path &root, std::string_view path,
                    std::string_view suffix) {
  std::string full(path);
  full += suffix;
  (void)remove_file(root / path_from_bytes(full));
}

void delete_sidecars(const fs::path &root, std::string_view path) {
  delete_sidecar(root, path, ".base");
  delete_sidecar(root, path, ".ours");
  delete_sidecar(root, path, ".theirs");
  for (int n = 2; n <= 64; ++n) {
    delete_sidecar(root, path, ".base" + std::to_string(n));
    delete_sidecar(root, path, ".theirs" + std::to_string(n));
  }
}

std::optional<ConflictValue> choose_value(const Conflict &conflict,
                                          std::string_view take) {
  if (take == "ours" && !conflict.adds.empty())
    return conflict.adds[0];
  if (take == "theirs" && conflict.adds.size() > 1)
    return conflict.adds[1];
  if (take == "base" && !conflict.removes.empty())
    return conflict.removes[0];
  return std::nullopt;
}

int resolve_command(std::string_view take, std::string_view tool,
                    const std::vector<std::string> &paths) {
  const auto root = discover_repo(".");
  if (!root) {
    error_prefix();
    std::cout << "not a veins repository\n";
    return 1;
  }
  const int snap = snapshot_run(*root);
  if (snap != 0)
    return snap;
  Store store = Store::open_all(*root);
  auto tx = Txn::begin(*root, store);
  if (!tx) {
    error_prefix();
    std::cout << "cannot load repository state\n";
    return 1;
  }
  const auto wc = working_copy_id(tx->view());
  if (!wc) {
    error_prefix();
    std::cout << "no working-copy commit\n";
    return 1;
  }
  auto loaded = load_commit(store, *wc);
  if (!loaded) {
    error_prefix();
    std::cout << "cannot read working-copy commit\n";
    return 1;
  }
  const Id old_root = loaded->commit.root_tree;
  Id mut_root = old_root;
  bool resolved_any = false;
  std::vector<std::string> normalized_paths;

  const auto cwd = cwd_relative(*root);
  for (const auto &arg : paths) {
    auto norm = cwd ? pathspec_normalize(*root, *cwd, arg) : std::nullopt;
    if (!norm || norm->empty()) {
      error_prefix();
      std::cout << "invalid path\n";
      continue;
    }
    normalized_paths.push_back(*norm);
    auto flat = flatten_store(store, mut_root);
    const FlatEntry *entry = find_flat_entry(flat, *norm);
    if (!entry || entry->kind != KIND_CONFLICT) {
      error_prefix();
      std::cout << "not a conflicted path: " << *norm << "\n";
      continue;
    }
    auto body = store.read_body(entry->target, TYPE_CONFLICT);
    if (!body)
      continue;
    auto conflict = decode_conflict(bytes_of(*body));
    if (!conflict)
      continue;

    bool present = false;
    std::uint8_t new_kind = KIND_FILE;
    std::optional<Id> new_target;
    if (auto chosen = choose_value(*conflict, take)) {
      if (chosen->kind != 0) {
        present = true;
        new_kind = chosen->kind;
        new_target = chosen->target;
      }
    } else if (!tool.empty()) {
      if (run_tool(*root, tool, *norm)) {
        if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {
          new_target = add_blob(*tx, bytes_of(*data));
          present = true;
          new_kind = KIND_FILE;
        }
      }
    } else {
      if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {
        new_target = add_blob(*tx, bytes_of(*data));
        present = true;
        new_kind = KIND_FILE;
      }
    }
    if (present) {
      if (auto info = stat_path(*root / path_from_bytes(*norm))) {
        if (info->executable)
          new_kind = KIND_EXECUTABLE;
      }
      if (new_kind == KIND_FILE || new_kind == KIND_EXECUTABLE) {
        if (auto conflict_body =
                store.read_body(entry->target, TYPE_CONFLICT)) {
          resolution_record(*root, bytes_of(*conflict_body),
                            *new_target);
        }
      }
    }
    auto replaced = tree_edit_replace(*tx, store, mut_root, *norm, present,
                                      new_kind, new_target.value_or(Id{}));
    if (replaced) {
      mut_root = *replaced;
      resolved_any = true;
    }
  }

  if (!resolved_any) {
    return 1;
  }

  Commit commit = loaded->commit;
  commit.root_tree = mut_root;
  commit.committer = identity_signature(*root);
  const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));
  remove_head(tx->view(), *wc);
  move_bookmarks(tx->view(), *wc, new_id);
  set_workspace(tx->view(), new_id);
  rebuild_heads(tx->view());
  const auto status = tx->finish("resolve");
  if (!status)
    return 1;
  Store refreshed = Store::open_all(*root);
  const int materialized =
      checkout_materialize_commit(*root, refreshed, old_root, mut_root);
  if (materialized != 0)
    return materialized;
  for (const auto &path : normalized_paths)
    delete_sidecars(*root, path);
  return 0;
}

} // namespace

// ---------------------------------------------------------------------------
// Argument parsing
// ---------------------------------------------------------------------------

int merge_run(const std::vector<std::string> &args) {
  std::vector<std::string> revs;
  bool end_flags = false;
  for (std::size_t i = 2; i < args.size(); ++i) {
    const std::string &arg = args[i];
    if (!end_flags && arg == "--") {
      end_flags = true;
    } else if (!end_flags && !arg.empty() && arg.front() == '-') {
      error_prefix();
      std::cout << "unknown flag: " << arg << "\n";
      return 1;
    } else {
      revs.push_back(arg);
    }
  }
  return merge_command(revs);
}

int rebase_run(const std::vector<std::string> &args) {
  std::string source;
  std::string dest;
  bool end_flags = false;
  for (std::size_t i = 2; i < args.size(); ++i) {
    const std::string &arg = args[i];
    if (!end_flags && arg == "--") {
      end_flags = true;
    } else if (!end_flags && (arg == "-s" || arg == "-source")) {
      if (i + 1 >= args.size()) {
        error_prefix();
        std::cout << arg << " requires a revision\n";
        return 1;
      }
      source = args[++i];
    } else if (!end_flags && (arg == "-d" || arg == "-destination")) {
      if (i + 1 >= args.size()) {
        error_prefix();
        std::cout << arg << " requires a revision\n";
        return 1;
      }
      dest = args[++i];
    } else if (!end_flags && !arg.empty() && arg.front() == '-') {
      error_prefix();
      std::cout << "unknown flag: " << arg << "\n";
      return 1;
    } else {
      error_prefix();
      std::cout << "unexpected argument: " << arg << "\n";
      return 1;
    }
  }
  if (source.empty() || dest.empty()) {
    error_prefix();
    std::cout << "rebase requires -s <rev> and -d <rev>\n";
    return 1;
  }
  return rebase_command(source, dest);
}

int xs_run(const std::vector<std::string> &args) {
  bool porcelain = false;
  bool end_flags = false;
  for (std::size_t i = 2; i < args.size(); ++i) {
    const std::string &arg = args[i];
    if (!end_flags && arg == "--") {
      end_flags = true;
    } else if (!end_flags && (arg == "-porcelain" || arg == "-p")) {
      porcelain = true;
    } else if (!end_flags && !arg.empty() && arg.front() == '-') {
      error_prefix();
      std::cout << "unknown flag: " << arg << "\n";
      return 1;
    } else {
      error_prefix();
      std::cout << "unexpected argument: " << arg << "\n";
      return 1;
    }
  }
  return xs_command(porcelain);
}

int resolve_run(const std::vector<std::string> &args) {
  std::string take;
  std::string tool;
  bool list_only = false;
  std::vector<std::string> paths;
  bool end_flags = false;
  for (std::size_t i = 2; i < args.size(); ++i) {
    const std::string &arg = args[i];
    if (!end_flags && arg == "--") {
      end_flags = true;
    } else if (!end_flags && (arg == "-list" || arg == "-l")) {
      list_only = true;
    } else if (!end_flags && (arg == "-take" || arg == "-t")) {
      if (i + 1 >= args.size()) {
        error_prefix();
        std::cout << arg << " requires ours, theirs, or base\n";
        return 1;
      }
      take = args[++i];
    } else if (!end_flags && arg == "-tool") {
      if (i + 1 >= args.size()) {
        error_prefix();
        std::cout << arg << " requires a command\n";
        return 1;
      }
      tool = args[++i];
    } else if (!end_flags && !arg.empty() && arg.front() == '-') {
      error_prefix();
      std::cout << "unknown flag: " << arg << "\n";
      return 1;
    } else {
      paths.push_back(arg);
    }
  }
  if (list_only)
    return xs_command(false);
  if (paths.empty()) {
    error_prefix();
    std::cout << "resolve requires at least one path\n";
    return 1;
  }
  return resolve_command(take, tool, paths);
}

} // namespace vn