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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
//! Repository information commands.
//!
//! Provides subcommands for inspecting repository statistics, size, and metadata.

use std::collections::HashMap;
use std::fs;
use std::io::IsTerminal;
use std::path::Path;

use ignore::WalkBuilder;
use serde::Serialize;
use void_core::{cid, config, refs, support::configure_walker};

use crate::context::{find_void_dir, open_repo, void_err_to_cli};
use crate::output::{run_command, CliError, CliOptions};
use crate::registry;

// ============================================================================
// Output structures
// ============================================================================

/// Stats for a single file extension.
#[derive(Debug, Clone, Serialize)]
pub struct ExtensionStats {
    pub extension: String,
    pub lines: u64,
    pub files: u64,
    pub bytes: u64,
    pub percent: f64,
}

/// Total stats across all files.
#[derive(Debug, Clone, Serialize)]
pub struct TotalStats {
    pub lines: u64,
    pub files: u64,
    pub bytes: u64,
}

/// Output for `repo stat` command.
#[derive(Debug, Clone, Serialize)]
pub struct StatOutput {
    pub stats: Vec<ExtensionStats>,
    pub total: TotalStats,
}

/// Size breakdown of the .void directory.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoidDirSize {
    pub total: u64,
    pub objects: u64,
    pub index: u64,
}

/// A single large file entry.
#[derive(Debug, Clone, Serialize)]
pub struct LargeFile {
    pub path: String,
    pub bytes: u64,
}

/// Output for `repo size` command.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SizeOutput {
    pub void_dir: VoidDirSize,
    pub working_tree: u64,
    pub total: u64,
    pub largest_files: Vec<LargeFile>,
}

/// HEAD reference information.
#[derive(Debug, Clone, Serialize)]
pub struct HeadInfo {
    #[serde(rename = "ref")]
    pub ref_name: Option<String>,
    pub cid: Option<String>,
}

/// Output for `repo info` command.
#[derive(Debug, Clone, Serialize)]
pub struct InfoOutput {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub root: String,
    pub head: HeadInfo,
    pub commits: u64,
    pub remotes: Vec<String>,
}

/// Output entry for `repo list` command.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RepoListEntry {
    pub id: String,
    pub name: String,
    pub origin: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub branches: Vec<String>,
    pub local_paths: Vec<String>,
    pub created: String,
    pub updated: String,
}

/// Output for `repo list` command.
#[derive(Debug, Clone, Serialize)]
pub struct RepoListOutput {
    pub repos: Vec<RepoListEntry>,
    pub count: usize,
}

/// Output for `repo registry` command.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RepoRegistryOutput {
    pub id: String,
    pub name: String,
    pub origin: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub head: HashMap<String, String>,
    pub trusted_sources: Vec<String>,
    pub local_paths: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_ref: Option<String>,
    pub created: String,
    pub updated: String,
}

/// Output for `repo unregister` command.
#[derive(Debug, Clone, Serialize)]
pub struct RepoUnregisterOutput {
    pub id: String,
    pub name: String,
    pub removed: bool,
}

// ============================================================================
// Arguments
// ============================================================================

/// Arguments for `repo stat` command.
pub struct StatArgs {
    pub all: bool,
    pub top: usize,
    pub sort: String,
    pub path: Option<String>,
    pub exclude: Vec<String>,
}

/// Arguments for `repo size` command.
pub struct SizeArgs {
    pub top: usize,
}

// ============================================================================
// Code file extensions (when --all is not specified)
// ============================================================================

/// Extensions considered "code" files (shown by default without --all).
const CODE_EXTENSIONS: &[&str] = &[
    // Rust
    "rs", // JavaScript/TypeScript
    "js", "jsx", "ts", "tsx", "mjs", "cjs", // Python
    "py", "pyi", // Go
    "go",  // C/C++
    "c", "h", "cpp", "cc", "cxx", "hpp", "hh", "hxx", // Java/Kotlin
    "java", "kt", "kts",   // Ruby
    "rb",    // PHP
    "php",   // Swift
    "swift", // Shell
    "sh", "bash", "zsh", "fish", // Web
    "html", "htm", "css", "scss", "sass", "less", // Data/Config
    "json", "yaml", "yml", "toml", "xml", // Documentation
    "md", "markdown", "rst", "txt", // SQL
    "sql", // Zig
    "zig", // Lua
    "lua", // Haskell
    "hs",  // OCaml
    "ml", "mli", // Elixir/Erlang
    "ex", "exs", "erl", // Clojure
    "clj", "cljs", "cljc",  // Scala
    "scala", // Julia
    "jl",    // R
    "r", "R",   // Vim
    "vim", // Make
    "mk", "makefile", "Makefile", // Nix
    "nix",      // Lock files
    "lock",     // Void
    "void",
];

/// Format a number with thousand separators.
fn format_number(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::new();
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.insert(0, ',');
        }
        result.insert(0, c);
    }
    result
}

/// Format bytes in human-readable format.
fn format_bytes(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.1} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

fn is_code_extension(ext: &str) -> bool {
    CODE_EXTENSIONS.contains(&ext)
}

// ============================================================================
// Implementation
// ============================================================================

/// Run `repo stat` command.
pub fn run_stat(cwd: &Path, args: StatArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("repo stat", opts, |ctx| {
        ctx.progress("Scanning files...");

        let void_dir = find_void_dir(cwd)?;
        let root = void_dir
            .parent()
            .ok_or_else(|| CliError::internal("void_dir has no parent"))?;

        // Determine which directory to scan
        let scan_root = if let Some(ref path) = args.path {
            root.join(path)
        } else {
            root.to_path_buf()
        };

        if !scan_root.exists() {
            return Err(CliError::not_found(format!(
                "path does not exist: {}",
                scan_root.display()
            )));
        }

        let void_dir_name = void_dir
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(".void")
            .to_string();

        // Parse exclude patterns: each entry may be comma-separated, and each entry
        // can come from a repeated --exclude flag. Supports both:
        //   --exclude "lock,json" AND --exclude lock --exclude json
        let exclude_extensions: Vec<String> = args
            .exclude
            .iter()
            .flat_map(|entry| entry.split(','))
            .map(|s| {
                s.trim()
                    .trim_start_matches("*.")
                    .trim_start_matches('.')
                    .to_lowercase()
            })
            .filter(|s| !s.is_empty())
            .collect();

        // Walk directory and collect stats by extension
        let mut stats_map: HashMap<String, (u64, u64, u64)> = HashMap::new(); // ext -> (lines, files, bytes)
        let mut total_lines: u64 = 0;
        let mut total_files: u64 = 0;
        let mut total_bytes: u64 = 0;

        let mut builder = WalkBuilder::new(&scan_root);
        configure_walker(&mut builder).filter_entry(move |entry| {
            let name = entry.file_name().to_string_lossy();
            // Skip .void, .git, node_modules
            name != void_dir_name && name != ".git" && name != "node_modules" && name != ".DS_Store"
        });

        for entry in builder.build().flatten() {
            if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
                continue;
            }

            let path = entry.path();
            let ext = path
                .extension()
                .and_then(|e| e.to_str())
                .map(|e| e.to_lowercase())
                .unwrap_or_default();

            // Skip non-code files unless --all is specified
            if !args.all && !ext.is_empty() && !is_code_extension(&ext) {
                continue;
            }

            // Skip excluded extensions
            if !exclude_extensions.is_empty() && exclude_extensions.contains(&ext) {
                continue;
            }

            let metadata = match fs::metadata(path) {
                Ok(m) => m,
                Err(_) => continue,
            };

            let bytes = metadata.len();
            let lines = match fs::read(path) {
                Ok(content) => void_core::support::count_lines(&content) as u64,
                Err(_) => 0,
            };

            // Use extension without dot for display (matching TS output)
            let display_ext = if ext.is_empty() {
                "(none)".to_string()
            } else {
                ext.clone()
            };

            let entry = stats_map.entry(display_ext).or_insert((0, 0, 0));
            entry.0 += lines;
            entry.1 += 1;
            entry.2 += bytes;

            total_lines += lines;
            total_files += 1;
            total_bytes += bytes;
        }

        // Convert to sorted vec
        let mut stats: Vec<ExtensionStats> = stats_map
            .into_iter()
            .map(|(ext, (lines, files, bytes))| {
                let percent = if total_lines > 0 {
                    match args.sort.as_str() {
                        "files" => (files as f64 / total_files as f64) * 100.0,
                        "bytes" => (bytes as f64 / total_bytes as f64) * 100.0,
                        _ => (lines as f64 / total_lines as f64) * 100.0,
                    }
                } else {
                    0.0
                };
                ExtensionStats {
                    extension: ext,
                    lines,
                    files,
                    bytes,
                    percent: (percent * 10.0).round() / 10.0, // Round to 1 decimal
                }
            })
            .collect();

        // Sort by the specified field (descending)
        match args.sort.as_str() {
            "files" => stats.sort_by(|a, b| b.files.cmp(&a.files)),
            "bytes" => stats.sort_by(|a, b| b.bytes.cmp(&a.bytes)),
            _ => stats.sort_by(|a, b| b.lines.cmp(&a.lines)),
        }

        // Take top N
        stats.truncate(args.top);

        // Print human-readable output (matching TS style)
        if !ctx.use_json() {
            // Check if TTY for colors
            let use_colors = std::io::stderr().is_terminal();
            let dim = if use_colors { "\x1b[2m" } else { "" };
            let reset = if use_colors { "\x1b[0m" } else { "" };
            let bold = if use_colors { "\x1b[1m" } else { "" };

            // Header
            ctx.info(format!(
                "{}{:<6} {:>8}  {:>3}  {:>5}  {:>10}{}",
                bold, "EXT", "LINES", "%", "FILES", "SIZE", reset
            ));
            ctx.info(format!("{}{}{}", dim, "".repeat(40), reset));

            // Rows
            for stat in &stats {
                ctx.info(format!(
                    "{:<6} {:>8}  {:>2}%  {:>5}  {:>10}",
                    stat.extension,
                    format_number(stat.lines),
                    stat.percent as u64,
                    format_number(stat.files),
                    format_bytes(stat.bytes)
                ));
            }

            // Footer
            ctx.info("");
            ctx.info(format!(
                "{}Total:{} {} lines, {} files, {}",
                bold,
                reset,
                format_number(total_lines),
                format_number(total_files),
                format_bytes(total_bytes)
            ));
        }

        Ok(StatOutput {
            stats,
            total: TotalStats {
                lines: total_lines,
                files: total_files,
                bytes: total_bytes,
            },
        })
    })
}

/// Run `repo size` command.
pub fn run_size(cwd: &Path, args: SizeArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("repo size", opts, |ctx| {
        ctx.progress("Calculating sizes...");

        let void_dir = find_void_dir(cwd)?;
        let root = void_dir
            .parent()
            .ok_or_else(|| CliError::internal("void_dir has no parent"))?;

        let void_dir_name = void_dir
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(".void")
            .to_string();

        // Calculate .void directory sizes
        let objects_dir = void_dir.join("objects");
        let index_path = void_dir.join("index");

        let objects_size = dir_size(&objects_dir);
        let index_size = if index_path.exists() {
            fs::metadata(&index_path).map(|m| m.len()).unwrap_or(0)
        } else {
            0
        };

        let void_total = dir_size(&void_dir);

        // Calculate working tree size and collect largest files
        let mut working_tree_size: u64 = 0;
        let mut file_sizes: Vec<(String, u64)> = Vec::new();

        let mut builder = WalkBuilder::new(root);
        configure_walker(&mut builder).filter_entry({
            let void_dir_name = void_dir_name.clone();
            move |entry| {
                let name = entry.file_name().to_string_lossy();
                name != void_dir_name
                    && name != ".git"
                    && name != "node_modules"
                    && name != ".DS_Store"
            }
        });

        for entry in builder.build().flatten() {
            if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
                continue;
            }

            let path = entry.path();
            let size = fs::metadata(path).map(|m| m.len()).unwrap_or(0);

            working_tree_size += size;

            // Track for largest files
            let rel_path = path
                .strip_prefix(root)
                .map(|p| p.to_string_lossy().replace('\\', "/"))
                .unwrap_or_else(|_| path.to_string_lossy().to_string());
            file_sizes.push((rel_path, size));
        }

        // Sort by size descending and take top N
        file_sizes.sort_by(|a, b| b.1.cmp(&a.1));
        file_sizes.truncate(args.top);

        let largest_files: Vec<LargeFile> = file_sizes
            .into_iter()
            .map(|(path, bytes)| LargeFile { path, bytes })
            .collect();

        let total = void_total + working_tree_size;

        // Print human-readable output
        if !ctx.use_json() {
            ctx.info("Repository size:");
            ctx.info(format!("  .void directory: {} bytes", void_total));
            ctx.info(format!("    objects:       {} bytes", objects_size));
            ctx.info(format!("    index:         {} bytes", index_size));
            ctx.info(format!("  Working tree:    {} bytes", working_tree_size));
            ctx.info(format!("  Total:           {} bytes", total));
            ctx.info("");
            ctx.info(format!("Top {} largest files:", args.top));
            for file in &largest_files {
                ctx.info(format!("  {:>12} bytes  {}", file.bytes, file.path));
            }
        }

        Ok(SizeOutput {
            void_dir: VoidDirSize {
                total: void_total,
                objects: objects_size,
                index: index_size,
            },
            working_tree: working_tree_size,
            total,
            largest_files,
        })
    })
}

/// Run `repo info` command.
pub fn run_info(cwd: &Path, opts: &CliOptions) -> Result<(), CliError> {
    run_command("repo info", opts, |ctx| {
        ctx.progress("Loading repository info...");

        let repo = open_repo(cwd)?;
        let void_dir = repo.void_dir();

        // Get root path
        let root = repo.root().to_string();

        // Read HEAD
        let head_ref = refs::read_head(void_dir).map_err(void_err_to_cli)?;

        let (ref_name, head_cid_opt) = match head_ref {
            Some(refs::HeadRef::Symbolic(branch)) => {
                let commit_cid = refs::read_branch(void_dir, &branch)
                    .map_err(void_err_to_cli)?;
                (Some(branch), commit_cid)
            }
            Some(refs::HeadRef::Detached(commit_cid)) => (None, Some(commit_cid)),
            None => (None, None),
        };

        let has_head = head_cid_opt.is_some();
        let head_cid = head_cid_opt.and_then(|c| {
            cid::from_bytes(c.as_bytes())
                .map(|v| v.to_string())
                .ok()
        });

        // Count commits by walking history
        let mut commits: u64 = 0;
        if has_head {
            commits = count_commits(repo.context())?;
        }

        // List remotes from config
        let cfg =
            config::load(void_dir.as_std_path()).map_err(|e| CliError::internal(e.to_string()))?;
        let mut remotes: Vec<String> = cfg.remote.keys().cloned().collect();
        remotes.sort();

        let repo_name = cfg.repo_name.clone();

        // Print human-readable output
        if !ctx.use_json() {
            if let Some(name) = &repo_name {
                ctx.info(format!("Repository: {}", name));
            }
            ctx.info(format!("Repository root: {}", root));
            ctx.info(format!(
                "HEAD: {} ({})",
                ref_name.as_deref().unwrap_or("(detached)"),
                head_cid.as_deref().unwrap_or("(no commits)")
            ));
            ctx.info(format!("Commits: {}", commits));
            if remotes.is_empty() {
                ctx.info("Remotes: (none)");
            } else {
                ctx.info(format!("Remotes: {}", remotes.join(", ")));
            }
        }

        Ok(InfoOutput {
            name: repo_name,
            root,
            head: HeadInfo {
                ref_name,
                cid: head_cid,
            },
            commits,
            remotes,
        })
    })
}

/// Run `repo list` command.
pub fn run_list(verbose: bool, opts: &CliOptions) -> Result<(), CliError> {
    run_command("repo list", opts, |ctx| {
        ctx.progress("Loading registry...");

        let records = registry::list_records()
            .map_err(|e| CliError::internal(format!("failed to load registry: {}", e)))?;

        if records.is_empty() {
            if !ctx.use_json() {
                ctx.info("No repositories registered.");
                ctx.info("Run 'void init' in a directory to register a repo.");
            }
            return Ok(RepoListOutput {
                repos: Vec::new(),
                count: 0,
            });
        }

        let entries: Vec<RepoListEntry> = records
            .iter()
            .map(|r| RepoListEntry {
                id: r.id.clone(),
                name: r.name.clone(),
                origin: r.origin.clone(),
                description: r.description.clone(),
                branches: r.head.keys().cloned().collect(),
                local_paths: r
                    .local_paths
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect(),
                created: r.created.clone(),
                updated: r.updated.clone(),
            })
            .collect();

        let count = entries.len();

        if !ctx.use_json() {
            let use_colors = std::io::stderr().is_terminal();
            let bold = if use_colors { "\x1b[1m" } else { "" };
            let dim = if use_colors { "\x1b[2m" } else { "" };
            let reset = if use_colors { "\x1b[0m" } else { "" };

            for entry in &entries {
                let short_id = if entry.id.len() > 8 {
                    &entry.id[..8]
                } else {
                    &entry.id
                };
                ctx.info(format!(
                    "{}{}{} {}{}{}",
                    bold, entry.name, reset, dim, short_id, reset
                ));

                if verbose {
                    ctx.info(format!("  Origin: {}", entry.origin));
                    if !entry.branches.is_empty() {
                        ctx.info(format!("  Branches: {}", entry.branches.join(", ")));
                    }
                    for path in &entry.local_paths {
                        ctx.info(format!("  Path: {}", path));
                    }
                    if let Some(ref desc) = entry.description {
                        ctx.info(format!("  Description: {}", desc));
                    }
                    ctx.info("");
                }
            }

            ctx.info(format!("{}{} repo(s) registered{}", dim, count, reset));
        }

        Ok(RepoListOutput {
            repos: entries,
            count,
        })
    })
}

/// Run `repo registry` command.
pub fn run_registry(target: &str, opts: &CliOptions) -> Result<(), CliError> {
    run_command("repo registry", opts, |ctx| {
        ctx.progress(format!("Looking up '{}'...", target));

        let record = registry::resolve_target_interactive(target).map_err(|e| CliError::not_found(e))?;

        if !ctx.use_json() {
            ctx.info(format!("Name:    {}", record.name));
            ctx.info(format!("ID:      {}", record.id));
            ctx.info(format!("Origin:  {}", record.origin));
            if let Some(ref desc) = record.description {
                ctx.info(format!("Desc:    {}", desc));
            }
            ctx.info(format!("Created: {}", record.created));
            ctx.info(format!("Updated: {}", record.updated));

            if !record.head.is_empty() {
                ctx.info("");
                ctx.info("Branches:");
                for (branch, cid_val) in &record.head {
                    let short_cid = if cid_val.len() > 16 {
                        &cid_val[..16]
                    } else {
                        cid_val
                    };
                    ctx.info(format!("  {} -> {}...", branch, short_cid));
                }
            }

            if !record.trusted_sources.is_empty() {
                ctx.info("");
                ctx.info("Trusted sources:");
                for src in &record.trusted_sources {
                    let short = if src.len() > 16 { &src[..16] } else { src };
                    ctx.info(format!("  {}...", short));
                }
            }

            if !record.local_paths.is_empty() {
                ctx.info("");
                ctx.info("Local paths:");
                for p in &record.local_paths {
                    let exists = p.join(".void").exists();
                    let marker = if exists { "" } else { " (missing)" };
                    ctx.info(format!("  {}{}", p.display(), marker));
                }
            }


        }

        Ok(RepoRegistryOutput {
            id: record.id,
            name: record.name,
            origin: record.origin,
            description: record.description,
            head: record.head,
            trusted_sources: record.trusted_sources,
            local_paths: record
                .local_paths
                .iter()
                .map(|p| p.display().to_string())
                .collect(),
            key_ref: record.key_ref,
            created: record.created,
            updated: record.updated,
        })
    })
}

/// Run `repo unregister` command.
pub fn run_unregister(target: &str, opts: &CliOptions) -> Result<(), CliError> {
    run_command("repo unregister", opts, |ctx| {
        ctx.progress(format!("Looking up '{}'...", target));

        let record = registry::resolve_target_interactive(target).map_err(|e| CliError::not_found(e))?;

        let id = record.id.clone();
        let name = record.name.clone();

        ctx.progress(format!("Removing '{}' from registry...", name));

        registry::delete_record(&id)
            .map_err(|e| CliError::internal(format!("failed to delete registry record: {}", e)))?;

        if !ctx.use_json() {
            ctx.info(format!(
                "Unregistered repo '{}' ({})",
                name,
                &id[..8.min(id.len())]
            ));
        }

        Ok(RepoUnregisterOutput {
            id,
            name,
            removed: true,
        })
    })
}

/// Calculate the total size of a directory recursively.
fn dir_size(path: &Path) -> u64 {
    if !path.exists() {
        return 0;
    }

    let mut size: u64 = 0;

    if path.is_file() {
        return fs::metadata(path).map(|m| m.len()).unwrap_or(0);
    }

    for entry in fs::read_dir(path).into_iter().flatten().flatten() {
        let entry_path = entry.path();
        if entry_path.is_dir() {
            size += dir_size(&entry_path);
        } else {
            size += fs::metadata(&entry_path).map(|m| m.len()).unwrap_or(0);
        }
    }

    size
}

/// Count commits by walking the commit history.
fn count_commits(ctx: &void_core::VoidContext) -> Result<u64, CliError> {
    use void_core::{
        crypto::{CommitReader, EncryptedCommit},
        metadata::Commit,
        store::ObjectStoreExt,
    };

    let head_cid = refs::resolve_head(&ctx.paths.void_dir).map_err(void_err_to_cli)?;

    let head_cid = match head_cid {
        Some(cid) => cid,
        None => return Ok(0),
    };

    let store = ctx.open_store().map_err(void_err_to_cli)?;

    let mut count: u64 = 0;
    let mut current_cid: Option<Vec<u8>> = Some(head_cid.into_bytes());

    while let Some(cid_bytes) = current_cid.take() {
        count += 1;

        let cid_obj = cid::from_bytes(&cid_bytes)
            .map_err(|e| CliError::internal(format!("invalid CID: {e}")))?;

        let encrypted: EncryptedCommit = match store.get_blob(&cid_obj) {
            Ok(data) => data,
            Err(_) => break, // Can't read commit, stop counting
        };

        let (commit_bytes, _reader) = CommitReader::open_with_vault(&ctx.crypto.vault, &encrypted)
            .map_err(|e| CliError::internal(format!("failed to open commit: {e}")))?;
        let commit: Commit = commit_bytes.parse()
            .map_err(|e| CliError::internal(format!("failed to parse commit: {e}")))?;

        current_cid = commit.first_parent().map(|p| p.as_bytes().to_vec());
    }

    Ok(count)
}

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

    #[test]
    fn test_code_extensions() {
        assert!(is_code_extension("rs"));
        assert!(is_code_extension("ts"));
        assert!(is_code_extension("py"));
        assert!(is_code_extension("go"));
        assert!(!is_code_extension("exe"));
        assert!(!is_code_extension("dll"));
        assert!(!is_code_extension("bin"));
    }

    #[test]
    fn test_extension_stats_serialization() {
        let stats = ExtensionStats {
            extension: ".rs".to_string(),
            lines: 5000,
            files: 50,
            bytes: 150000,
            percent: 45.5,
        };

        let json = serde_json::to_string(&stats).unwrap();
        assert!(json.contains("\"extension\":\".rs\""));
        assert!(json.contains("\"lines\":5000"));
        assert!(json.contains("\"files\":50"));
        assert!(json.contains("\"bytes\":150000"));
        assert!(json.contains("\"percent\":45.5"));
    }

    #[test]
    fn test_stat_output_serialization() {
        let output = StatOutput {
            stats: vec![ExtensionStats {
                extension: ".rs".to_string(),
                lines: 1000,
                files: 10,
                bytes: 50000,
                percent: 50.0,
            }],
            total: TotalStats {
                lines: 2000,
                files: 20,
                bytes: 100000,
            },
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"stats\""));
        assert!(json.contains("\"total\""));
    }

    #[test]
    fn test_size_output_serialization() {
        let output = SizeOutput {
            void_dir: VoidDirSize {
                total: 1048576,
                objects: 1000000,
                index: 48576,
            },
            working_tree: 500000,
            total: 1548576,
            largest_files: vec![LargeFile {
                path: "big.bin".to_string(),
                bytes: 100000,
            }],
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"voidDir\""));
        assert!(json.contains("\"workingTree\":500000"));
        assert!(json.contains("\"largestFiles\""));
    }

    #[test]
    fn test_info_output_serialization() {
        let output = InfoOutput {
            name: Some("my-repo".to_string()),
            root: "/path/to/repo".to_string(),
            head: HeadInfo {
                ref_name: Some("trunk".to_string()),
                cid: Some("bafy123".to_string()),
            },
            commits: 42,
            remotes: vec!["origin".to_string()],
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"name\":\"my-repo\""));
        assert!(json.contains("\"root\":\"/path/to/repo\""));
        assert!(json.contains("\"ref\":\"trunk\""));
        assert!(json.contains("\"cid\":\"bafy123\""));
        assert!(json.contains("\"commits\":42"));
        assert!(json.contains("\"remotes\":[\"origin\"]"));
    }
}