helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! The line diff and its display (`diff/diff.go` `diffStrings`, `printDiffRecords`).

use similar::{Algorithm, ChangeTag, TextDiff};

/// One line of a diff.
pub(super) struct Line<'a> {
    /// Whether the line is only before, only after, or on both sides.
    pub tag: ChangeTag,
    /// The line without its newline.
    pub text: &'a str,
}

/// Splits like Go's `strings.Split(value, "\n")` (so the empty string is one empty line),
/// optionally dropping one trailing `\r` per line.
fn split(value: &str, strip_trailing_cr: bool) -> Vec<&str> {
    value
        .split('\n')
        .map(|line| {
            if strip_trailing_cr {
                line.strip_suffix('\r').unwrap_or(line)
            } else {
                line
            }
        })
        .collect()
}

/// The line diff of `before` against `after`, every line in order.
pub(super) fn diff_lines<'a>(
    before: &'a str,
    after: &'a str,
    strip_trailing_cr: bool,
) -> Vec<Line<'a>> {
    let before = split(before, strip_trailing_cr);
    let after = split(after, strip_trailing_cr);

    TextDiff::configure()
        .algorithm(Algorithm::Myers)
        .diff_slices(&before, &after)
        .iter_all_changes()
        .map(|change| Line {
            tag: change.tag(),
            text: change.value(),
        })
        .collect()
}

/// Whether any line is an addition or a removal (`actualChanges`).
pub(super) fn has_changes(lines: &[Line<'_>]) -> bool {
    lines.iter().any(|line| line.tag != ChangeTag::Equal)
}

/// Prints the diff like helm-diff: `+ `, `- ` and two spaces before each line, an empty common
/// line as an empty line, and with a `context` every run of lines further than that from a
/// change as one `...` line.
pub(super) fn render(lines: &[Line<'_>], context: Option<usize>) -> String {
    let distances = context.map(|_| distances(lines));
    let mut out = String::new();
    let mut omitting = false;

    for (index, line) in lines.iter().enumerate() {
        if let (Some(context), Some(distances)) = (context, &distances)
            && distances[index] > context
        {
            if !omitting {
                out.push_str("...\n");
                omitting = true;
            }

            continue;
        }
        omitting = false;

        match line.tag {
            ChangeTag::Insert => out.push_str("+ "),
            ChangeTag::Delete => out.push_str("- "),
            ChangeTag::Equal if !line.text.is_empty() => out.push_str("  "),
            ChangeTag::Equal => {}
        }
        out.push_str(line.text);
        out.push('\n');
    }

    out
}

/// The distance of every line to the closest change (`calculateDistances`); `usize::MAX` when
/// there is none.
fn distances(lines: &[Line<'_>]) -> Vec<usize> {
    let mut distances = vec![usize::MAX; lines.len()];
    let mut last = None;

    for (index, line) in lines.iter().enumerate() {
        if line.tag != ChangeTag::Equal {
            last = Some(index);
        }
        if let Some(last) = last {
            distances[index] = index - last;
        }
    }
    last = None;

    for (index, line) in lines.iter().enumerate().rev() {
        if line.tag != ChangeTag::Equal {
            last = Some(index);
        }
        if let Some(last) = last {
            distances[index] = distances[index].min(last - index);
        }
    }

    distances
}