lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Global BranchManager API.
//!
//! This module provides a unified interface for all branch operations,
//! combining registry, commits, merging, and cherry-picking.

use alloc::string::{String, ToString};
use alloc::vec::Vec;

use super::cherrypick::{CherryPickOptions, CherryPickResult, CherryPicker};
use super::commit::{CommitBuilder, CommitStore, CommitValidator};
use super::log::{BranchStats, LogOptions, LogViewer};
use super::merge::{FileStateProvider, MergeAnalysis, ThreeWayMerge};
use super::ops::{BranchOps, BranchStatus, DatasetProvider};
use super::registry::BranchRegistry;
use super::types::{Branch, BranchError, Commit, FileChange, MergeResult, MergeStrategy};

// ═══════════════════════════════════════════════════════════════════════════════
// BRANCH MANAGER
// ═══════════════════════════════════════════════════════════════════════════════

/// Unified branch management interface.
///
/// The BranchManager provides a single entry point for all git-style
/// branching operations in LCPFS.
pub struct BranchManager<P>
where
    P: DatasetProvider + FileStateProvider,
{
    /// Dataset and file state provider.
    provider: P,
    /// Branch registry.
    registry: BranchRegistry,
    /// Commit store.
    commits: CommitStore,
    /// Default author for commits.
    default_author: String,
}

impl<P> BranchManager<P>
where
    P: DatasetProvider + FileStateProvider,
{
    /// Create a new branch manager.
    pub fn new(provider: P, author: impl Into<String>) -> Self {
        let timestamp = provider.current_timestamp();
        Self {
            provider,
            registry: BranchRegistry::new(0, timestamp),
            commits: CommitStore::new(),
            default_author: author.into(),
        }
    }

    /// Create from existing registry and commits.
    pub fn with_state(
        provider: P,
        registry: BranchRegistry,
        commits: CommitStore,
        author: impl Into<String>,
    ) -> Self {
        Self {
            provider,
            registry,
            commits,
            default_author: author.into(),
        }
    }

    /// Get the provider.
    pub fn provider(&self) -> &P {
        &self.provider
    }

    /// Get the provider mutably.
    pub fn provider_mut(&mut self) -> &mut P {
        &mut self.provider
    }

    /// Get the registry.
    pub fn registry(&self) -> &BranchRegistry {
        &self.registry
    }

    /// Get the commit store.
    pub fn commits(&self) -> &CommitStore {
        &self.commits
    }

    /// Set the default author.
    pub fn set_author(&mut self, author: impl Into<String>) {
        self.default_author = author.into();
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // BRANCH OPERATIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get the current branch.
    pub fn current_branch(&self) -> Option<&Branch> {
        self.registry.current_branch()
    }

    /// Get the current branch name.
    pub fn current_branch_name(&self) -> &str {
        self.registry.current()
    }

    /// Get a branch by name.
    pub fn get_branch(&self, name: &str) -> Option<&Branch> {
        self.registry.get(name)
    }

    /// List all branches.
    pub fn list_branches(&self) -> Vec<&Branch> {
        self.registry.list_sorted()
    }

    /// Check if a branch exists.
    pub fn branch_exists(&self, name: &str) -> bool {
        self.registry.contains(name)
    }

    /// Create a new branch from the current branch.
    pub fn create_branch(&mut self, name: &str) -> Result<Branch, BranchError> {
        let mut ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.create_branch(name)?;
        Ok(self.registry.get(name).unwrap().clone())
    }

    /// Create a branch from a specific parent.
    pub fn create_branch_from(&mut self, name: &str, parent: &str) -> Result<Branch, BranchError> {
        let mut ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.create_branch_from(name, parent)?;
        Ok(self.registry.get(name).unwrap().clone())
    }

    /// Switch to a branch.
    pub fn checkout(&mut self, name: &str) -> Result<Branch, BranchError> {
        let mut ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.checkout(name)?;
        Ok(self.registry.get(name).unwrap().clone())
    }

    /// Create and switch to a new branch.
    pub fn checkout_new(&mut self, name: &str) -> Result<Branch, BranchError> {
        let mut ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.checkout_new(name)?;
        Ok(self.registry.get(name).unwrap().clone())
    }

    /// Delete a branch.
    pub fn delete_branch(&mut self, name: &str, force: bool) -> Result<Branch, BranchError> {
        let mut ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.delete_branch(name, force)
    }

    /// Rename a branch.
    pub fn rename_branch(&mut self, old_name: &str, new_name: &str) -> Result<(), BranchError> {
        self.registry.rename(old_name, new_name)
    }

    /// Get branch status.
    pub fn branch_status(&mut self, name: &str) -> Result<BranchStatus, BranchError> {
        let ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.status(name)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // COMMIT OPERATIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Create a commit on the current branch.
    pub fn commit(
        &mut self,
        message: &str,
        changes: Vec<FileChange>,
    ) -> Result<Commit, BranchError> {
        self.commit_with_author(message, &self.default_author.clone(), changes)
    }

    /// Create a commit with a specific author.
    pub fn commit_with_author(
        &mut self,
        message: &str,
        author: &str,
        changes: Vec<FileChange>,
    ) -> Result<Commit, BranchError> {
        // Get current branch info
        let branch = self
            .registry
            .current_branch()
            .ok_or_else(|| BranchError::Internal("no current branch".into()))?;

        let current_name = branch.name.clone();
        let txg = branch.head_txg;
        let timestamp = self.provider.current_timestamp();

        // Get parent commit
        let parent = self.commits.get_head_hash(&current_name);

        // Build commit
        let mut builder = CommitBuilder::new(txg)
            .message(message)
            .author(author)
            .timestamp(timestamp)
            .changes(changes);

        if let Some(p) = parent {
            builder = builder.parent(p);
        }

        let commit = builder.build();

        // Validate
        CommitValidator::validate(&commit)?;

        // Add to store
        self.commits
            .add_commit_to_branch(commit.clone(), &current_name);

        Ok(commit)
    }

    /// Get a commit by hash.
    pub fn get_commit(&self, hash: &[u8; 32]) -> Option<&Commit> {
        self.commits.get(hash)
    }

    /// Get a commit by short hash.
    pub fn get_commit_by_short(&self, short: &str) -> Option<&Commit> {
        self.commits.get_by_short_hash(short)
    }

    /// Get the HEAD commit for a branch.
    pub fn get_head(&self, branch: &str) -> Option<&Commit> {
        self.commits.get_head(branch)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // LOG OPERATIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get log for the current branch.
    pub fn log(&self, options: LogOptions) -> Vec<super::log::LogEntry> {
        let viewer = LogViewer::new(&self.commits);
        viewer.log(self.registry.current(), options).collect()
    }

    /// Get log for a specific branch.
    pub fn log_branch(&self, branch: &str, options: LogOptions) -> Vec<super::log::LogEntry> {
        let viewer = LogViewer::new(&self.commits);
        viewer.log(branch, options).collect()
    }

    /// Get file history.
    pub fn file_history(&self, path: &str) -> Vec<super::log::LogEntry> {
        let viewer = LogViewer::new(&self.commits);
        viewer.file_history(self.registry.current(), path)
    }

    /// Get branch statistics.
    pub fn stats(&self, branch: &str) -> BranchStats {
        let viewer = LogViewer::new(&self.commits);
        viewer.stats(branch)
    }

    /// Get shortlog (commits per author).
    pub fn shortlog(&self, branch: &str) -> Vec<(String, usize)> {
        let viewer = LogViewer::new(&self.commits);
        viewer.shortlog(branch)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // MERGE OPERATIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Merge a branch into the current branch.
    pub fn merge(&mut self, source_branch: &str) -> Result<MergeResult, BranchError> {
        self.merge_with_strategy(source_branch, MergeStrategy::Normal)
    }

    /// Merge with a specific strategy.
    pub fn merge_with_strategy(
        &mut self,
        source_branch: &str,
        strategy: MergeStrategy,
    ) -> Result<MergeResult, BranchError> {
        // Get branch info
        let target = self
            .registry
            .current_branch()
            .ok_or_else(|| BranchError::Internal("no current branch".into()))?;

        let source = self
            .registry
            .get(source_branch)
            .ok_or_else(|| BranchError::BranchNotFound(source_branch.to_string()))?;

        let target_name = target.name.clone();
        let target_txg = target.head_txg;
        let source_txg = source.head_txg;

        // Find merge base
        let base_txg = self
            .registry
            .merge_base_txg(&target_name, source_branch)
            .ok_or(BranchError::NoCommonAncestor)?;

        // Perform three-way merge
        let merger = ThreeWayMerge::new(&self.provider, strategy);
        let analysis = merger.merge(base_txg, target_txg, source_txg)?;

        // Check for conflicts
        if !analysis.is_clean() && strategy == MergeStrategy::Normal {
            return Ok(MergeResult {
                merged_files: 0,
                conflicts: analysis.conflicts,
                result_txg: None,
                merge_commit: None,
            });
        }

        // Create merge commit
        let timestamp = self.provider.current_timestamp();
        let parent = self.commits.get_head_hash(&target_name);
        let new_txg = target_txg + 1;

        let message = alloc::format!("Merge branch '{}' into {}", source_branch, target_name);

        let mut builder = CommitBuilder::new(new_txg)
            .message(message)
            .author(&self.default_author)
            .timestamp(timestamp)
            .changes(analysis.changes.clone());

        if let Some(p) = parent {
            builder = builder.parent(p);
        }

        let commit = builder.build();

        // Update registry and store
        self.registry.update_head(&target_name, new_txg)?;
        self.commits
            .add_commit_to_branch(commit.clone(), &target_name);

        Ok(MergeResult {
            merged_files: analysis.change_count(),
            conflicts: analysis.conflicts,
            result_txg: Some(new_txg),
            merge_commit: Some(commit),
        })
    }

    /// Preview a merge without applying it.
    pub fn merge_preview(&self, source_branch: &str) -> Result<MergeAnalysis, BranchError> {
        let target = self
            .registry
            .current_branch()
            .ok_or_else(|| BranchError::Internal("no current branch".into()))?;

        let source = self
            .registry
            .get(source_branch)
            .ok_or_else(|| BranchError::BranchNotFound(source_branch.to_string()))?;

        let base_txg = self
            .registry
            .merge_base_txg(&target.name, source_branch)
            .ok_or(BranchError::NoCommonAncestor)?;

        let merger = ThreeWayMerge::new(&self.provider, MergeStrategy::Normal);
        merger.merge(base_txg, target.head_txg, source.head_txg)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // CHERRY-PICK OPERATIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Cherry-pick a commit onto the current branch.
    pub fn cherry_pick(&mut self, commit_hash: &[u8; 32]) -> Result<CherryPickResult, BranchError> {
        self.cherry_pick_with_options(commit_hash, &CherryPickOptions::default())
    }

    /// Cherry-pick with options.
    pub fn cherry_pick_with_options(
        &mut self,
        commit_hash: &[u8; 32],
        options: &CherryPickOptions,
    ) -> Result<CherryPickResult, BranchError> {
        let branch = self
            .registry
            .current_branch()
            .ok_or_else(|| BranchError::Internal("no current branch".into()))?;

        let current_txg = branch.head_txg;
        let new_txg = current_txg + 1;
        let branch_name = branch.name.clone();
        let timestamp = self.provider.current_timestamp();

        let picker = CherryPicker::new(&self.provider, &self.commits);
        let result = picker.cherry_pick(
            commit_hash,
            current_txg,
            new_txg,
            &self.default_author,
            timestamp,
            options,
        )?;

        // If successful, update state
        if result.is_success() {
            if let Some(ref commit) = result.new_commit {
                self.registry.update_head(&branch_name, new_txg)?;
                self.commits
                    .add_commit_to_branch(commit.clone(), &branch_name);
            }
        }

        Ok(result)
    }

    /// Cherry-pick multiple commits.
    pub fn cherry_pick_range(
        &mut self,
        commit_hashes: &[[u8; 32]],
        options: &CherryPickOptions,
    ) -> Result<Vec<CherryPickResult>, BranchError> {
        let branch = self
            .registry
            .current_branch()
            .ok_or_else(|| BranchError::Internal("no current branch".into()))?;

        let start_txg = branch.head_txg;
        let branch_name = branch.name.clone();
        let timestamp = self.provider.current_timestamp();

        let picker = CherryPicker::new(&self.provider, &self.commits);
        let results = picker.cherry_pick_range(
            commit_hashes,
            start_txg,
            &self.default_author,
            timestamp,
            options,
        )?;

        // Update state for successful cherry-picks
        let mut max_txg = start_txg;
        for result in &results {
            if result.is_success() {
                if let Some(ref commit) = result.new_commit {
                    max_txg = commit.txg;
                    self.commits
                        .add_commit_to_branch(commit.clone(), &branch_name);
                }
            }
        }

        if max_txg > start_txg {
            self.registry.update_head(&branch_name, max_txg)?;
        }

        Ok(results)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // SYNC OPERATIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Sync the current branch.
    pub fn sync(&mut self) -> Result<u64, BranchError> {
        let mut ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.sync_current()
    }

    /// Sync a specific branch.
    pub fn sync_branch(&mut self, name: &str) -> Result<u64, BranchError> {
        let mut ops = BranchOps::new(&mut self.provider, &mut self.registry);
        ops.sync_branch(name)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::super::merge::FileInfo;
    use super::*;
    use alloc::collections::BTreeMap;

    use alloc::vec;

    /// Combined mock provider.
    struct MockProvider {
        next_guid: u64,
        active_guid: Option<u64>,
        datasets: Vec<u64>,
        txg_map: BTreeMap<u64, u64>,
        file_states: BTreeMap<u64, BTreeMap<String, FileInfo>>,
    }

    impl MockProvider {
        fn new() -> Self {
            let mut provider = Self {
                next_guid: 2,
                active_guid: Some(1),
                datasets: vec![1],
                txg_map: BTreeMap::new(),
                file_states: BTreeMap::new(),
            };
            provider.txg_map.insert(1, 0);
            provider.file_states.insert(0, BTreeMap::new());
            provider
        }

        fn add_file(&mut self, txg: u64, path: &str, checksum: [u64; 4], size: u64) {
            let state = self.file_states.entry(txg).or_default();
            state.insert(
                path.to_string(),
                FileInfo {
                    path: path.to_string(),
                    size,
                    checksum,
                    mtime: txg * 1000,
                    is_dir: false,
                },
            );
        }
    }

    impl DatasetProvider for MockProvider {
        fn clone_dataset(
            &mut self,
            _source_guid: u64,
            _name: &str,
            at_txg: u64,
        ) -> Result<u64, String> {
            let guid = self.next_guid;
            self.next_guid += 1;
            self.datasets.push(guid);
            self.txg_map.insert(guid, at_txg);
            Ok(guid)
        }

        fn delete_dataset(&mut self, guid: u64) -> Result<(), String> {
            self.datasets.retain(|&g| g != guid);
            self.txg_map.remove(&guid);
            Ok(())
        }

        fn activate_dataset(&mut self, guid: u64) -> Result<(), String> {
            if self.datasets.contains(&guid) {
                self.active_guid = Some(guid);
                Ok(())
            } else {
                Err("dataset not found".into())
            }
        }

        fn get_dataset_txg(&self, guid: u64) -> Result<u64, String> {
            self.txg_map
                .get(&guid)
                .copied()
                .ok_or_else(|| "dataset not found".into())
        }

        fn sync_dataset(&mut self, guid: u64) -> Result<u64, String> {
            let txg = self
                .txg_map
                .get_mut(&guid)
                .ok_or_else(|| "dataset not found".to_string())?;
            *txg += 1;
            Ok(*txg)
        }

        fn current_timestamp(&self) -> u64 {
            1704067200
        }
    }

    impl FileStateProvider for MockProvider {
        fn list_files(&self, txg: u64) -> Result<Vec<FileInfo>, String> {
            Ok(self
                .file_states
                .get(&txg)
                .map(|s| s.values().cloned().collect())
                .unwrap_or_default())
        }

        fn get_file(&self, path: &str, txg: u64) -> Result<Option<FileInfo>, String> {
            Ok(self
                .file_states
                .get(&txg)
                .and_then(|s| s.get(path).cloned()))
        }

        fn read_file(&self, _path: &str, _txg: u64) -> Result<Vec<u8>, String> {
            Ok(alloc::vec![])
        }

        fn files_equal(
            &self,
            path1: &str,
            txg1: u64,
            path2: &str,
            txg2: u64,
        ) -> Result<bool, String> {
            let f1 = self.get_file(path1, txg1)?;
            let f2 = self.get_file(path2, txg2)?;
            match (f1, f2) {
                (Some(a), Some(b)) => Ok(a.checksum == b.checksum),
                (None, None) => Ok(true),
                _ => Ok(false),
            }
        }
    }

    #[test]
    fn test_branch_manager_new() {
        let provider = MockProvider::new();
        let manager = BranchManager::new(provider, "test@example.com");

        assert_eq!(manager.current_branch_name(), "main");
        assert!(manager.branch_exists("main"));
    }

    #[test]
    fn test_create_and_checkout() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        manager.create_branch("feature").unwrap();
        assert!(manager.branch_exists("feature"));

        manager.checkout("feature").unwrap();
        assert_eq!(manager.current_branch_name(), "feature");
    }

    #[test]
    fn test_commit() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        let commit = manager
            .commit(
                "Initial commit",
                alloc::vec![FileChange::created("/file.txt".into(), [1; 4], 100,)],
            )
            .unwrap();

        assert_eq!(commit.message, "Initial commit");
        assert_eq!(commit.author, "test");

        // Verify stored
        let head = manager.get_head("main");
        assert!(head.is_some());
        assert_eq!(head.unwrap().hash, commit.hash);
    }

    #[test]
    fn test_log() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        manager.commit("First", alloc::vec![]).unwrap();
        manager.commit("Second", alloc::vec![]).unwrap();
        manager.commit("Third", alloc::vec![]).unwrap();

        let log = manager.log(LogOptions::default());
        assert_eq!(log.len(), 3);
        assert_eq!(log[0].message, "Third");
        assert_eq!(log[2].message, "First");
    }

    #[test]
    fn test_list_branches() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        manager.create_branch("alpha").unwrap();
        manager.create_branch("beta").unwrap();

        let branches = manager.list_branches();
        assert_eq!(branches.len(), 3);
    }

    #[test]
    fn test_delete_branch() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        manager.create_branch("feature").unwrap();
        manager.delete_branch("feature", true).unwrap();

        assert!(!manager.branch_exists("feature"));
    }

    #[test]
    fn test_rename_branch() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        manager.create_branch("old-name").unwrap();
        manager.rename_branch("old-name", "new-name").unwrap();

        assert!(!manager.branch_exists("old-name"));
        assert!(manager.branch_exists("new-name"));
    }

    #[test]
    fn test_stats() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "alice");

        manager
            .commit(
                "First",
                alloc::vec![FileChange::created("/a.txt".into(), [1; 4], 100)],
            )
            .unwrap();
        manager
            .commit(
                "Second",
                alloc::vec![FileChange::created("/b.txt".into(), [2; 4], 200)],
            )
            .unwrap();

        let stats = manager.stats("main");
        assert_eq!(stats.commit_count, 2);
        assert_eq!(stats.total_additions, 2);
        assert_eq!(stats.author_count, 1);
    }

    #[test]
    fn test_shortlog() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "alice");

        manager.commit("By alice", alloc::vec![]).unwrap();
        manager.set_author("bob");
        manager.commit("By bob", alloc::vec![]).unwrap();
        manager.commit("By bob again", alloc::vec![]).unwrap();

        let shortlog = manager.shortlog("main");
        assert_eq!(shortlog.len(), 2);

        let bob = shortlog.iter().find(|(a, _)| a == "bob");
        assert!(bob.is_some());
        assert_eq!(bob.unwrap().1, 2);
    }

    #[test]
    fn test_checkout_new() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        manager.checkout_new("feature").unwrap();

        assert_eq!(manager.current_branch_name(), "feature");
        assert!(manager.branch_exists("feature"));
    }

    #[test]
    fn test_sync() {
        let provider = MockProvider::new();
        let mut manager = BranchManager::new(provider, "test");

        let txg = manager.sync().unwrap();
        assert_eq!(txg, 1);

        let branch = manager.current_branch().unwrap();
        assert_eq!(branch.head_txg, 1);
    }
}