Skip to main content

cascade_cli/git/
repository.rs

1use crate::cli::output::Output;
2use crate::errors::{CascadeError, Result};
3use chrono;
4use dialoguer::{theme::ColorfulTheme, Confirm, Select};
5use git2::{Oid, Repository, Signature};
6use std::path::{Path, PathBuf};
7use tracing::{debug, info, warn};
8
9/// Repository information
10#[derive(Debug, Clone)]
11pub struct RepositoryInfo {
12    pub path: PathBuf,
13    pub head_branch: Option<String>,
14    pub head_commit: Option<String>,
15    pub is_dirty: bool,
16    pub untracked_files: Vec<String>,
17}
18
19/// Backup information for force push operations
20#[derive(Debug, Clone)]
21struct ForceBackupInfo {
22    pub backup_branch_name: String,
23    pub remote_commit_id: String,
24    #[allow(dead_code)] // Used for logging/display purposes
25    pub commits_that_would_be_lost: usize,
26}
27
28/// Safety information for branch deletion operations
29#[derive(Debug, Clone)]
30struct BranchDeletionSafety {
31    pub unpushed_commits: Vec<String>,
32    pub remote_tracking_branch: Option<String>,
33    pub is_merged_to_main: bool,
34    pub main_branch_name: String,
35}
36
37/// Safety information for checkout operations
38#[derive(Debug, Clone)]
39struct CheckoutSafety {
40    #[allow(dead_code)] // Used in confirmation dialogs and future features
41    pub has_uncommitted_changes: bool,
42    pub modified_files: Vec<String>,
43    pub staged_files: Vec<String>,
44    pub untracked_files: Vec<String>,
45    #[allow(dead_code)] // Reserved for future automatic stashing implementation
46    pub stash_created: Option<String>,
47    #[allow(dead_code)] // Used for context in confirmation dialogs
48    pub current_branch: Option<String>,
49}
50
51/// SSL configuration for git operations
52#[derive(Debug, Clone)]
53pub struct GitSslConfig {
54    pub accept_invalid_certs: bool,
55    pub ca_bundle_path: Option<String>,
56}
57
58/// Summary of git repository status
59#[derive(Debug, Clone)]
60pub struct GitStatusSummary {
61    staged_files: usize,
62    unstaged_files: usize,
63    untracked_files: usize,
64}
65
66impl GitStatusSummary {
67    pub fn is_clean(&self) -> bool {
68        self.staged_files == 0 && self.unstaged_files == 0 && self.untracked_files == 0
69    }
70
71    pub fn has_staged_changes(&self) -> bool {
72        self.staged_files > 0
73    }
74
75    pub fn has_unstaged_changes(&self) -> bool {
76        self.unstaged_files > 0
77    }
78
79    pub fn has_untracked_files(&self) -> bool {
80        self.untracked_files > 0
81    }
82
83    pub fn staged_count(&self) -> usize {
84        self.staged_files
85    }
86
87    pub fn unstaged_count(&self) -> usize {
88        self.unstaged_files
89    }
90
91    pub fn untracked_count(&self) -> usize {
92        self.untracked_files
93    }
94}
95
96/// Wrapper around git2::Repository with safe operations
97///
98/// For thread safety, use the async variants (e.g., fetch_async, pull_async)
99/// which automatically handle threading using tokio::spawn_blocking.
100/// The async methods create new repository instances in background threads.
101pub struct GitRepository {
102    repo: Repository,
103    path: PathBuf,
104    ssl_config: Option<GitSslConfig>,
105    bitbucket_credentials: Option<BitbucketCredentials>,
106}
107
108#[derive(Debug, Clone)]
109struct BitbucketCredentials {
110    username: Option<String>,
111    token: Option<String>,
112}
113
114impl GitRepository {
115    /// Open a Git repository at the given path
116    /// Automatically loads SSL configuration from cascade config if available
117    pub fn open(path: &Path) -> Result<Self> {
118        let repo = Repository::discover(path)
119            .map_err(|e| CascadeError::config(format!("Not a git repository: {e}")))?;
120
121        let workdir = repo
122            .workdir()
123            .ok_or_else(|| CascadeError::config("Repository has no working directory"))?
124            .to_path_buf();
125
126        // Try to load SSL configuration from cascade config
127        let ssl_config = Self::load_ssl_config_from_cascade(&workdir);
128        let bitbucket_credentials = Self::load_bitbucket_credentials_from_cascade(&workdir);
129
130        Ok(Self {
131            repo,
132            path: workdir,
133            ssl_config,
134            bitbucket_credentials,
135        })
136    }
137
138    /// Load SSL configuration from cascade config file if it exists
139    fn load_ssl_config_from_cascade(repo_path: &Path) -> Option<GitSslConfig> {
140        // Try to load cascade configuration
141        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
142        let config_path = config_dir.join("config.json");
143        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
144
145        // Convert BitbucketConfig to GitSslConfig if SSL settings exist
146        if settings.bitbucket.accept_invalid_certs.is_some()
147            || settings.bitbucket.ca_bundle_path.is_some()
148        {
149            Some(GitSslConfig {
150                accept_invalid_certs: settings.bitbucket.accept_invalid_certs.unwrap_or(false),
151                ca_bundle_path: settings.bitbucket.ca_bundle_path,
152            })
153        } else {
154            None
155        }
156    }
157
158    /// Load Bitbucket credentials from cascade config file if it exists
159    fn load_bitbucket_credentials_from_cascade(repo_path: &Path) -> Option<BitbucketCredentials> {
160        // Try to load cascade configuration
161        let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
162        let config_path = config_dir.join("config.json");
163        let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
164
165        // Return credentials if any are configured
166        if settings.bitbucket.username.is_some() || settings.bitbucket.token.is_some() {
167            Some(BitbucketCredentials {
168                username: settings.bitbucket.username.clone(),
169                token: settings.bitbucket.token.clone(),
170            })
171        } else {
172            None
173        }
174    }
175
176    /// Get repository information
177    pub fn get_info(&self) -> Result<RepositoryInfo> {
178        let head_branch = self.get_current_branch().ok();
179        let head_commit = self.get_head_commit_hash().ok();
180        let is_dirty = self.is_dirty()?;
181        let untracked_files = self.get_untracked_files()?;
182
183        Ok(RepositoryInfo {
184            path: self.path.clone(),
185            head_branch,
186            head_commit,
187            is_dirty,
188            untracked_files,
189        })
190    }
191
192    /// Get the current branch name
193    pub fn get_current_branch(&self) -> Result<String> {
194        let head = self
195            .repo
196            .head()
197            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
198
199        if let Some(name) = head.shorthand() {
200            Ok(name.to_string())
201        } else {
202            // Detached HEAD - return commit hash
203            let commit = head
204                .peel_to_commit()
205                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
206            Ok(format!("HEAD@{}", commit.id()))
207        }
208    }
209
210    /// Get the HEAD commit hash
211    pub fn get_head_commit_hash(&self) -> Result<String> {
212        let head = self
213            .repo
214            .head()
215            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
216
217        let commit = head
218            .peel_to_commit()
219            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
220
221        Ok(commit.id().to_string())
222    }
223
224    /// Check if the working directory is dirty (has uncommitted changes)
225    /// Excludes .cascade/ directory changes as these are internal metadata
226    pub fn is_dirty(&self) -> Result<bool> {
227        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
228
229        for status in statuses.iter() {
230            let flags = status.status();
231
232            // Skip .cascade/ directory - it's internal metadata that shouldn't block operations
233            if let Some(path) = status.path() {
234                if path.starts_with(".cascade/") || path == ".cascade" {
235                    continue;
236                }
237            }
238
239            // Check for any modifications, additions, or deletions
240            if flags.intersects(
241                git2::Status::INDEX_MODIFIED
242                    | git2::Status::INDEX_NEW
243                    | git2::Status::INDEX_DELETED
244                    | git2::Status::WT_MODIFIED
245                    | git2::Status::WT_NEW
246                    | git2::Status::WT_DELETED,
247            ) {
248                return Ok(true);
249            }
250        }
251
252        Ok(false)
253    }
254
255    /// Get list of untracked files
256    pub fn get_untracked_files(&self) -> Result<Vec<String>> {
257        let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
258
259        let mut untracked = Vec::new();
260        for status in statuses.iter() {
261            if status.status().contains(git2::Status::WT_NEW) {
262                if let Some(path) = status.path() {
263                    untracked.push(path.to_string());
264                }
265            }
266        }
267
268        Ok(untracked)
269    }
270
271    /// Create a new branch
272    pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
273        let target_commit = if let Some(target) = target {
274            // Find the specified target commit/branch
275            let target_obj = self.repo.revparse_single(target).map_err(|e| {
276                CascadeError::branch(format!("Could not find target '{target}': {e}"))
277            })?;
278            target_obj.peel_to_commit().map_err(|e| {
279                CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
280            })?
281        } else {
282            // Use current HEAD
283            let head = self
284                .repo
285                .head()
286                .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
287            head.peel_to_commit()
288                .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
289        };
290
291        self.repo
292            .branch(name, &target_commit, false)
293            .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;
294
295        // Branch creation logging is handled by the caller for clean output
296        Ok(())
297    }
298
299    /// Update a branch to point to a specific commit (local operation only)
300    /// Creates the branch if it doesn't exist, updates it if it does
301    pub fn update_branch_to_commit(&self, branch_name: &str, commit_id: &str) -> Result<()> {
302        let commit_oid = Oid::from_str(commit_id).map_err(|e| {
303            CascadeError::branch(format!("Invalid commit ID '{}': {}", commit_id, e))
304        })?;
305
306        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
307            CascadeError::branch(format!("Commit '{}' not found: {}", commit_id, e))
308        })?;
309
310        // Try to find existing branch
311        if self
312            .repo
313            .find_branch(branch_name, git2::BranchType::Local)
314            .is_ok()
315        {
316            // Update existing branch to point to new commit
317            let refname = format!("refs/heads/{}", branch_name);
318            self.repo
319                .reference(
320                    &refname,
321                    commit_oid,
322                    true,
323                    "update branch to rebased commit",
324                )
325                .map_err(|e| {
326                    CascadeError::branch(format!(
327                        "Failed to update branch '{}': {}",
328                        branch_name, e
329                    ))
330                })?;
331        } else {
332            // Create new branch
333            self.repo.branch(branch_name, &commit, false).map_err(|e| {
334                CascadeError::branch(format!("Failed to create branch '{}': {}", branch_name, e))
335            })?;
336        }
337
338        Ok(())
339    }
340
341    /// Force-push a single branch to remote (simpler version for when branch is already updated locally)
342    pub fn force_push_single_branch(&self, branch_name: &str) -> Result<()> {
343        self.force_push_single_branch_with_options(branch_name, false, false)
344    }
345
346    /// Force push with option to skip user confirmation (for automated operations like sync)
347    pub fn force_push_single_branch_auto(&self, branch_name: &str) -> Result<()> {
348        self.force_push_single_branch_with_options(branch_name, true, false)
349    }
350
351    /// Force push a single branch without fetching first (assumes fetch already done)
352    /// Used in batch operations where we fetch once before pushing multiple branches
353    pub fn force_push_single_branch_auto_no_fetch(&self, branch_name: &str) -> Result<()> {
354        self.force_push_single_branch_with_options(branch_name, true, true)
355    }
356
357    fn force_push_single_branch_with_options(
358        &self,
359        branch_name: &str,
360        auto_confirm: bool,
361        skip_fetch: bool,
362    ) -> Result<()> {
363        // Validate branch exists before attempting push
364        // This provides a clearer error message than a failed git push
365        if self.get_branch_commit_hash(branch_name).is_err() {
366            return Err(CascadeError::branch(format!(
367                "Cannot push '{}': branch does not exist locally",
368                branch_name
369            )));
370        }
371
372        // CRITICAL: Fetch with retry to ensure we have latest remote state
373        // Using stale refs could cause silent data loss on force push!
374        // Skip if caller already fetched (batch operations)
375        if !skip_fetch {
376            self.fetch_with_retry()?;
377        }
378
379        // Check safety and create backup if needed
380        let safety_result = if auto_confirm {
381            self.check_force_push_safety_auto_no_fetch(branch_name)?
382        } else {
383            self.check_force_push_safety_enhanced(branch_name)?
384        };
385
386        if let Some(backup_info) = safety_result {
387            self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
388            Output::sub_item(format!(
389                "Created backup branch: {}",
390                backup_info.backup_branch_name
391            ));
392        }
393
394        // Ensure index is closed before CLI command to prevent lock conflicts
395        self.ensure_index_closed()?;
396
397        // Create marker file to signal pre-push hook to allow this internal push
398        // (Git hooks don't inherit env vars, so we use a file marker instead)
399        let marker_path = self.git_dir().join(".cascade-internal-push");
400        std::fs::write(&marker_path, "1")
401            .map_err(|e| CascadeError::branch(format!("Failed to create push marker: {}", e)))?;
402
403        // Force push using git CLI (more reliable than git2 for TLS)
404        let output = std::process::Command::new("git")
405            .args(["push", "--force", "origin", branch_name])
406            .current_dir(&self.path)
407            .output()
408            .map_err(|e| {
409                // Clean up marker on error
410                let _ = std::fs::remove_file(&marker_path);
411                CascadeError::branch(format!("Failed to execute git push: {}", e))
412            })?;
413
414        // Clean up marker file after push attempt
415        let _ = std::fs::remove_file(&marker_path);
416
417        if !output.status.success() {
418            let stderr = String::from_utf8_lossy(&output.stderr);
419            let stdout = String::from_utf8_lossy(&output.stdout);
420
421            // Combine stderr and stdout for full error context
422            let full_error = if !stdout.is_empty() {
423                format!("{}\n{}", stderr.trim(), stdout.trim())
424            } else {
425                stderr.trim().to_string()
426            };
427
428            return Err(CascadeError::branch(format!(
429                "Force push failed for '{}':\n{}",
430                branch_name, full_error
431            )));
432        }
433
434        Ok(())
435    }
436
437    /// Switch to a branch with safety checks
438    pub fn checkout_branch(&self, name: &str) -> Result<()> {
439        self.checkout_branch_with_options(name, false, true)
440    }
441
442    /// Switch to a branch silently (no output)
443    pub fn checkout_branch_silent(&self, name: &str) -> Result<()> {
444        self.checkout_branch_with_options(name, false, false)
445    }
446
447    /// Switch to a branch with force option to bypass safety checks
448    pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
449        self.checkout_branch_with_options(name, true, false)
450    }
451
452    /// Internal branch checkout implementation with safety options
453    fn checkout_branch_with_options(
454        &self,
455        name: &str,
456        force_unsafe: bool,
457        show_output: bool,
458    ) -> Result<()> {
459        debug!("Attempting to checkout branch: {}", name);
460
461        // Enhanced safety check: Detect uncommitted work before checkout
462        if !force_unsafe {
463            let safety_result = self.check_checkout_safety(name)?;
464            if let Some(safety_info) = safety_result {
465                // Repository has uncommitted changes, get user confirmation
466                self.handle_checkout_confirmation(name, &safety_info)?;
467            }
468        }
469
470        // Find the branch
471        let branch = self
472            .repo
473            .find_branch(name, git2::BranchType::Local)
474            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
475
476        let branch_ref = branch.get();
477        let tree = branch_ref.peel_to_tree().map_err(|e| {
478            CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
479        })?;
480
481        // Update HEAD first — this validates that the branch can be checked out
482        // (e.g., not already checked out in another worktree). Doing this before
483        // checkout_tree prevents leaving the working directory in an inconsistent
484        // state if set_head fails.
485        let old_head = self.repo.head().ok();
486        self.repo
487            .set_head(&format!("refs/heads/{name}"))
488            .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
489
490        // Now checkout the tree to update the working directory
491        let mut checkout_builder = git2::build::CheckoutBuilder::new();
492        checkout_builder.force(); // Overwrite modified files
493        checkout_builder.remove_untracked(false); // Keep untracked files
494
495        if let Err(e) = self
496            .repo
497            .checkout_tree(tree.as_object(), Some(&mut checkout_builder))
498        {
499            // Restore HEAD if checkout_tree fails so we don't leave HEAD
500            // pointing at a branch whose tree isn't checked out
501            if let Some(old) = old_head {
502                if let Some(old_name) = old.name() {
503                    let _ = self.repo.set_head(old_name);
504                }
505            }
506            return Err(CascadeError::branch(format!(
507                "Could not checkout branch '{name}': {e}"
508            )));
509        }
510
511        if show_output {
512            Output::success(format!("Switched to branch '{name}'"));
513        }
514        Ok(())
515    }
516
517    /// Checkout a specific commit (detached HEAD) with safety checks
518    pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
519        self.checkout_commit_with_options(commit_hash, false)
520    }
521
522    /// Checkout a specific commit with force option to bypass safety checks
523    pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
524        self.checkout_commit_with_options(commit_hash, true)
525    }
526
527    /// Internal commit checkout implementation with safety options
528    fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
529        debug!("Attempting to checkout commit: {}", commit_hash);
530
531        // Enhanced safety check: Detect uncommitted work before checkout
532        if !force_unsafe {
533            let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
534            if let Some(safety_info) = safety_result {
535                // Repository has uncommitted changes, get user confirmation
536                self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
537            }
538        }
539
540        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
541
542        let commit = self.repo.find_commit(oid).map_err(|e| {
543            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
544        })?;
545
546        let tree = commit.tree().map_err(|e| {
547            CascadeError::branch(format!(
548                "Could not get tree for commit '{commit_hash}': {e}"
549            ))
550        })?;
551
552        // Checkout the tree
553        self.repo
554            .checkout_tree(tree.as_object(), None)
555            .map_err(|e| {
556                CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
557            })?;
558
559        // Update HEAD to the commit (detached HEAD)
560        self.repo.set_head_detached(oid).map_err(|e| {
561            CascadeError::branch(format!(
562                "Could not update HEAD to commit '{commit_hash}': {e}"
563            ))
564        })?;
565
566        Output::success(format!(
567            "Checked out commit '{commit_hash}' (detached HEAD)"
568        ));
569        Ok(())
570    }
571
572    /// Check if a branch exists
573    pub fn branch_exists(&self, name: &str) -> bool {
574        self.repo.find_branch(name, git2::BranchType::Local).is_ok()
575    }
576
577    /// Check if a branch exists locally, and if not, attempt to fetch it from remote
578    pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
579        // 1. Check if branch exists locally first
580        if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
581            return Ok(true);
582        }
583
584        // 2. Try to fetch it from remote
585        crate::cli::output::Output::info(format!(
586            "Branch '{name}' not found locally, trying to fetch from remote..."
587        ));
588
589        use std::process::Command;
590
591        // Try: git fetch origin release/12.34:release/12.34
592        let fetch_result = Command::new("git")
593            .args(["fetch", "origin", &format!("{name}:{name}")])
594            .current_dir(&self.path)
595            .output();
596
597        match fetch_result {
598            Ok(output) => {
599                if output.status.success() {
600                    println!("✅ Successfully fetched '{name}' from origin");
601                    // 3. Check again locally after fetch
602                    return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
603                } else {
604                    let stderr = String::from_utf8_lossy(&output.stderr);
605                    tracing::debug!("Failed to fetch branch '{name}': {stderr}");
606                }
607            }
608            Err(e) => {
609                tracing::debug!("Git fetch command failed: {e}");
610            }
611        }
612
613        // 4. Try alternative fetch patterns for common branch naming
614        if name.contains('/') {
615            crate::cli::output::Output::info("Trying alternative fetch patterns...");
616
617            // Try: git fetch origin (to get all refs, then checkout locally)
618            let fetch_all_result = Command::new("git")
619                .args(["fetch", "origin"])
620                .current_dir(&self.path)
621                .output();
622
623            if let Ok(output) = fetch_all_result {
624                if output.status.success() {
625                    // Try to create local branch from remote
626                    let checkout_result = Command::new("git")
627                        .args(["checkout", "-b", name, &format!("origin/{name}")])
628                        .current_dir(&self.path)
629                        .output();
630
631                    if let Ok(checkout_output) = checkout_result {
632                        if checkout_output.status.success() {
633                            println!(
634                                "✅ Successfully created local branch '{name}' from origin/{name}"
635                            );
636                            return Ok(true);
637                        }
638                    }
639                }
640            }
641        }
642
643        // 5. Only fail if it doesn't exist anywhere
644        Ok(false)
645    }
646
647    /// Get the commit hash for a specific branch without switching branches
648    pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
649        let branch = self
650            .repo
651            .find_branch(branch_name, git2::BranchType::Local)
652            .map_err(|e| {
653                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
654            })?;
655
656        let commit = branch.get().peel_to_commit().map_err(|e| {
657            CascadeError::branch(format!(
658                "Could not get commit for branch '{branch_name}': {e}"
659            ))
660        })?;
661
662        Ok(commit.id().to_string())
663    }
664
665    /// List all local branches
666    pub fn list_branches(&self) -> Result<Vec<String>> {
667        let branches = self
668            .repo
669            .branches(Some(git2::BranchType::Local))
670            .map_err(CascadeError::Git)?;
671
672        let mut branch_names = Vec::new();
673        for branch in branches {
674            let (branch, _) = branch.map_err(CascadeError::Git)?;
675            if let Some(name) = branch.name().map_err(CascadeError::Git)? {
676                branch_names.push(name.to_string());
677            }
678        }
679
680        Ok(branch_names)
681    }
682
683    /// Get the upstream branch for a local branch
684    pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
685        // Try to get the upstream from git config
686        let config = self.repo.config().map_err(CascadeError::Git)?;
687
688        // Check for branch.{branch_name}.remote and branch.{branch_name}.merge
689        let remote_key = format!("branch.{branch_name}.remote");
690        let merge_key = format!("branch.{branch_name}.merge");
691
692        if let (Ok(remote), Ok(merge_ref)) = (
693            config.get_string(&remote_key),
694            config.get_string(&merge_key),
695        ) {
696            // Parse the merge ref (e.g., "refs/heads/feature-auth" -> "feature-auth")
697            if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
698                return Ok(Some(format!("{remote}/{branch_part}")));
699            }
700        }
701
702        // Fallback: check if there's a remote tracking branch with the same name
703        let potential_upstream = format!("origin/{branch_name}");
704        if self
705            .repo
706            .find_reference(&format!("refs/remotes/{potential_upstream}"))
707            .is_ok()
708        {
709            return Ok(Some(potential_upstream));
710        }
711
712        Ok(None)
713    }
714
715    /// Get ahead/behind counts compared to upstream
716    pub fn get_ahead_behind_counts(
717        &self,
718        local_branch: &str,
719        upstream_branch: &str,
720    ) -> Result<(usize, usize)> {
721        // Get the commit objects for both branches
722        let local_ref = self
723            .repo
724            .find_reference(&format!("refs/heads/{local_branch}"))
725            .map_err(|_| {
726                CascadeError::config(format!("Local branch '{local_branch}' not found"))
727            })?;
728        let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;
729
730        let upstream_ref = self
731            .repo
732            .find_reference(&format!("refs/remotes/{upstream_branch}"))
733            .map_err(|_| {
734                CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
735            })?;
736        let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;
737
738        // Use git2's graph_ahead_behind to calculate the counts
739        let (ahead, behind) = self
740            .repo
741            .graph_ahead_behind(local_commit.id(), upstream_commit.id())
742            .map_err(CascadeError::Git)?;
743
744        Ok((ahead, behind))
745    }
746
747    /// Set upstream tracking for a branch
748    pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
749        let mut config = self.repo.config().map_err(CascadeError::Git)?;
750
751        // Set branch.{branch_name}.remote = remote
752        let remote_key = format!("branch.{branch_name}.remote");
753        config
754            .set_str(&remote_key, remote)
755            .map_err(CascadeError::Git)?;
756
757        // Set branch.{branch_name}.merge = refs/heads/{remote_branch}
758        let merge_key = format!("branch.{branch_name}.merge");
759        let merge_value = format!("refs/heads/{remote_branch}");
760        config
761            .set_str(&merge_key, &merge_value)
762            .map_err(CascadeError::Git)?;
763
764        Ok(())
765    }
766
767    /// Create a commit with all staged changes
768    pub fn commit(&self, message: &str) -> Result<String> {
769        // Validate git user configuration before attempting commit operations
770        self.validate_git_user_config()?;
771
772        let signature = self.get_signature()?;
773        let tree_id = self.get_index_tree()?;
774        let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
775
776        // Get parent commits
777        let head = self.repo.head().map_err(CascadeError::Git)?;
778        let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
779
780        let commit_id = self
781            .repo
782            .commit(
783                Some("HEAD"),
784                &signature,
785                &signature,
786                message,
787                &tree,
788                &[&parent_commit],
789            )
790            .map_err(CascadeError::Git)?;
791
792        Output::success(format!("Created commit: {commit_id} - {message}"));
793        Ok(commit_id.to_string())
794    }
795
796    /// Commit any staged changes with a default message
797    pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
798        // Check if there are staged changes
799        let staged_files = self.get_staged_files()?;
800        if staged_files.is_empty() {
801            tracing::debug!("No staged changes to commit");
802            return Ok(None);
803        }
804
805        tracing::debug!("Committing {} staged files", staged_files.len());
806        let commit_hash = self.commit(default_message)?;
807        Ok(Some(commit_hash))
808    }
809
810    /// Stage all changes
811    pub fn stage_all(&self) -> Result<()> {
812        let mut index = self.repo.index().map_err(CascadeError::Git)?;
813
814        index
815            .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
816            .map_err(CascadeError::Git)?;
817
818        index.write().map_err(CascadeError::Git)?;
819        drop(index); // Explicitly close index after staging
820
821        tracing::debug!("Staged all changes");
822        Ok(())
823    }
824
825    /// Ensure the Git index is fully written and closed before external git CLI operations
826    /// This prevents "index is locked" errors when mixing libgit2 and git CLI commands
827    fn ensure_index_closed(&self) -> Result<()> {
828        // Open and immediately close the index to ensure any pending writes are flushed
829        // and file handles are released before we spawn git CLI processes
830        let mut index = self.repo.index().map_err(CascadeError::Git)?;
831        index.write().map_err(CascadeError::Git)?;
832        drop(index); // Explicit drop to release file handle
833
834        // Give the OS a moment to release file handles
835        // This is necessary because even after Rust drops the index,
836        // the OS might not immediately release the lock
837        std::thread::sleep(std::time::Duration::from_millis(10));
838
839        Ok(())
840    }
841
842    /// Stage only specific files (safer than stage_all during rebase)
843    pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
844        if file_paths.is_empty() {
845            tracing::debug!("No files to stage");
846            return Ok(());
847        }
848
849        let mut index = self.repo.index().map_err(CascadeError::Git)?;
850
851        for file_path in file_paths {
852            index
853                .add_path(std::path::Path::new(file_path))
854                .map_err(CascadeError::Git)?;
855        }
856
857        index.write().map_err(CascadeError::Git)?;
858        drop(index); // Explicitly close index after staging
859
860        tracing::debug!(
861            "Staged {} specific files: {:?}",
862            file_paths.len(),
863            file_paths
864        );
865        Ok(())
866    }
867
868    /// Stage only files that had conflicts (safer for rebase operations)
869    pub fn stage_conflict_resolved_files(&self) -> Result<()> {
870        let conflicted_files = self.get_conflicted_files()?;
871        if conflicted_files.is_empty() {
872            tracing::debug!("No conflicted files to stage");
873            return Ok(());
874        }
875
876        let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
877        self.stage_files(&file_paths)?;
878
879        tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
880        Ok(())
881    }
882
883    /// Clean up any in-progress merge/revert/cherry-pick state (removes CHERRY_PICK_HEAD etc.)
884    pub fn cleanup_state(&self) -> Result<()> {
885        let state = self.repo.state();
886        if state == git2::RepositoryState::Clean {
887            return Ok(());
888        }
889
890        tracing::debug!("Cleaning up repository state: {:?}", state);
891        self.repo.cleanup_state().map_err(|e| {
892            CascadeError::branch(format!(
893                "Failed to clean up repository state ({:?}): {}",
894                state, e
895            ))
896        })
897    }
898
899    /// Get repository path
900    pub fn path(&self) -> &Path {
901        &self.path
902    }
903
904    /// Per-worktree git directory.
905    /// Normal repos: /repo/.git/  |  Worktrees: /main/.git/worktrees/<name>/
906    pub fn git_dir(&self) -> &Path {
907        self.repo.path()
908    }
909
910    /// Shared common git directory (hooks, objects, refs).
911    /// Normal repos: same as git_dir()  |  Worktrees: /main/.git/
912    pub fn common_dir(&self) -> &Path {
913        self.repo.commondir()
914    }
915
916    /// Check if a commit exists
917    pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
918        match Oid::from_str(commit_hash) {
919            Ok(oid) => match self.repo.find_commit(oid) {
920                Ok(_) => Ok(true),
921                Err(_) => Ok(false),
922            },
923            Err(_) => Ok(false),
924        }
925    }
926
927    /// Check if a commit is already correctly based on a given parent
928    /// Returns true if the commit's parent matches the expected base
929    pub fn is_commit_based_on(&self, commit_hash: &str, expected_base: &str) -> Result<bool> {
930        let commit_oid = Oid::from_str(commit_hash).map_err(|e| {
931            CascadeError::branch(format!("Invalid commit hash '{}': {}", commit_hash, e))
932        })?;
933
934        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
935            CascadeError::branch(format!("Commit '{}' not found: {}", commit_hash, e))
936        })?;
937
938        // Get the commit's parent (first parent for merge commits)
939        if commit.parent_count() == 0 {
940            // Root commit has no parent
941            return Ok(false);
942        }
943
944        let parent = commit.parent(0).map_err(|e| {
945            CascadeError::branch(format!(
946                "Could not get parent of commit '{}': {}",
947                commit_hash, e
948            ))
949        })?;
950        let parent_hash = parent.id().to_string();
951
952        // Check if expected_base is a commit hash or a branch name
953        let expected_base_oid = if let Ok(oid) = Oid::from_str(expected_base) {
954            oid
955        } else {
956            // Try to resolve as a branch name
957            let branch_ref = format!("refs/heads/{}", expected_base);
958            let reference = self.repo.find_reference(&branch_ref).map_err(|e| {
959                CascadeError::branch(format!("Could not find base '{}': {}", expected_base, e))
960            })?;
961            reference.target().ok_or_else(|| {
962                CascadeError::branch(format!("Base '{}' has no target commit", expected_base))
963            })?
964        };
965
966        let expected_base_hash = expected_base_oid.to_string();
967
968        tracing::debug!(
969            "Checking if commit {} is based on {}: parent={}, expected={}",
970            &commit_hash[..8],
971            expected_base,
972            &parent_hash[..8],
973            &expected_base_hash[..8]
974        );
975
976        Ok(parent_hash == expected_base_hash)
977    }
978
979    /// Check whether `descendant` commit contains `ancestor` in its history
980    pub fn is_descendant_of(&self, descendant: &str, ancestor: &str) -> Result<bool> {
981        let descendant_oid = Oid::from_str(descendant).map_err(|e| {
982            CascadeError::branch(format!(
983                "Invalid commit hash '{}' for descendant check: {}",
984                descendant, e
985            ))
986        })?;
987        let ancestor_oid = Oid::from_str(ancestor).map_err(|e| {
988            CascadeError::branch(format!(
989                "Invalid commit hash '{}' for descendant check: {}",
990                ancestor, e
991            ))
992        })?;
993
994        self.repo
995            .graph_descendant_of(descendant_oid, ancestor_oid)
996            .map_err(CascadeError::Git)
997    }
998
999    /// Get the HEAD commit object
1000    pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
1001        let head = self
1002            .repo
1003            .head()
1004            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
1005        head.peel_to_commit()
1006            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
1007    }
1008
1009    /// Get a commit object by hash
1010    pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
1011        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1012
1013        self.repo.find_commit(oid).map_err(CascadeError::Git)
1014    }
1015
1016    /// Get the commit hash at the head of a branch
1017    pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
1018        let branch = self
1019            .repo
1020            .find_branch(branch_name, git2::BranchType::Local)
1021            .map_err(|e| {
1022                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
1023            })?;
1024
1025        let commit = branch.get().peel_to_commit().map_err(|e| {
1026            CascadeError::branch(format!(
1027                "Could not get commit for branch '{branch_name}': {e}"
1028            ))
1029        })?;
1030
1031        Ok(commit.id().to_string())
1032    }
1033
1034    /// Get the commit hash at the head of a remote branch
1035    pub fn get_remote_branch_head(&self, branch_name: &str) -> Result<String> {
1036        let refname = format!("refs/remotes/origin/{branch_name}");
1037        let reference = self.repo.find_reference(&refname).map_err(|e| {
1038            CascadeError::branch(format!("Remote branch '{branch_name}' not found: {e}"))
1039        })?;
1040
1041        let target = reference.target().ok_or_else(|| {
1042            CascadeError::branch(format!(
1043                "Remote branch '{branch_name}' does not have a target commit"
1044            ))
1045        })?;
1046
1047        Ok(target.to_string())
1048    }
1049
1050    /// Validate git user configuration is properly set
1051    pub fn validate_git_user_config(&self) -> Result<()> {
1052        if let Ok(config) = self.repo.config() {
1053            let name_result = config.get_string("user.name");
1054            let email_result = config.get_string("user.email");
1055
1056            if let (Ok(name), Ok(email)) = (name_result, email_result) {
1057                if !name.trim().is_empty() && !email.trim().is_empty() {
1058                    tracing::debug!("Git user config validated: {} <{}>", name, email);
1059                    return Ok(());
1060                }
1061            }
1062        }
1063
1064        // Check if this is a CI environment where validation can be skipped
1065        let is_ci = std::env::var("CI").is_ok();
1066
1067        if is_ci {
1068            tracing::debug!("CI environment - skipping git user config validation");
1069            return Ok(());
1070        }
1071
1072        Output::warning("Git user configuration missing or incomplete");
1073        Output::info("This can cause cherry-pick and commit operations to fail");
1074        Output::info("Please configure git user information:");
1075        Output::bullet("git config user.name \"Your Name\"".to_string());
1076        Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1077        Output::info("Or set globally with the --global flag");
1078
1079        // Don't fail - let operations continue with fallback signature
1080        // This preserves backward compatibility while providing guidance
1081        Ok(())
1082    }
1083
1084    /// Read the configured git user name and email from git config
1085    pub fn get_user_info(&self) -> (Option<String>, Option<String>) {
1086        let config = match self.repo.config() {
1087            Ok(c) => c,
1088            Err(_) => return (None, None),
1089        };
1090        let name = config.get_string("user.name").ok();
1091        let email = config.get_string("user.email").ok();
1092        (name, email)
1093    }
1094
1095    /// Get a signature for commits with comprehensive fallback and validation
1096    fn get_signature(&self) -> Result<Signature<'_>> {
1097        // Try to get signature from Git config first
1098        if let Ok(config) = self.repo.config() {
1099            // Try global/system config first
1100            let name_result = config.get_string("user.name");
1101            let email_result = config.get_string("user.email");
1102
1103            if let (Ok(name), Ok(email)) = (name_result, email_result) {
1104                if !name.trim().is_empty() && !email.trim().is_empty() {
1105                    tracing::debug!("Using git config: {} <{}>", name, email);
1106                    return Signature::now(&name, &email).map_err(CascadeError::Git);
1107                }
1108            } else {
1109                tracing::debug!("Git user config incomplete or missing");
1110            }
1111        }
1112
1113        // Check if this is a CI environment where fallback is acceptable
1114        let is_ci = std::env::var("CI").is_ok();
1115
1116        if is_ci {
1117            tracing::debug!("CI environment detected, using fallback signature");
1118            return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
1119        }
1120
1121        // Interactive environment - provide helpful guidance
1122        tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
1123
1124        // Try fallback signature, but warn about the issue
1125        match Signature::now("Cascade CLI", "cascade@example.com") {
1126            Ok(sig) => {
1127                Output::warning("Git user not configured - using fallback signature");
1128                Output::info("For better git history, run:");
1129                Output::bullet("git config user.name \"Your Name\"".to_string());
1130                Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1131                Output::info("Or set it globally with --global flag");
1132                Ok(sig)
1133            }
1134            Err(e) => {
1135                Err(CascadeError::branch(format!(
1136                    "Cannot create git signature: {e}. Please configure git user with:\n  git config user.name \"Your Name\"\n  git config user.email \"your.email@example.com\""
1137                )))
1138            }
1139        }
1140    }
1141
1142    /// Configure remote callbacks with SSL settings
1143    /// Priority: Cascade SSL config > Git config > Default
1144    fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
1145        self.configure_remote_callbacks_with_fallback(false)
1146    }
1147
1148    /// Determine if we should retry with DefaultCredentials based on git2 error classification
1149    fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
1150        match error.class() {
1151            // Authentication errors that might be resolved with DefaultCredentials
1152            git2::ErrorClass::Http => {
1153                // HTTP errors often indicate authentication issues in corporate environments
1154                match error.code() {
1155                    git2::ErrorCode::Auth => true,
1156                    _ => {
1157                        // Check for specific HTTP authentication replay errors
1158                        let error_string = error.to_string();
1159                        error_string.contains("too many redirects")
1160                            || error_string.contains("authentication replays")
1161                            || error_string.contains("authentication required")
1162                    }
1163                }
1164            }
1165            git2::ErrorClass::Net => {
1166                // Network errors that might be authentication-related
1167                let error_string = error.to_string();
1168                error_string.contains("authentication")
1169                    || error_string.contains("unauthorized")
1170                    || error_string.contains("forbidden")
1171            }
1172            _ => false,
1173        }
1174    }
1175
1176    /// Determine if we should fallback to git CLI based on git2 error classification
1177    fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
1178        match error.class() {
1179            // SSL/TLS errors that git CLI handles better
1180            git2::ErrorClass::Ssl => true,
1181
1182            // Certificate errors
1183            git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
1184
1185            // SSH errors that might need git CLI
1186            git2::ErrorClass::Ssh => {
1187                let error_string = error.to_string();
1188                error_string.contains("no callback set")
1189                    || error_string.contains("authentication required")
1190            }
1191
1192            // Network errors that might be proxy/firewall related
1193            git2::ErrorClass::Net => {
1194                let error_string = error.to_string();
1195                error_string.contains("TLS stream")
1196                    || error_string.contains("SSL")
1197                    || error_string.contains("proxy")
1198                    || error_string.contains("firewall")
1199            }
1200
1201            // General HTTP errors not handled by DefaultCredentials retry
1202            git2::ErrorClass::Http => {
1203                let error_string = error.to_string();
1204                error_string.contains("TLS stream")
1205                    || error_string.contains("SSL")
1206                    || error_string.contains("proxy")
1207            }
1208
1209            _ => false,
1210        }
1211    }
1212
1213    fn configure_remote_callbacks_with_fallback(
1214        &self,
1215        use_default_first: bool,
1216    ) -> Result<git2::RemoteCallbacks<'_>> {
1217        let mut callbacks = git2::RemoteCallbacks::new();
1218
1219        // Configure authentication with comprehensive credential support
1220        let bitbucket_credentials = self.bitbucket_credentials.clone();
1221        callbacks.credentials(move |url, username_from_url, allowed_types| {
1222            tracing::debug!(
1223                "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
1224                url,
1225                username_from_url,
1226                allowed_types
1227            );
1228
1229            // For SSH URLs with username
1230            if allowed_types.contains(git2::CredentialType::SSH_KEY) {
1231                if let Some(username) = username_from_url {
1232                    tracing::debug!("Trying SSH key authentication for user: {}", username);
1233                    return git2::Cred::ssh_key_from_agent(username);
1234                }
1235            }
1236
1237            // For HTTPS URLs, try multiple authentication methods in sequence
1238            if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
1239                // If we're in corporate network fallback mode, try DefaultCredentials first
1240                if use_default_first {
1241                    tracing::debug!("Corporate network mode: trying DefaultCredentials first");
1242                    return git2::Cred::default();
1243                }
1244
1245                if url.contains("bitbucket") {
1246                    if let Some(creds) = &bitbucket_credentials {
1247                        // Method 1: Username + Token (common for Bitbucket)
1248                        if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
1249                            tracing::debug!("Trying Bitbucket username + token authentication");
1250                            return git2::Cred::userpass_plaintext(username, token);
1251                        }
1252
1253                        // Method 2: Token as username, empty password (alternate Bitbucket format)
1254                        if let Some(token) = &creds.token {
1255                            tracing::debug!("Trying Bitbucket token-as-username authentication");
1256                            return git2::Cred::userpass_plaintext(token, "");
1257                        }
1258
1259                        // Method 3: Just username (will prompt for password or use credential helper)
1260                        if let Some(username) = &creds.username {
1261                            tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1262                            return git2::Cred::username(username);
1263                        }
1264                    }
1265                }
1266
1267                // Method 4: Default credential helper for all HTTPS URLs
1268                tracing::debug!("Trying default credential helper for HTTPS authentication");
1269                return git2::Cred::default();
1270            }
1271
1272            // Fallback to default for any other cases
1273            tracing::debug!("Using default credential fallback");
1274            git2::Cred::default()
1275        });
1276
1277        // Configure SSL certificate checking with system certificates by default
1278        // This matches what tools like Graphite, Sapling, and Phabricator do
1279        // Priority: 1. Use system certificates (default), 2. Manual overrides only if needed
1280
1281        let mut ssl_configured = false;
1282
1283        // Check for manual SSL overrides first (only when user explicitly needs them)
1284        if let Some(ssl_config) = &self.ssl_config {
1285            if ssl_config.accept_invalid_certs {
1286                Output::warning(
1287                    "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1288                );
1289                callbacks.certificate_check(|_cert, _host| {
1290                    tracing::debug!("⚠️  Accepting invalid certificate for host: {}", _host);
1291                    Ok(git2::CertificateCheckStatus::CertificateOk)
1292                });
1293                ssl_configured = true;
1294            } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1295                Output::info(format!(
1296                    "Using custom CA bundle from Cascade config: {ca_path}"
1297                ));
1298                callbacks.certificate_check(|_cert, host| {
1299                    tracing::debug!("Using custom CA bundle for host: {}", host);
1300                    Ok(git2::CertificateCheckStatus::CertificateOk)
1301                });
1302                ssl_configured = true;
1303            }
1304        }
1305
1306        // Check git config for manual overrides
1307        if !ssl_configured {
1308            if let Ok(config) = self.repo.config() {
1309                let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1310
1311                if !ssl_verify {
1312                    Output::warning(
1313                        "SSL certificate verification DISABLED via git config - this is insecure!",
1314                    );
1315                    callbacks.certificate_check(|_cert, host| {
1316                        tracing::debug!("⚠️  Bypassing SSL verification for host: {}", host);
1317                        Ok(git2::CertificateCheckStatus::CertificateOk)
1318                    });
1319                    ssl_configured = true;
1320                } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1321                    Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1322                    callbacks.certificate_check(|_cert, host| {
1323                        tracing::debug!("Using git config CA bundle for host: {}", host);
1324                        Ok(git2::CertificateCheckStatus::CertificateOk)
1325                    });
1326                    ssl_configured = true;
1327                }
1328            }
1329        }
1330
1331        // DEFAULT BEHAVIOR: Use system certificates (like git CLI and other modern tools)
1332        // This should work out-of-the-box in corporate environments
1333        if !ssl_configured {
1334            tracing::debug!(
1335                "Using system certificate store for SSL verification (default behavior)"
1336            );
1337
1338            // For macOS with SecureTransport backend, try default certificate validation first
1339            if cfg!(target_os = "macos") {
1340                tracing::debug!("macOS detected - using default certificate validation");
1341                // Don't set any certificate callback - let git2 use its default behavior
1342                // This often works better with SecureTransport backend on macOS
1343            } else {
1344                // Use CertificatePassthrough for other platforms
1345                callbacks.certificate_check(|_cert, host| {
1346                    tracing::debug!("System certificate validation for host: {}", host);
1347                    Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1348                });
1349            }
1350        }
1351
1352        Ok(callbacks)
1353    }
1354
1355    /// Get the tree ID from the current index
1356    fn get_index_tree(&self) -> Result<Oid> {
1357        let mut index = self.repo.index().map_err(CascadeError::Git)?;
1358
1359        index.write_tree().map_err(CascadeError::Git)
1360    }
1361
1362    /// Get repository status
1363    pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1364        self.repo.statuses(None).map_err(CascadeError::Git)
1365    }
1366
1367    /// Get a summary of repository status
1368    pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1369        let statuses = self.get_status()?;
1370
1371        let mut staged_files = 0;
1372        let mut unstaged_files = 0;
1373        let mut untracked_files = 0;
1374
1375        for status in statuses.iter() {
1376            let flags = status.status();
1377
1378            if flags.intersects(
1379                git2::Status::INDEX_MODIFIED
1380                    | git2::Status::INDEX_NEW
1381                    | git2::Status::INDEX_DELETED
1382                    | git2::Status::INDEX_RENAMED
1383                    | git2::Status::INDEX_TYPECHANGE,
1384            ) {
1385                staged_files += 1;
1386            }
1387
1388            if flags.intersects(
1389                git2::Status::WT_MODIFIED
1390                    | git2::Status::WT_DELETED
1391                    | git2::Status::WT_TYPECHANGE
1392                    | git2::Status::WT_RENAMED,
1393            ) {
1394                unstaged_files += 1;
1395            }
1396
1397            if flags.intersects(git2::Status::WT_NEW) {
1398                untracked_files += 1;
1399            }
1400        }
1401
1402        Ok(GitStatusSummary {
1403            staged_files,
1404            unstaged_files,
1405            untracked_files,
1406        })
1407    }
1408
1409    /// Get the current commit hash (alias for get_head_commit_hash)
1410    pub fn get_current_commit_hash(&self) -> Result<String> {
1411        self.get_head_commit_hash()
1412    }
1413
1414    /// Get the count of commits between two commits
1415    pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1416        let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1417        let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1418
1419        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1420        revwalk.push(to_oid).map_err(CascadeError::Git)?;
1421        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1422
1423        Ok(revwalk.count())
1424    }
1425
1426    /// Get remote URL for a given remote name
1427    pub fn get_remote_url(&self, name: &str) -> Result<String> {
1428        let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1429        Ok(remote.url().unwrap_or("unknown").to_string())
1430    }
1431
1432    /// Cherry-pick a specific commit to the current branch
1433    pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1434        tracing::debug!("Cherry-picking commit {}", commit_hash);
1435
1436        // Validate git user configuration before attempting commit operations
1437        self.validate_git_user_config()?;
1438
1439        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1440        let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1441
1442        // Get the commit's tree
1443        let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1444
1445        // Get parent tree for merge base
1446        let parent_commit = if commit.parent_count() > 0 {
1447            commit.parent(0).map_err(CascadeError::Git)?
1448        } else {
1449            // Root commit - use empty tree
1450            let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1451            let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1452            let sig = self.get_signature()?;
1453            return self
1454                .repo
1455                .commit(
1456                    Some("HEAD"),
1457                    &sig,
1458                    &sig,
1459                    commit.message().unwrap_or("Cherry-picked commit"),
1460                    &empty_tree,
1461                    &[],
1462                )
1463                .map(|oid| oid.to_string())
1464                .map_err(CascadeError::Git);
1465        };
1466
1467        let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1468
1469        // Get current HEAD tree for 3-way merge
1470        let head_commit = self.get_head_commit()?;
1471        let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1472
1473        // Perform 3-way merge
1474        let mut index = self
1475            .repo
1476            .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1477            .map_err(CascadeError::Git)?;
1478
1479        // Check for conflicts
1480        if index.has_conflicts() {
1481            // CRITICAL: Write the conflicted state to disk so auto-resolve can see it!
1482            // Without this, conflicts only exist in memory and Git's index stays clean
1483            debug!("Cherry-pick has conflicts - writing conflicted state to disk for resolution");
1484
1485            // The merge_trees() index is in-memory only. We need to:
1486            // 1. Get the repository's actual index
1487            // 2. Read entries from the merge result into it
1488            // 3. Write the repository index to disk
1489
1490            let mut repo_index = self.repo.index().map_err(CascadeError::Git)?;
1491
1492            // Clear the current index and read from the merge result
1493            repo_index.clear().map_err(CascadeError::Git)?;
1494            repo_index
1495                .read_tree(&head_tree)
1496                .map_err(CascadeError::Git)?;
1497
1498            // Now merge the commit tree into the repo index (this will create conflicts)
1499            repo_index
1500                .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
1501                .map_err(CascadeError::Git)?;
1502
1503            // Use git CLI to do the actual cherry-pick with conflicts
1504            // This is more reliable than trying to manually construct the conflicted index
1505
1506            // First, ensure our libgit2 index is closed so git CLI can work
1507            drop(repo_index);
1508            self.ensure_index_closed()?;
1509
1510            let cherry_pick_output = std::process::Command::new("git")
1511                .args(["cherry-pick", commit_hash])
1512                .current_dir(self.path())
1513                .output()
1514                .map_err(CascadeError::Io)?;
1515
1516            if !cherry_pick_output.status.success() {
1517                debug!("Git CLI cherry-pick failed as expected (has conflicts)");
1518                // This is expected - the cherry-pick failed due to conflicts
1519                // The conflicts are now in the working directory and index
1520            }
1521
1522            // CRITICAL: Reload the index from disk so libgit2 sees the conflicts
1523            // Git CLI wrote the conflicts to disk, but our in-memory index doesn't know yet
1524            self.repo
1525                .index()
1526                .and_then(|mut idx| idx.read(true).map(|_| ()))
1527                .map_err(CascadeError::Git)?;
1528
1529            debug!("Conflicted state written and index reloaded - auto-resolve can now process conflicts");
1530
1531            return Err(CascadeError::branch(format!(
1532                "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1533            )));
1534        }
1535
1536        // Write merged tree
1537        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1538        let merged_tree = self
1539            .repo
1540            .find_tree(merged_tree_oid)
1541            .map_err(CascadeError::Git)?;
1542
1543        // Create new commit with original message (preserve it exactly)
1544        let signature = self.get_signature()?;
1545        let message = commit.message().unwrap_or("Cherry-picked commit");
1546
1547        let new_commit_oid = self
1548            .repo
1549            .commit(
1550                Some("HEAD"),
1551                &signature,
1552                &signature,
1553                message,
1554                &merged_tree,
1555                &[&head_commit],
1556            )
1557            .map_err(CascadeError::Git)?;
1558
1559        // Update working directory to reflect the new commit
1560        let new_commit = self
1561            .repo
1562            .find_commit(new_commit_oid)
1563            .map_err(CascadeError::Git)?;
1564        let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1565
1566        self.repo
1567            .checkout_tree(
1568                new_tree.as_object(),
1569                Some(git2::build::CheckoutBuilder::new().force()),
1570            )
1571            .map_err(CascadeError::Git)?;
1572
1573        tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1574        Ok(new_commit_oid.to_string())
1575    }
1576
1577    /// Check for merge conflicts in the index
1578    pub fn has_conflicts(&self) -> Result<bool> {
1579        let index = self.repo.index().map_err(CascadeError::Git)?;
1580        Ok(index.has_conflicts())
1581    }
1582
1583    /// Get list of conflicted files
1584    pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1585        let index = self.repo.index().map_err(CascadeError::Git)?;
1586
1587        let mut conflicts = Vec::new();
1588
1589        // Iterate through index conflicts
1590        let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1591
1592        for conflict in conflict_iter {
1593            let conflict = conflict.map_err(CascadeError::Git)?;
1594            if let Some(our) = conflict.our {
1595                if let Ok(path) = std::str::from_utf8(&our.path) {
1596                    conflicts.push(path.to_string());
1597                }
1598            } else if let Some(their) = conflict.their {
1599                if let Ok(path) = std::str::from_utf8(&their.path) {
1600                    conflicts.push(path.to_string());
1601                }
1602            }
1603        }
1604
1605        Ok(conflicts)
1606    }
1607
1608    /// Fetch from remote origin
1609    pub fn fetch(&self) -> Result<()> {
1610        tracing::debug!("Fetching from origin");
1611
1612        // CRITICAL: Ensure index is closed before fetch operation
1613        // This prevents "index is locked" errors when fetch is called after cherry-pick/commit
1614        self.ensure_index_closed()?;
1615
1616        let mut remote = self
1617            .repo
1618            .find_remote("origin")
1619            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1620
1621        // Configure callbacks with SSL settings from git config
1622        let callbacks = self.configure_remote_callbacks()?;
1623
1624        // Fetch options with authentication and SSL config
1625        let mut fetch_options = git2::FetchOptions::new();
1626        fetch_options.remote_callbacks(callbacks);
1627
1628        // Fetch with authentication
1629        match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1630            Ok(_) => {
1631                tracing::debug!("Fetch completed successfully");
1632                Ok(())
1633            }
1634            Err(e) => {
1635                if self.should_retry_with_default_credentials(&e) {
1636                    tracing::debug!(
1637                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1638                        e.class(), e.code(), e
1639                    );
1640
1641                    // Retry with DefaultCredentials for corporate networks
1642                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1643                    let mut fetch_options = git2::FetchOptions::new();
1644                    fetch_options.remote_callbacks(callbacks);
1645
1646                    match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1647                        Ok(_) => {
1648                            tracing::debug!("Fetch succeeded with DefaultCredentials");
1649                            return Ok(());
1650                        }
1651                        Err(retry_error) => {
1652                            tracing::debug!(
1653                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1654                                retry_error
1655                            );
1656                            return self.fetch_with_git_cli();
1657                        }
1658                    }
1659                }
1660
1661                if self.should_fallback_to_git_cli(&e) {
1662                    tracing::debug!(
1663                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1664                        e.class(), e.code(), e
1665                    );
1666                    return self.fetch_with_git_cli();
1667                }
1668                Err(CascadeError::Git(e))
1669            }
1670        }
1671    }
1672
1673    /// Fetch from remote with exponential backoff retry logic
1674    /// This is critical for force push safety checks to prevent data loss from stale refs
1675    pub fn fetch_with_retry(&self) -> Result<()> {
1676        const MAX_RETRIES: u32 = 3;
1677        const BASE_DELAY_MS: u64 = 500;
1678
1679        let mut last_error = None;
1680
1681        for attempt in 0..MAX_RETRIES {
1682            match self.fetch() {
1683                Ok(_) => return Ok(()),
1684                Err(e) => {
1685                    last_error = Some(e);
1686
1687                    if attempt < MAX_RETRIES - 1 {
1688                        let delay_ms = BASE_DELAY_MS * 2_u64.pow(attempt);
1689                        debug!(
1690                            "Fetch attempt {} failed, retrying in {}ms...",
1691                            attempt + 1,
1692                            delay_ms
1693                        );
1694                        std::thread::sleep(std::time::Duration::from_millis(delay_ms));
1695                    }
1696                }
1697            }
1698        }
1699
1700        // All retries failed - this is CRITICAL for force push safety
1701        Err(CascadeError::Git(git2::Error::from_str(&format!(
1702            "Critical: Failed to fetch remote refs after {} attempts. Cannot safely proceed with force push - \
1703             stale remote refs could cause data loss. Error: {}. Please check network connection.",
1704            MAX_RETRIES,
1705            last_error.unwrap()
1706        ))))
1707    }
1708
1709    /// Pull changes from remote (fetch + merge)
1710    pub fn pull(&self, branch: &str) -> Result<()> {
1711        tracing::debug!("Pulling branch: {}", branch);
1712
1713        // First fetch - this now includes TLS fallback
1714        match self.fetch() {
1715            Ok(_) => {}
1716            Err(e) => {
1717                // If fetch failed even with CLI fallback, try full git pull as last resort
1718                let error_string = e.to_string();
1719                if error_string.contains("TLS stream") || error_string.contains("SSL") {
1720                    tracing::warn!(
1721                        "git2 error detected: {}, falling back to git CLI for pull operation",
1722                        e
1723                    );
1724                    return self.pull_with_git_cli(branch);
1725                }
1726                return Err(e);
1727            }
1728        }
1729
1730        // Get remote tracking branch
1731        let remote_branch_name = format!("origin/{branch}");
1732        let remote_oid = self
1733            .repo
1734            .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1735            .map_err(|e| {
1736                CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1737            })?;
1738
1739        let remote_commit = self
1740            .repo
1741            .find_commit(remote_oid)
1742            .map_err(CascadeError::Git)?;
1743
1744        // Get current HEAD
1745        let head_commit = self.get_head_commit()?;
1746
1747        // Check if already up to date
1748        if head_commit.id() == remote_commit.id() {
1749            tracing::debug!("Already up to date");
1750            return Ok(());
1751        }
1752
1753        // Check if we can fast-forward (local is ancestor of remote)
1754        let merge_base_oid = self
1755            .repo
1756            .merge_base(head_commit.id(), remote_commit.id())
1757            .map_err(CascadeError::Git)?;
1758
1759        if merge_base_oid == head_commit.id() {
1760            // Fast-forward: local is direct ancestor of remote, just move pointer
1761            tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1762
1763            // Update the branch reference to point to remote commit
1764            let refname = format!("refs/heads/{}", branch);
1765            self.repo
1766                .reference(&refname, remote_oid, true, "pull: Fast-forward")
1767                .map_err(CascadeError::Git)?;
1768
1769            // Update HEAD to point to the new commit
1770            self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1771
1772            // Checkout the new commit (update working directory)
1773            self.repo
1774                .checkout_head(Some(
1775                    git2::build::CheckoutBuilder::new()
1776                        .force()
1777                        .remove_untracked(false),
1778                ))
1779                .map_err(CascadeError::Git)?;
1780
1781            tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1782            return Ok(());
1783        }
1784
1785        // If we can't fast-forward, the local branch has diverged
1786        // This should NOT happen on protected branches!
1787        Err(CascadeError::branch(format!(
1788            "Branch '{}' has diverged from remote. Local has commits not in remote. \
1789             Protected branches should not have local commits. \
1790             Try: git reset --hard origin/{}",
1791            branch, branch
1792        )))
1793    }
1794
1795    /// Push current branch to remote
1796    pub fn push(&self, branch: &str) -> Result<()> {
1797        // Pushing branch to remote
1798
1799        let mut remote = self
1800            .repo
1801            .find_remote("origin")
1802            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1803
1804        let remote_url = remote.url().unwrap_or("unknown").to_string();
1805        tracing::debug!("Remote URL: {}", remote_url);
1806
1807        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1808        tracing::debug!("Push refspec: {}", refspec);
1809
1810        // Configure callbacks with enhanced SSL settings and error handling
1811        let mut callbacks = self.configure_remote_callbacks()?;
1812
1813        // Add enhanced progress and error callbacks for better debugging
1814        callbacks.push_update_reference(|refname, status| {
1815            if let Some(msg) = status {
1816                tracing::debug!("Push failed for ref {}: {}", refname, msg);
1817                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1818            }
1819            tracing::debug!("Push succeeded for ref: {}", refname);
1820            Ok(())
1821        });
1822
1823        // Push options with authentication and SSL config
1824        let mut push_options = git2::PushOptions::new();
1825        push_options.remote_callbacks(callbacks);
1826
1827        // Attempt push with enhanced error reporting
1828        match remote.push(&[&refspec], Some(&mut push_options)) {
1829            Ok(_) => {
1830                tracing::debug!("Push completed successfully for branch: {}", branch);
1831                Ok(())
1832            }
1833            Err(e) => {
1834                tracing::debug!(
1835                    "git2 push error: {} (class: {:?}, code: {:?})",
1836                    e,
1837                    e.class(),
1838                    e.code()
1839                );
1840
1841                if self.should_retry_with_default_credentials(&e) {
1842                    tracing::debug!(
1843                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1844                        e.class(), e.code(), e
1845                    );
1846
1847                    // Retry with DefaultCredentials for corporate networks
1848                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1849                    let mut push_options = git2::PushOptions::new();
1850                    push_options.remote_callbacks(callbacks);
1851
1852                    match remote.push(&[&refspec], Some(&mut push_options)) {
1853                        Ok(_) => {
1854                            tracing::debug!("Push succeeded with DefaultCredentials");
1855                            return Ok(());
1856                        }
1857                        Err(retry_error) => {
1858                            tracing::debug!(
1859                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1860                                retry_error
1861                            );
1862                            return self.push_with_git_cli(branch);
1863                        }
1864                    }
1865                }
1866
1867                if self.should_fallback_to_git_cli(&e) {
1868                    tracing::debug!(
1869                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1870                        e.class(), e.code(), e
1871                    );
1872                    return self.push_with_git_cli(branch);
1873                }
1874
1875                // Create concise error message
1876                let error_msg = if e.to_string().contains("authentication") {
1877                    format!(
1878                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1879                    )
1880                } else {
1881                    format!("Failed to push branch '{branch}': {e}")
1882                };
1883
1884                Err(CascadeError::branch(error_msg))
1885            }
1886        }
1887    }
1888
1889    /// Fallback push method using git CLI instead of git2
1890    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
1891    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1892        // Ensure index is closed before CLI command
1893        self.ensure_index_closed()?;
1894
1895        let output = std::process::Command::new("git")
1896            .args(["push", "origin", branch])
1897            .current_dir(&self.path)
1898            .output()
1899            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1900
1901        if output.status.success() {
1902            // Silent success - no need to log when fallback works
1903            Ok(())
1904        } else {
1905            let stderr = String::from_utf8_lossy(&output.stderr);
1906            let _stdout = String::from_utf8_lossy(&output.stdout);
1907            // Extract the most relevant error message
1908            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1909                "Network error: Unable to connect to repository (VPN may be required)".to_string()
1910            } else if stderr.contains("repository") && stderr.contains("not found") {
1911                "Repository not found - check your Bitbucket configuration".to_string()
1912            } else if stderr.contains("authentication") || stderr.contains("403") {
1913                "Authentication failed - check your credentials".to_string()
1914            } else {
1915                // For other errors, just show the stderr without the verbose prefix
1916                stderr.trim().to_string()
1917            };
1918            Err(CascadeError::branch(error_msg))
1919        }
1920    }
1921
1922    /// Fallback fetch method using git CLI instead of git2
1923    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1924    fn fetch_with_git_cli(&self) -> Result<()> {
1925        tracing::debug!("Using git CLI fallback for fetch operation");
1926
1927        // Ensure index is closed before CLI command
1928        self.ensure_index_closed()?;
1929
1930        let output = std::process::Command::new("git")
1931            .args(["fetch", "origin"])
1932            .current_dir(&self.path)
1933            .output()
1934            .map_err(|e| {
1935                CascadeError::Git(git2::Error::from_str(&format!(
1936                    "Failed to execute git command: {e}"
1937                )))
1938            })?;
1939
1940        if output.status.success() {
1941            tracing::debug!("Git CLI fetch succeeded");
1942            Ok(())
1943        } else {
1944            let stderr = String::from_utf8_lossy(&output.stderr);
1945            let stdout = String::from_utf8_lossy(&output.stdout);
1946            let error_msg = format!(
1947                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1948                output.status, stdout, stderr
1949            );
1950            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1951        }
1952    }
1953
1954    /// Fallback pull method using git CLI instead of git2
1955    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1956    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1957        tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1958
1959        // Ensure index is closed before CLI command
1960        self.ensure_index_closed()?;
1961
1962        let output = std::process::Command::new("git")
1963            .args(["pull", "origin", branch])
1964            .current_dir(&self.path)
1965            .output()
1966            .map_err(|e| {
1967                CascadeError::Git(git2::Error::from_str(&format!(
1968                    "Failed to execute git command: {e}"
1969                )))
1970            })?;
1971
1972        if output.status.success() {
1973            tracing::debug!("Git CLI pull succeeded for branch: {}", branch);
1974            Ok(())
1975        } else {
1976            let stderr = String::from_utf8_lossy(&output.stderr);
1977            let stdout = String::from_utf8_lossy(&output.stdout);
1978            let error_msg = format!(
1979                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1980                branch, output.status, stdout, stderr
1981            );
1982            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1983        }
1984    }
1985
1986    /// Fallback force push method using git CLI instead of git2
1987    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1988    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1989        tracing::debug!(
1990            "Using git CLI fallback for force push operation: {}",
1991            branch
1992        );
1993
1994        let output = std::process::Command::new("git")
1995            .args(["push", "--force", "origin", branch])
1996            .current_dir(&self.path)
1997            .output()
1998            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1999
2000        if output.status.success() {
2001            tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
2002            Ok(())
2003        } else {
2004            let stderr = String::from_utf8_lossy(&output.stderr);
2005            let stdout = String::from_utf8_lossy(&output.stdout);
2006            let error_msg = format!(
2007                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
2008                branch, output.status, stdout, stderr
2009            );
2010            Err(CascadeError::branch(error_msg))
2011        }
2012    }
2013
2014    /// Delete a local branch
2015    pub fn delete_branch(&self, name: &str) -> Result<()> {
2016        self.delete_branch_with_options(name, false)
2017    }
2018
2019    /// Delete a local branch with force option to bypass safety checks
2020    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
2021        self.delete_branch_with_options(name, true)
2022    }
2023
2024    /// Internal branch deletion implementation with safety options
2025    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
2026        debug!("Attempting to delete branch: {}", name);
2027
2028        // Enhanced safety check: Detect unpushed commits before deletion
2029        if !force_unsafe {
2030            let safety_result = self.check_branch_deletion_safety(name)?;
2031            if let Some(safety_info) = safety_result {
2032                // Branch has unpushed commits, get user confirmation
2033                self.handle_branch_deletion_confirmation(name, &safety_info)?;
2034            }
2035        }
2036
2037        let mut branch = self
2038            .repo
2039            .find_branch(name, git2::BranchType::Local)
2040            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
2041
2042        branch
2043            .delete()
2044            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
2045
2046        debug!("Successfully deleted branch '{}'", name);
2047        Ok(())
2048    }
2049
2050    /// Get commits between two references
2051    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
2052        let from_oid = self
2053            .repo
2054            .refname_to_id(&format!("refs/heads/{from}"))
2055            .or_else(|_| Oid::from_str(from))
2056            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
2057
2058        let to_oid = self
2059            .repo
2060            .refname_to_id(&format!("refs/heads/{to}"))
2061            .or_else(|_| Oid::from_str(to))
2062            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
2063
2064        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2065
2066        revwalk.push(to_oid).map_err(CascadeError::Git)?;
2067        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
2068
2069        let mut commits = Vec::new();
2070        for oid in revwalk {
2071            let oid = oid.map_err(CascadeError::Git)?;
2072            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
2073            commits.push(commit);
2074        }
2075
2076        Ok(commits)
2077    }
2078
2079    /// Force push one branch's content to another branch name
2080    /// This is used to preserve PR history while updating branch contents after rebase
2081    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2082        self.force_push_branch_with_options(target_branch, source_branch, false)
2083    }
2084
2085    /// Force push with explicit force flag to bypass safety checks
2086    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2087        self.force_push_branch_with_options(target_branch, source_branch, true)
2088    }
2089
2090    /// Internal force push implementation with safety options
2091    fn force_push_branch_with_options(
2092        &self,
2093        target_branch: &str,
2094        source_branch: &str,
2095        force_unsafe: bool,
2096    ) -> Result<()> {
2097        debug!(
2098            "Force pushing {} content to {} to preserve PR history",
2099            source_branch, target_branch
2100        );
2101
2102        // Enhanced safety check: Detect potential data loss and get user confirmation
2103        if !force_unsafe {
2104            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
2105            if let Some(backup_info) = safety_result {
2106                // Create backup branch before force push
2107                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
2108                Output::sub_item(format!(
2109                    "Created backup branch: {}",
2110                    backup_info.backup_branch_name
2111                ));
2112            }
2113        }
2114
2115        // First, ensure we have the latest changes for the source branch
2116        let source_ref = self
2117            .repo
2118            .find_reference(&format!("refs/heads/{source_branch}"))
2119            .map_err(|e| {
2120                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
2121            })?;
2122        let _source_commit = source_ref.peel_to_commit().map_err(|e| {
2123            CascadeError::config(format!(
2124                "Failed to get commit for source branch {source_branch}: {e}"
2125            ))
2126        })?;
2127
2128        // Force push to remote without modifying local target branch
2129        let mut remote = self
2130            .repo
2131            .find_remote("origin")
2132            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
2133
2134        // Push source branch content to remote target branch
2135        let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
2136
2137        // Configure callbacks with SSL settings from git config
2138        let callbacks = self.configure_remote_callbacks()?;
2139
2140        // Push options for force push with SSL config
2141        let mut push_options = git2::PushOptions::new();
2142        push_options.remote_callbacks(callbacks);
2143
2144        match remote.push(&[&refspec], Some(&mut push_options)) {
2145            Ok(_) => {}
2146            Err(e) => {
2147                if self.should_retry_with_default_credentials(&e) {
2148                    tracing::debug!(
2149                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
2150                        e.class(), e.code(), e
2151                    );
2152
2153                    // Retry with DefaultCredentials for corporate networks
2154                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
2155                    let mut push_options = git2::PushOptions::new();
2156                    push_options.remote_callbacks(callbacks);
2157
2158                    match remote.push(&[&refspec], Some(&mut push_options)) {
2159                        Ok(_) => {
2160                            tracing::debug!("Force push succeeded with DefaultCredentials");
2161                            // Success - continue to normal success path
2162                        }
2163                        Err(retry_error) => {
2164                            tracing::debug!(
2165                                "DefaultCredentials retry failed: {}, falling back to git CLI",
2166                                retry_error
2167                            );
2168                            return self.force_push_with_git_cli(target_branch);
2169                        }
2170                    }
2171                } else if self.should_fallback_to_git_cli(&e) {
2172                    tracing::debug!(
2173                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
2174                        e.class(), e.code(), e
2175                    );
2176                    return self.force_push_with_git_cli(target_branch);
2177                } else {
2178                    return Err(CascadeError::config(format!(
2179                        "Failed to force push {target_branch}: {e}"
2180                    )));
2181                }
2182            }
2183        }
2184
2185        tracing::debug!(
2186            "Successfully force pushed {} to preserve PR history",
2187            target_branch
2188        );
2189        Ok(())
2190    }
2191
2192    /// Enhanced safety check for force push operations with user confirmation
2193    /// Returns backup info if data would be lost and user confirms
2194    fn check_force_push_safety_enhanced(
2195        &self,
2196        target_branch: &str,
2197    ) -> Result<Option<ForceBackupInfo>> {
2198        // First fetch latest remote changes to ensure we have up-to-date information
2199        match self.fetch() {
2200            Ok(_) => {}
2201            Err(e) => {
2202                // If fetch fails, warn but don't block the operation
2203                debug!("Could not fetch latest changes for safety check: {}", e);
2204            }
2205        }
2206
2207        // Check if there are commits on the remote that would be lost
2208        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2209        let local_ref = format!("refs/heads/{target_branch}");
2210
2211        // Try to find both local and remote references
2212        let local_commit = match self.repo.find_reference(&local_ref) {
2213            Ok(reference) => reference.peel_to_commit().ok(),
2214            Err(_) => None,
2215        };
2216
2217        let remote_commit = match self.repo.find_reference(&remote_ref) {
2218            Ok(reference) => reference.peel_to_commit().ok(),
2219            Err(_) => None,
2220        };
2221
2222        // If we have both commits, check for divergence
2223        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2224            if local.id() != remote.id() {
2225                // Check if the remote has commits that the local doesn't have
2226                let merge_base_oid = self
2227                    .repo
2228                    .merge_base(local.id(), remote.id())
2229                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2230
2231                // If merge base != remote commit, remote has commits that would be lost
2232                if merge_base_oid != remote.id() {
2233                    let commits_to_lose = self.count_commits_between(
2234                        &merge_base_oid.to_string(),
2235                        &remote.id().to_string(),
2236                    )?;
2237
2238                    // Create backup branch name with timestamp
2239                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2240                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2241
2242                    debug!(
2243                        "Force push to '{}' would overwrite {} commits on remote",
2244                        target_branch, commits_to_lose
2245                    );
2246
2247                    // Check if we're in a non-interactive environment (CI/testing)
2248                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2249                    {
2250                        info!(
2251                            "Non-interactive environment detected, proceeding with backup creation"
2252                        );
2253                        return Ok(Some(ForceBackupInfo {
2254                            backup_branch_name,
2255                            remote_commit_id: remote.id().to_string(),
2256                            commits_that_would_be_lost: commits_to_lose,
2257                        }));
2258                    }
2259
2260                    // Automatically create backup - this is normal stacked diff workflow
2261                    return Ok(Some(ForceBackupInfo {
2262                        backup_branch_name,
2263                        remote_commit_id: remote.id().to_string(),
2264                        commits_that_would_be_lost: commits_to_lose,
2265                    }));
2266                }
2267            }
2268        }
2269
2270        Ok(None)
2271    }
2272
2273    /// Check force push safety without user confirmation (auto-creates backup)
2274    /// Used for automated operations like sync where user already confirmed the operation
2275    ///
2276    /// When skip_fetch=false: Fetches latest remote state before checking (default behavior)
2277    /// When skip_fetch=true: Assumes fetch already done (batch operations)
2278    fn check_force_push_safety_auto_no_fetch(
2279        &self,
2280        target_branch: &str,
2281    ) -> Result<Option<ForceBackupInfo>> {
2282        // Check if there are commits on the remote that would be lost
2283        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2284        let local_ref = format!("refs/heads/{target_branch}");
2285
2286        // Try to find both local and remote references
2287        let local_commit = match self.repo.find_reference(&local_ref) {
2288            Ok(reference) => reference.peel_to_commit().ok(),
2289            Err(_) => None,
2290        };
2291
2292        let remote_commit = match self.repo.find_reference(&remote_ref) {
2293            Ok(reference) => reference.peel_to_commit().ok(),
2294            Err(_) => None,
2295        };
2296
2297        // If we have both commits, check for divergence
2298        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2299            if local.id() != remote.id() {
2300                // Check if the remote has commits that the local doesn't have
2301                let merge_base_oid = self
2302                    .repo
2303                    .merge_base(local.id(), remote.id())
2304                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2305
2306                // If merge base != remote commit, remote has commits that would be lost
2307                if merge_base_oid != remote.id() {
2308                    let commits_to_lose = self.count_commits_between(
2309                        &merge_base_oid.to_string(),
2310                        &remote.id().to_string(),
2311                    )?;
2312
2313                    // Create backup branch name with timestamp
2314                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2315                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2316
2317                    tracing::debug!(
2318                        "Auto-creating backup '{}' for force push to '{}' (would overwrite {} commits)",
2319                        backup_branch_name, target_branch, commits_to_lose
2320                    );
2321
2322                    // Automatically create backup without confirmation
2323                    return Ok(Some(ForceBackupInfo {
2324                        backup_branch_name,
2325                        remote_commit_id: remote.id().to_string(),
2326                        commits_that_would_be_lost: commits_to_lose,
2327                    }));
2328                }
2329            }
2330        }
2331
2332        Ok(None)
2333    }
2334
2335    /// Create a backup branch pointing to the remote commit that would be lost
2336    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2337        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2338        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2339
2340        // Parse the commit ID
2341        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2342            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2343        })?;
2344
2345        // Find the commit
2346        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2347            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2348        })?;
2349
2350        // Create the backup branch
2351        self.repo
2352            .branch(&backup_branch_name, &commit, false)
2353            .map_err(|e| {
2354                CascadeError::config(format!(
2355                    "Failed to create backup branch {backup_branch_name}: {e}"
2356                ))
2357            })?;
2358
2359        debug!(
2360            "Created backup branch '{}' pointing to {}",
2361            backup_branch_name,
2362            &remote_commit_id[..8]
2363        );
2364        Ok(())
2365    }
2366
2367    /// Check if branch deletion is safe by detecting unpushed commits
2368    /// Returns safety info if there are concerns that need user attention
2369    fn check_branch_deletion_safety(
2370        &self,
2371        branch_name: &str,
2372    ) -> Result<Option<BranchDeletionSafety>> {
2373        // First, try to fetch latest remote changes
2374        match self.fetch() {
2375            Ok(_) => {}
2376            Err(e) => {
2377                warn!(
2378                    "Could not fetch latest changes for branch deletion safety check: {}",
2379                    e
2380                );
2381            }
2382        }
2383
2384        // Find the branch
2385        let branch = self
2386            .repo
2387            .find_branch(branch_name, git2::BranchType::Local)
2388            .map_err(|e| {
2389                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2390            })?;
2391
2392        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2393            CascadeError::branch(format!(
2394                "Could not get commit for branch '{branch_name}': {e}"
2395            ))
2396        })?;
2397
2398        // Determine the main branch (try common names)
2399        let main_branch_name = self.detect_main_branch()?;
2400
2401        // Check if branch is merged to main
2402        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2403
2404        // Find the upstream/remote tracking branch
2405        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2406
2407        let mut unpushed_commits = Vec::new();
2408
2409        // Check for unpushed commits compared to remote tracking branch
2410        if let Some(ref remote_branch) = remote_tracking_branch {
2411            match self.get_commits_between(remote_branch, branch_name) {
2412                Ok(commits) => {
2413                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2414                }
2415                Err(_) => {
2416                    // If we can't compare with remote, check against main branch
2417                    if !is_merged_to_main {
2418                        if let Ok(commits) =
2419                            self.get_commits_between(&main_branch_name, branch_name)
2420                        {
2421                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2422                        }
2423                    }
2424                }
2425            }
2426        } else if !is_merged_to_main {
2427            // No remote tracking branch, check against main
2428            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2429                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2430            }
2431        }
2432
2433        // If there are concerns, return safety info
2434        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2435        {
2436            Ok(Some(BranchDeletionSafety {
2437                unpushed_commits,
2438                remote_tracking_branch,
2439                is_merged_to_main,
2440                main_branch_name,
2441            }))
2442        } else {
2443            Ok(None)
2444        }
2445    }
2446
2447    /// Handle user confirmation for branch deletion with safety concerns
2448    fn handle_branch_deletion_confirmation(
2449        &self,
2450        branch_name: &str,
2451        safety_info: &BranchDeletionSafety,
2452    ) -> Result<()> {
2453        // Check if we're in a non-interactive environment
2454        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2455            return Err(CascadeError::branch(
2456                format!(
2457                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2458                    safety_info.unpushed_commits.len()
2459                )
2460            ));
2461        }
2462
2463        // Interactive warning and confirmation
2464        println!();
2465        Output::warning("BRANCH DELETION WARNING");
2466        println!("Branch '{branch_name}' has potential issues:");
2467
2468        if !safety_info.unpushed_commits.is_empty() {
2469            println!(
2470                "\n🔍 Unpushed commits ({} total):",
2471                safety_info.unpushed_commits.len()
2472            );
2473
2474            // Show details of unpushed commits
2475            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2476                if let Ok(oid) = Oid::from_str(commit_id) {
2477                    if let Ok(commit) = self.repo.find_commit(oid) {
2478                        let short_hash = &commit_id[..8];
2479                        let summary = commit.summary().unwrap_or("<no message>");
2480                        println!("  {}. {} - {}", i + 1, short_hash, summary);
2481                    }
2482                }
2483            }
2484
2485            if safety_info.unpushed_commits.len() > 5 {
2486                println!(
2487                    "  ... and {} more commits",
2488                    safety_info.unpushed_commits.len() - 5
2489                );
2490            }
2491        }
2492
2493        if !safety_info.is_merged_to_main {
2494            println!();
2495            crate::cli::output::Output::section("Branch status");
2496            crate::cli::output::Output::bullet(format!(
2497                "Not merged to '{}'",
2498                safety_info.main_branch_name
2499            ));
2500            if let Some(ref remote) = safety_info.remote_tracking_branch {
2501                crate::cli::output::Output::bullet(format!("Remote tracking branch: {remote}"));
2502            } else {
2503                crate::cli::output::Output::bullet("No remote tracking branch");
2504            }
2505        }
2506
2507        println!();
2508        crate::cli::output::Output::section("Safer alternatives");
2509        if !safety_info.unpushed_commits.is_empty() {
2510            if let Some(ref _remote) = safety_info.remote_tracking_branch {
2511                println!("  • Push commits first: git push origin {branch_name}");
2512            } else {
2513                println!("  • Create and push to remote: git push -u origin {branch_name}");
2514            }
2515        }
2516        if !safety_info.is_merged_to_main {
2517            println!(
2518                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
2519                safety_info.main_branch_name, safety_info.main_branch_name
2520            );
2521        }
2522
2523        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2524            .with_prompt("Do you want to proceed with deleting this branch?")
2525            .default(false)
2526            .interact()
2527            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2528
2529        if !confirmed {
2530            return Err(CascadeError::branch(
2531                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2532            ));
2533        }
2534
2535        Ok(())
2536    }
2537
2538    /// Detect the main branch name (main, master, develop)
2539    pub fn detect_main_branch(&self) -> Result<String> {
2540        let main_candidates = ["main", "master", "develop", "trunk"];
2541
2542        for candidate in &main_candidates {
2543            if self
2544                .repo
2545                .find_branch(candidate, git2::BranchType::Local)
2546                .is_ok()
2547            {
2548                return Ok(candidate.to_string());
2549            }
2550        }
2551
2552        // Fallback to HEAD's target if it's a symbolic reference
2553        if let Ok(head) = self.repo.head() {
2554            if let Some(name) = head.shorthand() {
2555                return Ok(name.to_string());
2556            }
2557        }
2558
2559        // Final fallback
2560        Ok("main".to_string())
2561    }
2562
2563    /// Check if a branch is merged to the main branch
2564    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2565        // Get the commits between main and the branch
2566        match self.get_commits_between(main_branch, branch_name) {
2567            Ok(commits) => Ok(commits.is_empty()),
2568            Err(_) => {
2569                // If we can't determine, assume not merged for safety
2570                Ok(false)
2571            }
2572        }
2573    }
2574
2575    /// Get the remote tracking branch for a local branch
2576    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2577        // Try common remote tracking branch patterns
2578        let remote_candidates = [
2579            format!("origin/{branch_name}"),
2580            format!("remotes/origin/{branch_name}"),
2581        ];
2582
2583        for candidate in &remote_candidates {
2584            if self
2585                .repo
2586                .find_reference(&format!(
2587                    "refs/remotes/{}",
2588                    candidate.replace("remotes/", "")
2589                ))
2590                .is_ok()
2591            {
2592                return Some(candidate.clone());
2593            }
2594        }
2595
2596        None
2597    }
2598
2599    /// Check if checkout operation is safe
2600    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2601        // Check if there are uncommitted changes
2602        let is_dirty = self.is_dirty()?;
2603        if !is_dirty {
2604            // No uncommitted changes, checkout is safe
2605            return Ok(None);
2606        }
2607
2608        // Get current branch for context
2609        let current_branch = self.get_current_branch().ok();
2610
2611        // Get detailed information about uncommitted changes
2612        let modified_files = self.get_modified_files()?;
2613        let staged_files = self.get_staged_files()?;
2614        let untracked_files = self.get_untracked_files()?;
2615
2616        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2617
2618        if has_uncommitted_changes || !untracked_files.is_empty() {
2619            return Ok(Some(CheckoutSafety {
2620                has_uncommitted_changes,
2621                modified_files,
2622                staged_files,
2623                untracked_files,
2624                stash_created: None,
2625                current_branch,
2626            }));
2627        }
2628
2629        Ok(None)
2630    }
2631
2632    /// Handle user confirmation for checkout operations with uncommitted changes
2633    fn handle_checkout_confirmation(
2634        &self,
2635        target: &str,
2636        safety_info: &CheckoutSafety,
2637    ) -> Result<()> {
2638        // Check if we're in a non-interactive environment FIRST (before any output)
2639        let is_ci = std::env::var("CI").is_ok();
2640        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2641        let is_non_interactive = is_ci || no_confirm;
2642
2643        if is_non_interactive {
2644            return Err(CascadeError::branch(
2645                format!(
2646                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2647                )
2648            ));
2649        }
2650
2651        // Interactive warning and confirmation
2652        println!("\nCHECKOUT WARNING");
2653        println!("Attempting to checkout: {}", target);
2654        println!("You have uncommitted changes that could be lost:");
2655
2656        if !safety_info.modified_files.is_empty() {
2657            println!("\nModified files ({}):", safety_info.modified_files.len());
2658            for file in safety_info.modified_files.iter().take(10) {
2659                println!("   - {file}");
2660            }
2661            if safety_info.modified_files.len() > 10 {
2662                println!("   ... and {} more", safety_info.modified_files.len() - 10);
2663            }
2664        }
2665
2666        if !safety_info.staged_files.is_empty() {
2667            println!("\nStaged files ({}):", safety_info.staged_files.len());
2668            for file in safety_info.staged_files.iter().take(10) {
2669                println!("   - {file}");
2670            }
2671            if safety_info.staged_files.len() > 10 {
2672                println!("   ... and {} more", safety_info.staged_files.len() - 10);
2673            }
2674        }
2675
2676        if !safety_info.untracked_files.is_empty() {
2677            println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2678            for file in safety_info.untracked_files.iter().take(5) {
2679                println!("   - {file}");
2680            }
2681            if safety_info.untracked_files.len() > 5 {
2682                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
2683            }
2684        }
2685
2686        println!("\nOptions:");
2687        println!("1. Stash changes and checkout (recommended)");
2688        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2689        println!("3. Cancel checkout");
2690
2691        // Use proper selection dialog instead of y/n confirmation
2692        let selection = Select::with_theme(&ColorfulTheme::default())
2693            .with_prompt("Choose an action")
2694            .items(&[
2695                "Stash changes and checkout (recommended)",
2696                "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2697                "Cancel checkout",
2698            ])
2699            .default(0)
2700            .interact()
2701            .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2702
2703        match selection {
2704            0 => {
2705                // Option 1: Stash changes and checkout
2706                let stash_message = format!(
2707                    "Auto-stash before checkout to {} at {}",
2708                    target,
2709                    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2710                );
2711
2712                match self.create_stash(&stash_message) {
2713                    Ok(stash_id) => {
2714                        crate::cli::output::Output::success(format!(
2715                            "Created stash: {stash_message} ({stash_id})"
2716                        ));
2717                        crate::cli::output::Output::tip("You can restore with: git stash pop");
2718                    }
2719                    Err(e) => {
2720                        crate::cli::output::Output::error(format!("Failed to create stash: {e}"));
2721
2722                        // If stash failed, provide better options
2723                        use dialoguer::Select;
2724                        let stash_failed_options = vec![
2725                            "Commit staged changes and proceed",
2726                            "Force checkout (WILL LOSE CHANGES)",
2727                            "Cancel and handle manually",
2728                        ];
2729
2730                        let stash_selection = Select::with_theme(&ColorfulTheme::default())
2731                            .with_prompt("Stash failed. What would you like to do?")
2732                            .items(&stash_failed_options)
2733                            .default(0)
2734                            .interact()
2735                            .map_err(|e| {
2736                                CascadeError::branch(format!("Could not get user selection: {e}"))
2737                            })?;
2738
2739                        match stash_selection {
2740                            0 => {
2741                                // Try to commit staged changes
2742                                let staged_files = self.get_staged_files()?;
2743                                if !staged_files.is_empty() {
2744                                    println!(
2745                                        "📝 Committing {} staged files...",
2746                                        staged_files.len()
2747                                    );
2748                                    match self
2749                                        .commit_staged_changes("WIP: Auto-commit before checkout")
2750                                    {
2751                                        Ok(Some(commit_hash)) => {
2752                                            crate::cli::output::Output::success(format!(
2753                                                "Committed staged changes as {}",
2754                                                &commit_hash[..8]
2755                                            ));
2756                                            crate::cli::output::Output::tip(
2757                                                "You can undo with: git reset HEAD~1",
2758                                            );
2759                                        }
2760                                        Ok(None) => {
2761                                            crate::cli::output::Output::info(
2762                                                "No staged changes found to commit",
2763                                            );
2764                                        }
2765                                        Err(commit_err) => {
2766                                            println!(
2767                                                "❌ Failed to commit staged changes: {commit_err}"
2768                                            );
2769                                            return Err(CascadeError::branch(
2770                                                "Could not commit staged changes".to_string(),
2771                                            ));
2772                                        }
2773                                    }
2774                                } else {
2775                                    println!("No staged changes to commit");
2776                                }
2777                            }
2778                            1 => {
2779                                // Force checkout anyway
2780                                Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2781                            }
2782                            2 => {
2783                                // Cancel
2784                                return Err(CascadeError::branch(
2785                                    "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2786                                ));
2787                            }
2788                            _ => unreachable!(),
2789                        }
2790                    }
2791                }
2792            }
2793            1 => {
2794                // Option 2: Force checkout (lose changes)
2795                Output::warning(
2796                    "Proceeding with force checkout - uncommitted changes will be lost!",
2797                );
2798            }
2799            2 => {
2800                // Option 3: Cancel
2801                return Err(CascadeError::branch(
2802                    "Checkout cancelled by user".to_string(),
2803                ));
2804            }
2805            _ => unreachable!(),
2806        }
2807
2808        Ok(())
2809    }
2810
2811    /// Create a stash with uncommitted changes
2812    fn create_stash(&self, message: &str) -> Result<String> {
2813        use crate::cli::output::Output;
2814
2815        tracing::debug!("Creating stash: {}", message);
2816
2817        // Use git CLI for stashing since git2 stashing is complex and unreliable
2818        let output = std::process::Command::new("git")
2819            .args(["stash", "push", "-m", message])
2820            .current_dir(&self.path)
2821            .output()
2822            .map_err(|e| {
2823                CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2824            })?;
2825
2826        if output.status.success() {
2827            let stdout = String::from_utf8_lossy(&output.stdout);
2828
2829            // Extract stash hash if available (git stash outputs like "Saved working directory and index state WIP on branch: message")
2830            let stash_id = if stdout.contains("Saved working directory") {
2831                // Get the most recent stash ID
2832                let stash_list_output = std::process::Command::new("git")
2833                    .args(["stash", "list", "-n", "1", "--format=%H"])
2834                    .current_dir(&self.path)
2835                    .output()
2836                    .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2837
2838                if stash_list_output.status.success() {
2839                    String::from_utf8_lossy(&stash_list_output.stdout)
2840                        .trim()
2841                        .to_string()
2842                } else {
2843                    "stash@{0}".to_string() // fallback
2844                }
2845            } else {
2846                "stash@{0}".to_string() // fallback
2847            };
2848
2849            Output::success(format!("Created stash: {} ({})", message, stash_id));
2850            Output::tip("You can restore with: git stash pop");
2851            Ok(stash_id)
2852        } else {
2853            let stderr = String::from_utf8_lossy(&output.stderr);
2854            let stdout = String::from_utf8_lossy(&output.stdout);
2855
2856            // Check for common stash failure reasons
2857            if stderr.contains("No local changes to save")
2858                || stdout.contains("No local changes to save")
2859            {
2860                return Err(CascadeError::branch("No local changes to save".to_string()));
2861            }
2862
2863            Err(CascadeError::branch(format!(
2864                "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2865                output.status, stderr, stdout
2866            )))
2867        }
2868    }
2869
2870    /// Get modified files in working directory
2871    fn get_modified_files(&self) -> Result<Vec<String>> {
2872        let mut opts = git2::StatusOptions::new();
2873        opts.include_untracked(false).include_ignored(false);
2874
2875        let statuses = self
2876            .repo
2877            .statuses(Some(&mut opts))
2878            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2879
2880        let mut modified_files = Vec::new();
2881        for status in statuses.iter() {
2882            let flags = status.status();
2883            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2884            {
2885                if let Some(path) = status.path() {
2886                    modified_files.push(path.to_string());
2887                }
2888            }
2889        }
2890
2891        Ok(modified_files)
2892    }
2893
2894    /// Get staged files in index
2895    pub fn get_staged_files(&self) -> Result<Vec<String>> {
2896        let mut opts = git2::StatusOptions::new();
2897        opts.include_untracked(false).include_ignored(false);
2898
2899        let statuses = self
2900            .repo
2901            .statuses(Some(&mut opts))
2902            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2903
2904        let mut staged_files = Vec::new();
2905        for status in statuses.iter() {
2906            let flags = status.status();
2907            if flags.contains(git2::Status::INDEX_MODIFIED)
2908                || flags.contains(git2::Status::INDEX_NEW)
2909                || flags.contains(git2::Status::INDEX_DELETED)
2910            {
2911                if let Some(path) = status.path() {
2912                    staged_files.push(path.to_string());
2913                }
2914            }
2915        }
2916
2917        Ok(staged_files)
2918    }
2919
2920    /// Count commits between two references
2921    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2922        let commits = self.get_commits_between(from, to)?;
2923        Ok(commits.len())
2924    }
2925
2926    /// Resolve a reference (branch name, tag, or commit hash) to a commit
2927    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2928        // Try to parse as commit hash first
2929        if let Ok(oid) = Oid::from_str(reference) {
2930            if let Ok(commit) = self.repo.find_commit(oid) {
2931                return Ok(commit);
2932            }
2933        }
2934
2935        // Try to resolve as a reference (branch, tag, etc.)
2936        let obj = self.repo.revparse_single(reference).map_err(|e| {
2937            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2938        })?;
2939
2940        obj.peel_to_commit().map_err(|e| {
2941            CascadeError::branch(format!(
2942                "Reference '{reference}' does not point to a commit: {e}"
2943            ))
2944        })
2945    }
2946
2947    /// Reset HEAD to a specific reference (soft reset)
2948    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2949        let target_commit = self.resolve_reference(target_ref)?;
2950
2951        self.repo
2952            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2953            .map_err(CascadeError::Git)?;
2954
2955        Ok(())
2956    }
2957
2958    /// Reset working directory and index to match HEAD (hard reset)
2959    /// This clears all uncommitted changes and staged files
2960    pub fn reset_to_head(&self) -> Result<()> {
2961        tracing::debug!("Resetting working directory and index to HEAD");
2962
2963        let repo_path = self.path();
2964
2965        // Use lock retry wrapper to handle stale locks automatically
2966        crate::utils::git_lock::with_lock_retry(repo_path, || {
2967            let head = self.repo.head()?;
2968            let head_commit = head.peel_to_commit()?;
2969
2970            // Hard reset: resets index and working tree
2971            let mut checkout_builder = git2::build::CheckoutBuilder::new();
2972            checkout_builder.force(); // Force checkout to overwrite any local changes
2973            checkout_builder.remove_untracked(false); // Don't remove untracked files
2974
2975            self.repo.reset(
2976                head_commit.as_object(),
2977                git2::ResetType::Hard,
2978                Some(&mut checkout_builder),
2979            )?;
2980
2981            Ok(())
2982        })?;
2983
2984        tracing::debug!("Successfully reset working directory to HEAD");
2985        Ok(())
2986    }
2987
2988    /// Find which branch contains a specific commit
2989    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2990        let oid = Oid::from_str(commit_hash).map_err(|e| {
2991            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2992        })?;
2993
2994        // Get all local branches
2995        let branches = self
2996            .repo
2997            .branches(Some(git2::BranchType::Local))
2998            .map_err(CascadeError::Git)?;
2999
3000        for branch_result in branches {
3001            let (branch, _) = branch_result.map_err(CascadeError::Git)?;
3002
3003            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
3004                // Check if this branch contains the commit
3005                if let Ok(branch_head) = branch.get().peel_to_commit() {
3006                    // Walk the commit history from this branch's HEAD
3007                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
3008                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
3009
3010                    for commit_oid in revwalk {
3011                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
3012                        if commit_oid == oid {
3013                            return Ok(branch_name.to_string());
3014                        }
3015                    }
3016                }
3017            }
3018        }
3019
3020        // If not found in any branch, might be on current HEAD
3021        Err(CascadeError::branch(format!(
3022            "Commit {commit_hash} not found in any local branch"
3023        )))
3024    }
3025
3026    // Async wrappers for potentially blocking operations
3027
3028    /// Fetch from remote origin (async)
3029    pub async fn fetch_async(&self) -> Result<()> {
3030        let repo_path = self.path.clone();
3031        crate::utils::async_ops::run_git_operation(move || {
3032            let repo = GitRepository::open(&repo_path)?;
3033            repo.fetch()
3034        })
3035        .await
3036    }
3037
3038    /// Pull changes from remote (async)
3039    pub async fn pull_async(&self, branch: &str) -> Result<()> {
3040        let repo_path = self.path.clone();
3041        let branch_name = branch.to_string();
3042        crate::utils::async_ops::run_git_operation(move || {
3043            let repo = GitRepository::open(&repo_path)?;
3044            repo.pull(&branch_name)
3045        })
3046        .await
3047    }
3048
3049    /// Push branch to remote (async)
3050    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
3051        let repo_path = self.path.clone();
3052        let branch = branch_name.to_string();
3053        crate::utils::async_ops::run_git_operation(move || {
3054            let repo = GitRepository::open(&repo_path)?;
3055            repo.push(&branch)
3056        })
3057        .await
3058    }
3059
3060    /// Cherry-pick commit (async)
3061    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
3062        let repo_path = self.path.clone();
3063        let hash = commit_hash.to_string();
3064        crate::utils::async_ops::run_git_operation(move || {
3065            let repo = GitRepository::open(&repo_path)?;
3066            repo.cherry_pick(&hash)
3067        })
3068        .await
3069    }
3070
3071    /// Get commit hashes between two refs (async)
3072    pub async fn get_commit_hashes_between_async(
3073        &self,
3074        from: &str,
3075        to: &str,
3076    ) -> Result<Vec<String>> {
3077        let repo_path = self.path.clone();
3078        let from_str = from.to_string();
3079        let to_str = to.to_string();
3080        crate::utils::async_ops::run_git_operation(move || {
3081            let repo = GitRepository::open(&repo_path)?;
3082            let commits = repo.get_commits_between(&from_str, &to_str)?;
3083            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
3084        })
3085        .await
3086    }
3087
3088    /// Reset a branch to point to a specific commit
3089    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
3090        info!(
3091            "Resetting branch '{}' to commit {}",
3092            branch_name,
3093            &commit_hash[..8]
3094        );
3095
3096        // Find the target commit
3097        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
3098            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3099        })?;
3100
3101        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
3102            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
3103        })?;
3104
3105        // Find the branch
3106        let _branch = self
3107            .repo
3108            .find_branch(branch_name, git2::BranchType::Local)
3109            .map_err(|e| {
3110                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3111            })?;
3112
3113        // Update the branch reference to point to the target commit
3114        let branch_ref_name = format!("refs/heads/{branch_name}");
3115        self.repo
3116            .reference(
3117                &branch_ref_name,
3118                target_oid,
3119                true,
3120                &format!("Reset {branch_name} to {commit_hash}"),
3121            )
3122            .map_err(|e| {
3123                CascadeError::branch(format!(
3124                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3125                ))
3126            })?;
3127
3128        tracing::info!(
3129            "Successfully reset branch '{}' to commit {}",
3130            branch_name,
3131            &commit_hash[..8]
3132        );
3133        Ok(())
3134    }
3135
3136    /// Detect the parent branch of the current branch using multiple strategies
3137    pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3138        let current_branch = self.get_current_branch()?;
3139
3140        // Strategy 1: Check if current branch has an upstream tracking branch
3141        if let Ok(Some(upstream)) = self.get_upstream_branch(&current_branch) {
3142            // Extract the branch name from "origin/branch-name" format
3143            if let Some(branch_name) = upstream.split('/').nth(1) {
3144                if self.branch_exists(branch_name) {
3145                    tracing::debug!(
3146                        "Detected parent branch '{}' from upstream tracking",
3147                        branch_name
3148                    );
3149                    return Ok(Some(branch_name.to_string()));
3150                }
3151            }
3152        }
3153
3154        // Strategy 2: Use git's default branch detection
3155        if let Ok(default_branch) = self.detect_main_branch() {
3156            // Don't suggest the current branch as its own parent
3157            if current_branch != default_branch {
3158                tracing::debug!(
3159                    "Detected parent branch '{}' as repository default",
3160                    default_branch
3161                );
3162                return Ok(Some(default_branch));
3163            }
3164        }
3165
3166        // Strategy 3: Find the branch with the most recent common ancestor
3167        // Get all local branches and find the one with the shortest commit distance
3168        if let Ok(branches) = self.list_branches() {
3169            let current_commit = self.get_head_commit()?;
3170            let current_commit_hash = current_commit.id().to_string();
3171            let current_oid = current_commit.id();
3172
3173            let mut best_candidate = None;
3174            let mut best_distance = usize::MAX;
3175
3176            for branch in branches {
3177                // Skip the current branch and any branches that look like version branches
3178                if branch == current_branch
3179                    || branch.contains("-v")
3180                    || branch.ends_with("-v2")
3181                    || branch.ends_with("-v3")
3182                {
3183                    continue;
3184                }
3185
3186                if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3187                    if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3188                        // Find merge base between current branch and this branch
3189                        if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3190                            // Count commits from merge base to current head
3191                            if let Ok(distance) = self.count_commits_between(
3192                                &merge_base_oid.to_string(),
3193                                &current_commit_hash,
3194                            ) {
3195                                // Prefer branches with shorter distances (more recent common ancestor)
3196                                // Also prefer branches that look like base branches
3197                                let is_likely_base = self.is_likely_base_branch(&branch);
3198                                let adjusted_distance = if is_likely_base {
3199                                    distance
3200                                } else {
3201                                    distance + 1000
3202                                };
3203
3204                                if adjusted_distance < best_distance {
3205                                    best_distance = adjusted_distance;
3206                                    best_candidate = Some(branch.clone());
3207                                }
3208                            }
3209                        }
3210                    }
3211                }
3212            }
3213
3214            if let Some(ref candidate) = best_candidate {
3215                tracing::debug!(
3216                    "Detected parent branch '{}' with distance {}",
3217                    candidate,
3218                    best_distance
3219                );
3220            }
3221
3222            return Ok(best_candidate);
3223        }
3224
3225        tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3226        Ok(None)
3227    }
3228
3229    /// Check if a branch name looks like a typical base branch
3230    fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3231        let base_patterns = [
3232            "main",
3233            "master",
3234            "develop",
3235            "dev",
3236            "development",
3237            "staging",
3238            "stage",
3239            "release",
3240            "production",
3241            "prod",
3242        ];
3243
3244        base_patterns.contains(&branch_name)
3245    }
3246}
3247
3248#[cfg(test)]
3249mod tests {
3250    use super::*;
3251    use std::process::Command;
3252    use tempfile::TempDir;
3253
3254    fn create_test_repo() -> (TempDir, PathBuf) {
3255        let temp_dir = TempDir::new().unwrap();
3256        let repo_path = temp_dir.path().to_path_buf();
3257
3258        // Initialize git repository
3259        Command::new("git")
3260            .args(["init"])
3261            .current_dir(&repo_path)
3262            .output()
3263            .unwrap();
3264        Command::new("git")
3265            .args(["config", "user.name", "Test"])
3266            .current_dir(&repo_path)
3267            .output()
3268            .unwrap();
3269        Command::new("git")
3270            .args(["config", "user.email", "test@test.com"])
3271            .current_dir(&repo_path)
3272            .output()
3273            .unwrap();
3274
3275        // Create initial commit
3276        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3277        Command::new("git")
3278            .args(["add", "."])
3279            .current_dir(&repo_path)
3280            .output()
3281            .unwrap();
3282        Command::new("git")
3283            .args(["commit", "-m", "Initial commit"])
3284            .current_dir(&repo_path)
3285            .output()
3286            .unwrap();
3287
3288        (temp_dir, repo_path)
3289    }
3290
3291    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3292        let file_path = repo_path.join(filename);
3293        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3294
3295        Command::new("git")
3296            .args(["add", filename])
3297            .current_dir(repo_path)
3298            .output()
3299            .unwrap();
3300        Command::new("git")
3301            .args(["commit", "-m", message])
3302            .current_dir(repo_path)
3303            .output()
3304            .unwrap();
3305    }
3306
3307    #[test]
3308    fn test_repository_info() {
3309        let (_temp_dir, repo_path) = create_test_repo();
3310        let repo = GitRepository::open(&repo_path).unwrap();
3311
3312        let info = repo.get_info().unwrap();
3313        assert!(!info.is_dirty); // Should be clean after commit
3314        assert!(
3315            info.head_branch == Some("master".to_string())
3316                || info.head_branch == Some("main".to_string()),
3317            "Expected default branch to be 'master' or 'main', got {:?}",
3318            info.head_branch
3319        );
3320        assert!(info.head_commit.is_some()); // Just check it exists
3321        assert!(info.untracked_files.is_empty()); // Should be empty after commit
3322    }
3323
3324    #[test]
3325    fn test_force_push_branch_basic() {
3326        let (_temp_dir, repo_path) = create_test_repo();
3327        let repo = GitRepository::open(&repo_path).unwrap();
3328
3329        // Get the actual default branch name
3330        let default_branch = repo.get_current_branch().unwrap();
3331
3332        // Create source branch with commits
3333        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3334        Command::new("git")
3335            .args(["checkout", "-b", "source-branch"])
3336            .current_dir(&repo_path)
3337            .output()
3338            .unwrap();
3339        create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3340
3341        // Create target branch
3342        Command::new("git")
3343            .args(["checkout", &default_branch])
3344            .current_dir(&repo_path)
3345            .output()
3346            .unwrap();
3347        Command::new("git")
3348            .args(["checkout", "-b", "target-branch"])
3349            .current_dir(&repo_path)
3350            .output()
3351            .unwrap();
3352        create_commit(&repo_path, "Target commit", "target.rs");
3353
3354        // Test force push from source to target
3355        let result = repo.force_push_branch("target-branch", "source-branch");
3356
3357        // Should succeed in test environment (even though it doesn't actually push to remote)
3358        // The important thing is that the function doesn't panic and handles the git2 operations
3359        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
3360    }
3361
3362    #[test]
3363    fn test_force_push_branch_nonexistent_branches() {
3364        let (_temp_dir, repo_path) = create_test_repo();
3365        let repo = GitRepository::open(&repo_path).unwrap();
3366
3367        // Get the actual default branch name
3368        let default_branch = repo.get_current_branch().unwrap();
3369
3370        // Test force push with nonexistent source branch
3371        let result = repo.force_push_branch("target", "nonexistent-source");
3372        assert!(result.is_err());
3373
3374        // Test force push with nonexistent target branch
3375        let result = repo.force_push_branch("nonexistent-target", &default_branch);
3376        assert!(result.is_err());
3377    }
3378
3379    #[test]
3380    fn test_force_push_workflow_simulation() {
3381        let (_temp_dir, repo_path) = create_test_repo();
3382        let repo = GitRepository::open(&repo_path).unwrap();
3383
3384        // Simulate the smart force push workflow:
3385        // 1. Original branch exists with PR
3386        Command::new("git")
3387            .args(["checkout", "-b", "feature-auth"])
3388            .current_dir(&repo_path)
3389            .output()
3390            .unwrap();
3391        create_commit(&repo_path, "Add authentication", "auth.rs");
3392
3393        // 2. Rebase creates versioned branch
3394        Command::new("git")
3395            .args(["checkout", "-b", "feature-auth-v2"])
3396            .current_dir(&repo_path)
3397            .output()
3398            .unwrap();
3399        create_commit(&repo_path, "Fix auth validation", "auth.rs");
3400
3401        // 3. Smart force push: update original branch from versioned branch
3402        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3403
3404        // Verify the operation is handled properly (success or expected error)
3405        match result {
3406            Ok(_) => {
3407                // Force push succeeded - verify branch state if possible
3408                Command::new("git")
3409                    .args(["checkout", "feature-auth"])
3410                    .current_dir(&repo_path)
3411                    .output()
3412                    .unwrap();
3413                let log_output = Command::new("git")
3414                    .args(["log", "--oneline", "-2"])
3415                    .current_dir(&repo_path)
3416                    .output()
3417                    .unwrap();
3418                let log_str = String::from_utf8_lossy(&log_output.stdout);
3419                assert!(
3420                    log_str.contains("Fix auth validation")
3421                        || log_str.contains("Add authentication")
3422                );
3423            }
3424            Err(_) => {
3425                // Expected in test environment without remote - that's fine
3426                // The important thing is we tested the code path without panicking
3427            }
3428        }
3429    }
3430
3431    #[test]
3432    fn test_branch_operations() {
3433        let (_temp_dir, repo_path) = create_test_repo();
3434        let repo = GitRepository::open(&repo_path).unwrap();
3435
3436        // Test get current branch - accept either main or master
3437        let current = repo.get_current_branch().unwrap();
3438        assert!(
3439            current == "master" || current == "main",
3440            "Expected default branch to be 'master' or 'main', got '{current}'"
3441        );
3442
3443        // Test create branch
3444        Command::new("git")
3445            .args(["checkout", "-b", "test-branch"])
3446            .current_dir(&repo_path)
3447            .output()
3448            .unwrap();
3449        let current = repo.get_current_branch().unwrap();
3450        assert_eq!(current, "test-branch");
3451    }
3452
3453    #[test]
3454    fn test_commit_operations() {
3455        let (_temp_dir, repo_path) = create_test_repo();
3456        let repo = GitRepository::open(&repo_path).unwrap();
3457
3458        // Test get head commit
3459        let head = repo.get_head_commit().unwrap();
3460        assert_eq!(head.message().unwrap().trim(), "Initial commit");
3461
3462        // Test get commit by hash
3463        let hash = head.id().to_string();
3464        let same_commit = repo.get_commit(&hash).unwrap();
3465        assert_eq!(head.id(), same_commit.id());
3466    }
3467
3468    #[test]
3469    fn test_checkout_safety_clean_repo() {
3470        let (_temp_dir, repo_path) = create_test_repo();
3471        let repo = GitRepository::open(&repo_path).unwrap();
3472
3473        // Create a test branch
3474        create_commit(&repo_path, "Second commit", "test.txt");
3475        Command::new("git")
3476            .args(["checkout", "-b", "test-branch"])
3477            .current_dir(&repo_path)
3478            .output()
3479            .unwrap();
3480
3481        // Test checkout safety with clean repo
3482        let safety_result = repo.check_checkout_safety("main");
3483        assert!(safety_result.is_ok());
3484        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
3485    }
3486
3487    #[test]
3488    fn test_checkout_safety_with_modified_files() {
3489        let (_temp_dir, repo_path) = create_test_repo();
3490        let repo = GitRepository::open(&repo_path).unwrap();
3491
3492        // Create a test branch
3493        Command::new("git")
3494            .args(["checkout", "-b", "test-branch"])
3495            .current_dir(&repo_path)
3496            .output()
3497            .unwrap();
3498
3499        // Modify a file to create uncommitted changes
3500        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3501
3502        // Test checkout safety with modified files
3503        let safety_result = repo.check_checkout_safety("main");
3504        assert!(safety_result.is_ok());
3505        let safety_info = safety_result.unwrap();
3506        assert!(safety_info.is_some());
3507
3508        let info = safety_info.unwrap();
3509        assert!(!info.modified_files.is_empty());
3510        assert!(info.modified_files.contains(&"README.md".to_string()));
3511    }
3512
3513    #[test]
3514    fn test_unsafe_checkout_methods() {
3515        let (_temp_dir, repo_path) = create_test_repo();
3516        let repo = GitRepository::open(&repo_path).unwrap();
3517
3518        // Create a test branch
3519        create_commit(&repo_path, "Second commit", "test.txt");
3520        Command::new("git")
3521            .args(["checkout", "-b", "test-branch"])
3522            .current_dir(&repo_path)
3523            .output()
3524            .unwrap();
3525
3526        // Modify a file to create uncommitted changes
3527        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3528
3529        // Test unsafe checkout methods bypass safety checks
3530        let _result = repo.checkout_branch_unsafe("main");
3531        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
3532        // The important thing is that it doesn't trigger our safety confirmation
3533
3534        // Test unsafe commit checkout
3535        let head_commit = repo.get_head_commit().unwrap();
3536        let commit_hash = head_commit.id().to_string();
3537        let _result = repo.checkout_commit_unsafe(&commit_hash);
3538        // Similar to above - testing that safety is bypassed
3539    }
3540
3541    #[test]
3542    fn test_get_modified_files() {
3543        let (_temp_dir, repo_path) = create_test_repo();
3544        let repo = GitRepository::open(&repo_path).unwrap();
3545
3546        // Initially should have no modified files
3547        let modified = repo.get_modified_files().unwrap();
3548        assert!(modified.is_empty());
3549
3550        // Modify a file
3551        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3552
3553        // Should now detect the modified file
3554        let modified = repo.get_modified_files().unwrap();
3555        assert_eq!(modified.len(), 1);
3556        assert!(modified.contains(&"README.md".to_string()));
3557    }
3558
3559    #[test]
3560    fn test_get_staged_files() {
3561        let (_temp_dir, repo_path) = create_test_repo();
3562        let repo = GitRepository::open(&repo_path).unwrap();
3563
3564        // Initially should have no staged files
3565        let staged = repo.get_staged_files().unwrap();
3566        assert!(staged.is_empty());
3567
3568        // Create and stage a new file
3569        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3570        Command::new("git")
3571            .args(["add", "staged.txt"])
3572            .current_dir(&repo_path)
3573            .output()
3574            .unwrap();
3575
3576        // Should now detect the staged file
3577        let staged = repo.get_staged_files().unwrap();
3578        assert_eq!(staged.len(), 1);
3579        assert!(staged.contains(&"staged.txt".to_string()));
3580    }
3581
3582    #[test]
3583    fn test_create_stash_fallback() {
3584        let (_temp_dir, repo_path) = create_test_repo();
3585        let repo = GitRepository::open(&repo_path).unwrap();
3586
3587        // Test stash creation - newer git versions allow empty stashes
3588        let result = repo.create_stash("test stash");
3589
3590        // Either succeeds (newer git with empty stash) or fails with helpful message
3591        match result {
3592            Ok(stash_id) => {
3593                // Modern git allows empty stashes, verify we got a stash ID
3594                assert!(!stash_id.is_empty());
3595                assert!(stash_id.contains("stash") || stash_id.len() >= 7); // SHA or stash@{n}
3596            }
3597            Err(error) => {
3598                // Older git should fail with helpful message
3599                let error_msg = error.to_string();
3600                assert!(
3601                    error_msg.contains("No local changes to save")
3602                        || error_msg.contains("git stash push")
3603                );
3604            }
3605        }
3606    }
3607
3608    #[test]
3609    fn test_delete_branch_unsafe() {
3610        let (_temp_dir, repo_path) = create_test_repo();
3611        let repo = GitRepository::open(&repo_path).unwrap();
3612
3613        // Create a test branch
3614        create_commit(&repo_path, "Second commit", "test.txt");
3615        Command::new("git")
3616            .args(["checkout", "-b", "test-branch"])
3617            .current_dir(&repo_path)
3618            .output()
3619            .unwrap();
3620
3621        // Add another commit to the test branch to make it different from main
3622        create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3623
3624        // Go back to main
3625        Command::new("git")
3626            .args(["checkout", "main"])
3627            .current_dir(&repo_path)
3628            .output()
3629            .unwrap();
3630
3631        // Test unsafe delete bypasses safety checks
3632        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
3633        let result = repo.delete_branch_unsafe("test-branch");
3634        // Even if it fails, the key is that it didn't prompt for user confirmation
3635        // So we just check that it attempted the operation without interactive prompts
3636        let _ = result; // Don't assert success since delete may fail for git reasons
3637    }
3638
3639    #[test]
3640    fn test_force_push_unsafe() {
3641        let (_temp_dir, repo_path) = create_test_repo();
3642        let repo = GitRepository::open(&repo_path).unwrap();
3643
3644        // Create a test branch
3645        create_commit(&repo_path, "Second commit", "test.txt");
3646        Command::new("git")
3647            .args(["checkout", "-b", "test-branch"])
3648            .current_dir(&repo_path)
3649            .output()
3650            .unwrap();
3651
3652        // Test unsafe force push bypasses safety checks
3653        // Note: This will likely fail due to no remote, but it tests the safety bypass
3654        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3655        // The key is that it doesn't trigger safety confirmation dialogs
3656    }
3657
3658    #[test]
3659    fn test_cherry_pick_basic() {
3660        let (_temp_dir, repo_path) = create_test_repo();
3661        let repo = GitRepository::open(&repo_path).unwrap();
3662
3663        // Create a branch with a commit to cherry-pick
3664        repo.create_branch("source", None).unwrap();
3665        repo.checkout_branch("source").unwrap();
3666
3667        std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3668        Command::new("git")
3669            .args(["add", "."])
3670            .current_dir(&repo_path)
3671            .output()
3672            .unwrap();
3673
3674        Command::new("git")
3675            .args(["commit", "-m", "Cherry commit"])
3676            .current_dir(&repo_path)
3677            .output()
3678            .unwrap();
3679
3680        let cherry_commit = repo.get_head_commit_hash().unwrap();
3681
3682        // Switch back to previous branch (where source was created from)
3683        // Using `git checkout -` is environment-agnostic
3684        Command::new("git")
3685            .args(["checkout", "-"])
3686            .current_dir(&repo_path)
3687            .output()
3688            .unwrap();
3689
3690        repo.create_branch("target", None).unwrap();
3691        repo.checkout_branch("target").unwrap();
3692
3693        // Cherry-pick the commit
3694        let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3695
3696        // Verify cherry-pick succeeded (commit exists)
3697        repo.repo
3698            .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3699            .unwrap();
3700
3701        // Verify file exists on target branch
3702        assert!(
3703            repo_path.join("cherry.txt").exists(),
3704            "Cherry-picked file should exist"
3705        );
3706
3707        // Verify source branch is unchanged
3708        repo.checkout_branch("source").unwrap();
3709        let source_head = repo.get_head_commit_hash().unwrap();
3710        assert_eq!(
3711            source_head, cherry_commit,
3712            "Source branch should be unchanged"
3713        );
3714    }
3715
3716    #[test]
3717    fn test_cherry_pick_preserves_commit_message() {
3718        let (_temp_dir, repo_path) = create_test_repo();
3719        let repo = GitRepository::open(&repo_path).unwrap();
3720
3721        // Create commit with specific message
3722        repo.create_branch("msg-test", None).unwrap();
3723        repo.checkout_branch("msg-test").unwrap();
3724
3725        std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3726        Command::new("git")
3727            .args(["add", "."])
3728            .current_dir(&repo_path)
3729            .output()
3730            .unwrap();
3731
3732        let commit_msg = "Test: Special commit message\n\nWith body";
3733        Command::new("git")
3734            .args(["commit", "-m", commit_msg])
3735            .current_dir(&repo_path)
3736            .output()
3737            .unwrap();
3738
3739        let original_commit = repo.get_head_commit_hash().unwrap();
3740
3741        // Cherry-pick to another branch (use previous branch via git checkout -)
3742        Command::new("git")
3743            .args(["checkout", "-"])
3744            .current_dir(&repo_path)
3745            .output()
3746            .unwrap();
3747        let new_commit = repo.cherry_pick(&original_commit).unwrap();
3748
3749        // Get commit message of new commit
3750        let output = Command::new("git")
3751            .args(["log", "-1", "--format=%B", &new_commit])
3752            .current_dir(&repo_path)
3753            .output()
3754            .unwrap();
3755
3756        let new_msg = String::from_utf8_lossy(&output.stdout);
3757        assert!(
3758            new_msg.contains("Special commit message"),
3759            "Should preserve commit message"
3760        );
3761    }
3762
3763    #[test]
3764    fn test_cherry_pick_handles_conflicts() {
3765        let (_temp_dir, repo_path) = create_test_repo();
3766        let repo = GitRepository::open(&repo_path).unwrap();
3767
3768        // Create conflicting content
3769        std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3770        Command::new("git")
3771            .args(["add", "."])
3772            .current_dir(&repo_path)
3773            .output()
3774            .unwrap();
3775
3776        Command::new("git")
3777            .args(["commit", "-m", "Add conflict file"])
3778            .current_dir(&repo_path)
3779            .output()
3780            .unwrap();
3781
3782        // Create branch with different content
3783        repo.create_branch("conflict-branch", None).unwrap();
3784        repo.checkout_branch("conflict-branch").unwrap();
3785
3786        std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3787        Command::new("git")
3788            .args(["add", "."])
3789            .current_dir(&repo_path)
3790            .output()
3791            .unwrap();
3792
3793        Command::new("git")
3794            .args(["commit", "-m", "Modify conflict file"])
3795            .current_dir(&repo_path)
3796            .output()
3797            .unwrap();
3798
3799        let conflict_commit = repo.get_head_commit_hash().unwrap();
3800
3801        // Try to cherry-pick (should fail due to conflict)
3802        // Go back to previous branch
3803        Command::new("git")
3804            .args(["checkout", "-"])
3805            .current_dir(&repo_path)
3806            .output()
3807            .unwrap();
3808        std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3809        Command::new("git")
3810            .args(["add", "."])
3811            .current_dir(&repo_path)
3812            .output()
3813            .unwrap();
3814
3815        Command::new("git")
3816            .args(["commit", "-m", "Different change"])
3817            .current_dir(&repo_path)
3818            .output()
3819            .unwrap();
3820
3821        // Cherry-pick should fail with conflict
3822        let result = repo.cherry_pick(&conflict_commit);
3823        assert!(result.is_err(), "Cherry-pick with conflict should fail");
3824    }
3825
3826    #[test]
3827    fn test_reset_to_head_clears_staged_files() {
3828        let (_temp_dir, repo_path) = create_test_repo();
3829        let repo = GitRepository::open(&repo_path).unwrap();
3830
3831        // Create and stage some files
3832        std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3833        std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3834
3835        Command::new("git")
3836            .args(["add", "staged1.txt", "staged2.txt"])
3837            .current_dir(&repo_path)
3838            .output()
3839            .unwrap();
3840
3841        // Verify files are staged
3842        let staged_before = repo.get_staged_files().unwrap();
3843        assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3844
3845        // Reset to HEAD
3846        repo.reset_to_head().unwrap();
3847
3848        // Verify no files are staged after reset
3849        let staged_after = repo.get_staged_files().unwrap();
3850        assert_eq!(
3851            staged_after.len(),
3852            0,
3853            "Should have no staged files after reset"
3854        );
3855    }
3856
3857    #[test]
3858    fn test_reset_to_head_clears_modified_files() {
3859        let (_temp_dir, repo_path) = create_test_repo();
3860        let repo = GitRepository::open(&repo_path).unwrap();
3861
3862        // Modify an existing file
3863        std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3864
3865        // Stage the modification
3866        Command::new("git")
3867            .args(["add", "README.md"])
3868            .current_dir(&repo_path)
3869            .output()
3870            .unwrap();
3871
3872        // Verify file is modified and staged
3873        assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3874
3875        // Reset to HEAD
3876        repo.reset_to_head().unwrap();
3877
3878        // Verify repo is clean
3879        assert!(
3880            !repo.is_dirty().unwrap(),
3881            "Repo should be clean after reset"
3882        );
3883
3884        // Verify file content is restored
3885        let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3886        assert_eq!(
3887            content, "# Test",
3888            "File should be restored to original content"
3889        );
3890    }
3891
3892    #[test]
3893    fn test_reset_to_head_preserves_untracked_files() {
3894        let (_temp_dir, repo_path) = create_test_repo();
3895        let repo = GitRepository::open(&repo_path).unwrap();
3896
3897        // Create untracked file
3898        std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3899
3900        // Stage some other file
3901        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3902        Command::new("git")
3903            .args(["add", "staged.txt"])
3904            .current_dir(&repo_path)
3905            .output()
3906            .unwrap();
3907
3908        // Reset to HEAD
3909        repo.reset_to_head().unwrap();
3910
3911        // Verify untracked file still exists
3912        assert!(
3913            repo_path.join("untracked.txt").exists(),
3914            "Untracked file should be preserved"
3915        );
3916
3917        // Verify staged file was removed (since it was never committed)
3918        assert!(
3919            !repo_path.join("staged.txt").exists(),
3920            "Staged but uncommitted file should be removed"
3921        );
3922    }
3923
3924    #[test]
3925    fn test_cherry_pick_does_not_modify_source() {
3926        let (_temp_dir, repo_path) = create_test_repo();
3927        let repo = GitRepository::open(&repo_path).unwrap();
3928
3929        // Create source branch with multiple commits
3930        repo.create_branch("feature", None).unwrap();
3931        repo.checkout_branch("feature").unwrap();
3932
3933        // Add multiple commits
3934        for i in 1..=3 {
3935            std::fs::write(
3936                repo_path.join(format!("file{i}.txt")),
3937                format!("Content {i}"),
3938            )
3939            .unwrap();
3940            Command::new("git")
3941                .args(["add", "."])
3942                .current_dir(&repo_path)
3943                .output()
3944                .unwrap();
3945
3946            Command::new("git")
3947                .args(["commit", "-m", &format!("Commit {i}")])
3948                .current_dir(&repo_path)
3949                .output()
3950                .unwrap();
3951        }
3952
3953        // Get source branch state
3954        let source_commits = Command::new("git")
3955            .args(["log", "--format=%H", "feature"])
3956            .current_dir(&repo_path)
3957            .output()
3958            .unwrap();
3959        let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3960
3961        // Cherry-pick middle commit to another branch
3962        let commits: Vec<&str> = source_state.lines().collect();
3963        let middle_commit = commits[1];
3964
3965        // Go back to previous branch
3966        Command::new("git")
3967            .args(["checkout", "-"])
3968            .current_dir(&repo_path)
3969            .output()
3970            .unwrap();
3971        repo.create_branch("target", None).unwrap();
3972        repo.checkout_branch("target").unwrap();
3973
3974        repo.cherry_pick(middle_commit).unwrap();
3975
3976        // Verify source branch is completely unchanged
3977        let after_commits = Command::new("git")
3978            .args(["log", "--format=%H", "feature"])
3979            .current_dir(&repo_path)
3980            .output()
3981            .unwrap();
3982        let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3983
3984        assert_eq!(
3985            source_state, after_state,
3986            "Source branch should be completely unchanged after cherry-pick"
3987        );
3988    }
3989
3990    #[test]
3991    fn test_detect_parent_branch() {
3992        let (_temp_dir, repo_path) = create_test_repo();
3993        let repo = GitRepository::open(&repo_path).unwrap();
3994
3995        // Create a custom base branch (not just main/master)
3996        repo.create_branch("dev123", None).unwrap();
3997        repo.checkout_branch("dev123").unwrap();
3998        create_commit(&repo_path, "Base commit on dev123", "base.txt");
3999
4000        // Create feature branch from dev123
4001        repo.create_branch("feature-branch", None).unwrap();
4002        repo.checkout_branch("feature-branch").unwrap();
4003        create_commit(&repo_path, "Feature commit", "feature.txt");
4004
4005        // Should detect dev123 as parent since it's the most recent common ancestor
4006        let detected_parent = repo.detect_parent_branch().unwrap();
4007
4008        // The algorithm should find dev123 through either Strategy 2 (default branch)
4009        // or Strategy 3 (common ancestor analysis)
4010        assert!(detected_parent.is_some(), "Should detect a parent branch");
4011
4012        // Since we can't guarantee which strategy will work in the test environment,
4013        // just verify it returns something reasonable
4014        let parent = detected_parent.unwrap();
4015        assert!(
4016            parent == "dev123" || parent == "main" || parent == "master",
4017            "Parent should be dev123, main, or master, got: {parent}"
4018        );
4019    }
4020}