vtcode-core 0.9.1

Core library for VTCode - a Rust-based terminal coding agent
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
568
569
570
571
572
573
574
use console::Style;
use std::path::Path;

/// Style presets for diff rendering
pub struct DiffStyles;

impl DiffStyles {
    /// File header style (bold blue)
    pub fn file_header() -> Style {
        Style::new().bold().blue()
    }

    /// File path style (bold cyan)
    pub fn file_path() -> Style {
        Style::new().bold().cyan()
    }

    /// Stats header style (bold magenta)
    pub fn stats_header() -> Style {
        Style::new().bold().magenta()
    }

    /// Additions count style (bold green)
    pub fn additions_count() -> Style {
        Style::new().bold().green()
    }

    /// Deletions count style (bold red)
    pub fn deletions_count() -> Style {
        Style::new().bold().red()
    }

    /// Changes count style (bold yellow)
    pub fn changes_count() -> Style {
        Style::new().bold().yellow()
    }

    /// Summary header style (bold cyan)
    pub fn summary_header() -> Style {
        Style::new().bold().cyan()
    }

    /// Added line style (green)
    pub fn added_line() -> Style {
        Style::new().green()
    }

    /// Removed line style (red)
    pub fn removed_line() -> Style {
        Style::new().red()
    }

    /// Context line style (dim white)
    pub fn context_line() -> Style {
        Style::new().white().dim()
    }

    /// Header line style (bold blue)
    pub fn header_line() -> Style {
        Style::new().bold().blue()
    }

    /// Apply style to text
    pub fn apply_style(style: &Style, text: &str) -> String {
        style.apply_to(text).to_string()
    }
}

#[derive(Debug, Clone)]
pub struct DiffLine {
    pub line_type: DiffLineType,
    pub content: String,
    pub line_number_old: Option<usize>,
    pub line_number_new: Option<usize>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum DiffLineType {
    Added,
    Removed,
    Context,
    Header,
}

#[derive(Debug)]
pub struct FileDiff {
    pub file_path: String,
    pub old_content: String,
    pub new_content: String,
    pub lines: Vec<DiffLine>,
    pub stats: DiffStats,
}

#[derive(Debug)]
pub struct DiffStats {
    pub additions: usize,
    pub deletions: usize,
    pub changes: usize,
}

pub struct DiffRenderer {
    show_line_numbers: bool,
    context_lines: usize,
    use_colors: bool,
}

impl DiffRenderer {
    pub fn new(show_line_numbers: bool, context_lines: usize, use_colors: bool) -> Self {
        Self {
            show_line_numbers,
            context_lines,
            use_colors,
        }
    }

    pub fn render_diff(&self, diff: &FileDiff) -> String {
        let mut output = String::new();

        // File header
        output.push_str(&self.render_header(&diff.file_path, &diff.stats));

        // Render each diff line
        for line in &diff.lines {
            output.push_str(&self.render_line(line));
            output.push('\n');
        }

        // Footer with summary
        output.push_str(&self.render_footer(&diff.stats));

        output
    }

    fn render_header(&self, file_path: &str, stats: &DiffStats) -> String {
        let file_header_style = if self.use_colors {
            DiffStyles::file_header()
        } else {
            Style::new()
        };
        let file_path_style = if self.use_colors {
            DiffStyles::file_path()
        } else {
            Style::new()
        };

        let mut header = format!(
            "\n{}{} File: {}{}\n",
            file_header_style.apply_to("FILE"),
            if self.use_colors { "\x1b[0m" } else { "" },
            file_path_style.apply_to(file_path),
            if self.use_colors { "\x1b[0m" } else { "" }
        );

        let stats_header_style = if self.use_colors {
            DiffStyles::stats_header()
        } else {
            Style::new()
        };
        let additions_style = if self.use_colors {
            DiffStyles::additions_count()
        } else {
            Style::new()
        };
        let deletions_style = if self.use_colors {
            DiffStyles::deletions_count()
        } else {
            Style::new()
        };
        let changes_style = if self.use_colors {
            DiffStyles::changes_count()
        } else {
            Style::new()
        };

        header.push_str(&format!(
            "{}{} Changes: {}{} additions, {}{} deletions, {}{} modifications\n",
            stats_header_style.apply_to("STATS"),
            if self.use_colors { "\x1b[0m" } else { "" },
            additions_style.apply_to(&stats.additions.to_string()),
            if self.use_colors { "\x1b[0m" } else { "" },
            deletions_style.apply_to(&stats.deletions.to_string()),
            if self.use_colors { "\x1b[0m" } else { "" },
            changes_style.apply_to(&stats.changes.to_string()),
            if self.use_colors { "\x1b[0m" } else { "" }
        ));

        if self.show_line_numbers {
            header.push_str("┌─────┬─────────────────────────────────────────────────\n");
        } else {
            header.push_str("┌───────────────────────────────────────────────────────\n");
        }

        header
    }

    fn render_line(&self, line: &DiffLine) -> String {
        let prefix = match line.line_type {
            DiffLineType::Added => "+",
            DiffLineType::Removed => "-",
            DiffLineType::Context => " ",
            DiffLineType::Header => "@",
        };

        let style = match line.line_type {
            DiffLineType::Added => DiffStyles::added_line(),
            DiffLineType::Removed => DiffStyles::removed_line(),
            DiffLineType::Context => DiffStyles::context_line(),
            DiffLineType::Header => DiffStyles::header_line(),
        };

        let mut result = String::new();

        if self.show_line_numbers {
            let old_num = line
                .line_number_old
                .map_or("".to_string(), |n| format!("{:4}", n));
            let new_num = line
                .line_number_new
                .map_or("".to_string(), |n| format!("{:4}", n));
            result.push_str(&format!("{}/{}", old_num, new_num));
        }

        if self.use_colors {
            let styled_prefix = self.colorize(prefix, &style);
            let styled_content = self.colorize(&line.content, &style);
            result.push_str(&format!("{}{}", styled_prefix, styled_content));
        } else {
            result.push_str(&format!("{}{}", prefix, line.content));
        }

        result
    }

    fn render_footer(&self, stats: &DiffStats) -> String {
        let mut footer = String::new();

        if self.show_line_numbers {
            footer.push_str("└─────┴─────────────────────────────────────────────────\n");
        } else {
            footer.push_str("└───────────────────────────────────────────────────────\n");
        }

        let summary_header_style = if self.use_colors {
            DiffStyles::summary_header()
        } else {
            Style::new()
        };
        let summary_additions_style = if self.use_colors {
            DiffStyles::additions_count()
        } else {
            Style::new()
        };
        let summary_deletions_style = if self.use_colors {
            DiffStyles::deletions_count()
        } else {
            Style::new()
        };
        let summary_changes_style = if self.use_colors {
            DiffStyles::changes_count()
        } else {
            Style::new()
        };

        footer.push_str(&format!(
            "{}{} Summary: {}{} lines added, {}{} lines removed, {}{} lines changed\n\n",
            summary_header_style.apply_to("SUMMARY"),
            if self.use_colors { "\x1b[0m" } else { "" },
            summary_additions_style.apply_to(&stats.additions.to_string()),
            if self.use_colors { "\x1b[0m" } else { "" },
            summary_deletions_style.apply_to(&stats.deletions.to_string()),
            if self.use_colors { "\x1b[0m" } else { "" },
            summary_changes_style.apply_to(&stats.changes.to_string()),
            if self.use_colors { "\x1b[0m" } else { "" }
        ));

        footer
    }

    fn colorize(&self, text: &str, style: &Style) -> String {
        if self.use_colors {
            DiffStyles::apply_style(style, text)
        } else {
            text.to_string()
        }
    }

    pub fn generate_diff(&self, old_content: &str, new_content: &str, file_path: &str) -> FileDiff {
        let old_lines: Vec<&str> = old_content.lines().collect();
        let new_lines: Vec<&str> = new_content.lines().collect();

        let mut lines = Vec::new();
        let mut additions = 0;
        let mut deletions = 0;
        let _changes = 0;

        // Simple diff algorithm - can be enhanced with more sophisticated diffing
        let mut old_idx = 0;
        let mut new_idx = 0;

        while old_idx < old_lines.len() || new_idx < new_lines.len() {
            if old_idx < old_lines.len() && new_idx < new_lines.len() {
                if old_lines[old_idx] == new_lines[new_idx] {
                    // Same line - context
                    lines.push(DiffLine {
                        line_type: DiffLineType::Context,
                        content: old_lines[old_idx].to_string(),
                        line_number_old: Some(old_idx + 1),
                        line_number_new: Some(new_idx + 1),
                    });
                    old_idx += 1;
                    new_idx += 1;
                } else {
                    // Lines differ - find the difference
                    let (old_end, new_end) =
                        self.find_difference(&old_lines, &new_lines, old_idx, new_idx);

                    // Add removed lines
                    for i in old_idx..old_end {
                        lines.push(DiffLine {
                            line_type: DiffLineType::Removed,
                            content: old_lines[i].to_string(),
                            line_number_old: Some(i + 1),
                            line_number_new: None,
                        });
                        deletions += 1;
                    }

                    // Add added lines
                    for i in new_idx..new_end {
                        lines.push(DiffLine {
                            line_type: DiffLineType::Added,
                            content: new_lines[i].to_string(),
                            line_number_old: None,
                            line_number_new: Some(i + 1),
                        });
                        additions += 1;
                    }

                    old_idx = old_end;
                    new_idx = new_end;
                }
            } else if old_idx < old_lines.len() {
                // Remaining old lines are deletions
                lines.push(DiffLine {
                    line_type: DiffLineType::Removed,
                    content: old_lines[old_idx].to_string(),
                    line_number_old: Some(old_idx + 1),
                    line_number_new: None,
                });
                deletions += 1;
                old_idx += 1;
            } else if new_idx < new_lines.len() {
                // Remaining new lines are additions
                lines.push(DiffLine {
                    line_type: DiffLineType::Added,
                    content: new_lines[new_idx].to_string(),
                    line_number_old: None,
                    line_number_new: Some(new_idx + 1),
                });
                additions += 1;
                new_idx += 1;
            }
        }

        let changes = additions + deletions;

        FileDiff {
            file_path: file_path.to_string(),
            old_content: old_content.to_string(),
            new_content: new_content.to_string(),
            lines,
            stats: DiffStats {
                additions,
                deletions,
                changes,
            },
        }
    }

    fn find_difference(
        &self,
        old_lines: &[&str],
        new_lines: &[&str],
        start_old: usize,
        start_new: usize,
    ) -> (usize, usize) {
        let mut old_end = start_old;
        let mut new_end = start_new;

        // Look for the next matching line
        while old_end < old_lines.len() && new_end < new_lines.len() {
            if old_lines[old_end] == new_lines[new_end] {
                return (old_end, new_end);
            }

            // Check if we can find a match within context window
            let mut found = false;
            for i in 1..=self.context_lines {
                if old_end + i < old_lines.len() && new_end + i < new_lines.len() {
                    if old_lines[old_end + i] == new_lines[new_end + i] {
                        old_end += i;
                        new_end += i;
                        found = true;
                        break;
                    }
                }
            }

            if !found {
                old_end += 1;
                new_end += 1;
            }
        }

        (old_end, new_end)
    }
}

pub struct DiffChatRenderer {
    diff_renderer: DiffRenderer,
}

impl DiffChatRenderer {
    pub fn new(show_line_numbers: bool, context_lines: usize, use_colors: bool) -> Self {
        Self {
            diff_renderer: DiffRenderer::new(show_line_numbers, context_lines, use_colors),
        }
    }

    pub fn render_file_change(
        &self,
        file_path: &Path,
        old_content: &str,
        new_content: &str,
    ) -> String {
        let diff = self.diff_renderer.generate_diff(
            old_content,
            new_content,
            &file_path.to_string_lossy(),
        );
        self.diff_renderer.render_diff(&diff)
    }

    pub fn render_multiple_changes(&self, changes: Vec<(String, String, String)>) -> String {
        let mut output = format!("\nMultiple File Changes ({} files)\n", changes.len());
        output.push_str("".repeat(60).as_str());
        output.push_str("\n\n");

        for (file_path, old_content, new_content) in changes {
            let diff = self
                .diff_renderer
                .generate_diff(&old_content, &new_content, &file_path);
            output.push_str(&self.diff_renderer.render_diff(&diff));
        }

        output
    }

    pub fn render_operation_summary(
        &self,
        operation: &str,
        files_affected: usize,
        success: bool,
    ) -> String {
        let status = if success { "[Success]" } else { "[Failure]" };
        let mut summary = format!("\n{} {}\n", status, operation);
        summary.push_str(&format!(" Files affected: {}\n", files_affected));

        if success {
            summary.push_str("Operation completed successfully!\n");
        } else {
            summary.push_str(" Operation completed with errors\n");
        }

        summary
    }
}

pub fn generate_unified_diff(old_content: &str, new_content: &str, filename: &str) -> String {
    let mut diff = format!("--- a/{}\n+++ b/{}\n", filename, filename);

    let old_lines: Vec<&str> = old_content.lines().collect();
    let new_lines: Vec<&str> = new_content.lines().collect();

    let mut old_idx = 0;
    let mut new_idx = 0;

    while old_idx < old_lines.len() || new_idx < new_lines.len() {
        // Find the next difference
        let start_old = old_idx;
        let start_new = new_idx;

        // Skip matching lines
        while old_idx < old_lines.len()
            && new_idx < new_lines.len()
            && old_lines[old_idx] == new_lines[new_idx]
        {
            old_idx += 1;
            new_idx += 1;
        }

        if old_idx == old_lines.len() && new_idx == new_lines.len() {
            break; // No more differences
        }

        // Find the end of the difference
        let mut end_old = old_idx;
        let mut end_new = new_idx;

        // Look for next matching context
        let mut context_found = false;
        for i in 0..3 {
            // Look ahead 3 lines for context
            if end_old + i < old_lines.len() && end_new + i < new_lines.len() {
                if old_lines[end_old + i] == new_lines[end_new + i] {
                    end_old += i;
                    end_new += i;
                    context_found = true;
                    break;
                }
            }
        }

        if !context_found {
            end_old = old_lines.len();
            end_new = new_lines.len();
        }

        // Generate hunk
        let old_count = end_old - start_old;
        let new_count = end_new - start_new;

        diff.push_str(&format!(
            "@@ -{},{} +{},{} @@\n",
            start_old + 1,
            old_count,
            start_new + 1,
            new_count
        ));

        // Add context before
        for i in (start_old.saturating_sub(3))..start_old {
            if i < old_lines.len() {
                diff.push_str(&format!(" {}\n", old_lines[i]));
            }
        }

        // Add removed lines
        for i in start_old..end_old {
            if i < old_lines.len() {
                diff.push_str(&format!("-{}\n", old_lines[i]));
            }
        }

        // Add added lines
        for i in start_new..end_new {
            if i < new_lines.len() {
                diff.push_str(&format!("+{}\n", new_lines[i]));
            }
        }

        // Add context after
        for i in end_old..(end_old + 3) {
            if i < old_lines.len() {
                diff.push_str(&format!(" {}\n", old_lines[i]));
            }
        }

        old_idx = end_old;
        new_idx = end_new;
    }

    diff
}