Skip to main content

diff_viewer/
diff_viewer.rs

1//! Diff viewer — display and inspect unified diffs with syntax highlighting.
2//!
3//! Demonstrates how to use the new diff viewing capabilities with Scriba's
4//! structured output. Shows both simple and colored diff rendering.
5//!
6//! Run with:
7//! ```sh
8//! cargo run --example diff_viewer
9//! ```
10
11use scriba::{Format, Output, Ui};
12
13fn main() -> scriba::Result<()> {
14    // Example unified diff content
15    let patch = r#"--- a/src/main.rs
16+++ b/src/main.rs
17@@ -1,5 +1,6 @@
18 fn main() {
19-    println!("Hello, world!");
20+    println!("Hello, Scriba!");
21+    println!("Diff viewer is great!");
22     
23     let x = 42;
24-    println!("x = {}", x);
25+    println!("x = {}", x * 2);
26"#;
27
28    println!("=== TEXT FORMAT (default) ===\n");
29    let ui_text = Ui::new().with_format(Format::Text);
30    ui_text.show_diff("src/main.rs", patch)?;
31
32    println!("\n=== MARKDOWN FORMAT ===\n");
33    let ui_markdown = Ui::new().with_format(Format::Markdown);
34    ui_markdown.show_diff("src/main.rs", patch)?;
35
36    println!("\n=== COLORED DIFF (for terminal output) ===\n");
37    let ui_colored = Ui::new().with_format(Format::Text);
38    ui_colored.show_diff_colored("src/main.rs", patch, true)?;
39
40    println!("\n=== JSON FORMAT ===\n");
41    let ui_json = Ui::new().with_format(Format::Json);
42    ui_json.show_diff("src/main.rs", patch)?;
43
44    // Example: Working with parsed diff lines
45    println!("\n=== PARSED DIFF LINES ===\n");
46    let diff_lines = scriba::parse_diff(patch);
47    let mut output = Output::new()
48        .title("Parsed Diff Analysis")
49        .subtitle("Breaking down the diff into structured lines");
50
51    let mut stats = String::new();
52    stats.push_str(&format!(
53        "Total lines: {}\n",
54        diff_lines.len()
55    ));
56
57    let added = diff_lines
58        .iter()
59        .filter(|l| l.kind == scriba::DiffLineKind::Added)
60        .count();
61    let removed = diff_lines
62        .iter()
63        .filter(|l| l.kind == scriba::DiffLineKind::Removed)
64        .count();
65    let context = diff_lines
66        .iter()
67        .filter(|l| l.kind == scriba::DiffLineKind::Context)
68        .count();
69
70    stats.push_str(&format!("Added: {}\n", added));
71    stats.push_str(&format!("Removed: {}\n", removed));
72    stats.push_str(&format!("Context: {}", context));
73
74    output = output.section("Statistics", stats, "text".to_string());
75
76    let ui_stats = Ui::new().with_format(Format::Markdown);
77    ui_stats.print(&output)?;
78
79    Ok(())
80}