oyo-core 0.1.10

Core diff engine for oyo - step-through diff viewer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Diff computation engine

use crate::change::{Change, ChangeKind, ChangeSpan};
use similar::{ChangeTag, TextDiff};
use std::path::Path;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum DiffError {
    #[error("Failed to read file: {0}")]
    FileRead(#[from] std::io::Error),
    #[error("Diff computation failed: {0}")]
    ComputeFailed(String),
}

/// A hunk is a group of related changes that are close together
#[derive(Debug, Clone)]
pub struct Hunk {
    /// Unique ID for this hunk
    pub id: usize,
    /// IDs of changes in this hunk (in order)
    pub change_ids: Vec<usize>,
    /// Starting line number in old file
    pub old_start: Option<usize>,
    /// Starting line number in new file
    pub new_start: Option<usize>,
    /// Number of insertions in this hunk
    pub insertions: usize,
    /// Number of deletions in this hunk
    pub deletions: usize,
}

impl Hunk {
    /// Get the number of changes in this hunk
    pub fn len(&self) -> usize {
        self.change_ids.len()
    }

    /// Check if hunk is empty
    pub fn is_empty(&self) -> bool {
        self.change_ids.is_empty()
    }
}

/// Result of a diff operation
#[derive(Debug, Clone)]
pub struct DiffResult {
    /// All changes in order
    pub changes: Vec<Change>,
    /// Only the actual changes (excluding context)
    pub significant_changes: Vec<usize>,
    /// Hunks (groups of related changes)
    pub hunks: Vec<Hunk>,
    /// Total number of insertions
    pub insertions: usize,
    /// Total number of deletions
    pub deletions: usize,
}

impl DiffResult {
    /// Get only the significant (non-context) changes
    pub fn get_significant_changes(&self) -> Vec<&Change> {
        self.significant_changes
            .iter()
            .filter_map(|&id| self.changes.iter().find(|c| c.id == id))
            .collect()
    }

    /// Get a hunk by ID
    pub fn get_hunk(&self, hunk_id: usize) -> Option<&Hunk> {
        self.hunks.iter().find(|h| h.id == hunk_id)
    }

    /// Find which hunk a change belongs to
    pub fn hunk_for_change(&self, change_id: usize) -> Option<&Hunk> {
        self.hunks
            .iter()
            .find(|h| h.change_ids.contains(&change_id))
    }
}

/// A diff for a single file
#[derive(Debug, Clone)]
pub struct FileDiff {
    pub old_path: Option<String>,
    pub new_path: Option<String>,
    pub result: DiffResult,
}

/// The main diff engine
pub struct DiffEngine {
    /// Number of context lines to include
    context_lines: usize,
    /// Whether to do word-level diffing within changed lines
    word_level: bool,
}

impl Default for DiffEngine {
    fn default() -> Self {
        Self {
            context_lines: 3,
            word_level: true,
        }
    }
}

impl DiffEngine {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_context(mut self, lines: usize) -> Self {
        self.context_lines = lines;
        self
    }

    pub fn with_word_level(mut self, enabled: bool) -> Self {
        self.word_level = enabled;
        self
    }

    /// Compute diff between two strings
    pub fn diff_strings(&self, old: &str, new: &str) -> DiffResult {
        let text_diff = TextDiff::from_lines(old, new);
        let mut changes = Vec::new();
        let mut significant_changes = Vec::new();
        let mut insertions = 0;
        let mut deletions = 0;
        let mut change_id = 0;

        let mut old_line_num = 1usize;
        let mut new_line_num = 1usize;

        // Group consecutive changes together for word-level diffing
        let mut pending_deletes: Vec<(String, usize)> = Vec::new();
        let mut pending_inserts: Vec<(String, usize)> = Vec::new();

        let ops: Vec<_> = text_diff.iter_all_changes().collect();

        for change in ops.iter() {
            match change.tag() {
                ChangeTag::Equal => {
                    // Flush any pending changes before processing equal
                    self.flush_pending_changes(
                        &mut pending_deletes,
                        &mut pending_inserts,
                        &mut changes,
                        &mut significant_changes,
                        &mut change_id,
                        &mut insertions,
                        &mut deletions,
                    );

                    let span = ChangeSpan::equal(change.value().trim_end_matches('\n'))
                        .with_lines(Some(old_line_num), Some(new_line_num));
                    changes.push(Change::single(change_id, span));
                    change_id += 1;
                    old_line_num += 1;
                    new_line_num += 1;
                }
                ChangeTag::Delete => {
                    pending_deletes.push((
                        change.value().trim_end_matches('\n').to_string(),
                        old_line_num,
                    ));
                    old_line_num += 1;
                }
                ChangeTag::Insert => {
                    pending_inserts.push((
                        change.value().trim_end_matches('\n').to_string(),
                        new_line_num,
                    ));
                    new_line_num += 1;
                }
            }
        }

        // Flush remaining changes
        self.flush_pending_changes(
            &mut pending_deletes,
            &mut pending_inserts,
            &mut changes,
            &mut significant_changes,
            &mut change_id,
            &mut insertions,
            &mut deletions,
        );

        // Compute hunks by grouping nearby changes
        let hunks = Self::compute_hunks(&significant_changes, &changes);

        DiffResult {
            changes,
            significant_changes,
            hunks,
            insertions,
            deletions,
        }
    }

    /// Compute hunks by grouping consecutive changes that are close together
    /// Changes within PROXIMITY_THRESHOLD lines are grouped into the same hunk
    fn compute_hunks(significant_changes: &[usize], changes: &[Change]) -> Vec<Hunk> {
        const PROXIMITY_THRESHOLD: usize = 3;

        let mut hunks = Vec::new();
        if significant_changes.is_empty() {
            return hunks;
        }

        let mut current_hunk_changes: Vec<usize> = Vec::new();
        let mut current_hunk_old_start: Option<usize> = None;
        let mut current_hunk_new_start: Option<usize> = None;
        let mut last_old_line: Option<usize> = None;
        let mut last_new_line: Option<usize> = None;
        let mut current_insertions = 0;
        let mut current_deletions = 0;
        let mut hunk_id = 0;

        for &change_id in significant_changes {
            let change = match changes.iter().find(|c| c.id == change_id) {
                Some(c) => c,
                None => continue,
            };

            // Get line numbers from first span
            let (old_line, new_line) = change
                .spans
                .first()
                .map(|s| (s.old_line, s.new_line))
                .unwrap_or((None, None));

            // Determine if this change is close to the previous one
            let is_close = match (last_old_line, last_new_line, old_line, new_line) {
                (Some(lo), _, Some(co), _) => co.saturating_sub(lo) <= PROXIMITY_THRESHOLD,
                (_, Some(ln), _, Some(cn)) => cn.saturating_sub(ln) <= PROXIMITY_THRESHOLD,
                _ => current_hunk_changes.is_empty(), // First change always starts a hunk
            };

            if is_close {
                // Add to current hunk
                current_hunk_changes.push(change_id);
                if current_hunk_old_start.is_none() {
                    current_hunk_old_start = old_line;
                }
                if current_hunk_new_start.is_none() {
                    current_hunk_new_start = new_line;
                }
            } else {
                // Save current hunk and start a new one
                if !current_hunk_changes.is_empty() {
                    hunks.push(Hunk {
                        id: hunk_id,
                        change_ids: current_hunk_changes.clone(),
                        old_start: current_hunk_old_start,
                        new_start: current_hunk_new_start,
                        insertions: current_insertions,
                        deletions: current_deletions,
                    });
                    hunk_id += 1;
                }

                // Start new hunk
                current_hunk_changes = vec![change_id];
                current_hunk_old_start = old_line;
                current_hunk_new_start = new_line;
                current_insertions = 0;
                current_deletions = 0;
            }

            // Update last line numbers
            if old_line.is_some() {
                last_old_line = old_line;
            }
            if new_line.is_some() {
                last_new_line = new_line;
            }

            // Count insertions/deletions in this change
            for span in &change.spans {
                match span.kind {
                    ChangeKind::Insert => current_insertions += 1,
                    ChangeKind::Delete => current_deletions += 1,
                    ChangeKind::Replace => {
                        current_insertions += 1;
                        current_deletions += 1;
                    }
                    ChangeKind::Equal => {}
                }
            }
        }

        // Don't forget the last hunk
        if !current_hunk_changes.is_empty() {
            hunks.push(Hunk {
                id: hunk_id,
                change_ids: current_hunk_changes,
                old_start: current_hunk_old_start,
                new_start: current_hunk_new_start,
                insertions: current_insertions,
                deletions: current_deletions,
            });
        }

        hunks
    }

    #[allow(clippy::too_many_arguments)]
    fn flush_pending_changes(
        &self,
        pending_deletes: &mut Vec<(String, usize)>,
        pending_inserts: &mut Vec<(String, usize)>,
        changes: &mut Vec<Change>,
        significant_changes: &mut Vec<usize>,
        change_id: &mut usize,
        insertions: &mut usize,
        deletions: &mut usize,
    ) {
        if pending_deletes.is_empty() && pending_inserts.is_empty() {
            return;
        }

        // Try to match deletes with inserts for replace operations
        if self.word_level && pending_deletes.len() == pending_inserts.len() {
            for ((old_text, old_line), (new_text, new_line)) in
                pending_deletes.iter().zip(pending_inserts.iter())
            {
                let spans = self.compute_word_diff(old_text, new_text, *old_line, *new_line);
                let change = Change::new(*change_id, spans);
                significant_changes.push(*change_id);
                changes.push(change);
                *change_id += 1;
                *insertions += 1;
                *deletions += 1;
            }
        } else {
            // Output as separate deletes and inserts
            for (text, line) in pending_deletes.iter() {
                let span = ChangeSpan::delete(text.clone()).with_lines(Some(*line), None);
                significant_changes.push(*change_id);
                changes.push(Change::single(*change_id, span));
                *change_id += 1;
                *deletions += 1;
            }
            for (text, line) in pending_inserts.iter() {
                let span = ChangeSpan::insert(text.clone()).with_lines(None, Some(*line));
                significant_changes.push(*change_id);
                changes.push(Change::single(*change_id, span));
                *change_id += 1;
                *insertions += 1;
            }
        }

        pending_deletes.clear();
        pending_inserts.clear();
    }
}

/// Tokenize code for word-level diffing
/// Separates identifiers from punctuation for accurate diffs
fn tokenize_code(line: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut buf = String::new();
    let mut in_word = false;

    for ch in line.chars() {
        let is_word = ch.is_alphanumeric() || ch == '_';
        if is_word {
            if !in_word {
                if !buf.is_empty() {
                    tokens.push(std::mem::take(&mut buf));
                }
                in_word = true;
            }
            buf.push(ch);
        } else {
            if in_word {
                if !buf.is_empty() {
                    tokens.push(std::mem::take(&mut buf));
                }
                in_word = false;
            }
            if ch.is_whitespace() {
                // Group consecutive whitespace
                if !buf.is_empty() && !buf.chars().all(char::is_whitespace) {
                    tokens.push(std::mem::take(&mut buf));
                }
                buf.push(ch);
            } else {
                // Each punctuation char is its own token
                if !buf.is_empty() {
                    tokens.push(std::mem::take(&mut buf));
                }
                tokens.push(ch.to_string());
            }
        }
    }
    if !buf.is_empty() {
        tokens.push(buf);
    }
    tokens
}

impl DiffEngine {
    /// Compute word-level diff within a line
    fn compute_word_diff(
        &self,
        old: &str,
        new: &str,
        old_line: usize,
        new_line: usize,
    ) -> Vec<ChangeSpan> {
        let old_tokens = tokenize_code(old);
        let new_tokens = tokenize_code(new);
        let old_refs: Vec<&str> = old_tokens.iter().map(|s| s.as_str()).collect();
        let new_refs: Vec<&str> = new_tokens.iter().map(|s| s.as_str()).collect();
        let word_diff = TextDiff::from_slices(&old_refs, &new_refs);
        let mut spans = Vec::new();

        for change in word_diff.iter_all_changes() {
            let text = change.value().to_string();
            let span = match change.tag() {
                ChangeTag::Equal => ChangeSpan::equal(text),
                ChangeTag::Delete => ChangeSpan::delete(text),
                ChangeTag::Insert => ChangeSpan::insert(text),
            }
            .with_lines(Some(old_line), Some(new_line));
            spans.push(span);
        }

        spans
    }

    /// Compute diff between two files
    pub fn diff_files(&self, old_path: &Path, new_path: &Path) -> Result<FileDiff, DiffError> {
        let old_content = std::fs::read_to_string(old_path)?;
        let new_content = std::fs::read_to_string(new_path)?;

        let result = self.diff_strings(&old_content, &new_content);

        Ok(FileDiff {
            old_path: Some(old_path.to_string_lossy().to_string()),
            new_path: Some(new_path.to_string_lossy().to_string()),
            result,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_diff() {
        let engine = DiffEngine::new();
        let old = "foo\nbar\nbaz";
        let new = "foo\nqux\nbaz";

        let result = engine.diff_strings(old, new);

        assert_eq!(result.insertions, 1);
        assert_eq!(result.deletions, 1);
        assert!(!result.significant_changes.is_empty());
    }

    #[test]
    fn test_no_changes() {
        let engine = DiffEngine::new();
        let text = "foo\nbar\nbaz";

        let result = engine.diff_strings(text, text);

        assert_eq!(result.insertions, 0);
        assert_eq!(result.deletions, 0);
        assert!(result.significant_changes.is_empty());
    }

    #[test]
    fn test_word_level_diff() {
        let engine = DiffEngine::new().with_word_level(true);
        let old = "const foo = 4";
        let new = "const bar = 4";

        let result = engine.diff_strings(old, new);

        // Should have a single change with word-level spans
        assert_eq!(result.significant_changes.len(), 1);
    }

    #[test]
    fn test_tokenize_code_basic() {
        let tokens = tokenize_code("KeyModifiers, MouseEventKind}");
        assert_eq!(
            tokens,
            vec!["KeyModifiers", ",", " ", "MouseEventKind", "}"]
        );
    }

    #[test]
    fn test_tokenize_code_identifiers() {
        let tokens = tokenize_code("foo_bar baz123");
        assert_eq!(tokens, vec!["foo_bar", " ", "baz123"]);
    }

    #[test]
    fn test_tokenize_code_punctuation() {
        let tokens = tokenize_code("use foo::{A, B};");
        assert_eq!(
            tokens,
            vec!["use", " ", "foo", ":", ":", "{", "A", ",", " ", "B", "}", ";"]
        );
    }

    #[test]
    fn test_word_diff_punctuation_separation() {
        use crate::change::ChangeKind;

        // This is the exact bug case: adding MouseEventKind to an import list
        let engine = DiffEngine::new().with_word_level(true);
        let old = "use foo::{KeyModifiers};";
        let new = "use foo::{KeyModifiers, MouseEventKind};";

        let result = engine.diff_strings(old, new);

        // Should have one change
        assert_eq!(result.significant_changes.len(), 1);

        let change = &result.changes[result.significant_changes[0]];

        // Find spans by kind
        let equal_content: String = change
            .spans
            .iter()
            .filter(|s| s.kind == ChangeKind::Equal)
            .map(|s| s.text.as_str())
            .collect();
        let insert_content: String = change
            .spans
            .iter()
            .filter(|s| s.kind == ChangeKind::Insert)
            .map(|s| s.text.as_str())
            .collect();

        // KeyModifiers should be in equal spans (unchanged)
        assert!(
            equal_content.contains("KeyModifiers"),
            "KeyModifiers should be equal, got equal: '{}', insert: '{}'",
            equal_content,
            insert_content
        );

        // MouseEventKind should be in insert spans (new)
        assert!(
            insert_content.contains("MouseEventKind"),
            "MouseEventKind should be inserted, got equal: '{}', insert: '{}'",
            equal_content,
            insert_content
        );

        // KeyModifiers should NOT be in insert spans
        assert!(
            !insert_content.contains("KeyModifiers"),
            "KeyModifiers should not be inserted, got insert: '{}'",
            insert_content
        );
    }
}