void-cli 0.0.4

CLI for void — anonymous encrypted source control
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Diff command implementation.
//!
//! Shows changes between commits, index, and working tree.
//! Supports 4 modes matching the TypeScript CLI:
//! - 0 refs: index vs working tree (unstaged changes)
//! - 1 ref: commit vs working tree
//! - 2 refs: commit vs commit
//! - --staged: HEAD vs index (staged changes)

use std::io::{self, IsTerminal, Write};
use std::path::Path;

use serde::Serialize;

use crate::context::{open_repo, resolve_ref, void_err_to_cli};
use crate::output::{run_command, CliError, CliOptions};
use void_core::cid;
use void_core::diff::{
    content_diff_commits, content_diff_index, content_diff_staged, content_diff_working,
    diff_commits, diff_index, diff_staged, diff_working, ContentDiff, DiffKind, TreeDiff,
};
use void_core::index::read_index;

/// JSON output for a single file diff.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileDiffOutput {
    /// Path of the file (new path for renames).
    pub path: String,
    /// Type of change: "added", "modified", "deleted", or "renamed".
    pub kind: String,
    /// Old content hash (hex, 64 chars). None for added files.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_hash: Option<String>,
    /// New content hash (hex, 64 chars). None for deleted files.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_hash: Option<String>,
    /// Original path for renamed files.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rename_from: Option<String>,
    /// Similarity percentage for renamed files (0-100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rename_similarity: Option<u8>,
    /// True if binary content detected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub binary: Option<bool>,
    /// True if file exceeds size limit for diffing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub too_large: Option<bool>,
    /// Unified diff patch string (standard format, like `git diff` output).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub patch: Option<String>,
}

/// Statistics about a diff (matches TypeScript CLI).
#[derive(Debug, Clone, Serialize, Default)]
pub struct DiffStats {
    pub added: usize,
    pub modified: usize,
    pub deleted: usize,
    pub renamed: usize,
}

/// JSON output for diff command (matches TypeScript CLI).
#[derive(Debug, Clone, Serialize)]
pub struct DiffOutput {
    /// List of file differences.
    pub files: Vec<FileDiffOutput>,
    /// Statistics summary.
    pub stats: DiffStats,
}

impl From<TreeDiff> for DiffOutput {
    fn from(diff: TreeDiff) -> Self {
        let mut stats = DiffStats::default();

        let files = diff
            .files
            .into_iter()
            .map(|f| {
                let (kind, rename_from, rename_similarity) = match &f.kind {
                    DiffKind::Added => {
                        stats.added += 1;
                        ("added".to_string(), None, None)
                    }
                    DiffKind::Modified => {
                        stats.modified += 1;
                        ("modified".to_string(), None, None)
                    }
                    DiffKind::Deleted => {
                        stats.deleted += 1;
                        ("deleted".to_string(), None, None)
                    }
                    DiffKind::Renamed { from, similarity } => {
                        stats.renamed += 1;
                        ("renamed".to_string(), Some(from.clone()), Some(*similarity))
                    }
                };
                FileDiffOutput {
                    path: f.path,
                    kind,
                    old_hash: f.old_hash.map(hex::encode),
                    new_hash: f.new_hash.map(hex::encode),
                    rename_from,
                    rename_similarity,
                    binary: None,
                    too_large: None,
                    patch: None,
                }
            })
            .collect();

        DiffOutput { files, stats }
    }
}

/// ANSI color codes for human-readable output.
mod colors {
    pub const GREEN: &str = "\x1b[32m";
    pub const RED: &str = "\x1b[31m";
    pub const BLUE: &str = "\x1b[34m";
    pub const YELLOW: &str = "\x1b[33m";
    pub const CYAN: &str = "\x1b[36m";
    pub const BOLD: &str = "\x1b[1m";
    pub const RESET: &str = "\x1b[0m";
}

/// Format a stat line for a single file.
fn format_stat_line(file: &FileDiffOutput, use_color: bool) -> String {
    let (prefix, color) = match file.kind.as_str() {
        "added" => ("+", colors::GREEN),
        "modified" => ("M", colors::BLUE),
        "deleted" => ("-", colors::RED),
        "renamed" => ("R", colors::YELLOW),
        _ => ("?", colors::RESET),
    };

    if use_color {
        if file.kind == "renamed" {
            let from = file.rename_from.as_deref().unwrap_or("?");
            format!(
                "{}{}{} {} (from {})",
                color,
                prefix,
                colors::RESET,
                file.path,
                from
            )
        } else {
            format!("{}{}{} {}", color, prefix, colors::RESET, file.path)
        }
    } else if file.kind == "renamed" {
        let from = file.rename_from.as_deref().unwrap_or("?");
        format!("{} {} (from {})", prefix, file.path, from)
    } else {
        format!("{} {}", prefix, file.path)
    }
}

/// Format the summary line showing counts of each change type.
fn format_stat_summary(stats: &DiffStats) -> Option<String> {
    let mut parts = Vec::new();

    if stats.added > 0 {
        parts.push(format!("{} added", stats.added));
    }
    if stats.modified > 0 {
        parts.push(format!("{} modified", stats.modified));
    }
    if stats.deleted > 0 {
        parts.push(format!("{} deleted", stats.deleted));
    }
    if stats.renamed > 0 {
        parts.push(format!("{} renamed", stats.renamed));
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join(", "))
    }
}

/// Print human-readable stat summary to stdout.
fn print_stat_summary(output: &DiffOutput, use_color: bool) {
    let stdout = io::stdout();
    let mut handle = stdout.lock();

    for file in &output.files {
        let line = format_stat_line(file, use_color);
        let _ = writeln!(handle, " {}", line);
    }

    if let Some(summary) = format_stat_summary(&output.stats) {
        let _ = writeln!(handle);
        let _ = writeln!(handle, " {}", summary);
    }
}

/// Format a `ContentDiff` as a unified diff patch string.
fn format_patch(diff: &ContentDiff) -> String {
    let old_path = diff.rename_from.as_deref().unwrap_or(&diff.path);
    let new_path = &diff.path;
    let is_add = matches!(diff.kind, DiffKind::Added);
    let is_del = matches!(diff.kind, DiffKind::Deleted);
    let mut out = String::new();

    if is_add {
        out.push_str("--- /dev/null\n");
    } else {
        out.push_str(&format!("--- a/{}\n", old_path));
    }
    if is_del {
        out.push_str("+++ /dev/null\n");
    } else {
        out.push_str(&format!("+++ b/{}\n", new_path));
    }

    for hunk in &diff.hunks {
        out.push_str(&format!(
            "@@ -{},{} +{},{} @@\n",
            hunk.old_start, hunk.old_count, hunk.new_start, hunk.new_count
        ));
        for line in &hunk.lines {
            if line.tag == ' ' {
                out.push_str(&format!(" {}\n", line.content));
            } else {
                out.push_str(&format!("{}{}\n", line.tag, line.content));
            }
        }
    }

    out
}

/// Print unified diff output to stdout.
fn print_unified_diff(diffs: &[ContentDiff], use_color: bool) {
    let stdout = io::stdout();
    let mut handle = stdout.lock();

    for diff in diffs {
        let old_path = diff.rename_from.as_deref().unwrap_or(&diff.path);
        let new_path = &diff.path;
        let is_add = matches!(diff.kind, DiffKind::Added);
        let is_del = matches!(diff.kind, DiffKind::Deleted);

        // File header
        if use_color {
            let _ = writeln!(
                handle,
                "{}diff --void a/{} b/{}{}",
                colors::BOLD,
                old_path,
                new_path,
                colors::RESET
            );
        } else {
            let _ = writeln!(handle, "diff --void a/{} b/{}", old_path, new_path);
        }

        if diff.rename_from.is_some() {
            let _ = writeln!(handle, "rename from {}", old_path);
            let _ = writeln!(handle, "rename to {}", new_path);
        }

        // Binary files
        if diff.binary {
            let _ = writeln!(handle, "Binary files differ");
            continue;
        }

        // Too-large files
        if diff.too_large {
            let _ = writeln!(handle, "File too large to diff");
            continue;
        }

        // --- / +++ headers (use /dev/null for added/deleted like git)
        let old_label = if is_add {
            "/dev/null".to_string()
        } else {
            format!("a/{}", old_path)
        };
        let new_label = if is_del {
            "/dev/null".to_string()
        } else {
            format!("b/{}", new_path)
        };

        if use_color {
            let _ = writeln!(handle, "{}--- {}{}", colors::BOLD, old_label, colors::RESET);
            let _ = writeln!(handle, "{}+++ {}{}", colors::BOLD, new_label, colors::RESET);
        } else {
            let _ = writeln!(handle, "--- {}", old_label);
            let _ = writeln!(handle, "+++ {}", new_label);
        }

        // Hunks
        for hunk in &diff.hunks {
            let header = format!(
                "@@ -{},{} +{},{} @@",
                hunk.old_start, hunk.old_count, hunk.new_start, hunk.new_count
            );

            if use_color {
                let _ = writeln!(handle, "{}{}{}", colors::CYAN, header, colors::RESET);
            } else {
                let _ = writeln!(handle, "{}", header);
            }

            for line in &hunk.lines {
                match (use_color, line.tag) {
                    (true, '+') => {
                        let _ = writeln!(
                            handle,
                            "{}+{}{}",
                            colors::GREEN,
                            line.content,
                            colors::RESET
                        );
                    }
                    (true, '-') => {
                        let _ = writeln!(
                            handle,
                            "{}-{}{}",
                            colors::RED,
                            line.content,
                            colors::RESET
                        );
                    }
                    (_, ' ') => {
                        let _ = writeln!(handle, " {}", line.content);
                    }
                    (_, tag) => {
                        let _ = writeln!(handle, "{}{}", tag, line.content);
                    }
                }
            }
        }
    }
}

/// Run the diff command.
///
/// # Arguments
/// * `cwd` - Current working directory
/// * `commits` - Commit references to compare (0, 1, or 2)
/// * `staged` - Show staged changes (index vs HEAD)
/// * `stat` - Show only file-level summary (no content diff)
/// * `no_color` - Disable colored output
/// * `opts` - CLI options
pub fn run(
    cwd: &Path,
    commits: Vec<String>,
    staged: bool,
    stat: bool,
    no_color: bool,
    opts: &CliOptions,
) -> Result<(), CliError> {
    run_command("diff", opts, |ctx| {
        // Diff output is commonly piped to a pager (e.g. `void diff | less`),
        // so default to human-readable output even when stdout is not a TTY.
        ctx.set_prefer_human();

        // Validate arguments
        if staged && !commits.is_empty() {
            return Err(CliError::invalid_args(
                "--staged does not accept commit arguments",
            ));
        }

        if commits.len() > 2 {
            return Err(CliError::invalid_args("Too many commit arguments (max 2)"));
        }

        // Get repository context
        let repo = open_repo(cwd)?;

        // Determine if we should use colors (TTY and not disabled)
        let use_color = !no_color && io::stdout().is_terminal();

        // Load the workspace index
        let index = read_index(repo.void_dir().as_std_path(), repo.vault().index_key().map_err(|e| void_err_to_cli(e.into()))?)
            .map_err(void_err_to_cli)?;

        // Create object store for reading commits
        let store = repo.store().map_err(void_err_to_cli)?;

        // Phase 1: Compute hash-only TreeDiff (fast)
        let tree_diff = match (staged, commits.len()) {
            (true, _) => {
                ctx.verbose("Computing staged changes (index vs HEAD)...");
                diff_staged(
                    &store,
                    repo.vault(),
                    repo.void_dir().as_std_path(),
                    &index,
                )
                .map_err(void_err_to_cli)?
            }
            (false, 0) => {
                ctx.verbose("Computing unstaged changes (working tree vs index)...");
                diff_index(&index, repo.root().as_std_path()).map_err(void_err_to_cli)?
            }
            (false, 1) => {
                ctx.verbose(&format!(
                    "Computing changes from {} to working tree...",
                    commits[0]
                ));
                let commit_cid_typed = resolve_ref(repo.void_dir().as_std_path(), &commits[0])?;
                let commit_cid = cid::from_bytes(commit_cid_typed.as_bytes()).map_err(void_err_to_cli)?;
                diff_working(
                    &store,
                    repo.vault(),
                    &commit_cid,
                    repo.root().as_std_path(),
                )
                .map_err(void_err_to_cli)?
            }
            (false, 2) => {
                ctx.verbose(&format!(
                    "Computing changes from {} to {}...",
                    commits[0], commits[1]
                ));
                let old_typed = resolve_ref(repo.void_dir().as_std_path(), &commits[0])?;
                let new_typed = resolve_ref(repo.void_dir().as_std_path(), &commits[1])?;
                let old_cid = cid::from_bytes(old_typed.as_bytes()).map_err(void_err_to_cli)?;
                let new_cid = cid::from_bytes(new_typed.as_bytes()).map_err(void_err_to_cli)?;
                diff_commits(&store, repo.vault(), Some(&old_cid), &new_cid)
                    .map_err(void_err_to_cli)?
            }
            _ => unreachable!(),
        };

        // Phase 2: Compute content diffs when needed (not --stat, not empty)
        let content_diffs = if !stat && !tree_diff.is_empty() {
            let result = match (staged, commits.len()) {
                (true, _) => content_diff_staged(
                    &tree_diff,
                    repo.context(),
                )
                .map_err(void_err_to_cli)?,
                (false, 0) => content_diff_index(
                    &tree_diff,
                    &index,
                    repo.root().as_std_path(),
                    repo.void_dir().as_std_path(),
                    repo.vault().staged_key().map_err(|e| void_err_to_cli(e.into()))?,
                )
                .map_err(void_err_to_cli)?,
                (false, 1) => {
                    let commit_cid_typed = resolve_ref(repo.void_dir().as_std_path(), &commits[0])?;
                    let commit_cid = cid::from_bytes(commit_cid_typed.as_bytes()).map_err(void_err_to_cli)?;
                    content_diff_working(
                        &tree_diff,
                        repo.context(),
                        &commit_cid,
                        repo.root().as_std_path(),
                    )
                    .map_err(void_err_to_cli)?
                }
                (false, 2) => {
                    let old_typed = resolve_ref(repo.void_dir().as_std_path(), &commits[0])?;
                    let new_typed = resolve_ref(repo.void_dir().as_std_path(), &commits[1])?;
                    let old_cid = cid::from_bytes(old_typed.as_bytes()).map_err(void_err_to_cli)?;
                    let new_cid = cid::from_bytes(new_typed.as_bytes()).map_err(void_err_to_cli)?;
                    content_diff_commits(
                        &tree_diff,
                        repo.context(),
                        &old_cid,
                        &new_cid,
                    )
                    .map_err(void_err_to_cli)?
                }
                _ => unreachable!(),
            };
            Some(result)
        } else {
            None
        };

        // Convert to output format
        let mut output: DiffOutput = tree_diff.into();

        // Merge content diffs into output (for JSON patch field)
        if let Some(ref diffs) = content_diffs {
            for content_diff in diffs {
                if let Some(file_out) = output
                    .files
                    .iter_mut()
                    .find(|f| f.path == content_diff.path)
                {
                    if content_diff.binary {
                        file_out.binary = Some(true);
                    } else if content_diff.too_large {
                        file_out.too_large = Some(true);
                    } else if !content_diff.hunks.is_empty() {
                        file_out.patch = Some(format_patch(content_diff));
                    }
                }
            }
        }

        // Print human-readable output if not JSON mode
        if !ctx.use_json() {
            if output.files.is_empty() {
                if staged {
                    ctx.info("No staged changes");
                } else if commits.is_empty() {
                    ctx.info("No unstaged changes");
                } else {
                    ctx.info("No changes");
                }
            } else if stat {
                print_stat_summary(&output, use_color);
            } else if let Some(ref diffs) = content_diffs {
                print_unified_diff(diffs, use_color);
            }
        }

        Ok(output)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use void_core::ContentHash;
    use void_core::diff::{DiffKind, FileDiff, TreeDiff};

    #[test]
    fn test_diff_output_from_tree_diff() {
        let tree_diff = TreeDiff {
            files: vec![
                FileDiff {
                    path: "new_file.rs".to_string(),
                    kind: DiffKind::Added,
                    old_hash: None,
                    new_hash: Some(ContentHash([0u8; 32])),
                },
                FileDiff {
                    path: "changed.rs".to_string(),
                    kind: DiffKind::Modified,
                    old_hash: Some(ContentHash([1u8; 32])),
                    new_hash: Some(ContentHash([2u8; 32])),
                },
                FileDiff {
                    path: "removed.rs".to_string(),
                    kind: DiffKind::Deleted,
                    old_hash: Some(ContentHash([3u8; 32])),
                    new_hash: None,
                },
                FileDiff {
                    path: "new_name.rs".to_string(),
                    kind: DiffKind::Renamed {
                        from: "old_name.rs".to_string(),
                        similarity: 95,
                    },
                    old_hash: Some(ContentHash([4u8; 32])),
                    new_hash: Some(ContentHash([4u8; 32])),
                },
            ],
        };

        let output: DiffOutput = tree_diff.into();

        assert_eq!(output.files.len(), 4);
        assert_eq!(output.stats.added, 1);
        assert_eq!(output.stats.modified, 1);
        assert_eq!(output.stats.deleted, 1);
        assert_eq!(output.stats.renamed, 1);

        assert_eq!(output.files[0].path, "new_file.rs");
        assert_eq!(output.files[0].kind, "added");
        assert!(output.files[0].old_hash.is_none());
        assert!(output.files[0].new_hash.is_some());
        assert!(output.files[0].rename_from.is_none());

        assert_eq!(output.files[1].path, "changed.rs");
        assert_eq!(output.files[1].kind, "modified");
        assert!(output.files[1].old_hash.is_some());
        assert!(output.files[1].new_hash.is_some());

        assert_eq!(output.files[2].path, "removed.rs");
        assert_eq!(output.files[2].kind, "deleted");
        assert!(output.files[2].old_hash.is_some());
        assert!(output.files[2].new_hash.is_none());

        assert_eq!(output.files[3].path, "new_name.rs");
        assert_eq!(output.files[3].kind, "renamed");
        assert_eq!(output.files[3].rename_from, Some("old_name.rs".to_string()));
        assert_eq!(output.files[3].rename_similarity, Some(95));
    }

    #[test]
    fn test_format_stat_line_no_color() {
        let added = FileDiffOutput {
            path: "src/new.rs".to_string(),
            kind: "added".to_string(),
            old_hash: None,
            new_hash: Some("abc".to_string()),
            rename_from: None,
            rename_similarity: None,
            binary: None,
            too_large: None,
            patch: None,
        };
        assert_eq!(format_stat_line(&added, false), "+ src/new.rs");

        let modified = FileDiffOutput {
            path: "src/changed.rs".to_string(),
            kind: "modified".to_string(),
            old_hash: Some("old".to_string()),
            new_hash: Some("new".to_string()),
            rename_from: None,
            rename_similarity: None,
            binary: None,
            too_large: None,
            patch: None,
        };
        assert_eq!(format_stat_line(&modified, false), "M src/changed.rs");

        let deleted = FileDiffOutput {
            path: "src/removed.rs".to_string(),
            kind: "deleted".to_string(),
            old_hash: Some("old".to_string()),
            new_hash: None,
            rename_from: None,
            rename_similarity: None,
            binary: None,
            too_large: None,
            patch: None,
        };
        assert_eq!(format_stat_line(&deleted, false), "- src/removed.rs");

        let renamed = FileDiffOutput {
            path: "new_name.rs".to_string(),
            kind: "renamed".to_string(),
            old_hash: Some("hash".to_string()),
            new_hash: Some("hash".to_string()),
            rename_from: Some("old_name.rs".to_string()),
            rename_similarity: Some(100),
            binary: None,
            too_large: None,
            patch: None,
        };
        assert_eq!(
            format_stat_line(&renamed, false),
            "R new_name.rs (from old_name.rs)"
        );
    }

    #[test]
    fn test_format_stat_summary() {
        let stats = DiffStats {
            added: 2,
            modified: 1,
            deleted: 0,
            renamed: 1,
        };
        assert_eq!(
            format_stat_summary(&stats),
            Some("2 added, 1 modified, 1 renamed".to_string())
        );

        let empty_stats = DiffStats::default();
        assert_eq!(format_stat_summary(&empty_stats), None);
    }

    #[test]
    fn test_empty_diff_output() {
        let tree_diff = TreeDiff { files: vec![] };
        let output: DiffOutput = tree_diff.into();
        assert!(output.files.is_empty());
        assert_eq!(output.stats.added, 0);
        assert_eq!(output.stats.modified, 0);
        assert_eq!(output.stats.deleted, 0);
        assert_eq!(output.stats.renamed, 0);
    }
}