zub-store 0.0.3

Git-like content-addressed filesystem store with metadata preservation
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
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
//! zubCLI - git-like object tree command line interface

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};

use std::io::{self, Write};

use zub::ops::{
    checkout, commit, diff, fsck, gc, log, ls_tree, ls_tree_recursive, map, union_checkout,
    union_trees, CheckoutOptions, ConflictResolution, MapOptions, UnionCheckoutOptions,
    UnionOptions,
};
use zub::transport::{pull_local, push_local, PullOptions, PushOptions};
use zub::{read_blob, read_commit, read_tree, Hash, Repo};

#[derive(Parser)]
#[command(name = "zub")]
#[command(about = "git-like object tree - content-addressed filesystem store")]
#[command(version)]
struct Cli {
    /// repository path (default: ZUB_REPO env, .zub symlink/dir, or current directory)
    #[arg(short, long, env = "ZUB_REPO")]
    repo: Option<PathBuf>,

    #[command(subcommand)]
    command: Commands,
}

/// resolve the repository path from CLI arg, .zub symlink, or .zub directory
fn resolve_repo_path(repo_arg: Option<PathBuf>) -> PathBuf {
    if let Some(path) = repo_arg {
        return path;
    }

    let zub_path = Path::new(".zub");

    // check for .zub symlink
    if zub_path.is_symlink() {
        if let Ok(target) = std::fs::read_link(zub_path) {
            return target;
        }
    }

    // check for .zub directory
    if zub_path.is_dir() {
        return zub_path.to_path_buf();
    }

    // default to current directory
    PathBuf::from(".")
}

#[derive(Subcommand)]
enum Commands {
    /// initialize a new repository
    Init {
        /// path to create repository at
        #[arg(default_value = ".")]
        path: PathBuf,
    },

    /// commit a directory to a ref
    Commit {
        /// source directory to commit
        source: PathBuf,

        /// ref name to commit to
        #[arg(short = 'r', long)]
        ref_name: String,

        /// commit message
        #[arg(short, long)]
        message: Option<String>,

        /// author name
        #[arg(short, long)]
        author: Option<String>,
    },

    /// checkout a ref to a directory
    Checkout {
        /// ref to checkout
        ref_name: String,

        /// destination directory
        destination: PathBuf,

        /// use copy instead of hardlinks
        #[arg(long)]
        copy: bool,

        /// preserve sparse file holes
        #[arg(long)]
        sparse: bool,
    },

    /// show commit log for a ref
    Log {
        /// ref to show log for
        ref_name: String,

        /// maximum number of commits to show
        #[arg(short = 'n', long)]
        max_count: Option<usize>,
    },

    /// list tree contents
    LsTree {
        /// ref to list
        ref_name: String,

        /// path within tree
        #[arg(short, long)]
        path: Option<PathBuf>,

        /// list recursively
        #[arg(short, long)]
        recursive: bool,
    },

    /// show differences between two refs
    Diff {
        /// first ref
        ref1: String,

        /// second ref
        ref2: String,
    },

    /// merge multiple refs into one
    Union {
        /// refs to merge
        #[arg(required = true)]
        refs: Vec<String>,

        /// output ref name
        #[arg(short, long)]
        output: String,

        /// conflict resolution: error, first, last
        #[arg(long, default_value = "error")]
        on_conflict: String,

        /// commit message
        #[arg(short, long)]
        message: Option<String>,
    },

    /// checkout union of multiple refs
    UnionCheckout {
        /// refs to merge
        #[arg(required = true)]
        refs: Vec<String>,

        /// destination directory
        #[arg(short, long)]
        destination: PathBuf,

        /// conflict resolution: error, first, last
        #[arg(long, default_value = "error")]
        on_conflict: String,

        /// use copy instead of hardlinks
        #[arg(long)]
        copy: bool,
    },

    /// verify repository integrity
    Fsck,

    /// garbage collect unreachable objects
    Gc {
        /// only show what would be removed
        #[arg(long)]
        dry_run: bool,
    },

    /// show repository statistics
    Stats,

    /// show disk usage per ref
    Du {
        /// optional glob pattern to filter refs (e.g. "x86_64/pkg/*/neovim/*")
        pattern: Option<String>,

        /// number of top refs to show (default: 20)
        #[arg(short, long, default_value = "20")]
        limit: usize,
    },

    /// truncate history, keeping only latest commit per ref
    TruncateHistory {
        /// only show what would be done
        #[arg(long)]
        dry_run: bool,
    },

    /// remap blob ownership to current user namespace
    Remap {
        /// skip blobs that can't be remapped instead of erroring
        #[arg(long)]
        force: bool,

        /// only show what would be done
        #[arg(long)]
        dry_run: bool,
    },

    /// push a ref to another repository
    Push {
        /// destination repository path
        destination: PathBuf,

        /// ref to push
        ref_name: String,

        /// force non-fast-forward update
        #[arg(short, long)]
        force: bool,

        /// dry run - show what would be transferred without doing it
        #[arg(long)]
        dry_run: bool,
    },

    /// pull a ref from another repository
    Pull {
        /// source repository path
        source: PathBuf,

        /// ref to pull
        ref_name: String,

        /// only fetch objects, don't update ref
        #[arg(long)]
        fetch_only: bool,

        /// dry run - show what would be transferred without doing it
        #[arg(long)]
        dry_run: bool,
    },

    /// list refs
    Refs,

    /// show ref hash
    ShowRef {
        /// ref name
        ref_name: String,
    },

    /// delete a ref
    DeleteRef {
        /// ref name
        ref_name: String,
    },

    /// delete refs matching a glob pattern
    DeleteRefs {
        /// glob pattern (e.g. "x86_64/pkg/*/neovim/*")
        pattern: String,
    },

    /// show contents of an object
    CatFile {
        /// object type (blob, tree, commit)
        object_type: String,

        /// object hash
        object: String,
    },

    /// resolve a ref to a hash
    RevParse {
        /// ref or hash to resolve
        rev: String,

        /// output short hash (first 12 chars)
        #[arg(long)]
        short: bool,
    },

    /// show commit information
    Show {
        /// ref or commit hash to show
        rev: String,

        /// print specific metadata key
        #[arg(long = "print-metadata-key")]
        metadata_key: Option<String>,
    },

    /// remote helper (used by SSH transport)
    #[command(name = "zub-remote")]
    Remote {
        /// repository path
        path: PathBuf,
    },
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    if let Err(e) = run(cli) {
        eprintln!("error: {}", e);
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

fn run(cli: Cli) -> zub::Result<()> {
    let repo_path = resolve_repo_path(cli.repo);

    match cli.command {
        Commands::Init { path } => {
            Repo::init(&path)?;
            println!("initialized zub repository at {}", path.display());
        }

        Commands::Commit {
            source,
            ref_name,
            message,
            author,
        } => {
            let repo = Repo::open(&repo_path)?;
            let hash = commit(
                &repo,
                &source,
                &ref_name,
                message.as_deref(),
                author.as_deref(),
            )?;
            println!("{}", hash);
        }

        Commands::Checkout {
            ref_name,
            destination,
            copy,
            sparse,
        } => {
            let repo = Repo::open(&repo_path)?;
            let options = CheckoutOptions {
                force: false,
                hardlink: !copy,
                preserve_sparse: sparse,
            };
            checkout(&repo, &ref_name, &destination, options)?;
            println!("checked out {} to {}", ref_name, destination.display());
        }

        Commands::Log {
            ref_name,
            max_count,
        } => {
            let repo = Repo::open(&repo_path)?;
            let entries = log(&repo, &ref_name, max_count)?;

            for entry in entries {
                println!("{}", entry);
            }
        }

        Commands::LsTree {
            ref_name,
            path,
            recursive,
        } => {
            let repo = Repo::open(&repo_path)?;

            let entries = if recursive {
                ls_tree_recursive(&repo, &ref_name)?
            } else {
                ls_tree(&repo, &ref_name, path.as_deref())?
            };

            for entry in entries {
                println!("{}", entry);
            }
        }

        Commands::Diff { ref1, ref2 } => {
            let repo = Repo::open(&repo_path)?;
            let changes = diff(&repo, &ref1, &ref2)?;

            for change in changes {
                let prefix = match change.kind {
                    zub::ChangeKind::Added => "+",
                    zub::ChangeKind::Deleted => "-",
                    zub::ChangeKind::Modified => "M",
                    zub::ChangeKind::MetadataOnly => "m",
                };
                println!("{} {}", prefix, change.path);
            }
        }

        Commands::Union {
            refs,
            output,
            on_conflict,
            message,
        } => {
            let repo = Repo::open(&repo_path)?;
            let resolution = parse_conflict_resolution(&on_conflict)?;
            let ref_strs: Vec<&str> = refs.iter().map(|s| s.as_str()).collect();

            let opts = UnionOptions {
                message,
                author: None,
                on_conflict: resolution,
            };
            let hash = union_trees(&repo, &ref_strs, &output, opts)?;
            println!("{}", hash);
        }

        Commands::UnionCheckout {
            refs,
            destination,
            on_conflict,
            copy,
        } => {
            let repo = Repo::open(&repo_path)?;
            let resolution = parse_conflict_resolution(&on_conflict)?;
            let ref_strs: Vec<&str> = refs.iter().map(|s| s.as_str()).collect();

            let options = UnionCheckoutOptions {
                force: false,
                on_conflict: resolution,
                hardlink: !copy,
            };
            union_checkout(&repo, &ref_strs, &destination, options)?;
            println!(
                "checked out union of {} refs to {}",
                refs.len(),
                destination.display()
            );
        }

        Commands::Fsck => {
            let repo = Repo::open(&repo_path)?;
            let report = fsck(&repo)?;

            println!("objects checked: {}", report.objects_checked);

            if !report.corrupt_objects.is_empty() {
                println!("\ncorrupt objects:");
                for obj in &report.corrupt_objects {
                    println!("  {} {}: {}", obj.object_type, obj.hash, obj.message);
                }
            }

            if !report.missing_objects.is_empty() {
                println!("\nmissing objects:");
                for obj in &report.missing_objects {
                    println!(
                        "  {} {} (referenced by {})",
                        obj.object_type, obj.hash, obj.referenced_by
                    );
                }
            }

            if !report.dangling_objects.is_empty() {
                println!("\ndangling objects: {}", report.dangling_objects.len());
            }

            if report.is_ok() {
                println!("\nrepository is healthy");
            } else {
                println!("\nrepository has issues");
                return Err(zub::Error::CorruptObjectMessage(
                    "repository integrity check failed".to_string(),
                ));
            }
        }

        Commands::Gc { dry_run } => {
            let repo = Repo::open(&repo_path)?;
            let stats = gc(&repo, dry_run)?;

            let action = if dry_run { "would remove" } else { "removed" };
            println!(
                "{} {} blobs, {} trees, {} commits",
                action, stats.blobs_removed, stats.trees_removed, stats.commits_removed
            );
            println!("freed {} bytes", stats.bytes_freed);
        }

        Commands::Stats => {
            let repo = Repo::open(&repo_path)?;
            let s = zub::stats(&repo)?;

            println!("refs: {}", s.total_refs);
            println!();
            println!("objects:");
            println!(
                "  blobs:   {:>8} total, {:>8} reachable ({:.1} MB on disk)",
                s.total_blobs,
                s.reachable_blobs,
                s.total_blobs_bytes as f64 / 1_000_000.0
            );
            println!(
                "  trees:   {:>8} total, {:>8} reachable ({:.1} MB on disk)",
                s.total_trees,
                s.reachable_trees,
                s.total_trees_bytes as f64 / 1_000_000.0
            );
            println!(
                "  commits: {:>8} total, {:>8} reachable ({:.1} MB on disk)",
                s.total_commits,
                s.reachable_commits,
                s.total_commits_bytes as f64 / 1_000_000.0
            );
            println!();
            if s.unreachable_blobs_bytes > 0 {
                println!(
                    "unreachable blob data: {:.1} MB (run gc to free)",
                    s.unreachable_blobs_bytes as f64 / 1_000_000.0
                );
            }
        }

        Commands::Du { pattern, limit } => {
            let repo = Repo::open(&repo_path)?;
            let sizes = zub::du(&repo, pattern.as_deref())?;

            for entry in sizes.iter().take(limit) {
                let mb = entry.bytes as f64 / 1_000_000.0;
                println!("{:>10.1} MB  {}", mb, entry.ref_name);
            }

            if sizes.len() > limit {
                println!("... and {} more refs", sizes.len() - limit);
            }
        }

        Commands::TruncateHistory { dry_run } => {
            let repo = Repo::open(&repo_path)?;
            let stats = zub::truncate_history(&repo, dry_run)?;

            let action = if dry_run {
                "would truncate"
            } else {
                "truncated"
            };
            println!(
                "{} {}/{} refs",
                action, stats.refs_truncated, stats.refs_processed
            );
            if !dry_run && stats.refs_truncated > 0 {
                println!("run gc to free unreachable objects");
            }
        }

        Commands::Remap { force, dry_run } => {
            let mut repo = Repo::open(&repo_path)?;
            let options = MapOptions { force, dry_run };
            let stats = map(&mut repo, &options)?;

            if stats.total == 0 && stats.remapped == 0 {
                println!("namespace mappings match, nothing to do");
            } else {
                let action = if dry_run { "would remap" } else { "remapped" };
                println!("{} {} of {} blobs", action, stats.remapped, stats.total);
                if stats.skipped_unmapped_source > 0 {
                    println!(
                        "skipped {} blobs (uid/gid not in source namespace)",
                        stats.skipped_unmapped_source
                    );
                }
                if stats.skipped_unmapped_target > 0 {
                    println!(
                        "skipped {} blobs (uid/gid not mappable to current namespace)",
                        stats.skipped_unmapped_target
                    );
                }
            }
        }

        Commands::Push {
            destination,
            ref_name,
            force,
            dry_run,
        } => {
            let src = Repo::open(&repo_path)?;
            let dst = Repo::open(&destination)?;

            let options = PushOptions { force, dry_run };
            let result = push_local(&src, &dst, &ref_name, &options)?;

            if dry_run {
                println!("would push {} to {}", result.hash, destination.display());
                println!("would transfer {} objects", result.objects_to_transfer);
            } else {
                println!("pushed {} to {}", result.hash, destination.display());
                println!(
                    "transferred: {} copied, {} hardlinked, {} skipped, {} bytes",
                    result.stats.copied,
                    result.stats.hardlinked,
                    result.stats.skipped,
                    result.stats.bytes_transferred
                );
            }
        }

        Commands::Pull {
            source,
            ref_name,
            fetch_only,
            dry_run,
        } => {
            let src = Repo::open(&source)?;
            let dst = Repo::open(&repo_path)?;

            let options = PullOptions {
                fetch_only,
                dry_run,
            };
            let result = pull_local(&src, &dst, &ref_name, &options)?;

            if dry_run {
                println!("would pull {} from {}", result.hash, source.display());
                println!("would transfer {} objects", result.objects_to_transfer);
            } else {
                println!("pulled {} from {}", result.hash, source.display());
                println!(
                    "transferred: {} copied, {} hardlinked, {} skipped, {} bytes",
                    result.stats.copied,
                    result.stats.hardlinked,
                    result.stats.skipped,
                    result.stats.bytes_transferred
                );
            }
        }

        Commands::Refs => {
            let repo = Repo::open(&repo_path)?;
            let refs = zub::list_refs(&repo)?;

            for ref_name in refs {
                let hash = zub::read_ref(&repo, &ref_name)?;
                println!("{} {}", hash, ref_name);
            }
        }

        Commands::ShowRef { ref_name } => {
            let repo = Repo::open(&repo_path)?;
            let hash = zub::resolve_ref(&repo, &ref_name)?;
            println!("{}", hash);
        }

        Commands::DeleteRef { ref_name } => {
            let repo = Repo::open(&repo_path)?;
            zub::delete_ref(&repo, &ref_name)?;
            println!("deleted ref {}", ref_name);
        }

        Commands::DeleteRefs { pattern } => {
            let repo = Repo::open(&repo_path)?;
            let deleted = zub::delete_refs_matching(&repo, &pattern)?;
            if deleted.is_empty() {
                println!("no refs matched pattern {}", pattern);
            } else {
                for r in deleted {
                    println!("deleted ref {}", r);
                }
            }
        }

        Commands::CatFile {
            object_type,
            object,
        } => {
            let repo = Repo::open(&repo_path)?;
            let hash = Hash::from_hex(&object)?;

            match object_type.as_str() {
                "blob" => {
                    let data = read_blob(&repo, &hash)?;
                    io::stdout().write_all(&data).map_err(|e| zub::Error::Io {
                        path: "stdout".into(),
                        source: e,
                    })?;
                }
                "tree" => {
                    let tree = read_tree(&repo, &hash)?;
                    for entry in tree.entries() {
                        println!("{} {}", entry.kind.type_name(), entry.name);
                    }
                }
                "commit" => {
                    let commit = read_commit(&repo, &hash)?;
                    println!("tree {}", commit.tree);
                    for parent in &commit.parents {
                        println!("parent {}", parent);
                    }
                    println!("author {}", commit.author);
                    println!("timestamp {}", commit.timestamp);
                    println!();
                    println!("{}", commit.message);
                }
                _ => {
                    return Err(zub::Error::InvalidObjectType(object_type));
                }
            }
        }

        Commands::RevParse { rev, short } => {
            let repo = Repo::open(&repo_path)?;
            let hash = zub::resolve_ref(&repo, &rev)?;
            if short {
                println!("{}", &hash.to_hex()[..12]);
            } else {
                println!("{}", hash);
            }
        }

        Commands::Show { rev, metadata_key } => {
            let repo = Repo::open(&repo_path)?;
            let hash = zub::resolve_ref(&repo, &rev)?;
            let commit = read_commit(&repo, &hash)?;

            match metadata_key {
                Some(key) => {
                    // print specific metadata key
                    match commit.metadata.get(&key) {
                        Some(value) => println!("{}", value),
                        None => {
                            return Err(zub::Error::MetadataKeyNotFound(key));
                        }
                    }
                }
                None => {
                    // print full commit info
                    println!("commit {}", hash);
                    println!("tree {}", commit.tree);
                    for parent in &commit.parents {
                        println!("parent {}", parent);
                    }
                    println!("author {}", commit.author);
                    println!("timestamp {}", commit.timestamp);
                    if !commit.metadata.is_empty() {
                        println!();
                        println!("metadata:");
                        for (k, v) in &commit.metadata {
                            println!("  {}: {}", k, v);
                        }
                    }
                    println!();
                    println!("{}", commit.message);
                }
            }
        }

        Commands::Remote { path } => {
            run_remote_helper(&path)?;
        }
    }

    Ok(())
}

fn parse_conflict_resolution(s: &str) -> zub::Result<ConflictResolution> {
    match s.to_lowercase().as_str() {
        "error" => Ok(ConflictResolution::Error),
        "first" => Ok(ConflictResolution::First),
        "last" => Ok(ConflictResolution::Last),
        _ => Err(zub::Error::InvalidConflictResolution(s.to_string())),
    }
}

/// run the remote helper protocol (server side of SSH transport)
fn run_remote_helper(repo_path: &Path) -> zub::Result<()> {
    let repo = Repo::open(repo_path)?;
    zub::transport::serve_remote(&repo)
}