vtcode-core 0.182.3

Core library for VT Code - a Rust-based terminal coding agent
Documentation
pub(crate) struct PatchContextMatcher<'a> {
    lines: &'a [String],
    /// Normalised form of every file line, computed once at construction so
    /// repeated `seek` calls (and thus repeated patch hunks) don't re-normalise
    /// the whole file on every lookup.
    norm_lines: Vec<String>,
}

impl<'a> PatchContextMatcher<'a> {
    pub(crate) fn new(lines: &'a [String]) -> Self {
        let norm_lines = lines.iter().map(|l| normalise_text(l)).collect();
        Self { lines, norm_lines }
    }

    pub(crate) fn seek(&self, pattern: &[String], start: usize, eof: bool) -> Option<usize> {
        if pattern.is_empty() {
            return Some(start);
        }

        if pattern.len() > self.lines.len() {
            return None;
        }

        let search_start = if eof && self.lines.len() >= pattern.len() {
            self.lines.len().saturating_sub(pattern.len())
        } else {
            start
        };

        let max_start = self.lines.len().saturating_sub(pattern.len());

        for idx in search_start..=max_start {
            if self.lines[idx..idx + pattern.len()] == *pattern {
                return Some(idx);
            }
        }

        for idx in search_start..=max_start {
            let mut ok = true;
            for (offset, pat) in pattern.iter().enumerate() {
                if self.lines[idx + offset].trim_end() != pat.trim_end() {
                    ok = false;
                    break;
                }
            }
            if ok {
                return Some(idx);
            }
        }

        for idx in search_start..=max_start {
            let mut ok = true;
            for (offset, pat) in pattern.iter().enumerate() {
                if self.lines[idx + offset].trim() != pat.trim() {
                    ok = false;
                    break;
                }
            }
            if ok {
                return Some(idx);
            }
        }

        // Compare against the pre-computed normalised file lines (built once in
        // `new`), avoiding re-normalising the whole file on every `seek` call.
        let norm_pattern: Vec<String> = pattern.iter().map(|p| normalise_text(p)).collect();
        let norm_lines = &self.norm_lines;
        for idx in search_start..=max_start {
            let mut ok = true;
            for (offset, norm_pat) in norm_pattern.iter().enumerate() {
                if norm_lines[idx + offset] != *norm_pat {
                    ok = false;
                    break;
                }
            }
            if ok {
                return Some(idx);
            }
        }

        None
    }
}

pub(crate) fn seek_segment(
    matcher: &PatchContextMatcher,
    old_segment: &mut Vec<String>,
    new_segment: &mut Vec<String>,
    start: usize,
    eof: bool,
) -> Option<usize> {
    let mut found = matcher.seek(old_segment, start, eof);

    if found.is_none() && old_segment.last().is_some_and(|line| line.is_empty()) {
        old_segment.pop();
        if new_segment.last().is_some_and(|line| line.is_empty()) {
            new_segment.pop();
        }
        found = matcher.seek(old_segment, start, eof);
    }

    found
}

/// Diagnose only; never use a redacted match to select a mutation target.
pub(crate) fn redacted_context_matches(lines: &[String], pattern: &[String], start: usize, eof: bool) -> bool {
    const MARKER: &str = "[REDACTED_SECRET]";
    if pattern.is_empty() || pattern.len() > lines.len() || !pattern.iter().any(|line| line.contains(MARKER)) {
        return false;
    }
    let search_start = if eof { lines.len() - pattern.len() } else { start };
    lines.windows(pattern.len()).skip(search_start).any(|window| {
        let mut changed_marker = false;
        for (original, expected) in window.iter().zip(pattern) {
            if original == expected {
                continue;
            }
            if !expected.contains(MARKER) {
                if normalise_text(original) != normalise_text(expected) {
                    return false;
                }
                continue;
            }
            let redacted = vtcode_commons::sanitizer::redact_secrets(original.clone());
            if normalise_text(&redacted) != normalise_text(expected) {
                return false;
            }
            changed_marker |= original != &redacted && expected.contains(MARKER);
        }
        changed_marker
    })
}

pub(crate) fn normalise_text(input: &str) -> String {
    let trimmed = input.trim();
    let mut result = String::with_capacity(trimmed.len());
    for c in trimmed.chars() {
        let normalised = match c {
            '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}' | '\u{2212}' => '-',
            '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' => '\'',
            '\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' => '"',
            '\u{00A0}' | '\u{2002}' | '\u{2003}' | '\u{2004}' | '\u{2005}' | '\u{2006}' | '\u{2007}' | '\u{2008}'
            | '\u{2009}' | '\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' => ' ',
            other => other,
        };
        result.push(normalised);
    }
    result
}

#[cfg(test)]
mod tests {
    use super::{PatchContextMatcher, redacted_context_matches};

    #[test]
    fn redacted_context_respects_start_and_end_of_file() {
        let lines = vec!["password=fixture-private-value".to_string(), "other".to_string()];
        let pattern = vec!["password=[REDACTED_SECRET]".to_string()];
        assert!(redacted_context_matches(&lines, &pattern, 0, false));
        assert!(!redacted_context_matches(&lines, &pattern, 1, false));
        assert!(!redacted_context_matches(&lines, &pattern, 0, true));
        assert!(!redacted_context_matches(&lines, &[], 0, false));
        let indented = vec!["    password=fixture-private-value".to_string(), "   after".to_string()];
        let trimmed = vec!["password=[REDACTED_SECRET]".to_string(), "after".to_string()];
        assert!(redacted_context_matches(&indented, &trimmed, 0, false));
        let incorrect = vec!["password = [REDACTED_SECRET]".to_string(), "after".to_string()];
        assert!(!redacted_context_matches(&indented, &incorrect, 0, false));
    }

    #[test]
    fn matching_preserves_internal_whitespace_and_full_lines() {
        let lines = vec!["X   Y".to_string()];
        let matcher = PatchContextMatcher::new(&lines);
        assert_eq!(matcher.seek(&["X   Y".to_string()], 0, false), Some(0));
        assert_eq!(matcher.seek(&["X  Y".to_string()], 0, false), None);
        assert_eq!(matcher.seek(&["X".to_string()], 0, false), None);
    }

    #[test]
    fn matching_supports_boundary_whitespace_and_unicode_punctuation() {
        let lines = vec!["  A \u{2014} B  ".to_string()];
        let matcher = PatchContextMatcher::new(&lines);
        assert_eq!(matcher.seek(&["A - B".to_string()], 0, false), Some(0));
        assert_eq!(matcher.seek(&["A  - B".to_string()], 0, false), None);
    }
}