navid/veins / bc0b02d957b7af60232a5b91bf4caefba5dfba19c68970ec43e5c39830934f19 / veinsrs/src/cli/diff.rs

diff.rs

← veinsrs/src/cli · 11174 bytes · raw · download

use crate::object::id::Id;
use crate::object::tree::{KIND_CONFLICT, KIND_MISSING};
use crate::store::graph;
use crate::store::reader::Store;

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

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

fn build_ops_lcs(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {
    let n = a.len();
    let m = b.len();
    let columns = m + 1;
    let mut dp = vec![0u32; (n + 1) * columns];
    for i in 1..=n {
        for j in 1..=m {
            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 ops = Vec::with_capacity(n + m);
    let mut i = n;
    let mut j = m;
    while i > 0 || j > 0 {
        if i > 0 && j > 0 && a[i - 1] == b[j - 1] {
            ops.push(DiffOp {
                tag: b' ',
                ai: i - 1,
                bi: j - 1,
            });
            i -= 1;
            j -= 1;
        } else if j > 0 && (i == 0 || dp[i * columns + (j - 1)] >= dp[(i - 1) * columns + j]) {
            ops.push(DiffOp {
                tag: b'+',
                ai: 0,
                bi: j - 1,
            });
            j -= 1;
        } else {
            ops.push(DiffOp {
                tag: b'-',
                ai: i - 1,
                bi: 0,
            });
            i -= 1;
        }
    }
    ops.reverse();
    ops
}

fn build_ops_myers(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {
    let n = a.len() as isize;
    let m = b.len() as isize;
    let max_d = n + m;
    let offset = max_d;
    let length = (2 * max_d + 1) as usize;
    let mut v = vec![0isize; length];
    let mut trace: Vec<Vec<isize>> = Vec::new();
    const TRACE_CAP: usize = 64 * 1024 * 1024;
    let mut found = -1isize;
    for d in 0..=max_d {
        if (trace.len() + 1) * length * std::mem::size_of::<isize>() > TRACE_CAP {
            return Vec::new();
        }
        trace.push(v.clone());
        let mut k = -d;
        while k <= d {
            let mut x = if k == -d
                || (k != d && v[(offset + k - 1) as usize] < v[(offset + k + 1) as usize])
            {
                v[(offset + k + 1) as usize]
            } else {
                v[(offset + k - 1) as usize] + 1
            };
            let mut y = x - k;
            while x < n && y < m && a[x as usize] == b[y as usize] {
                x += 1;
                y += 1;
            }
            v[(offset + k) as usize] = x;
            if x >= n && y >= m {
                found = d;
                break;
            }
            k += 2;
        }
        if found >= 0 {
            break;
        }
    }
    if found < 0 {
        return Vec::new();
    }
    let mut ops = Vec::new();
    let mut x = n;
    let mut y = m;
    let mut d = found;
    while d >= 0 {
        let previous = &trace[d as usize];
        let k = x - y;
        let previous_k = if k == -d
            || (k != d && previous[(offset + k - 1) as usize] < previous[(offset + k + 1) as usize])
        {
            k + 1
        } else {
            k - 1
        };
        let previous_x = previous[(offset + previous_k) as usize];
        let previous_y = previous_x - previous_k;
        while x > previous_x && y > previous_y {
            ops.push(DiffOp {
                tag: b' ',
                ai: (x - 1) as usize,
                bi: (y - 1) as usize,
            });
            x -= 1;
            y -= 1;
        }
        if d > 0 {
            if x == previous_x {
                ops.push(DiffOp {
                    tag: b'+',
                    ai: 0,
                    bi: (y - 1) as usize,
                });
                y -= 1;
            } else {
                ops.push(DiffOp {
                    tag: b'-',
                    ai: (x - 1) as usize,
                    bi: 0,
                });
                x -= 1;
            }
        }
        d -= 1;
    }
    ops.reverse();
    ops
}

fn build_ops_fallback(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {
    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 ops = Vec::with_capacity(a.len() + b.len());
    for index in 0..prefix {
        ops.push(DiffOp {
            tag: b' ',
            ai: index,
            bi: index,
        });
    }
    for index in prefix..a.len() - suffix {
        ops.push(DiffOp {
            tag: b'-',
            ai: index,
            bi: 0,
        });
    }
    for index in prefix..b.len() - suffix {
        ops.push(DiffOp {
            tag: b'+',
            ai: 0,
            bi: index,
        });
    }
    for index in 0..suffix {
        ops.push(DiffOp {
            tag: b' ',
            ai: a.len() - suffix + index,
            bi: b.len() - suffix + index,
        });
    }
    ops
}

fn build_ops(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {
    if a.is_empty() && b.is_empty() {
        return Vec::new();
    }
    if !a.is_empty() && !b.is_empty() && (a.len() <= 2048 && b.len() <= 2048) {
        return build_ops_lcs(a, b);
    }
    if !a.is_empty() && !b.is_empty() && a.len() * b.len() <= 4_000_000 {
        return build_ops_lcs(a, b);
    }
    let myers = build_ops_myers(a, b);
    if !myers.is_empty() {
        return myers;
    }
    build_ops_fallback(a, b)
}

pub fn render_unified_for(a: &[&[u8]], b: &[&[u8]], output: &mut String) {
    render_unified(a, b, output);
}

fn render_unified(a: &[&[u8]], b: &[&[u8]], output: &mut String) {
    let ops = build_ops(a, b);
    let changes: Vec<usize> = ops
        .iter()
        .enumerate()
        .filter(|(_, op)| op.tag != b' ')
        .map(|(index, _)| index)
        .collect();
    const CONTEXT: usize = 3;
    let mut position = 0;
    let mut old_seen = 0;
    let mut new_seen = 0;
    let mut change_index = 0;
    while change_index < changes.len() {
        let first = changes[change_index];
        let start = first.saturating_sub(CONTEXT);
        let mut last = first;
        change_index += 1;
        while change_index < changes.len() && changes[change_index] <= last + CONTEXT * 2 {
            last = changes[change_index];
            change_index += 1;
        }
        let end = (last + CONTEXT + 1).min(ops.len());
        while position < start {
            match ops[position].tag {
                b' ' => {
                    old_seen += 1;
                    new_seen += 1;
                }
                b'-' => old_seen += 1,
                _ => new_seen += 1,
            }
            position += 1;
        }
        let mut old_count = 0;
        let mut new_count = 0;
        for op in &ops[start..end] {
            match op.tag {
                b' ' => {
                    old_count += 1;
                    new_count += 1;
                }
                b'-' => old_count += 1,
                _ => new_count += 1,
            }
        }
        let old_start = old_seen + usize::from(old_count > 0);
        let new_start = new_seen + usize::from(new_count > 0);
        output.push_str(&format!(
            "@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"
        ));
        while position < end {
            let op = ops[position];
            match op.tag {
                b' ' => {
                    output.push(' ');
                    output.push_str(&String::from_utf8_lossy(a[op.ai]));
                    output.push('\n');
                    old_seen += 1;
                    new_seen += 1;
                }
                b'-' => {
                    output.push_str(&super::output::red("-"));
                    output.push_str(&super::output::red(&String::from_utf8_lossy(a[op.ai])));
                    output.push('\n');
                    old_seen += 1;
                }
                _ => {
                    output.push_str(&super::output::green("+"));
                    output.push_str(&super::output::green(&String::from_utf8_lossy(b[op.bi])));
                    output.push('\n');
                    new_seen += 1;
                }
            }
            position += 1;
        }
    }
}

fn contains_nul(data: &[u8]) -> bool {
    data.iter().take(8192).any(|byte| *byte == 0)
}

pub fn render_diff(
    store: &mut Store,
    old_tree: Option<Id>,
    new_tree: Option<Id>,
    announce: bool,
    path_filter: &[u8],
) -> crate::error::Result<usize> {
    let mut changes = graph::compare_trees(store, old_tree, new_tree)?;
    if !path_filter.is_empty() {
        changes.retain(|change| {
            change.path == path_filter
                || (change.path.len() > path_filter.len()
                    && change.path.starts_with(path_filter)
                    && change.path[path_filter.len()] == b'/')
        });
    }
    let mut output = String::new();
    for change in &changes {
        let path = String::from_utf8_lossy(&change.path);
        if change.new_kind == KIND_CONFLICT {
            output.push_str(&format!("Conflict: {path}\n"));
            continue;
        }
        let old_data = match (change.old_kind, change.old_id) {
            (KIND_MISSING, _) | (_, None) => Vec::new(),
            (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),
        };
        let new_data = match (change.new_kind, change.new_id) {
            (KIND_MISSING, _) | (_, None) => Vec::new(),
            (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),
        };
        if contains_nul(&old_data) || contains_nul(&new_data) {
            output.push_str(&format!("Binary files a/{path} and b/{path} differ\n"));
            continue;
        }
        output.push_str(&super::output::red("--- "));
        if change.old_kind == KIND_MISSING {
            output.push_str(&super::output::red("/dev/null"));
        } else {
            output.push_str(&super::output::red(&format!("a/{path}")));
        }
        output.push('\n');
        output.push_str(&super::output::green("+++ "));
        if change.new_kind == KIND_MISSING {
            output.push_str(&super::output::green("/dev/null"));
        } else {
            output.push_str(&super::output::green(&format!("b/{path}")));
        }
        output.push('\n');
        render_unified(
            &split_lines(&old_data),
            &split_lines(&new_data),
            &mut output,
        );
    }
    if announce && changes.is_empty() {
        super::output::info_prefix();
        output.push_str("no diff to show\n");
    }
    print!("{output}");
    Ok(changes.len())
}