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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Core types for git-style branching.
//!
//! This module defines the fundamental data structures for branch management,
//! including branches, commits, merge results, and file changes.

use alloc::string::String;
use alloc::vec::Vec;

// ═══════════════════════════════════════════════════════════════════════════════
// BRANCH
// ═══════════════════════════════════════════════════════════════════════════════

/// Branch metadata.
///
/// A branch represents an independent line of development within a dataset.
/// Due to COW semantics, creating a branch is nearly free (zero-copy).
#[derive(Debug, Clone, PartialEq)]
pub struct Branch {
    /// Branch name (e.g., "main", "feature-xyz").
    pub name: String,
    /// Dataset GUID for this branch.
    pub guid: u64,
    /// Parent branch name (None for the initial/main branch).
    pub parent: Option<String>,
    /// TXG where this branch diverged from parent.
    pub fork_txg: u64,
    /// Current head TXG of this branch.
    pub head_txg: u64,
    /// Branch creation timestamp (Unix epoch seconds).
    pub created: u64,
    /// Is this the default branch?
    pub is_default: bool,
}

impl Branch {
    /// Create a new branch.
    pub fn new(
        name: String,
        guid: u64,
        parent: Option<String>,
        fork_txg: u64,
        created: u64,
    ) -> Self {
        Self {
            name,
            guid,
            parent,
            fork_txg,
            head_txg: fork_txg,
            created,
            is_default: false,
        }
    }

    /// Create the initial "main" branch.
    pub fn main(guid: u64, txg: u64, created: u64) -> Self {
        Self {
            name: "main".into(),
            guid,
            parent: None,
            fork_txg: txg,
            head_txg: txg,
            created,
            is_default: true,
        }
    }

    /// Check if this is a root branch (no parent).
    pub fn is_root(&self) -> bool {
        self.parent.is_none()
    }

    /// Get the number of TXGs since fork.
    pub fn txgs_since_fork(&self) -> u64 {
        self.head_txg.saturating_sub(self.fork_txg)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// COMMIT
// ═══════════════════════════════════════════════════════════════════════════════

/// A commit (change record).
///
/// Commits are explicit save points with a message describing the changes.
/// The hash is computed as BLAKE3(parent_hash || message || changes).
#[derive(Debug, Clone)]
pub struct Commit {
    /// Commit hash (BLAKE3 of content).
    pub hash: [u8; 32],
    /// Parent commit hash.
    pub parent: Option<[u8; 32]>,
    /// TXG of this commit.
    pub txg: u64,
    /// Commit message.
    pub message: String,
    /// Author name/email.
    pub author: String,
    /// Timestamp (Unix epoch seconds).
    pub timestamp: u64,
    /// Changed files in this commit.
    pub changes: Vec<FileChange>,
}

impl Commit {
    /// Get a short hash (first 8 hex characters).
    pub fn short_hash(&self) -> String {
        use alloc::format;
        format!(
            "{:02x}{:02x}{:02x}{:02x}",
            self.hash[0], self.hash[1], self.hash[2], self.hash[3]
        )
    }

    /// Get the full hash as hex string.
    pub fn hash_hex(&self) -> String {
        use alloc::format;
        let mut s = String::with_capacity(64);
        for byte in &self.hash {
            s.push_str(&format!("{:02x}", byte));
        }
        s
    }

    /// Check if this is the initial commit (no parent).
    pub fn is_initial(&self) -> bool {
        self.parent.is_none()
    }

    /// Get the number of files changed.
    pub fn files_changed(&self) -> usize {
        self.changes.len()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FILE CHANGE
// ═══════════════════════════════════════════════════════════════════════════════

/// A file change within a commit.
#[derive(Debug, Clone, PartialEq)]
pub struct FileChange {
    /// File path.
    pub path: String,
    /// Type of change.
    pub change_type: ChangeType,
    /// Old checksum (before change).
    pub old_checksum: Option<[u64; 4]>,
    /// New checksum (after change).
    pub new_checksum: Option<[u64; 4]>,
    /// Old size in bytes.
    pub old_size: Option<u64>,
    /// New size in bytes.
    pub new_size: Option<u64>,
}

impl FileChange {
    /// Create a new file creation change.
    pub fn created(path: String, checksum: [u64; 4], size: u64) -> Self {
        Self {
            path,
            change_type: ChangeType::Created,
            old_checksum: None,
            new_checksum: Some(checksum),
            old_size: None,
            new_size: Some(size),
        }
    }

    /// Create a file modification change.
    pub fn modified(
        path: String,
        old_checksum: [u64; 4],
        new_checksum: [u64; 4],
        old_size: u64,
        new_size: u64,
    ) -> Self {
        Self {
            path,
            change_type: ChangeType::Modified,
            old_checksum: Some(old_checksum),
            new_checksum: Some(new_checksum),
            old_size: Some(old_size),
            new_size: Some(new_size),
        }
    }

    /// Create a file deletion change.
    pub fn deleted(path: String, checksum: [u64; 4], size: u64) -> Self {
        Self {
            path,
            change_type: ChangeType::Deleted,
            old_checksum: Some(checksum),
            new_checksum: None,
            old_size: Some(size),
            new_size: None,
        }
    }

    /// Create a file rename change.
    pub fn renamed(old_path: String, new_path: String, checksum: [u64; 4], size: u64) -> Self {
        Self {
            path: new_path,
            change_type: ChangeType::Renamed { old_path },
            old_checksum: Some(checksum),
            new_checksum: Some(checksum),
            old_size: Some(size),
            new_size: Some(size),
        }
    }
}

/// Type of file change.
#[derive(Debug, Clone, PartialEq)]
pub enum ChangeType {
    /// File was created.
    Created,
    /// File was modified.
    Modified,
    /// File was deleted.
    Deleted,
    /// File was renamed.
    Renamed {
        /// Previous path.
        old_path: String,
    },
}

impl ChangeType {
    /// Get a short name for the change type.
    pub fn short_name(&self) -> &'static str {
        match self {
            ChangeType::Created => "A",
            ChangeType::Modified => "M",
            ChangeType::Deleted => "D",
            ChangeType::Renamed { .. } => "R",
        }
    }

    /// Get the full name for the change type.
    pub fn name(&self) -> &'static str {
        match self {
            ChangeType::Created => "created",
            ChangeType::Modified => "modified",
            ChangeType::Deleted => "deleted",
            ChangeType::Renamed { .. } => "renamed",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MERGE TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of a merge operation.
#[derive(Debug, Clone)]
pub struct MergeResult {
    /// Number of files successfully merged.
    pub merged_files: usize,
    /// Conflicts detected during merge.
    pub conflicts: Vec<MergeConflict>,
    /// New TXG after merge (None if merge aborted).
    pub result_txg: Option<u64>,
    /// Commit created for the merge (if successful).
    pub merge_commit: Option<Commit>,
}

impl MergeResult {
    /// Check if merge was successful (no conflicts).
    pub fn is_success(&self) -> bool {
        self.conflicts.is_empty() && self.result_txg.is_some()
    }

    /// Check if there are conflicts.
    pub fn has_conflicts(&self) -> bool {
        !self.conflicts.is_empty()
    }

    /// Get the number of conflicts.
    pub fn conflict_count(&self) -> usize {
        self.conflicts.len()
    }
}

/// A merge conflict.
#[derive(Debug, Clone)]
pub struct MergeConflict {
    /// File path where conflict occurred.
    pub path: String,
    /// Type of conflict.
    pub conflict_type: ConflictType,
    /// Base version (common ancestor).
    pub base: Option<FileVersion>,
    /// Our version (target branch).
    pub ours: Option<FileVersion>,
    /// Their version (source branch).
    pub theirs: Option<FileVersion>,
}

impl MergeConflict {
    /// Create a "both modified" conflict.
    pub fn both_modified(
        path: String,
        base: FileVersion,
        ours: FileVersion,
        theirs: FileVersion,
    ) -> Self {
        Self {
            path,
            conflict_type: ConflictType::BothModified,
            base: Some(base),
            ours: Some(ours),
            theirs: Some(theirs),
        }
    }

    /// Create a "modify/delete" conflict.
    pub fn modify_delete(path: String, base: FileVersion, ours: FileVersion) -> Self {
        Self {
            path,
            conflict_type: ConflictType::ModifyDelete,
            base: Some(base),
            ours: Some(ours),
            theirs: None,
        }
    }

    /// Create a "delete/modify" conflict.
    pub fn delete_modify(path: String, base: FileVersion, theirs: FileVersion) -> Self {
        Self {
            path,
            conflict_type: ConflictType::DeleteModify,
            base: Some(base),
            ours: None,
            theirs: Some(theirs),
        }
    }

    /// Create a "both created" conflict.
    pub fn both_created(path: String, ours: FileVersion, theirs: FileVersion) -> Self {
        Self {
            path,
            conflict_type: ConflictType::BothCreated,
            base: None,
            ours: Some(ours),
            theirs: Some(theirs),
        }
    }
}

/// Type of merge conflict.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConflictType {
    /// Both branches modified the same file.
    BothModified,
    /// We modified, they deleted.
    ModifyDelete,
    /// They modified, we deleted.
    DeleteModify,
    /// Both branches created the same path.
    BothCreated,
}

impl ConflictType {
    /// Get a human-readable description.
    pub fn description(&self) -> &'static str {
        match self {
            ConflictType::BothModified => "both modified",
            ConflictType::ModifyDelete => "modified here, deleted there",
            ConflictType::DeleteModify => "deleted here, modified there",
            ConflictType::BothCreated => "both created",
        }
    }
}

/// File version for conflict resolution.
#[derive(Debug, Clone)]
pub struct FileVersion {
    /// TXG of this version.
    pub txg: u64,
    /// File size.
    pub size: u64,
    /// File checksum.
    pub checksum: [u64; 4],
    /// Modification time.
    pub mtime: u64,
}

impl FileVersion {
    /// Create a new file version.
    pub fn new(txg: u64, size: u64, checksum: [u64; 4], mtime: u64) -> Self {
        Self {
            txg,
            size,
            checksum,
            mtime,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MERGE STRATEGY
// ═══════════════════════════════════════════════════════════════════════════════

/// Merge strategy for handling conflicts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MergeStrategy {
    /// Try automatic merge, fail on conflict.
    #[default]
    Normal,
    /// Keep ours on conflict.
    Ours,
    /// Keep theirs on conflict.
    Theirs,
    /// Create conflict markers (like git).
    ConflictMarkers,
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERRORS
// ═══════════════════════════════════════════════════════════════════════════════

/// Errors from branch operations.
#[derive(Debug, Clone)]
pub enum BranchError {
    /// Branch already exists.
    BranchExists(String),
    /// Branch not found.
    BranchNotFound(String),
    /// Cannot delete the current branch.
    CannotDeleteCurrent(String),
    /// Cannot delete the default branch.
    CannotDeleteDefault(String),
    /// Branch has unmerged changes.
    UnmergedChanges(String),
    /// Commit not found.
    CommitNotFound(String),
    /// Dataset not found.
    DatasetNotFound(String),
    /// Merge conflict.
    MergeConflict(usize),
    /// Invalid branch name.
    InvalidBranchName(String),
    /// Already on this branch.
    AlreadyOnBranch(String),
    /// Rebase in progress.
    RebaseInProgress,
    /// Merge in progress.
    MergeInProgress,
    /// No common ancestor found.
    NoCommonAncestor,
    /// IO error.
    IoError(String),
    /// Internal error.
    Internal(String),
}

impl core::fmt::Display for BranchError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            BranchError::BranchExists(name) => write!(f, "branch '{}' already exists", name),
            BranchError::BranchNotFound(name) => write!(f, "branch '{}' not found", name),
            BranchError::CannotDeleteCurrent(name) => {
                write!(f, "cannot delete current branch '{}'", name)
            }
            BranchError::CannotDeleteDefault(name) => {
                write!(f, "cannot delete default branch '{}'", name)
            }
            BranchError::UnmergedChanges(name) => {
                write!(f, "branch '{}' has unmerged changes", name)
            }
            BranchError::CommitNotFound(hash) => write!(f, "commit '{}' not found", hash),
            BranchError::DatasetNotFound(name) => write!(f, "dataset '{}' not found", name),
            BranchError::MergeConflict(count) => write!(f, "merge conflict: {} files", count),
            BranchError::InvalidBranchName(name) => {
                write!(f, "invalid branch name: '{}'", name)
            }
            BranchError::AlreadyOnBranch(name) => write!(f, "already on branch '{}'", name),
            BranchError::RebaseInProgress => write!(f, "rebase already in progress"),
            BranchError::MergeInProgress => write!(f, "merge already in progress"),
            BranchError::NoCommonAncestor => write!(f, "no common ancestor found"),
            BranchError::IoError(msg) => write!(f, "IO error: {}", msg),
            BranchError::Internal(msg) => write!(f, "internal error: {}", msg),
        }
    }
}

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

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

    #[test]
    fn test_branch_creation() {
        let branch = Branch::new(
            "feature".into(),
            12345,
            Some("main".into()),
            100,
            1704067200,
        );

        assert_eq!(branch.name, "feature");
        assert_eq!(branch.guid, 12345);
        assert_eq!(branch.parent, Some("main".into()));
        assert_eq!(branch.fork_txg, 100);
        assert_eq!(branch.head_txg, 100);
        assert!(!branch.is_default);
        assert!(!branch.is_root());
    }

    #[test]
    fn test_main_branch() {
        let main = Branch::main(1, 0, 1704067200);

        assert_eq!(main.name, "main");
        assert!(main.is_default);
        assert!(main.is_root());
        assert_eq!(main.parent, None);
    }

    #[test]
    fn test_commit_hash() {
        let commit = Commit {
            hash: [
                0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc,
                0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78,
                0x9a, 0xbc, 0xde, 0xf0,
            ],
            parent: None,
            txg: 100,
            message: "Initial commit".into(),
            author: "test".into(),
            timestamp: 1704067200,
            changes: vec![],
        };

        assert_eq!(commit.short_hash(), "12345678");
        assert!(commit.hash_hex().starts_with("123456789abcdef0"));
        assert!(commit.is_initial());
    }

    #[test]
    fn test_file_change() {
        let created = FileChange::created("/new.txt".into(), [1; 4], 100);
        assert!(matches!(created.change_type, ChangeType::Created));
        assert_eq!(created.old_checksum, None);
        assert_eq!(created.new_checksum, Some([1; 4]));

        let deleted = FileChange::deleted("/old.txt".into(), [2; 4], 200);
        assert!(matches!(deleted.change_type, ChangeType::Deleted));
        assert_eq!(deleted.old_checksum, Some([2; 4]));
        assert_eq!(deleted.new_checksum, None);
    }

    #[test]
    fn test_merge_result() {
        let result = MergeResult {
            merged_files: 5,
            conflicts: vec![],
            result_txg: Some(200),
            merge_commit: None,
        };

        assert!(result.is_success());
        assert!(!result.has_conflicts());

        let with_conflict = MergeResult {
            merged_files: 3,
            conflicts: vec![MergeConflict {
                path: "/conflict.txt".into(),
                conflict_type: ConflictType::BothModified,
                base: None,
                ours: None,
                theirs: None,
            }],
            result_txg: None,
            merge_commit: None,
        };

        assert!(!with_conflict.is_success());
        assert!(with_conflict.has_conflicts());
        assert_eq!(with_conflict.conflict_count(), 1);
    }

    #[test]
    fn test_conflict_types() {
        assert_eq!(ConflictType::BothModified.description(), "both modified");
        assert_eq!(
            ConflictType::ModifyDelete.description(),
            "modified here, deleted there"
        );
    }

    #[test]
    fn test_change_type_names() {
        assert_eq!(ChangeType::Created.short_name(), "A");
        assert_eq!(ChangeType::Modified.short_name(), "M");
        assert_eq!(ChangeType::Deleted.short_name(), "D");
        assert_eq!(
            ChangeType::Renamed {
                old_path: "".into()
            }
            .short_name(),
            "R"
        );
    }

    #[test]
    fn test_merge_strategy_default() {
        assert_eq!(MergeStrategy::default(), MergeStrategy::Normal);
    }
}