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
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Cherry-pick implementation for applying commits across branches.
//!
//! Cherry-picking allows you to apply the changes from a specific commit
//! to a different branch, creating a new commit with those changes.

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

use super::commit::{CommitBuilder, CommitStore};
use super::merge::{DiffEntry, FileInfo, FileStateProvider};
use super::types::{
    BranchError, ChangeType, Commit, ConflictType, FileChange, FileVersion, MergeConflict,
    MergeResult,
};

// ═══════════════════════════════════════════════════════════════════════════════
// CHERRY-PICK OPTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Options for cherry-pick operation.
#[derive(Debug, Clone)]
pub struct CherryPickOptions {
    /// Keep the original author.
    pub keep_author: bool,
    /// Preserve original commit timestamp.
    pub keep_timestamp: bool,
    /// Strategy for handling conflicts.
    pub on_conflict: ConflictStrategy,
    /// Custom commit message (None = use original).
    pub message: Option<String>,
    /// Append "(cherry picked from commit X)" to message.
    pub append_cherry_picked_from: bool,
    /// Only show what would happen, don't apply.
    pub dry_run: bool,
}

impl Default for CherryPickOptions {
    fn default() -> Self {
        Self {
            keep_author: true,
            keep_timestamp: false,
            on_conflict: ConflictStrategy::Fail,
            message: None,
            append_cherry_picked_from: true,
            dry_run: false,
        }
    }
}

impl CherryPickOptions {
    /// Create options for dry run.
    pub fn dry_run() -> Self {
        Self {
            dry_run: true,
            ..Default::default()
        }
    }

    /// Set conflict strategy.
    pub fn with_conflict_strategy(mut self, strategy: ConflictStrategy) -> Self {
        self.on_conflict = strategy;
        self
    }

    /// Set custom message.
    pub fn with_message(mut self, msg: impl Into<String>) -> Self {
        self.message = Some(msg.into());
        self
    }

    /// Don't append cherry-pick source info.
    pub fn no_cherry_picked_from(mut self) -> Self {
        self.append_cherry_picked_from = false;
        self
    }

    /// Don't keep original author.
    pub fn with_new_author(mut self) -> Self {
        self.keep_author = false;
        self
    }
}

/// Strategy for handling conflicts during cherry-pick.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConflictStrategy {
    /// Fail the cherry-pick if conflicts occur.
    Fail,
    /// Skip commits that conflict.
    Skip,
    /// Keep our version on conflict.
    KeepOurs,
    /// Keep their version on conflict.
    KeepTheirs,
}

// ═══════════════════════════════════════════════════════════════════════════════
// CHERRY-PICK RESULT
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of a cherry-pick operation.
#[derive(Debug, Clone)]
pub struct CherryPickResult {
    /// The new commit created (if successful).
    pub new_commit: Option<Commit>,
    /// Original commit that was cherry-picked.
    pub original_hash: [u8; 32],
    /// Conflicts that occurred.
    pub conflicts: Vec<MergeConflict>,
    /// Files that were successfully applied.
    pub applied_changes: Vec<FileChange>,
    /// Was this a dry run?
    pub dry_run: bool,
    /// Status of the operation.
    pub status: CherryPickStatus,
}

impl CherryPickResult {
    /// Check if cherry-pick was successful.
    pub fn is_success(&self) -> bool {
        matches!(self.status, CherryPickStatus::Success)
    }

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

/// Status of cherry-pick operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CherryPickStatus {
    /// Successfully applied.
    Success,
    /// Conflicts occurred.
    Conflict,
    /// Commit was skipped.
    Skipped,
    /// No changes to apply.
    Empty,
    /// Dry run completed.
    DryRun,
}

// ═══════════════════════════════════════════════════════════════════════════════
// CHERRY-PICKER
// ═══════════════════════════════════════════════════════════════════════════════

/// Cherry-pick executor.
pub struct CherryPicker<'a, P: FileStateProvider> {
    /// File state provider.
    provider: &'a P,
    /// Commit store.
    commits: &'a CommitStore,
}

impl<'a, P: FileStateProvider> CherryPicker<'a, P> {
    /// Create a new cherry-picker.
    pub fn new(provider: &'a P, commits: &'a CommitStore) -> Self {
        Self { provider, commits }
    }

    /// Cherry-pick a single commit onto the current HEAD.
    pub fn cherry_pick(
        &self,
        commit_hash: &[u8; 32],
        current_txg: u64,
        new_txg: u64,
        current_author: &str,
        timestamp: u64,
        options: &CherryPickOptions,
    ) -> Result<CherryPickResult, BranchError> {
        // Get the commit to cherry-pick
        let commit = self
            .commits
            .get(commit_hash)
            .ok_or_else(|| BranchError::CommitNotFound(hex_string(commit_hash)))?;

        // Get the commit's parent for diffing
        let parent_txg = if let Some(parent_hash) = &commit.parent {
            self.commits
                .get(parent_hash)
                .map(|c| c.txg)
                .unwrap_or(commit.txg.saturating_sub(1))
        } else {
            // Initial commit - diff against empty state
            0
        };

        // Compute the changes introduced by this commit
        let changes = self.compute_changes(parent_txg, commit.txg)?;

        if changes.is_empty() {
            return Ok(CherryPickResult {
                new_commit: None,
                original_hash: *commit_hash,
                conflicts: vec![],
                applied_changes: vec![],
                dry_run: options.dry_run,
                status: CherryPickStatus::Empty,
            });
        }

        // Check for conflicts against current state
        let (applicable, conflicts) =
            self.check_conflicts(&changes, current_txg, &options.on_conflict)?;

        if !conflicts.is_empty() {
            match options.on_conflict {
                ConflictStrategy::Fail => {
                    return Ok(CherryPickResult {
                        new_commit: None,
                        original_hash: *commit_hash,
                        conflicts,
                        applied_changes: vec![],
                        dry_run: options.dry_run,
                        status: CherryPickStatus::Conflict,
                    });
                }
                ConflictStrategy::Skip => {
                    return Ok(CherryPickResult {
                        new_commit: None,
                        original_hash: *commit_hash,
                        conflicts,
                        applied_changes: vec![],
                        dry_run: options.dry_run,
                        status: CherryPickStatus::Skipped,
                    });
                }
                // KeepOurs and KeepTheirs continue with applicable changes
                _ => {}
            }
        }

        // Dry run - just report what would happen
        if options.dry_run {
            return Ok(CherryPickResult {
                new_commit: None,
                original_hash: *commit_hash,
                conflicts,
                applied_changes: applicable,
                dry_run: true,
                status: CherryPickStatus::DryRun,
            });
        }

        // Build the new commit
        let message = self.build_message(commit, options);
        let author = if options.keep_author {
            commit.author.clone()
        } else {
            current_author.to_string()
        };
        let ts = if options.keep_timestamp {
            commit.timestamp
        } else {
            timestamp
        };

        // Get parent hash (current HEAD)
        let parent = self.commits.get_by_txg(current_txg).map(|c| c.hash);

        let mut builder = CommitBuilder::new(new_txg)
            .message(message)
            .author(author)
            .timestamp(ts)
            .changes(applicable.clone());

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

        let new_commit = builder.build();

        Ok(CherryPickResult {
            new_commit: Some(new_commit),
            original_hash: *commit_hash,
            conflicts,
            applied_changes: applicable,
            dry_run: false,
            status: CherryPickStatus::Success,
        })
    }

    /// Cherry-pick multiple commits.
    pub fn cherry_pick_range(
        &self,
        commit_hashes: &[[u8; 32]],
        start_txg: u64,
        current_author: &str,
        timestamp: u64,
        options: &CherryPickOptions,
    ) -> Result<Vec<CherryPickResult>, BranchError> {
        let mut results = Vec::new();
        let mut current_txg = start_txg;

        for hash in commit_hashes {
            let new_txg = current_txg + 1;
            let result = self.cherry_pick(
                hash,
                current_txg,
                new_txg,
                current_author,
                timestamp,
                options,
            )?;

            // If successful, advance TXG
            if result.is_success() {
                current_txg = new_txg;
            }

            // If conflict with Fail strategy, stop
            if matches!(result.status, CherryPickStatus::Conflict)
                && options.on_conflict == ConflictStrategy::Fail
            {
                results.push(result);
                break;
            }

            results.push(result);
        }

        Ok(results)
    }

    /// Compute changes introduced by a commit.
    fn compute_changes(
        &self,
        parent_txg: u64,
        commit_txg: u64,
    ) -> Result<Vec<FileChange>, BranchError> {
        let parent_files = self
            .provider
            .list_files(parent_txg)
            .map_err(BranchError::IoError)?;
        let commit_files = self
            .provider
            .list_files(commit_txg)
            .map_err(BranchError::IoError)?;

        // Index by path
        let parent_map: alloc::collections::BTreeMap<_, _> = parent_files
            .into_iter()
            .map(|f| (f.path.clone(), f))
            .collect();
        let commit_map: alloc::collections::BTreeMap<_, _> = commit_files
            .into_iter()
            .map(|f| (f.path.clone(), f))
            .collect();

        let mut changes = Vec::new();

        // Find additions and modifications
        for (path, file) in &commit_map {
            match parent_map.get(path) {
                Some(parent_file) => {
                    if parent_file.checksum != file.checksum {
                        changes.push(FileChange::modified(
                            path.clone(),
                            parent_file.checksum,
                            file.checksum,
                            parent_file.size,
                            file.size,
                        ));
                    }
                }
                None => {
                    changes.push(FileChange::created(path.clone(), file.checksum, file.size));
                }
            }
        }

        // Find deletions
        for (path, file) in &parent_map {
            if !commit_map.contains_key(path) {
                changes.push(FileChange::deleted(path.clone(), file.checksum, file.size));
            }
        }

        Ok(changes)
    }

    /// Check for conflicts when applying changes.
    fn check_conflicts(
        &self,
        changes: &[FileChange],
        current_txg: u64,
        strategy: &ConflictStrategy,
    ) -> Result<(Vec<FileChange>, Vec<MergeConflict>), BranchError> {
        let current_files = self
            .provider
            .list_files(current_txg)
            .map_err(BranchError::IoError)?;

        let current_map: alloc::collections::BTreeMap<_, _> = current_files
            .into_iter()
            .map(|f| (f.path.clone(), f))
            .collect();

        let mut applicable = Vec::new();
        let mut conflicts = Vec::new();

        for change in changes {
            let current_file = current_map.get(&change.path);

            match (&change.change_type, current_file) {
                // Creating a file that already exists
                (ChangeType::Created, Some(existing)) => {
                    if Some(existing.checksum) == change.new_checksum {
                        // Same content - no conflict, skip
                    } else {
                        // Different content - conflict
                        conflicts.push(MergeConflict {
                            path: change.path.clone(),
                            conflict_type: ConflictType::BothCreated,
                            base: None,
                            ours: Some(existing.to_version(current_txg)),
                            theirs: change
                                .new_checksum
                                .map(|c| FileVersion::new(0, change.new_size.unwrap_or(0), c, 0)),
                        });

                        match strategy {
                            ConflictStrategy::KeepTheirs => {
                                applicable.push(change.clone());
                            }
                            ConflictStrategy::KeepOurs => {
                                // Skip this change
                            }
                            _ => {}
                        }
                    }
                }

                // Modifying a file
                (ChangeType::Modified, Some(existing)) => {
                    // Check if our version matches the expected base
                    if Some(existing.checksum) == change.old_checksum {
                        // Clean apply
                        applicable.push(change.clone());
                    } else {
                        // File was modified differently - conflict
                        conflicts.push(MergeConflict {
                            path: change.path.clone(),
                            conflict_type: ConflictType::BothModified,
                            base: change
                                .old_checksum
                                .map(|c| FileVersion::new(0, change.old_size.unwrap_or(0), c, 0)),
                            ours: Some(existing.to_version(current_txg)),
                            theirs: change
                                .new_checksum
                                .map(|c| FileVersion::new(0, change.new_size.unwrap_or(0), c, 0)),
                        });

                        match strategy {
                            ConflictStrategy::KeepTheirs => {
                                applicable.push(change.clone());
                            }
                            ConflictStrategy::KeepOurs => {
                                // Skip this change
                            }
                            _ => {}
                        }
                    }
                }

                // Modifying a file that doesn't exist
                (ChangeType::Modified, None) => {
                    // File was deleted - conflict
                    conflicts.push(MergeConflict {
                        path: change.path.clone(),
                        conflict_type: ConflictType::DeleteModify,
                        base: change
                            .old_checksum
                            .map(|c| FileVersion::new(0, change.old_size.unwrap_or(0), c, 0)),
                        ours: None,
                        theirs: change
                            .new_checksum
                            .map(|c| FileVersion::new(0, change.new_size.unwrap_or(0), c, 0)),
                    });

                    match strategy {
                        ConflictStrategy::KeepTheirs => {
                            // Re-create the file
                            applicable.push(FileChange::created(
                                change.path.clone(),
                                change.new_checksum.unwrap_or([0; 4]),
                                change.new_size.unwrap_or(0),
                            ));
                        }
                        ConflictStrategy::KeepOurs => {
                            // Keep deleted
                        }
                        _ => {}
                    }
                }

                // Deleting a file
                (ChangeType::Deleted, Some(existing)) => {
                    if Some(existing.checksum) == change.old_checksum {
                        // File hasn't changed - safe to delete
                        applicable.push(change.clone());
                    } else {
                        // File was modified - conflict
                        conflicts.push(MergeConflict {
                            path: change.path.clone(),
                            conflict_type: ConflictType::ModifyDelete,
                            base: change
                                .old_checksum
                                .map(|c| FileVersion::new(0, change.old_size.unwrap_or(0), c, 0)),
                            ours: Some(existing.to_version(current_txg)),
                            theirs: None,
                        });

                        match strategy {
                            ConflictStrategy::KeepTheirs => {
                                applicable.push(change.clone());
                            }
                            ConflictStrategy::KeepOurs => {
                                // Keep modified version
                            }
                            _ => {}
                        }
                    }
                }

                // Deleting a file that doesn't exist
                (ChangeType::Deleted, None) => {
                    // Already deleted - no-op
                }

                // Creating a file that doesn't exist
                (ChangeType::Created, None) => {
                    applicable.push(change.clone());
                }

                // Renamed file
                (ChangeType::Renamed { old_path }, _) => {
                    // Check if old path exists and matches
                    if let Some(old_file) = current_map.get(old_path) {
                        if Some(old_file.checksum) == change.old_checksum {
                            applicable.push(change.clone());
                        } else {
                            // Source was modified - conflict
                            conflicts.push(MergeConflict {
                                path: change.path.clone(),
                                conflict_type: ConflictType::BothModified,
                                base: change.old_checksum.map(|c| {
                                    FileVersion::new(0, change.old_size.unwrap_or(0), c, 0)
                                }),
                                ours: Some(old_file.to_version(current_txg)),
                                theirs: change.new_checksum.map(|c| {
                                    FileVersion::new(0, change.new_size.unwrap_or(0), c, 0)
                                }),
                            });
                        }
                    } else {
                        // Source doesn't exist
                        conflicts.push(MergeConflict {
                            path: change.path.clone(),
                            conflict_type: ConflictType::DeleteModify,
                            base: None,
                            ours: None,
                            theirs: change
                                .new_checksum
                                .map(|c| FileVersion::new(0, change.new_size.unwrap_or(0), c, 0)),
                        });
                    }
                }
            }
        }

        Ok((applicable, conflicts))
    }

    /// Build the commit message.
    fn build_message(&self, original: &Commit, options: &CherryPickOptions) -> String {
        let base_message = options
            .message
            .clone()
            .unwrap_or_else(|| original.message.clone());

        if options.append_cherry_picked_from {
            alloc::format!(
                "{}\n\n(cherry picked from commit {})",
                base_message,
                original.short_hash()
            )
        } else {
            base_message
        }
    }
}

/// Convert bytes to hex string.
fn hex_string(bytes: &[u8]) -> String {
    let mut s = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        s.push_str(&alloc::format!("{:02x}", byte));
    }
    s
}

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

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

    /// Mock file state provider.
    struct MockProvider {
        states: BTreeMap<u64, BTreeMap<String, FileInfo>>,
    }

    impl MockProvider {
        fn new() -> Self {
            Self {
                states: BTreeMap::new(),
            }
        }

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

        fn set_state(&mut self, txg: u64, files: BTreeMap<String, FileInfo>) {
            self.states.insert(txg, files);
        }
    }

    impl FileStateProvider for MockProvider {
        fn list_files(&self, txg: u64) -> Result<Vec<FileInfo>, String> {
            Ok(self
                .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.states.get(&txg).and_then(|s| s.get(path).cloned()))
        }

        fn read_file(&self, _path: &str, _txg: u64) -> Result<Vec<u8>, String> {
            Ok(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_cherry_pick_simple() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        // State at TXG 0 (empty)
        provider.set_state(0, BTreeMap::new());

        // Commit at TXG 1 adds a file
        provider.add_file(1, "/file.txt", [1; 4], 100);

        let commit = CommitBuilder::new(1)
            .message("Add file")
            .author("test")
            .timestamp(1000)
            .change(FileChange::created("/file.txt".into(), [1; 4], 100))
            .build();

        let hash = commit.hash;
        commits.add_commit(commit);

        // Current state at TXG 10 (empty, different branch)
        provider.set_state(10, BTreeMap::new());

        let picker = CherryPicker::new(&provider, &commits);
        let result = picker
            .cherry_pick(
                &hash,
                10,
                11,
                "cherry-picker",
                2000,
                &CherryPickOptions::default(),
            )
            .unwrap();

        assert!(result.is_success());
        assert!(result.new_commit.is_some());
        assert_eq!(result.applied_changes.len(), 1);
    }

    #[test]
    fn test_cherry_pick_conflict() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        // State at TXG 0 has file
        provider.add_file(0, "/file.txt", [1; 4], 100);

        // Commit at TXG 1 modifies file
        provider.add_file(1, "/file.txt", [2; 4], 200);

        let commit = CommitBuilder::new(1)
            .parent([0; 32]) // Fake parent
            .message("Modify file")
            .author("test")
            .timestamp(1000)
            .change(FileChange::modified(
                "/file.txt".into(),
                [1; 4],
                [2; 4],
                100,
                200,
            ))
            .build();

        let hash = commit.hash;
        commits.add_commit(commit);

        // Current state at TXG 10 has same file but different content
        provider.add_file(10, "/file.txt", [3; 4], 300);

        let picker = CherryPicker::new(&provider, &commits);
        let result = picker
            .cherry_pick(
                &hash,
                10,
                11,
                "cherry-picker",
                2000,
                &CherryPickOptions::default(),
            )
            .unwrap();

        assert!(!result.is_success());
        assert!(result.has_conflicts());
        assert_eq!(result.status, CherryPickStatus::Conflict);
    }

    #[test]
    fn test_cherry_pick_dry_run() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        provider.set_state(0, BTreeMap::new());
        provider.add_file(1, "/file.txt", [1; 4], 100);

        let commit = CommitBuilder::new(1)
            .message("Add file")
            .author("test")
            .timestamp(1000)
            .change(FileChange::created("/file.txt".into(), [1; 4], 100))
            .build();

        let hash = commit.hash;
        commits.add_commit(commit);

        provider.set_state(10, BTreeMap::new());

        let picker = CherryPicker::new(&provider, &commits);
        let result = picker
            .cherry_pick(
                &hash,
                10,
                11,
                "cherry-picker",
                2000,
                &CherryPickOptions::dry_run(),
            )
            .unwrap();

        assert_eq!(result.status, CherryPickStatus::DryRun);
        assert!(result.new_commit.is_none()); // No commit created
        assert!(!result.applied_changes.is_empty()); // But changes are computed
    }

    #[test]
    fn test_cherry_pick_keep_theirs() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        provider.add_file(0, "/file.txt", [1; 4], 100);
        provider.add_file(1, "/file.txt", [2; 4], 200);

        let commit = CommitBuilder::new(1)
            .parent([0; 32])
            .message("Modify file")
            .author("test")
            .timestamp(1000)
            .change(FileChange::modified(
                "/file.txt".into(),
                [1; 4],
                [2; 4],
                100,
                200,
            ))
            .build();

        let hash = commit.hash;
        commits.add_commit(commit);

        provider.add_file(10, "/file.txt", [3; 4], 300);

        let picker = CherryPicker::new(&provider, &commits);
        let options =
            CherryPickOptions::default().with_conflict_strategy(ConflictStrategy::KeepTheirs);
        let result = picker
            .cherry_pick(&hash, 10, 11, "cherry-picker", 2000, &options)
            .unwrap();

        // With KeepTheirs, conflicts are recorded but changes are applied
        assert!(result.is_success());
        assert!(result.has_conflicts());
        assert!(!result.applied_changes.is_empty());
    }

    #[test]
    fn test_cherry_pick_skip_on_conflict() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        provider.add_file(0, "/file.txt", [1; 4], 100);
        provider.add_file(1, "/file.txt", [2; 4], 200);

        let commit = CommitBuilder::new(1)
            .parent([0; 32])
            .message("Modify file")
            .author("test")
            .timestamp(1000)
            .change(FileChange::modified(
                "/file.txt".into(),
                [1; 4],
                [2; 4],
                100,
                200,
            ))
            .build();

        let hash = commit.hash;
        commits.add_commit(commit);

        provider.add_file(10, "/file.txt", [3; 4], 300);

        let picker = CherryPicker::new(&provider, &commits);
        let options = CherryPickOptions::default().with_conflict_strategy(ConflictStrategy::Skip);
        let result = picker
            .cherry_pick(&hash, 10, 11, "cherry-picker", 2000, &options)
            .unwrap();

        assert_eq!(result.status, CherryPickStatus::Skipped);
        assert!(result.new_commit.is_none());
    }

    #[test]
    fn test_cherry_pick_empty() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        // Same state at both TXGs
        provider.add_file(0, "/file.txt", [1; 4], 100);
        provider.add_file(1, "/file.txt", [1; 4], 100);

        let commit = CommitBuilder::new(1)
            .parent([0; 32])
            .message("No changes")
            .author("test")
            .timestamp(1000)
            .build();

        let hash = commit.hash;
        commits.add_commit(commit);

        provider.add_file(10, "/file.txt", [1; 4], 100);

        let picker = CherryPicker::new(&provider, &commits);
        let result = picker
            .cherry_pick(
                &hash,
                10,
                11,
                "cherry-picker",
                2000,
                &CherryPickOptions::default(),
            )
            .unwrap();

        assert_eq!(result.status, CherryPickStatus::Empty);
    }

    #[test]
    fn test_cherry_pick_message() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        provider.set_state(0, BTreeMap::new());
        provider.add_file(1, "/file.txt", [1; 4], 100);

        let commit = CommitBuilder::new(1)
            .message("Original message")
            .author("original-author")
            .timestamp(1000)
            .change(FileChange::created("/file.txt".into(), [1; 4], 100))
            .build();

        let hash = commit.hash;
        let short_hash = commit.short_hash();
        commits.add_commit(commit);

        provider.set_state(10, BTreeMap::new());

        let picker = CherryPicker::new(&provider, &commits);
        let result = picker
            .cherry_pick(
                &hash,
                10,
                11,
                "new-author",
                2000,
                &CherryPickOptions::default(),
            )
            .unwrap();

        let new_commit = result.new_commit.unwrap();
        assert!(new_commit.message.contains("Original message"));
        assert!(new_commit.message.contains("cherry picked from commit"));
        assert!(new_commit.message.contains(&short_hash));
        // Author should be kept
        assert_eq!(new_commit.author, "original-author");
    }

    #[test]
    fn test_cherry_pick_custom_message() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        provider.set_state(0, BTreeMap::new());
        provider.add_file(1, "/file.txt", [1; 4], 100);

        let commit = CommitBuilder::new(1)
            .message("Original message")
            .author("test")
            .timestamp(1000)
            .change(FileChange::created("/file.txt".into(), [1; 4], 100))
            .build();

        let hash = commit.hash;
        commits.add_commit(commit);

        provider.set_state(10, BTreeMap::new());

        let picker = CherryPicker::new(&provider, &commits);
        let options = CherryPickOptions::default()
            .with_message("Custom message")
            .no_cherry_picked_from()
            .with_new_author();
        let result = picker
            .cherry_pick(&hash, 10, 11, "new-author", 2000, &options)
            .unwrap();

        let new_commit = result.new_commit.unwrap();
        assert_eq!(new_commit.message, "Custom message");
        assert_eq!(new_commit.author, "new-author");
    }

    #[test]
    fn test_cherry_pick_range() {
        let mut provider = MockProvider::new();
        let mut commits = CommitStore::new();

        // Create chain of commits
        provider.set_state(0, BTreeMap::new());
        provider.add_file(1, "/file1.txt", [1; 4], 100);
        provider.add_file(2, "/file1.txt", [1; 4], 100);
        provider.add_file(2, "/file2.txt", [2; 4], 200);

        let c1 = CommitBuilder::new(1)
            .message("Add file1")
            .author("test")
            .timestamp(1000)
            .change(FileChange::created("/file1.txt".into(), [1; 4], 100))
            .build();

        let c2 = CommitBuilder::new(2)
            .parent(c1.hash)
            .message("Add file2")
            .author("test")
            .timestamp(2000)
            .change(FileChange::created("/file2.txt".into(), [2; 4], 200))
            .build();

        let h1 = c1.hash;
        let h2 = c2.hash;
        commits.add_commit(c1);
        commits.add_commit(c2);

        // Target branch is empty
        provider.set_state(10, BTreeMap::new());

        let picker = CherryPicker::new(&provider, &commits);
        let results = picker
            .cherry_pick_range(&[h1, h2], 10, "test", 3000, &CherryPickOptions::default())
            .unwrap();

        assert_eq!(results.len(), 2);
        assert!(results[0].is_success());
        assert!(results[1].is_success());
    }
}