git-sync-rs 0.7.7

Automatic git repository synchronization with file watching
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
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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
mod transport;

use crate::error::{Result, SyncError};
use chrono::Local;
use git2::{BranchType, MergeOptions, Oid, Repository, Status, StatusOptions};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{debug, error, info, warn};

pub use transport::{CommandGitTransport, CommitOutcome, GitTransport};

/// Prefix for fallback branches created by git-sync
pub const FALLBACK_BRANCH_PREFIX: &str = "git-sync/";

/// Configuration for the synchronizer
#[derive(Debug, Clone)]
pub struct SyncConfig {
    /// Whether to sync new/untracked files
    pub sync_new_files: bool,

    /// Whether to skip git hooks when committing
    pub skip_hooks: bool,

    /// Custom commit message (can include {hostname} and {timestamp} placeholders)
    pub commit_message: Option<String>,

    /// Remote name to sync with (e.g., "origin")
    pub remote_name: String,

    /// Branch name to sync (current working branch)
    pub branch_name: String,

    /// When true, create a fallback branch on merge conflicts instead of failing
    pub conflict_branch: bool,

    /// The target branch we want to track (used for returning from fallback)
    /// If None, defaults to the repository's default branch
    pub target_branch: Option<String>,
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            sync_new_files: true, // Default to syncing untracked files
            skip_hooks: false,
            commit_message: None,
            remote_name: "origin".to_string(),
            branch_name: "main".to_string(),
            conflict_branch: false,
            target_branch: None,
        }
    }
}

/// Repository state that might prevent syncing
#[derive(Debug, Clone, PartialEq)]
pub enum RepositoryState {
    /// Repository is clean and ready
    Clean,

    /// Repository has uncommitted changes
    Dirty,

    /// Repository is in the middle of a rebase
    Rebasing,

    /// Repository is in the middle of a merge
    Merging,

    /// Repository is cherry-picking
    CherryPicking,

    /// Repository is bisecting
    Bisecting,

    /// Repository is applying patches (git am)
    ApplyingPatches,

    /// Repository is in the middle of a revert
    Reverting,

    /// HEAD is detached
    DetachedHead,
}

/// Sync state relative to remote
#[derive(Debug, Clone, PartialEq)]
pub enum SyncState {
    /// Local and remote are equal
    Equal,

    /// Local is ahead of remote
    Ahead(usize),

    /// Local is behind remote
    Behind(usize),

    /// Local and remote have diverged
    Diverged { ahead: usize, behind: usize },

    /// No upstream branch
    NoUpstream,
}

/// Unhandled file state that prevents sync
#[derive(Debug, Clone, PartialEq)]
pub enum UnhandledFileState {
    /// File has merge conflicts
    Conflicted { path: String },
}

/// State for tracking fallback branch return attempts (in-memory only)
#[derive(Debug, Clone, Default)]
pub struct FallbackState {
    /// The OID of the target branch when we last checked if return was possible
    /// Used to avoid redundant merge checks when target hasn't moved
    pub last_checked_target_oid: Option<Oid>,
}

/// Main synchronizer struct
pub struct RepositorySynchronizer {
    repo: Repository,
    config: SyncConfig,
    _repo_path: PathBuf,
    fallback_state: FallbackState,
    transport: Arc<dyn GitTransport>,
}

impl RepositorySynchronizer {
    /// Create a new synchronizer for the given repository path
    pub fn new(repo_path: impl AsRef<Path>, config: SyncConfig) -> Result<Self> {
        Self::new_with_transport(repo_path, config, Arc::new(CommandGitTransport))
    }

    /// Create a new synchronizer with explicit git transport implementation
    pub fn new_with_transport(
        repo_path: impl AsRef<Path>,
        config: SyncConfig,
        transport: Arc<dyn GitTransport>,
    ) -> Result<Self> {
        let repo_path = repo_path.as_ref().to_path_buf();
        let repo = Repository::open(&repo_path).map_err(|_| SyncError::NotARepository {
            path: repo_path.display().to_string(),
        })?;

        Ok(Self {
            repo,
            config,
            _repo_path: repo_path,
            fallback_state: FallbackState::default(),
            transport,
        })
    }

    /// Create a new synchronizer with auto-detected branch name
    pub fn new_with_detected_branch(
        repo_path: impl AsRef<Path>,
        config: SyncConfig,
    ) -> Result<Self> {
        Self::new_with_detected_branch_and_transport(
            repo_path,
            config,
            Arc::new(CommandGitTransport),
        )
    }

    /// Create a new synchronizer with auto-detected branch and explicit git transport
    pub fn new_with_detected_branch_and_transport(
        repo_path: impl AsRef<Path>,
        mut config: SyncConfig,
        transport: Arc<dyn GitTransport>,
    ) -> Result<Self> {
        let repo_path = repo_path.as_ref().to_path_buf();
        let repo = Repository::open(&repo_path).map_err(|_| SyncError::NotARepository {
            path: repo_path.display().to_string(),
        })?;

        // Try to detect current branch
        if let Ok(head) = repo.head() {
            if head.is_branch() {
                if let Some(branch_name) = head.shorthand() {
                    config.branch_name = branch_name.to_string();
                }
            }
        }

        Ok(Self {
            repo,
            config,
            _repo_path: repo_path,
            fallback_state: FallbackState::default(),
            transport,
        })
    }

    /// Get the current repository state
    pub fn get_repository_state(&self) -> Result<RepositoryState> {
        // Check if HEAD is detached
        match self.repo.head_detached() {
            Ok(true) => return Ok(RepositoryState::DetachedHead),
            Ok(false) => {}
            // Unborn branches are valid in bootstrap flows.
            Err(e) if e.code() == git2::ErrorCode::UnbornBranch => {}
            Err(e) => return Err(e.into()),
        }

        // Check for various in-progress operations
        let state = self.repo.state();
        match state {
            git2::RepositoryState::Clean => {
                // Check if working directory is dirty
                let mut status_opts = StatusOptions::new();
                status_opts.include_untracked(true);
                let statuses = self.repo.statuses(Some(&mut status_opts))?;

                if statuses.is_empty() {
                    Ok(RepositoryState::Clean)
                } else {
                    Ok(RepositoryState::Dirty)
                }
            }
            git2::RepositoryState::Merge => Ok(RepositoryState::Merging),
            git2::RepositoryState::Rebase
            | git2::RepositoryState::RebaseInteractive
            | git2::RepositoryState::RebaseMerge => Ok(RepositoryState::Rebasing),
            git2::RepositoryState::CherryPick | git2::RepositoryState::CherryPickSequence => {
                Ok(RepositoryState::CherryPicking)
            }
            git2::RepositoryState::Revert | git2::RepositoryState::RevertSequence => {
                Ok(RepositoryState::Reverting)
            }
            git2::RepositoryState::Bisect => Ok(RepositoryState::Bisecting),
            git2::RepositoryState::ApplyMailbox | git2::RepositoryState::ApplyMailboxOrRebase => {
                Ok(RepositoryState::ApplyingPatches)
            }
        }
    }

    /// Check if there are local changes that need to be committed
    pub fn has_local_changes(&self) -> Result<bool> {
        let mut status_opts = StatusOptions::new();
        status_opts.include_untracked(self.config.sync_new_files);

        let statuses = self.repo.statuses(Some(&mut status_opts))?;

        for entry in statuses.iter() {
            let status = entry.status();
            let tracked_or_staged_changes = Status::WT_MODIFIED
                | Status::WT_DELETED
                | Status::WT_RENAMED
                | Status::WT_TYPECHANGE
                | Status::INDEX_MODIFIED
                | Status::INDEX_DELETED
                | Status::INDEX_RENAMED
                | Status::INDEX_TYPECHANGE
                | Status::INDEX_NEW;

            if self.config.sync_new_files {
                // Check for any changes including new files
                if status.intersects(tracked_or_staged_changes | Status::WT_NEW) {
                    return Ok(true);
                }
            } else {
                // Only check for modifications to tracked files
                if status.intersects(tracked_or_staged_changes) {
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }

    /// Check if there are unhandled file states that should prevent sync
    pub fn check_unhandled_files(&self) -> Result<Option<UnhandledFileState>> {
        let mut status_opts = StatusOptions::new();
        status_opts.include_untracked(true);

        let statuses = self.repo.statuses(Some(&mut status_opts))?;

        for entry in statuses.iter() {
            let status = entry.status();
            let path = entry.path().unwrap_or("<unknown>").to_string();

            // Check for conflicted files
            if status.is_conflicted() {
                return Ok(Some(UnhandledFileState::Conflicted { path }));
            }
        }

        Ok(None)
    }

    /// Get the current branch name
    pub fn get_current_branch(&self) -> Result<String> {
        let head = match self.repo.head() {
            Ok(head) => head,
            Err(e) if e.code() == git2::ErrorCode::UnbornBranch => {
                if let Some(branch) = self.unborn_head_branch_name()? {
                    return Ok(branch);
                }
                if !self.config.branch_name.is_empty() {
                    return Ok(self.config.branch_name.clone());
                }
                return Err(SyncError::Other(
                    "Repository HEAD is unborn and branch name could not be determined".to_string(),
                ));
            }
            Err(e) => return Err(e.into()),
        };

        if !head.is_branch() {
            return Err(SyncError::DetachedHead);
        }

        let branch_name = head
            .shorthand()
            .ok_or_else(|| SyncError::Other("Could not get branch name".to_string()))?;

        Ok(branch_name.to_string())
    }

    /// Get the sync state relative to the remote
    pub fn get_sync_state(&self) -> Result<SyncState> {
        let branch_name = self.get_current_branch()?;
        let local_branch = self.repo.find_branch(&branch_name, BranchType::Local)?;

        // Get the upstream branch
        let upstream = match local_branch.upstream() {
            Ok(upstream) => upstream,
            Err(_) => return Ok(SyncState::NoUpstream),
        };

        // Get the OIDs for comparison
        let local_oid = local_branch
            .get()
            .target()
            .ok_or_else(|| SyncError::Other("Could not get local branch OID".to_string()))?;
        let upstream_oid = upstream
            .get()
            .target()
            .ok_or_else(|| SyncError::Other("Could not get upstream branch OID".to_string()))?;

        // If they're the same, we're in sync
        if local_oid == upstream_oid {
            return Ok(SyncState::Equal);
        }

        // Count commits ahead and behind
        let (ahead, behind) = self.repo.graph_ahead_behind(local_oid, upstream_oid)?;

        match (ahead, behind) {
            (0, 0) => Ok(SyncState::Equal),
            (a, 0) if a > 0 => Ok(SyncState::Ahead(a)),
            (0, b) if b > 0 => Ok(SyncState::Behind(b)),
            (a, b) if a > 0 && b > 0 => Ok(SyncState::Diverged {
                ahead: a,
                behind: b,
            }),
            _ => Ok(SyncState::Equal),
        }
    }

    /// Auto-commit local changes
    pub fn auto_commit(&self) -> Result<()> {
        info!("Auto-committing local changes");

        // Stage changes
        let mut index = self.repo.index()?;

        if self.config.sync_new_files {
            // Add all changes including new files
            //
            // libgit2 can surface untracked nested repositories (e.g. git worktrees) as a
            // directory path with a trailing slash like `.worktrees/foo/`. Those directory
            // marker paths are not valid index paths, so attempting to add them fails with:
            //   invalid path: '.../'; class=Index (10)
            //
            // Use an `add_all` callback to skip these directory markers, and (when they look
            // like nested repos) skip their contents too.
            let repo_root = self._repo_path.clone();
            let mut nested_repo_prefixes: Vec<String> = Vec::new();
            let mut cb = |path: &Path, _matched_spec: &[u8]| -> i32 {
                let path_s = path.to_string_lossy();

                // Skip anything under a nested git repo we already detected.
                if nested_repo_prefixes.iter().any(|p| path_s.starts_with(p)) {
                    return 1;
                }

                // Avoid ever attempting to add `.git` internals (for nested repos).
                if path_s.contains("/.git/") || path_s.ends_with("/.git") {
                    return 1;
                }

                // Skip directory markers (they are not valid index paths). If it looks like a
                // nested git repo, remember the prefix so we skip its contents too.
                if path_s.ends_with('/') {
                    let no_slash = path_s.trim_end_matches('/');
                    if repo_root.join(no_slash).join(".git").exists() {
                        nested_repo_prefixes.push(format!("{}/", no_slash));
                    }
                    return 1;
                }

                0
            };

            index.add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, Some(&mut cb))?;
        } else {
            // Only update tracked files
            index.update_all(["*"].iter(), None)?;
        }

        index.write()?;

        // Prepare commit message
        let message = if let Some(ref msg) = self.config.commit_message {
            msg.replace("{hostname}", &hostname::get()?.to_string_lossy())
                .replace(
                    "{timestamp}",
                    &Local::now().format("%Y-%m-%d %I:%M:%S %p %Z").to_string(),
                )
        } else {
            format!(
                "changes from {} on {}",
                hostname::get()?.to_string_lossy(),
                Local::now().format("%Y-%m-%d %I:%M:%S %p %Z")
            )
        };

        match self
            .transport
            .commit(&self._repo_path, &message, self.config.skip_hooks)?
        {
            CommitOutcome::Created => info!("Created auto-commit: {}", message),
            CommitOutcome::NoChanges => {
                debug!("No changes to commit");
            }
        }

        Ok(())
    }

    /// Fetch a specific branch from remote
    pub fn fetch_branch(&self, branch: &str) -> Result<()> {
        info!(
            "Fetching branch {} from remote: {}",
            branch, self.config.remote_name
        );

        if let Err(e) =
            self.transport
                .fetch_branch(&self._repo_path, &self.config.remote_name, branch)
        {
            error!("Git fetch failed: {}", e);
            return Err(e);
        }

        info!(
            "Fetch completed successfully for branch {} from remote: {}",
            branch, self.config.remote_name
        );
        Ok(())
    }

    /// Fetch from remote
    pub fn fetch(&self) -> Result<()> {
        let current_branch = self.get_current_branch()?;
        self.fetch_branch(&current_branch)?;

        // If we're on a fallback branch and have a target branch, also fetch that
        if self.config.conflict_branch {
            if let Ok(target) = self.get_target_branch() {
                if target != current_branch {
                    // Ignore errors fetching target - it might not be necessary
                    let _ = self.fetch_branch(&target);
                }
            }
        }

        Ok(())
    }

    /// Push to remote
    pub fn push(&self) -> Result<()> {
        info!("Pushing to remote: {}", self.config.remote_name);

        let current_branch = self.get_current_branch()?;
        let refspec = format!("{}:{}", current_branch, current_branch);
        self.transport
            .push_refspec(&self._repo_path, &self.config.remote_name, &refspec)?;

        info!(
            "Push completed successfully to remote: {}",
            self.config.remote_name
        );
        Ok(())
    }

    /// Perform a fast-forward merge
    pub fn fast_forward_merge(&self) -> Result<()> {
        info!("Performing fast-forward merge");

        let branch_name = self.get_current_branch()?;
        let local_branch = self.repo.find_branch(&branch_name, BranchType::Local)?;
        let upstream = local_branch.upstream()?;

        let upstream_oid = upstream
            .get()
            .target()
            .ok_or_else(|| SyncError::Other("Could not get upstream OID".to_string()))?;

        // Fast-forward by moving the reference
        let mut reference = self.repo.head()?;
        reference.set_target(upstream_oid, "fast-forward merge")?;

        // Checkout the new HEAD to update working directory
        let object = self.repo.find_object(upstream_oid, None)?;
        let mut checkout_builder = git2::build::CheckoutBuilder::new();
        checkout_builder.force(); // Force update working directory files
        self.repo
            .checkout_tree(&object, Some(&mut checkout_builder))?;

        // Update HEAD to point to the new commit
        self.repo.set_head(&format!("refs/heads/{}", branch_name))?;

        info!("Fast-forward merge completed - working tree updated");
        Ok(())
    }

    /// Perform a rebase
    pub fn rebase(&self) -> Result<()> {
        info!("Performing rebase");

        let branch_name = self.get_current_branch()?;
        let local_branch = self.repo.find_branch(&branch_name, BranchType::Local)?;
        let upstream = local_branch.upstream()?;

        let upstream_commit = upstream.get().peel_to_commit()?;
        let local_commit = local_branch.get().peel_to_commit()?;

        // Find merge base
        let merge_base = self
            .repo
            .merge_base(local_commit.id(), upstream_commit.id())?;
        let _merge_base_commit = self.repo.find_commit(merge_base)?;

        // Create signature
        let sig = self.repo.signature()?;

        // Get annotated commits from references
        let local_annotated = self
            .repo
            .reference_to_annotated_commit(local_branch.get())?;
        let upstream_annotated = self.repo.reference_to_annotated_commit(upstream.get())?;

        // Start rebase
        let mut rebase = self.repo.rebase(
            Some(&local_annotated),
            Some(&upstream_annotated),
            None,
            None,
        )?;

        // Process each commit
        while let Some(operation) = rebase.next() {
            let _operation = operation?;

            // Check if we can continue
            if self.repo.index()?.has_conflicts() {
                warn!("Conflicts detected during rebase");
                rebase.abort()?;

                // If conflict_branch is enabled, create a fallback branch
                if self.config.conflict_branch {
                    return self.handle_conflict_with_fallback();
                }

                return Err(SyncError::ManualInterventionRequired {
                    reason: "Rebase conflicts detected. Please resolve manually.".to_string(),
                });
            }

            // Continue with the rebase
            rebase.commit(None, &sig, None)?;
        }

        // Finish the rebase
        rebase.finish(Some(&sig))?;

        // Ensure working tree is properly updated after rebase
        let head = self.repo.head()?;
        let head_commit = head.peel_to_commit()?;
        let mut checkout_builder = git2::build::CheckoutBuilder::new();
        checkout_builder.force();
        self.repo
            .checkout_tree(head_commit.as_object(), Some(&mut checkout_builder))?;

        info!("Rebase completed successfully - working tree updated");
        Ok(())
    }

    /// Detect the repository's default branch
    pub fn detect_default_branch(&self) -> Result<String> {
        // Try to get the default branch from origin/HEAD
        if let Ok(reference) = self.repo.find_reference("refs/remotes/origin/HEAD") {
            if let Ok(resolved) = reference.resolve() {
                if let Some(name) = resolved.shorthand() {
                    // name will be like "origin/main", extract just "main"
                    if let Some(branch) = name.strip_prefix("origin/") {
                        debug!("Detected default branch from origin/HEAD: {}", branch);
                        return Ok(branch.to_string());
                    }
                }
            }
        }

        // Fallback: check if main or master exists
        if self.repo.find_branch("main", BranchType::Local).is_ok()
            || self.repo.find_reference("refs/remotes/origin/main").is_ok()
        {
            debug!("Falling back to 'main' as default branch");
            return Ok("main".to_string());
        }

        if self.repo.find_branch("master", BranchType::Local).is_ok()
            || self
                .repo
                .find_reference("refs/remotes/origin/master")
                .is_ok()
        {
            debug!("Falling back to 'master' as default branch");
            return Ok("master".to_string());
        }

        // Last resort: use current branch
        self.get_current_branch()
    }

    /// Get the target branch (the branch we want to be on)
    pub fn get_target_branch(&self) -> Result<String> {
        if let Some(ref target) = self.config.target_branch {
            if !target.is_empty() {
                return Ok(target.clone());
            }
        }
        self.detect_default_branch()
    }

    /// Check if we're currently on a fallback branch
    pub fn is_on_fallback_branch(&self) -> Result<bool> {
        let current = self.get_current_branch()?;
        Ok(current.starts_with(FALLBACK_BRANCH_PREFIX))
    }

    /// Generate a fallback branch name
    fn generate_fallback_branch_name() -> String {
        let hostname = hostname::get()
            .map(|h| h.to_string_lossy().to_string())
            .unwrap_or_else(|_| "unknown".to_string());
        let timestamp = Local::now().format("%Y-%m-%d-%H%M%S");
        format!("{}{}-{}", FALLBACK_BRANCH_PREFIX, hostname, timestamp)
    }

    /// Create and switch to a fallback branch
    pub fn create_fallback_branch(&self) -> Result<String> {
        let branch_name = Self::generate_fallback_branch_name();
        info!("Creating fallback branch: {}", branch_name);

        // Get current HEAD commit
        let head_commit = self.repo.head()?.peel_to_commit()?;

        // Create the new branch
        self.repo
            .branch(&branch_name, &head_commit, false)
            .map_err(|e| SyncError::Other(format!("Failed to create fallback branch: {}", e)))?;

        // Checkout the new branch
        let refname = format!("refs/heads/{}", branch_name);
        self.repo.set_head(&refname)?;

        // Update working directory
        let mut checkout_builder = git2::build::CheckoutBuilder::new();
        checkout_builder.force();
        self.repo
            .checkout_head(Some(&mut checkout_builder))
            .map_err(|e| SyncError::Other(format!("Failed to checkout fallback branch: {}", e)))?;

        info!("Switched to fallback branch: {}", branch_name);
        Ok(branch_name)
    }

    /// Push a branch to remote (used for fallback branches)
    pub fn push_branch(&self, branch_name: &str) -> Result<()> {
        info!("Pushing branch {} to remote", branch_name);

        self.transport.push_branch_upstream(
            &self._repo_path,
            &self.config.remote_name,
            branch_name,
        )?;

        info!("Successfully pushed branch {} to remote", branch_name);
        Ok(())
    }

    /// Check if merging target branch into current HEAD would succeed (in-memory, no working tree changes)
    pub fn can_merge_cleanly(&self, target_branch: &str) -> Result<bool> {
        // Get the target branch reference
        let target_ref = format!("refs/remotes/{}/{}", self.config.remote_name, target_branch);
        let target_reference = self.repo.find_reference(&target_ref).map_err(|e| {
            SyncError::Other(format!(
                "Failed to find target branch {}: {}",
                target_branch, e
            ))
        })?;
        let target_commit = target_reference.peel_to_commit()?;

        // Get current HEAD
        let head_commit = self.repo.head()?.peel_to_commit()?;

        // Check if we're already ancestors (fast-forward possible)
        if self
            .repo
            .graph_descendant_of(target_commit.id(), head_commit.id())?
        {
            debug!(
                "Target branch {} is descendant of current HEAD, clean merge possible",
                target_branch
            );
            return Ok(true);
        }

        // Perform in-memory merge to check for conflicts
        let merge_opts = MergeOptions::new();
        let index = self
            .repo
            .merge_commits(&head_commit, &target_commit, Some(&merge_opts))
            .map_err(|e| SyncError::Other(format!("Failed to perform merge check: {}", e)))?;

        let has_conflicts = index.has_conflicts();
        debug!("In-memory merge check: has_conflicts={}", has_conflicts);

        Ok(!has_conflicts)
    }

    /// Get the OID of the target branch on remote
    fn get_target_branch_oid(&self, target_branch: &str) -> Result<Oid> {
        let target_ref = format!("refs/remotes/{}/{}", self.config.remote_name, target_branch);
        let reference = self.repo.find_reference(&target_ref)?;
        reference
            .target()
            .ok_or_else(|| SyncError::Other("Target branch has no OID".to_string()))
    }

    /// Attempt to return to the target branch from a fallback branch
    pub fn try_return_to_target(&mut self) -> Result<bool> {
        if !self.is_on_fallback_branch()? {
            return Ok(false);
        }

        let target_branch = self.get_target_branch()?;
        info!(
            "On fallback branch, checking if we can return to {}",
            target_branch
        );

        // Get current target branch OID
        let target_oid = match self.get_target_branch_oid(&target_branch) {
            Ok(oid) => oid,
            Err(e) => {
                warn!("Could not find target branch {}: {}", target_branch, e);
                return Ok(false);
            }
        };

        // Check if target has moved since last check
        if let Some(last_checked) = self.fallback_state.last_checked_target_oid {
            if last_checked == target_oid {
                debug!(
                    "Target branch {} hasn't changed since last check, skipping merge check",
                    target_branch
                );
                return Ok(false);
            }
        }

        // Target has moved, check if we can merge cleanly
        if !self.can_merge_cleanly(&target_branch)? {
            info!(
                "Cannot cleanly merge {} into current branch, staying on fallback",
                target_branch
            );
            self.fallback_state.last_checked_target_oid = Some(target_oid);
            return Ok(false);
        }

        info!(
            "Clean merge possible, returning to target branch {}",
            target_branch
        );

        // Get current branch commits that need to be rebased onto target
        let current_branch = self.get_current_branch()?;
        let current_oid = self
            .repo
            .head()?
            .target()
            .ok_or_else(|| SyncError::Other("Current HEAD has no OID".to_string()))?;

        // Find merge base between our fallback branch and target
        let merge_base = self.repo.merge_base(current_oid, target_oid)?;

        // Check if we have commits to rebase
        let (ahead, _) = self.repo.graph_ahead_behind(current_oid, merge_base)?;
        let has_commits_to_rebase = ahead > 0;

        // Checkout target branch
        let target_ref = format!("refs/heads/{}", target_branch);

        // First, make sure local target branch exists and is up to date
        let remote_target_ref =
            format!("refs/remotes/{}/{}", self.config.remote_name, target_branch);
        let remote_target = self.repo.find_reference(&remote_target_ref)?;
        let remote_target_oid = remote_target
            .target()
            .ok_or_else(|| SyncError::Other("Remote target has no OID".to_string()))?;

        // Update or create local target branch
        if self.repo.find_reference(&target_ref).is_ok() {
            // Update existing branch
            self.repo.reference(
                &target_ref,
                remote_target_oid,
                true,
                "git-sync: updating target branch before return",
            )?;
        } else {
            // Create local tracking branch
            let remote_commit = self.repo.find_commit(remote_target_oid)?;
            self.repo.branch(&target_branch, &remote_commit, false)?;
        }

        // Checkout target branch
        self.repo.set_head(&target_ref)?;
        let mut checkout_builder = git2::build::CheckoutBuilder::new();
        checkout_builder.force();
        self.repo.checkout_head(Some(&mut checkout_builder))?;

        if has_commits_to_rebase {
            info!(
                "Rebasing {} commits from {} onto {}",
                ahead, current_branch, target_branch
            );

            // We need to rebase our commits from the fallback branch onto target
            // Get the commits from the fallback branch
            let fallback_ref = format!("refs/heads/{}", current_branch);
            let fallback_reference = self.repo.find_reference(&fallback_ref)?;
            let fallback_annotated = self
                .repo
                .reference_to_annotated_commit(&fallback_reference)?;

            let target_reference = self.repo.find_reference(&target_ref)?;
            let target_annotated = self.repo.reference_to_annotated_commit(&target_reference)?;

            let sig = self.repo.signature()?;

            // Start rebase
            let mut rebase = self.repo.rebase(
                Some(&fallback_annotated),
                Some(&target_annotated),
                None,
                None,
            )?;

            // Process each commit
            while let Some(operation) = rebase.next() {
                let _operation = operation?;

                if self.repo.index()?.has_conflicts() {
                    warn!("Conflicts during rebase back to target, aborting");
                    rebase.abort()?;
                    // Switch back to fallback branch
                    self.repo.set_head(&fallback_ref)?;
                    self.repo.checkout_head(Some(&mut checkout_builder))?;
                    self.fallback_state.last_checked_target_oid = Some(target_oid);
                    return Ok(false);
                }

                rebase.commit(None, &sig, None)?;
            }

            rebase.finish(Some(&sig))?;

            // Update working tree
            let head = self.repo.head()?;
            let head_commit = head.peel_to_commit()?;
            self.repo
                .checkout_tree(head_commit.as_object(), Some(&mut checkout_builder))?;
        }

        // Clear fallback state
        self.fallback_state.last_checked_target_oid = None;

        info!("Successfully returned to target branch {}", target_branch);
        Ok(true)
    }

    /// Handle a rebase conflict by creating a fallback branch (when conflict_branch is enabled)
    fn handle_conflict_with_fallback(&self) -> Result<()> {
        if !self.config.conflict_branch {
            return Err(SyncError::ManualInterventionRequired {
                reason: "Rebase conflicts detected. Please resolve manually.".to_string(),
            });
        }

        info!("Conflict detected with conflict_branch enabled, creating fallback branch");

        // Create fallback branch from current state
        let fallback_branch = self.create_fallback_branch()?;

        // Commit any uncommitted changes on the fallback branch
        if self.has_local_changes()? {
            self.auto_commit()?;
        }

        // Push the fallback branch
        self.push_branch(&fallback_branch)?;

        info!(
            "Switched to fallback branch {} due to conflicts. \
             Will automatically return to target branch when conflicts are resolved.",
            fallback_branch
        );

        Ok(())
    }

    /// Main sync operation
    pub fn sync(&mut self, check_only: bool) -> Result<()> {
        info!("Starting sync operation (check_only: {})", check_only);

        // Check repository state
        let repo_state = self.get_repository_state()?;
        match repo_state {
            RepositoryState::Clean | RepositoryState::Dirty => {
                // These states are OK to continue
            }
            RepositoryState::DetachedHead => {
                return Err(SyncError::DetachedHead);
            }
            _ => {
                return Err(SyncError::UnsafeRepositoryState {
                    state: format!("{:?}", repo_state),
                });
            }
        }

        // Check for unhandled files
        if let Some(unhandled) = self.check_unhandled_files()? {
            let reason = match unhandled {
                UnhandledFileState::Conflicted { path } => format!("Conflicted file: {}", path),
            };
            return Err(SyncError::ManualInterventionRequired { reason });
        }

        // If we're only checking, we're done
        if check_only {
            info!("Check passed, sync can proceed");
            return Ok(());
        }

        // Bootstrap flow for freshly cloned empty repositories.
        // In this state HEAD points to a branch name but has no commit yet.
        if self.is_head_unborn()? {
            info!("Repository HEAD is unborn; attempting initial publish");
            if self.has_local_changes()? {
                self.auto_commit()?;
                let branch = self.get_current_branch()?;
                self.push_branch(&branch)?;
            } else {
                info!("HEAD is unborn and there are no local changes to publish");
            }
            return Ok(());
        }

        // Fetch from remote first (needed for both normal sync and return-to-target check)
        self.fetch()?;

        // If we're on a fallback branch and conflict_branch is enabled,
        // try to return to the target branch
        if self.config.conflict_branch
            && self.is_on_fallback_branch()?
            && self.try_return_to_target()?
        {
            // Successfully returned to target, update branch name for sync state check
            info!("Returned to target branch, continuing with normal sync");
        }

        // Auto-commit if there are local changes
        if self.has_local_changes()? {
            self.auto_commit()?;
        }

        // Get sync state and handle accordingly
        let sync_state = self.get_sync_state()?;
        match sync_state {
            SyncState::Equal => {
                info!("Already in sync");
            }
            SyncState::Ahead(_) => {
                info!("Local is ahead, pushing");
                self.push()?;
            }
            SyncState::Behind(_) => {
                info!("Local is behind, fast-forwarding");
                self.fast_forward_merge()?;
            }
            SyncState::Diverged { .. } => {
                info!("Branches have diverged, rebasing");
                self.rebase()?;
                self.push()?;
            }
            SyncState::NoUpstream => {
                // If we're on a fallback branch that doesn't have upstream yet, push it
                if self.is_on_fallback_branch()? {
                    info!("Fallback branch has no upstream, pushing");
                    let branch = self.get_current_branch()?;
                    self.push_branch(&branch)?;
                } else {
                    let branch = self
                        .get_current_branch()
                        .unwrap_or_else(|_| "<unknown>".into());
                    return Err(SyncError::NoRemoteConfigured { branch });
                }
            }
        }

        // Verify we're in sync (skip for fallback branches that may not have upstream yet)
        let final_state = self.get_sync_state()?;
        if final_state != SyncState::Equal && final_state != SyncState::NoUpstream {
            warn!(
                "Sync completed but repository is not in sync: {:?}",
                final_state
            );
            return Err(SyncError::Other(
                "Sync completed but repository is not in sync".to_string(),
            ));
        }

        info!("Sync completed successfully");
        Ok(())
    }

    /// Returns true when HEAD points at an unborn branch (no commit yet).
    fn is_head_unborn(&self) -> Result<bool> {
        match self.repo.head() {
            Ok(head) => match head.peel_to_commit() {
                Ok(_) => Ok(false),
                Err(e) if e.code() == git2::ErrorCode::UnbornBranch => Ok(true),
                Err(e) => Err(e.into()),
            },
            Err(e) if e.code() == git2::ErrorCode::UnbornBranch => Ok(true),
            Err(e) => Err(e.into()),
        }
    }

    fn unborn_head_branch_name(&self) -> Result<Option<String>> {
        let head_path = self.repo.path().join("HEAD");
        let head_contents = fs::read_to_string(head_path)?;
        Ok(head_contents
            .trim()
            .strip_prefix("ref: refs/heads/")
            .map(|s| s.to_string()))
    }
}