navid/veins / 83508482911f348af86cb892949a35bdce0d6b2f949b4a0faab7cba9a499fb82 / veinsrs/src/merge/engine.rs

engine.rs

← veinsrs/src/merge · 51117 bytes · raw · download

use std::path::Path;

use crate::core;
use crate::error::{Error, Result};
use crate::identity;
use crate::object::blob::{self, BlobForm};
use crate::object::commit::{self, Commit, Rename, Sig};
use crate::object::conflict::{self, Conflict, ConflictValue};
use crate::object::id::{Id, object_id};
use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry};
use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};
use crate::store::Txn;
use crate::store::graph;
use crate::store::reader::Store;
use crate::store::writer::Writer;
use crate::worktree::snapshot;

fn same(left: Id, right: Id) -> bool {
    left == right
}

fn read_any(
    store: &mut Store,
    writer: Option<&Writer>,
    kind: u8,
    id: Id,
) -> Result<Option<Vec<u8>>> {
    if let Some(writer) = writer
        && let Some(body) = writer.find_cached(kind, id)
    {
        return Ok(Some(body.to_vec()));
    }
    store.body(id, kind)
}

fn append_blob(
    store: &mut Store,
    writer: Option<&Writer>,
    id: Id,
    output: &mut Vec<u8>,
    depth: usize,
) -> Result<bool> {
    if depth > 64 {
        return Ok(false);
    }
    let Some(body) = read_any(store, writer, TYPE_BLOB, id)? else {
        return Ok(false);
    };
    let blob = blob::decode(&body)?;
    match blob.form {
        BlobForm::Inline => output.extend_from_slice(&blob.data),
        BlobForm::Leaf => {
            for entry in blob.entries {
                let Some(chunk) = read_any(store, writer, TYPE_CHUNK, entry.id)? else {
                    return Ok(false);
                };
                output.extend_from_slice(&chunk);
            }
        }
        BlobForm::Interior => {
            for entry in blob.entries {
                if !append_blob(store, writer, entry.id, output, depth + 1)? {
                    return Ok(false);
                }
            }
        }
    }
    Ok(true)
}

pub fn read_blob_any(
    store: &mut Store,
    writer: Option<&Writer>,
    id: Id,
) -> Result<Option<Vec<u8>>> {
    let mut output = Vec::new();
    if append_blob(store, writer, id, &mut output, 0)? {
        Ok(Some(output))
    } else {
        Ok(None)
    }
}

fn collect_chunks(
    store: &mut Store,
    writer: Option<&Writer>,
    id: Id,
    output: &mut Vec<Id>,
    depth: usize,
) -> Result<bool> {
    if depth > 64 {
        return Ok(false);
    }
    let Some(body) = read_any(store, writer, TYPE_BLOB, id)? else {
        return Ok(false);
    };
    let blob = blob::decode(&body)?;
    match blob.form {
        BlobForm::Leaf => {
            for entry in blob.entries {
                output.push(entry.id);
            }
        }
        BlobForm::Interior => {
            for entry in blob.entries {
                if !collect_chunks(store, writer, entry.id, output, depth + 1)? {
                    return Ok(false);
                }
            }
        }
        BlobForm::Inline => {}
    }
    Ok(true)
}

fn flatten_into(
    store: &mut Store,
    writer: Option<&Writer>,
    tree_id: Id,
    prefix: &mut Vec<u8>,
    output: &mut Vec<FlatEntry>,
    depth: usize,
) -> Result<bool> {
    if depth > crate::object::MAX_TREE_DEPTH {
        return Ok(false);
    }
    let Some(body) = read_any(store, writer, TYPE_TREE, tree_id)? else {
        return Ok(false);
    };
    let tree = tree::decode(&body)?;
    for entry in tree.entries {
        let old_length = prefix.len();
        if !prefix.is_empty() {
            prefix.push(b'/');
        }
        prefix.extend_from_slice(&entry.name);
        if entry.kind == KIND_SUBTREE {
            let ok = flatten_into(store, writer, entry.target, prefix, output, depth + 1)?;
            prefix.truncate(old_length);
            if !ok {
                return Ok(false);
            }
        } else {
            output.push(FlatEntry {
                path: prefix.clone(),
                kind: entry.kind,
                target: entry.target,
            });
            prefix.truncate(old_length);
        }
    }
    Ok(true)
}

pub fn flatten_sorted(
    store: &mut Store,
    writer: Option<&Writer>,
    tree: Option<Id>,
) -> Result<Vec<FlatEntry>> {
    let Some(tree) = tree else {
        return Ok(Vec::new());
    };
    let mut output = Vec::new();
    flatten_into(store, writer, tree, &mut Vec::new(), &mut output, 0)?;
    output.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(output)
}

fn find_flat<'a>(entries: &'a [FlatEntry], path: &[u8]) -> Option<&'a FlatEntry> {
    entries
        .binary_search_by(|entry| entry.path.as_slice().cmp(path))
        .ok()
        .map(|index| &entries[index])
}

fn tree_empty(store: &mut Store, writer: Option<&Writer>, id: Id) -> Result<bool> {
    match read_any(store, writer, TYPE_TREE, id)? {
        Some(body) => Ok(tree::decode(&body)
            .map(|tree| tree.entries.is_empty())
            .unwrap_or(true)),
        None => Ok(true),
    }
}

fn add_tree(txn: &mut Txn, entries: &[TreeEntry]) -> Result<Id> {
    Ok(txn.add_object(TYPE_TREE, tree::encode(entries)?))
}

fn add_empty_tree(txn: &mut Txn) -> Result<Id> {
    add_tree(txn, &[])
}

fn add_blob(txn: &mut Txn, data: &[u8]) -> Id {
    let build = blob::build(data);
    for object in build.objects {
        txn.add_known(object.kind, object.id, object.body);
    }
    build.root
}

fn hash_line(line: &[u8]) -> u64 {
    let mut hash = 1_469_598_103_934_665_603u64;
    for byte in line {
        hash = (hash ^ *byte as u64).wrapping_mul(1_099_511_628_211);
    }
    hash
}

fn line_similarity(left: &[u8], right: &[u8]) -> u32 {
    fn lines(data: &[u8]) -> Vec<u64> {
        let mut output = Vec::new();
        let mut start = 0;
        for index in 0..=data.len() {
            if index == data.len() || data[index] == b'\n' {
                output.push(hash_line(&data[start..index]));
                start = index + 1;
            }
        }
        output.sort_unstable();
        output
    }
    let a = lines(left);
    let b = lines(right);
    let mut ia = 0;
    let mut ib = 0;
    let mut intersection = 0;
    while ia < a.len() && ib < b.len() {
        if a[ia] == b[ib] {
            intersection += 1;
            ia += 1;
            ib += 1;
        } else if a[ia] < b[ib] {
            ia += 1;
        } else {
            ib += 1;
        }
    }
    let total = a.len() + b.len() - intersection;
    if total == 0 {
        100
    } else {
        (intersection * 100 / total) as u32
    }
}

fn chunk_similarity(store: &mut Store, writer: Option<&Writer>, a: Id, b: Id) -> Result<u32> {
    let mut left = Vec::new();
    let mut right = Vec::new();
    if !collect_chunks(store, writer, a, &mut left, 0)?
        || !collect_chunks(store, writer, b, &mut right, 0)?
    {
        return Ok(0);
    }
    let mut intersection = 0;
    for item in &left {
        if right.contains(item) {
            intersection += 1;
        }
    }
    let total = left.len() + right.len() - intersection;
    Ok(if total == 0 {
        0
    } else {
        (intersection * 100 / total) as u32
    })
}

fn similarity(store: &mut Store, writer: Option<&Writer>, a: Id, b: Id) -> Result<u32> {
    if same(a, b) {
        return Ok(100);
    }
    let Some(left) = read_blob_any(store, writer, a)? else {
        return Ok(0);
    };
    let Some(right) = read_blob_any(store, writer, b)? else {
        return Ok(0);
    };
    let mut result = 0;
    if left.len() >= 131_072 && right.len() >= 131_072 {
        result = chunk_similarity(store, writer, a, b)?;
    }
    if result == 0 {
        result = line_similarity(&left, &right);
    }
    Ok(result)
}

pub fn detect(
    store: &mut Store,
    writer: Option<&Writer>,
    old_tree: Option<Id>,
    new_tree: Option<Id>,
    similar_pct: u32,
    parent_index: u64,
) -> Result<Vec<Rename>> {
    let old_entries = flatten_sorted(store, writer, old_tree)?;
    let new_entries = flatten_sorted(store, writer, new_tree)?;
    let deleted: Vec<&FlatEntry> = old_entries
        .iter()
        .filter(|entry| find_flat(&new_entries, &entry.path).is_none())
        .collect();
    let added: Vec<&FlatEntry> = new_entries
        .iter()
        .filter(|entry| find_flat(&old_entries, &entry.path).is_none())
        .collect();
    let mut used_old = vec![false; deleted.len()];
    let mut used_new = vec![false; added.len()];
    let mut output = Vec::new();
    for (old_index, old) in deleted.iter().enumerate() {
        if used_old[old_index] {
            continue;
        }
        for (new_index, new) in added.iter().enumerate() {
            if used_new[new_index] {
                continue;
            }
            if old.target == new.target {
                output.push(Rename {
                    parent_index,
                    kind: 0,
                    from_path: old.path.clone(),
                    to_path: new.path.clone(),
                });
                used_old[old_index] = true;
                used_new[new_index] = true;
                break;
            }
        }
    }
    if similar_pct > 0 {
        let mut pairs = Vec::new();
        for (old_index, old) in deleted.iter().enumerate() {
            if used_old[old_index] || !matches!(old.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE) {
                continue;
            }
            for (new_index, new) in added.iter().enumerate() {
                if used_new[new_index]
                    || !matches!(new.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE)
                {
                    continue;
                }
                pairs.push((
                    old_index,
                    new_index,
                    similarity(store, writer, old.target, new.target)?,
                ));
            }
        }
        loop {
            let mut best = None;
            for (old_index, new_index, score) in &pairs {
                if used_old[*old_index] || used_new[*new_index] {
                    continue;
                }
                if best.is_none_or(|(_, _, current): (usize, usize, u32)| *score > current) {
                    best = Some((*old_index, *new_index, *score));
                }
            }
            let Some((old_index, new_index, score)) = best else {
                break;
            };
            if score < similar_pct {
                break;
            }
            used_old[old_index] = true;
            used_new[new_index] = true;
            output.push(Rename {
                parent_index,
                kind: 0,
                from_path: deleted[old_index].path.clone(),
                to_path: added[new_index].path.clone(),
            });
        }
    }
    output.sort_by(|left, right| {
        left.parent_index
            .cmp(&right.parent_index)
            .then_with(|| left.to_path.cmp(&right.to_path))
    });
    Ok(output)
}

pub fn rename_similar_pct(root: &Path) -> u32 {
    match core::repo_config_value(root, "rename.autodetect").as_deref() {
        Some("off") => 0,
        _ => 60,
    }
}

fn split_lines(data: &[u8]) -> Vec<Vec<u8>> {
    let mut output = Vec::new();
    let mut start = 0;
    for index in 0..data.len() {
        if data[index] == b'\n' {
            output.push(data[start..=index].to_vec());
            start = index + 1;
        }
    }
    if start < data.len() {
        output.push(data[start..].to_vec());
    }
    output
}

#[derive(Clone, Copy)]
struct Op {
    tag: u8,
    bi: usize,
}

fn fallback_ops(a: &[Vec<u8>], b: &[Vec<u8>]) -> Vec<Op> {
    let mut prefix = 0;
    while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] {
        prefix += 1;
    }
    let mut suffix = 0;
    while suffix < a.len() - prefix
        && suffix < b.len() - prefix
        && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]
    {
        suffix += 1;
    }
    let mut output = Vec::new();
    for index in 0..prefix {
        output.push(Op {
            tag: b' ',
            bi: index,
        });
    }
    for _index in prefix..a.len() - suffix {
        output.push(Op { tag: b'-', bi: 0 });
    }
    for index in prefix..b.len() - suffix {
        output.push(Op {
            tag: b'+',
            bi: index,
        });
    }
    for index in 0..suffix {
        output.push(Op {
            tag: b' ',
            bi: b.len() - suffix + index,
        });
    }
    output
}

fn build_ops(a: &[Vec<u8>], b: &[Vec<u8>]) -> Vec<Op> {
    let cells = (a.len() as u64 + 1) * (b.len() as u64 + 1);
    if cells > 8_000_000 {
        return fallback_ops(a, b);
    }
    let columns = b.len() + 1;
    let mut dp = vec![0u32; cells as usize];
    for i in 1..=a.len() {
        for j in 1..=b.len() {
            dp[i * columns + j] = if a[i - 1] == b[j - 1] {
                dp[(i - 1) * columns + j - 1] + 1
            } else {
                dp[(i - 1) * columns + j].max(dp[i * columns + j - 1])
            };
        }
    }
    let mut output = Vec::new();
    let mut i = a.len();
    let mut j = b.len();
    while i > 0 || j > 0 {
        if i > 0 && j > 0 && a[i - 1] == b[j - 1] {
            output.push(Op {
                tag: b' ',
                bi: j - 1,
            });
            i -= 1;
            j -= 1;
        } else if j > 0 && (i == 0 || dp[i * columns + j - 1] >= dp[(i - 1) * columns + j]) {
            output.push(Op {
                tag: b'+',
                bi: j - 1,
            });
            j -= 1;
        } else {
            output.push(Op { tag: b'-', bi: 0 });
            i -= 1;
        }
    }
    output.reverse();
    output
}

#[derive(Clone)]
struct Hunk {
    start: usize,
    end: usize,
    lines: Vec<Vec<u8>>,
}

fn diff_hunks(base: &[Vec<u8>], side: &[Vec<u8>]) -> Vec<Hunk> {
    let ops = build_ops(base, side);
    let mut output = Vec::new();
    let mut base_position = 0;
    let mut index = 0;
    while index < ops.len() {
        if ops[index].tag == b' ' {
            base_position += 1;
            index += 1;
            continue;
        }
        let mut hunk = Hunk {
            start: base_position,
            end: 0,
            lines: Vec::new(),
        };
        while index < ops.len() && ops[index].tag != b' ' {
            if ops[index].tag == b'-' {
                base_position += 1;
            } else {
                hunk.lines.push(side[ops[index].bi].clone());
            }
            index += 1;
        }
        hunk.end = base_position;
        output.push(hunk);
    }
    output
}

#[derive(Clone, Copy)]
pub struct MergeRange {
    pub base_start: usize,
    pub base_end: usize,
    pub ours_start: usize,
    pub ours_end: usize,
    pub theirs_start: usize,
    pub theirs_end: usize,
}

pub struct EditResult {
    pub conflicted: bool,
    pub data: Vec<u8>,
    pub ranges: Vec<MergeRange>,
}

fn append_lines(output: &mut Vec<u8>, lines: &[Vec<u8>], start: usize, end: usize) {
    for index in start..end.min(lines.len()) {
        output.extend_from_slice(&lines[index]);
    }
}

fn apply_hunks(
    output: &mut Vec<u8>,
    base: &[Vec<u8>],
    from: usize,
    to: usize,
    hunks: &[Hunk],
    first: usize,
    last: usize,
) {
    let mut position = from;
    for hunk in &hunks[first..last] {
        if hunk.start > position && hunk.start <= to {
            append_lines(output, base, position, hunk.start);
        }
        for line in &hunk.lines {
            output.extend_from_slice(line);
        }
        if hunk.end > position {
            position = hunk.end;
        }
    }
    if position < to {
        append_lines(output, base, position, to);
    }
}

fn map_position(hunks: &[Hunk], position: usize) -> usize {
    let mut output = position as i64;
    for hunk in hunks {
        if hunk.end <= position {
            output += hunk.lines.len() as i64 - (hunk.end - hunk.start) as i64;
        } else if hunk.start < position {
            output += hunk.lines.len() as i64 - (position - hunk.start) as i64;
            break;
        } else {
            break;
        }
    }
    output.max(0) as usize
}

fn same_hunks(ours: &[Hunk], of: usize, ol: usize, theirs: &[Hunk], tf: usize, tl: usize) -> bool {
    let mut left = Vec::new();
    let mut right = Vec::new();
    for hunk in &ours[of..ol] {
        for line in &hunk.lines {
            left.extend_from_slice(line);
        }
    }
    for hunk in &theirs[tf..tl] {
        for line in &hunk.lines {
            right.extend_from_slice(line);
        }
    }
    left == right
}

pub fn merge_lines(base: &[u8], ours: &[u8], theirs: &[u8], adjacent: bool) -> EditResult {
    let base = split_lines(base);
    let ours = split_lines(ours);
    let theirs = split_lines(theirs);
    let ours_hunks = diff_hunks(&base, &ours);
    let theirs_hunks = diff_hunks(&base, &theirs);
    let mut result = EditResult {
        conflicted: false,
        data: Vec::new(),
        ranges: Vec::new(),
    };
    let mut oi = 0;
    let mut ti = 0;
    let mut position = 0;
    while oi < ours_hunks.len() || ti < theirs_hunks.len() {
        let have_ours = oi < ours_hunks.len();
        let have_theirs = ti < theirs_hunks.len();
        let ours_start = if have_ours { ours_hunks[oi].start } else { 0 };
        let theirs_start = if have_theirs {
            theirs_hunks[ti].start
        } else {
            0
        };
        let take_ours = have_ours && (!have_theirs || ours_start <= theirs_start);
        let cluster_start = if take_ours { ours_start } else { theirs_start };
        let of = oi;
        let tf = ti;
        let mut o_last = of;
        let mut t_last = tf;
        let mut end = cluster_start;
        let mut seen_ours = false;
        let mut seen_theirs = false;
        loop {
            let mut progress = false;
            if o_last < ours_hunks.len() {
                let hunk = &ours_hunks[o_last];
                let include = if o_last == of {
                    hunk.start <= end
                } else if adjacent {
                    hunk.start < end
                } else {
                    hunk.start <= end
                };
                if include {
                    seen_ours = true;
                    o_last += 1;
                    end = end.max(hunk.end);
                    progress = true;
                }
            }
            if t_last < theirs_hunks.len() {
                let hunk = &theirs_hunks[t_last];
                let include = if t_last == tf {
                    hunk.start <= end
                } else if adjacent {
                    hunk.start < end
                } else {
                    hunk.start <= end
                };
                if include {
                    seen_theirs = true;
                    t_last += 1;
                    end = end.max(hunk.end);
                    progress = true;
                }
            }
            if !progress {
                break;
            }
        }
        end = end.max(cluster_start);
        if seen_ours && !seen_theirs {
            apply_hunks(
                &mut result.data,
                &base,
                position,
                end,
                &ours_hunks,
                of,
                o_last,
            );
            position = end;
            oi = o_last;
            ti = t_last;
        } else if seen_theirs && !seen_ours {
            apply_hunks(
                &mut result.data,
                &base,
                position,
                end,
                &theirs_hunks,
                tf,
                t_last,
            );
            position = end;
            oi = o_last;
            ti = t_last;
        } else {
            if same_hunks(&ours_hunks, of, o_last, &theirs_hunks, tf, t_last) {
                apply_hunks(
                    &mut result.data,
                    &base,
                    position,
                    end,
                    &ours_hunks,
                    of,
                    o_last,
                );
                position = end;
            } else {
                result.conflicted = true;
                apply_hunks(
                    &mut result.data,
                    &base,
                    position,
                    end,
                    &ours_hunks,
                    of,
                    o_last,
                );
                result.ranges.push(MergeRange {
                    base_start: cluster_start,
                    base_end: end,
                    ours_start: map_position(&ours_hunks, cluster_start),
                    ours_end: map_position(&ours_hunks, end),
                    theirs_start: map_position(&theirs_hunks, cluster_start),
                    theirs_end: map_position(&theirs_hunks, end),
                });
                position = end;
            }
            oi = o_last;
            ti = t_last;
        }
    }
    if position < base.len() {
        append_lines(&mut result.data, &base, position, base.len());
    }
    result
}

fn merge_blobs(
    store: &mut Store,
    writer: Option<&Writer>,
    base: Id,
    ours: Id,
    theirs: Id,
    adjacent: bool,
) -> Result<Option<EditResult>> {
    let Some(base) = read_blob_any(store, writer, base)? else {
        return Ok(None);
    };
    let Some(ours) = read_blob_any(store, writer, ours)? else {
        return Ok(None);
    };
    let Some(theirs) = read_blob_any(store, writer, theirs)? else {
        return Ok(None);
    };
    Ok(Some(merge_lines(&base, &ours, &theirs, adjacent)))
}

fn value_equal(left: &ConflictValue, right: &ConflictValue) -> bool {
    left.kind == right.kind && (left.kind == 0 || left.target == right.target)
}

fn flatten_values(
    store: &mut Store,
    values: &[ConflictValue],
    positive: bool,
    adds: &mut Vec<ConflictValue>,
    removes: &mut Vec<ConflictValue>,
    depth: usize,
) -> Result<()> {
    for value in values {
        if value.kind == KIND_CONFLICT
            && let Some(target) = value.target
            && depth < 64
            && let Some(body) = store.body(target, TYPE_CONFLICT)?
            && let Ok(child) = conflict::decode(&body)
        {
            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(value.clone());
        } else {
            removes.push(value.clone());
        }
    }
    Ok(())
}

pub fn simplify(
    store: &mut Store,
    adds: &[ConflictValue],
    removes: &[ConflictValue],
) -> Result<Conflict> {
    let mut flat_adds = Vec::new();
    let mut flat_removes = Vec::new();
    flatten_values(store, adds, true, &mut flat_adds, &mut flat_removes, 0)?;
    flatten_values(store, removes, false, &mut flat_adds, &mut flat_removes, 0)?;
    let mut used_adds = vec![false; flat_adds.len()];
    let mut used_removes = vec![false; flat_removes.len()];
    for (remove_index, remove) in flat_removes.iter().enumerate() {
        for (add_index, add) in flat_adds.iter().enumerate() {
            if !used_adds[add_index] && value_equal(add, remove) {
                used_adds[add_index] = true;
                used_removes[remove_index] = true;
                break;
            }
        }
    }
    Ok(Conflict {
        adds: flat_adds
            .into_iter()
            .enumerate()
            .filter(|(index, _)| !used_adds[*index])
            .map(|(_, value)| value)
            .collect(),
        removes: flat_removes
            .into_iter()
            .enumerate()
            .filter(|(index, _)| !used_removes[*index])
            .map(|(_, value)| value)
            .collect(),
    })
}

pub fn resolved(conflict: &Conflict) -> Option<ConflictValue> {
    let first = conflict.adds.first()?;
    if conflict.adds.iter().all(|value| value_equal(value, first)) {
        Some(first.clone())
    } else {
        None
    }
}

fn all_files(conflict: &Conflict) -> bool {
    conflict
        .adds
        .iter()
        .chain(conflict.removes.iter())
        .all(|value| matches!(value.kind, 0 | tree::KIND_FILE | tree::KIND_EXECUTABLE))
}

fn merge_mode(conflict: &Conflict) -> i32 {
    if conflict.adds.len() != 2 || conflict.removes.len() != 1 {
        return -1;
    }
    let mode = |value: &ConflictValue| -> i32 {
        if value.kind == 0 {
            return -1;
        }
        if value.kind == tree::KIND_EXECUTABLE {
            1
        } else {
            0
        }
    };
    let zero = mode(&conflict.adds[0]);
    let one = mode(&conflict.adds[1]);
    let remove = mode(&conflict.removes[0]);
    if zero < 0 || one < 0 {
        return -1;
    }
    if zero == one {
        return zero;
    }
    if remove >= 0 && zero == remove {
        return one;
    }
    if remove >= 0 && one == remove {
        return zero;
    }
    -1
}

fn merge_binary(repo: &Path, path: &[u8]) -> bool {
    let Some(data) = core::read_file_opt(&repo.join(".vnmergedata"), 0) else {
        return false;
    };
    let text = String::from_utf8_lossy(&data);
    let path = String::from_utf8_lossy(path);
    let mut result = false;
    for raw in text.lines() {
        let line = core::trim_str(raw);
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split_whitespace();
        let Some(glob) = parts.next() else {
            continue;
        };
        let base = glob.rsplit('/').next().unwrap_or(glob);
        if !core::glob_match(glob, &path) && !(!glob.contains('/') && core::glob_match(base, &path))
        {
            continue;
        }
        for token in parts {
            if let Some(value) = token.strip_prefix("merge=") {
                if value == "binary" {
                    result = true;
                } else if value == "text" {
                    result = false;
                }
            }
        }
    }
    result
}

fn resolution_lookup(repo: &Path, body: &[u8]) -> Option<Id> {
    let key = crate::object::id::hash_bytes(body);
    let data = core::read_file_opt(
        &crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()),
        0,
    )?;
    if data.len() < 64 {
        return None;
    }
    Id::from_hex(std::str::from_utf8(&data[..64]).ok()?).ok()
}

fn resolution_record(repo: &Path, body: &[u8], blob: Id) {
    let key = crate::object::id::hash_bytes(body);
    let _ = core::write_file(
        &crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()),
        blob.to_hex().as_bytes(),
    );
}

type RenameMap = Vec<(Vec<u8>, Vec<u8>)>;

fn rename_lookup(map: &RenameMap, path: &[u8]) -> Option<Vec<u8>> {
    map.iter()
        .find(|(from, _)| from == path)
        .map(|(_, to)| to.clone())
}

fn rename_apply(map: &mut RenameMap, from: &[u8], to: &[u8]) {
    for (_, destination) in map.iter_mut() {
        if destination == from {
            *destination = to.to_vec();
            return;
        }
    }
    for (source, _) in map.iter_mut() {
        if source == from {
            return;
        }
    }
    map.push((from.to_vec(), to.to_vec()));
}

fn tree_of(store: &mut Store, commit: Id) -> Result<Option<Id>> {
    Ok(graph::load_commit(store, commit)?.map(|commit| commit.root_tree))
}

fn first_parent(store: &mut Store, commit: Id) -> Result<Option<Id>> {
    Ok(graph::load_commit(store, commit)?.and_then(|commit| commit.parents.first().copied()))
}

fn map_from(store: &mut Store, base: Id, side: Id) -> Result<RenameMap> {
    let mut map = RenameMap::new();
    if base == side {
        return Ok(map);
    }
    let mut chain = Vec::new();
    let mut current = side;
    let mut reached = false;
    for _ in 0..100_000 {
        if current == base {
            reached = true;
            break;
        }
        chain.push(current);
        let Some(parent) = first_parent(store, current)? else {
            break;
        };
        current = parent;
    }
    if !reached {
        return Ok(map);
    }
    for commit_id in chain.iter().rev() {
        let Some(loaded) = graph::load_commit(store, *commit_id)? else {
            continue;
        };
        if loaded.renames_state == commit::RENAMES_RECORDED {
            for rename in &loaded.renames {
                if rename.parent_index == 0 {
                    rename_apply(&mut map, &rename.from_path, &rename.to_path);
                }
            }
        } else {
            let Some(parent) = first_parent(store, *commit_id)? else {
                continue;
            };
            let old_tree = tree_of(store, parent)?;
            let new_tree = Some(loaded.root_tree);
            for rename in detect(store, None, old_tree, new_tree, 50, 0)? {
                rename_apply(&mut map, &rename.from_path, &rename.to_path);
            }
        }
    }
    Ok(map)
}

#[derive(Clone, Copy)]
struct TreeTerm {
    positive: bool,
    present: bool,
    id: Id,
}

#[derive(Clone)]
struct EntryTerm {
    positive: bool,
    present: bool,
    kind: u8,
    target: Option<Id>,
}

#[derive(Clone)]
struct OrigEntry {
    term: usize,
    path: Vec<u8>,
    kind: u8,
    target: Id,
}

#[derive(Clone)]
struct OutEntry {
    path: Vec<u8>,
    kind: u8,
    target: Id,
}

pub struct MergeOutcome {
    pub tree: Id,
    pub rerere: usize,
}

fn build_level(
    txn: &mut Txn,
    entries: &[OutEntry],
    start: usize,
    end: usize,
    prefix: usize,
) -> Result<Id> {
    let mut output = Vec::new();
    let mut index = start;
    while index < end {
        let entry = &entries[index];
        let cut = entry.path[prefix..]
            .iter()
            .position(|byte| *byte == b'/')
            .map(|offset| prefix + offset)
            .unwrap_or(entry.path.len());
        let name = entry.path[prefix..cut].to_vec();
        if cut == entry.path.len() {
            output.push(TreeEntry {
                name,
                kind: entry.kind,
                target: entry.target,
            });
            index += 1;
        } else {
            let mut next = index + 1;
            while next < end {
                let other = &entries[next];
                let other_cut = other.path[prefix..]
                    .iter()
                    .position(|byte| *byte == b'/')
                    .map(|offset| prefix + offset)
                    .unwrap_or(other.path.len());
                if other_cut != cut || other.path[prefix..cut] != entry.path[prefix..cut] {
                    break;
                }
                next += 1;
            }
            let child = build_level(txn, entries, index, next, cut + 1)?;
            output.push(TreeEntry {
                name,
                kind: KIND_SUBTREE,
                target: child,
            });
            index = next;
        }
    }
    add_tree(txn, &output)
}

fn build_from_entries(txn: &mut Txn, entries: &mut [OutEntry]) -> Result<Id> {
    if entries.is_empty() {
        return add_empty_tree(txn);
    }
    entries.sort_by(|left, right| left.path.cmp(&right.path));
    build_level(txn, entries, 0, entries.len(), 0)
}

fn build_subtree(txn: &mut Txn, canon: &[OrigEntry], term: usize, prefix: &[u8]) -> Result<Id> {
    let mut entries = Vec::new();
    for entry in canon {
        if entry.term == term && has_prefix(&entry.path, prefix) {
            entries.push(OutEntry {
                path: entry.path[prefix.len() + 1..].to_vec(),
                kind: entry.kind,
                target: entry.target,
            });
        }
    }
    build_from_entries(txn, &mut entries)
}

fn has_prefix(path: &[u8], prefix: &[u8]) -> bool {
    path.len() > prefix.len() && path.starts_with(prefix) && path[prefix.len()] == b'/'
}

fn merge_entry(
    repo: &Path,
    txn: &mut Txn,
    store: &mut Store,
    path: &[u8],
    terms: &[EntryTerm],
    adjacent: bool,
    rerere: &mut usize,
) -> Result<Option<OutEntry>> {
    let mut adds = Vec::new();
    let mut removes = Vec::new();
    for term in terms {
        let value = ConflictValue {
            kind: if term.present { term.kind } else { 0 },
            target: term.target,
        };
        if term.positive {
            adds.push(value);
        } else {
            removes.push(value);
        }
    }
    let sum = simplify(store, &adds, &removes)?;
    if let Some(value) = resolved(&sum) {
        if value.kind == 0 {
            return Ok(None);
        }
        return Ok(Some(OutEntry {
            path: path.to_vec(),
            kind: value.kind,
            target: value
                .target
                .ok_or_else(|| Error::new("missing conflict target"))?,
        }));
    }
    if all_files(&sum)
        && sum.adds.len() == 2
        && sum.removes.len() == 1
        && sum.adds[0].kind != 0
        && sum.adds[1].kind != 0
        && sum.removes[0].kind != 0
        && !merge_binary(repo, path)
    {
        let base = sum.removes[0].target.unwrap();
        let ours = sum.adds[0].target.unwrap();
        let theirs = sum.adds[1].target.unwrap();
        if let Some(merged) = merge_blobs(store, Some(txn.writer()), base, ours, theirs, adjacent)?
        {
            if !merged.conflicted {
                let blob = add_blob(txn, &merged.data);
                let mode = merge_mode(&sum);
                if mode >= 0 {
                    return Ok(Some(OutEntry {
                        path: path.to_vec(),
                        kind: if mode == 1 {
                            tree::KIND_EXECUTABLE
                        } else {
                            tree::KIND_FILE
                        },
                        target: blob,
                    }));
                }
            }
        }
    }
    let body = conflict::encode(&sum);
    if all_files(&sum)
        && let Some(blob) = resolution_lookup(repo, &body)
    {
        *rerere += 1;
        return Ok(Some(OutEntry {
            path: path.to_vec(),
            kind: tree::KIND_FILE,
            target: blob,
        }));
    }
    let id = txn.add_object(TYPE_CONFLICT, body);
    Ok(Some(OutEntry {
        path: path.to_vec(),
        kind: KIND_CONFLICT,
        target: id,
    }))
}

fn treemerge(
    repo: &Path,
    txn: &mut Txn,
    store: &mut Store,
    terms: &[TreeTerm],
    maps: &[RenameMap],
    adjacent: bool,
) -> Result<MergeOutcome> {
    let mut orig = Vec::new();
    for (term_index, term) in terms.iter().enumerate() {
        if !term.present {
            continue;
        }
        for entry in flatten_sorted(store, Some(txn.writer()), Some(term.id))? {
            orig.push(OrigEntry {
                term: term_index,
                path: entry.path,
                kind: entry.kind,
                target: entry.target,
            });
        }
    }
    let canonical_targets = |path: &[u8]| -> Vec<(usize, Vec<u8>)> {
        let mut output: Vec<(usize, Vec<u8>)> = Vec::new();
        for (index, map) in maps.iter().enumerate() {
            if let Some(destination) = rename_lookup(map, path) {
                if !output.iter().any(|(_, value)| value == &destination) {
                    output.push((index, destination));
                }
            }
        }
        output
    };
    let mut canon = Vec::new();
    let mut special = Vec::new();
    let mut consumed: Vec<Vec<u8>> = Vec::new();
    for entry in &orig {
        let targets = canonical_targets(&entry.path);
        if targets.len() > 1 && !special.contains(&entry.path) {
            special.push(entry.path.clone());
        }
        let canonical = if targets.len() == 1 {
            targets[0].1.clone()
        } else {
            entry.path.clone()
        };
        canon.push(OrigEntry {
            term: entry.term,
            path: canonical,
            kind: entry.kind,
            target: entry.target,
        });
    }
    let find_orig = |term: usize, path: &[u8]| -> Option<&OrigEntry> {
        orig.iter()
            .find(|entry| entry.term == term && entry.path == path)
    };
    let find_canon = |term: usize, path: &[u8]| -> Option<&OrigEntry> {
        canon
            .iter()
            .find(|entry| entry.term == term && entry.path == path)
    };
    let mut output = Vec::new();
    let mut rerere = 0;
    for path in &special {
        let targets = canonical_targets(path);
        let mut entries = Vec::new();
        for (term, destination) in &targets {
            let mut value = EntryTerm {
                positive: true,
                present: false,
                kind: 0,
                target: None,
            };
            if let Some(found) = find_orig(*term, destination) {
                value.present = true;
                value.kind = found.kind;
                value.target = Some(found.target);
            }
            entries.push(value);
            if !consumed.contains(destination) {
                consumed.push(destination.clone());
            }
        }
        if let Some(base_term) = terms.iter().position(|term| !term.positive) {
            let mut value = EntryTerm {
                positive: false,
                present: false,
                kind: 0,
                target: None,
            };
            if let Some(found) = find_orig(base_term, path) {
                value.present = true;
                value.kind = found.kind;
                value.target = Some(found.target);
            }
            entries.push(value);
        }
        if let Some(merged) = merge_entry(repo, txn, store, path, &entries, adjacent, &mut rerere)?
        {
            output.push(merged);
        }
        if !consumed.contains(path) {
            consumed.push(path.clone());
        }
    }
    let mut paths: Vec<Vec<u8>> = Vec::new();
    for entry in &canon {
        if !paths.contains(&entry.path) {
            paths.push(entry.path.clone());
        }
    }
    paths.sort();
    for path in paths {
        if consumed.contains(&path) {
            continue;
        }
        let mut any_exact = false;
        let mut any_children = false;
        for term in 0..terms.len() {
            if find_canon(term, &path).is_some() {
                any_exact = true;
            }
            if canon
                .iter()
                .any(|entry| entry.term == term && has_prefix(&entry.path, &path))
            {
                any_children = true;
            }
        }
        if !any_exact {
            continue;
        }
        let mixed = any_children;
        let mut entries = Vec::new();
        for term in 0..terms.len() {
            let mut value = EntryTerm {
                positive: terms[term].positive,
                present: false,
                kind: 0,
                target: None,
            };
            if let Some(exact) = find_canon(term, &path) {
                value.present = true;
                value.kind = exact.kind;
                value.target = Some(exact.target);
            } else if mixed
                && canon
                    .iter()
                    .any(|entry| entry.term == term && has_prefix(&entry.path, &path))
            {
                value.present = true;
                value.kind = KIND_SUBTREE;
                value.target = Some(build_subtree(txn, &canon, term, &path)?);
            }
            entries.push(value);
        }
        if let Some(merged) = merge_entry(repo, txn, store, &path, &entries, adjacent, &mut rerere)?
        {
            output.push(merged);
        }
        if mixed {
            for entry in &canon {
                if has_prefix(&entry.path, &path) && !consumed.contains(&entry.path) {
                    consumed.push(entry.path.clone());
                }
            }
        }
    }
    Ok(MergeOutcome {
        tree: build_from_entries(txn, &mut output)?,
        rerere,
    })
}

pub fn merge_bases(store: &mut Store, a: Id, b: Id) -> Result<Vec<Id>> {
    let left = graph::collect_commits(store, &[a])?;
    let right = graph::collect_commits(store, &[b])?;
    let common: Vec<Id> = left.into_iter().filter(|id| right.contains(id)).collect();
    let mut output = Vec::new();
    for candidate in &common {
        let mut dominated = false;
        for other in &common {
            if candidate == other {
                continue;
            }
            let descendants = graph::collect_commits(store, &[*candidate])?;
            if descendants.contains(other) {
                dominated = true;
                break;
            }
        }
        if !dominated {
            output.push(*candidate);
        }
    }
    Ok(output)
}

pub fn is_ancestor(store: &mut Store, ancestor: Id, descendant: Id) -> Result<bool> {
    if ancestor == descendant {
        return Ok(true);
    }
    Ok(graph::collect_commits(store, &[descendant])?.contains(&ancestor))
}

fn base_tree(
    repo: &Path,
    txn: &mut Txn,
    store: &mut Store,
    bases: &[Id],
    adjacent: bool,
) -> Result<Option<Id>> {
    if bases.is_empty() {
        return Ok(None);
    }
    if bases.len() == 1 {
        return tree_of(store, bases[0]);
    }
    let t0 = tree_of(store, bases[0])?;
    let t1 = tree_of(store, bases[1])?;
    let lcas = merge_bases(store, bases[0], bases[1])?;
    let mut terms = vec![
        TreeTerm {
            positive: true,
            present: t0.is_some(),
            id: t0.unwrap_or_default(),
        },
        TreeTerm {
            positive: true,
            present: t1.is_some(),
            id: t1.unwrap_or_default(),
        },
    ];
    if let Some(first) = lcas.first() {
        let tree = tree_of(store, *first)?;
        terms.push(TreeTerm {
            positive: false,
            present: tree.is_some(),
            id: tree.unwrap_or_default(),
        });
    } else {
        terms.push(TreeTerm {
            positive: false,
            present: false,
            id: Id::default(),
        });
    }
    Ok(Some(
        treemerge(
            repo,
            txn,
            store,
            &terms,
            &[RenameMap::new(), RenameMap::new(), RenameMap::new()],
            adjacent,
        )?
        .tree,
    ))
}

pub fn merge_many(
    repo: &Path,
    txn: &mut Txn,
    store: &mut Store,
    heads: &[Id],
    adjacent: bool,
) -> Result<MergeOutcome> {
    if heads.len() == 1 {
        let tree = tree_of(store, heads[0])?;
        return treemerge(
            repo,
            txn,
            store,
            &[TreeTerm {
                positive: true,
                present: tree.is_some(),
                id: tree.unwrap_or_default(),
            }],
            &[RenameMap::new()],
            adjacent,
        );
    }
    let mut terms = Vec::new();
    let mut maps = Vec::new();
    let map_base = if heads.len() > 1 {
        merge_bases(store, heads[0], heads[1])?.first().copied()
    } else {
        None
    };
    for head in heads {
        let tree = tree_of(store, *head)?;
        terms.push(TreeTerm {
            positive: true,
            present: tree.is_some(),
            id: tree.unwrap_or_default(),
        });
        maps.push(match map_base {
            Some(base) => map_from(store, base, *head)?,
            None => RenameMap::new(),
        });
    }
    for head in &heads[1..] {
        let bases = merge_bases(store, heads[0], *head)?;
        let tree = base_tree(repo, txn, store, &bases, adjacent)?;
        terms.push(TreeTerm {
            positive: false,
            present: tree.is_some(),
            id: tree.unwrap_or_default(),
        });
        maps.push(RenameMap::new());
    }
    treemerge(repo, txn, store, &terms, &maps, adjacent)
}

pub fn rewrite_tree(
    repo: &Path,
    txn: &mut Txn,
    store: &mut Store,
    old_commit: Id,
    commit_tree: Id,
    old_parents: &[Id],
    new_parents: &[Id],
    new_parent_trees: &[Id],
    adjacent: bool,
) -> Result<MergeOutcome> {
    let mut terms = vec![TreeTerm {
        positive: true,
        present: true,
        id: commit_tree,
    }];
    let mut maps = Vec::new();
    maps.push(if let Some(parent) = old_parents.first() {
        map_from(store, *parent, old_commit)?
    } else {
        RenameMap::new()
    });
    if old_parents.is_empty() {
        for tree in new_parent_trees {
            terms.push(TreeTerm {
                positive: true,
                present: true,
                id: *tree,
            });
            maps.push(RenameMap::new());
        }
        terms.push(TreeTerm {
            positive: false,
            present: false,
            id: Id::default(),
        });
        maps.push(RenameMap::new());
    } else {
        for (index, parent) in old_parents.iter().enumerate() {
            let old_tree = tree_of(store, *parent)?;
            let new_tree = new_parent_trees.get(index).copied().unwrap_or_default();
            terms.push(TreeTerm {
                positive: true,
                present: true,
                id: new_tree,
            });
            terms.push(TreeTerm {
                positive: false,
                present: old_tree.is_some(),
                id: old_tree.unwrap_or_default(),
            });
            maps.push(if let Some(new_parent) = new_parents.get(index) {
                map_from(store, *parent, *new_parent)?
            } else {
                RenameMap::new()
            });
            maps.push(RenameMap::new());
        }
    }
    treemerge(repo, txn, store, &terms, &maps, adjacent)
}

pub fn make_commit(
    txn: &mut Txn,
    store: &mut Store,
    repo: &Path,
    parents: &[Id],
    root: Id,
    change: [u8; 16],
    author: Sig,
    message: &str,
    renames_state: u8,
    extra: &[(Vec<u8>, Vec<u8>)],
) -> Result<Id> {
    let mut renames = Vec::new();
    if renames_state == commit::RENAMES_RECORDED {
        for (index, parent) in parents.iter().enumerate() {
            let parent_tree = tree_of(store, *parent)?;
            let detected = detect(
                store,
                Some(txn.writer()),
                parent_tree,
                Some(root),
                0,
                index as u64,
            )?;
            renames.extend(detected);
        }
    }
    let commit = Commit {
        version: 1,
        parents: parents.to_vec(),
        root_tree: root,
        change_id: change,
        author,
        committer: identity::signature(repo),
        message: message.as_bytes().to_vec(),
        renames_state,
        renames,
        extra: extra.to_vec(),
    };
    Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))
}

fn adjacent_config(root: &Path) -> bool {
    core::repo_config_value(root, "merge.adjacent").as_deref() == Some("merge")
}

pub fn conflict_kind_label(conflict: &Conflict) -> &'static str {
    if conflict
        .adds
        .iter()
        .chain(conflict.removes.iter())
        .any(|value| value.kind == KIND_SUBTREE)
    {
        return "tree";
    }
    if conflict
        .adds
        .iter()
        .chain(conflict.removes.iter())
        .any(|value| value.kind == 0)
    {
        return "delete/modify";
    }
    "text"
}

pub fn conflict_ranges(
    store: &mut Store,
    conflict: &Conflict,
    adjacent: bool,
) -> Result<Option<EditResult>> {
    if conflict.adds.len() != 2 || conflict.removes.len() != 1 {
        return Ok(None);
    }
    let ours = &conflict.adds[0];
    let theirs = &conflict.adds[1];
    let base = &conflict.removes[0];
    if ours.kind == 0 || theirs.kind == 0 || base.kind == 0 {
        return Ok(None);
    }
    if ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE || base.kind == KIND_SUBTREE {
        return Ok(None);
    }
    merge_blobs(
        store,
        None,
        base.target.unwrap(),
        ours.target.unwrap(),
        theirs.target.unwrap(),
        adjacent,
    )
}

pub fn edit_tree(
    txn: &mut Txn,
    store: &mut Store,
    tree_id: Id,
    path: &[u8],
    present: bool,
    kind: u8,
    target: Id,
) -> Result<Option<Id>> {
    edit_tree_into(txn, store, tree_id, path, present, kind, target, 0)
}

fn edit_tree_into(
    txn: &mut Txn,
    store: &mut Store,
    tree_id: Id,
    path: &[u8],
    present: bool,
    kind: u8,
    target: Id,
    depth: usize,
) -> Result<Option<Id>> {
    if depth > crate::object::MAX_TREE_DEPTH {
        return Ok(None);
    }
    let Some(body) = read_any(store, Some(txn.writer()), TYPE_TREE, tree_id)? else {
        return Ok(None);
    };
    let tree = tree::decode(&body)?;
    let cut = path
        .iter()
        .position(|byte| *byte == b'/')
        .unwrap_or(path.len());
    let name = &path[..cut];
    let mut entries = Vec::new();
    let mut found = false;
    for entry in tree.entries {
        if entry.name != name {
            entries.push(entry);
            continue;
        }
        found = true;
        if cut == path.len() {
            if present {
                entries.push(TreeEntry {
                    name: entry.name,
                    kind,
                    target,
                });
            }
        } else if entry.kind == KIND_SUBTREE {
            if let Some(child) = edit_tree_into(
                txn,
                store,
                entry.target,
                &path[cut + 1..],
                present,
                kind,
                target,
                depth + 1,
            )? {
                if !tree_empty(store, Some(txn.writer()), child)? {
                    entries.push(TreeEntry {
                        name: entry.name,
                        kind: KIND_SUBTREE,
                        target: child,
                    });
                }
            } else {
                entries.push(entry);
            }
        } else {
            entries.push(entry);
        }
    }
    if !found && cut == path.len() && present {
        entries.push(TreeEntry {
            name: name.to_vec(),
            kind,
            target,
        });
    }
    Ok(Some(add_tree(txn, &entries)?))
}

pub fn snapshot_run(root: &Path) -> Result<()> {
    snapshot::run(root)?;
    Ok(())
}

pub fn add_blob_data(txn: &mut Txn, data: &[u8]) -> Id {
    add_blob(txn, data)
}

pub fn object_id_of(kind: u8, body: &[u8]) -> Id {
    object_id(kind, body)
}

pub fn rename_from_map(map: &RenameMap, path: &[u8]) -> Option<Vec<u8>> {
    rename_lookup(map, path)
}

pub fn adjacent(root: &Path) -> bool {
    adjacent_config(root)
}

pub fn resolution_store(repo: &Path, body: &[u8], blob: Id) {
    resolution_record(repo, body, blob);
}

pub fn maps_empty() -> RenameMap {
    RenameMap::new()
}

pub fn apply_rename(map: &mut RenameMap, from: &[u8], to: &[u8]) {
    rename_apply(map, from, to);
}

pub fn first_parent_of(store: &mut Store, id: Id) -> Result<Option<Id>> {
    first_parent(store, id)
}

pub fn tree_of_commit(store: &mut Store, id: Id) -> Result<Option<Id>> {
    tree_of(store, id)
}

pub fn merge_binary_path(repo: &Path, path: &[u8]) -> bool {
    merge_binary(repo, path)
}