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.path.join(".git").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    /// Check if a commit exists
905    pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
906        match Oid::from_str(commit_hash) {
907            Ok(oid) => match self.repo.find_commit(oid) {
908                Ok(_) => Ok(true),
909                Err(_) => Ok(false),
910            },
911            Err(_) => Ok(false),
912        }
913    }
914
915    /// Check if a commit is already correctly based on a given parent
916    /// Returns true if the commit's parent matches the expected base
917    pub fn is_commit_based_on(&self, commit_hash: &str, expected_base: &str) -> Result<bool> {
918        let commit_oid = Oid::from_str(commit_hash).map_err(|e| {
919            CascadeError::branch(format!("Invalid commit hash '{}': {}", commit_hash, e))
920        })?;
921
922        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
923            CascadeError::branch(format!("Commit '{}' not found: {}", commit_hash, e))
924        })?;
925
926        // Get the commit's parent (first parent for merge commits)
927        if commit.parent_count() == 0 {
928            // Root commit has no parent
929            return Ok(false);
930        }
931
932        let parent = commit.parent(0).map_err(|e| {
933            CascadeError::branch(format!(
934                "Could not get parent of commit '{}': {}",
935                commit_hash, e
936            ))
937        })?;
938        let parent_hash = parent.id().to_string();
939
940        // Check if expected_base is a commit hash or a branch name
941        let expected_base_oid = if let Ok(oid) = Oid::from_str(expected_base) {
942            oid
943        } else {
944            // Try to resolve as a branch name
945            let branch_ref = format!("refs/heads/{}", expected_base);
946            let reference = self.repo.find_reference(&branch_ref).map_err(|e| {
947                CascadeError::branch(format!("Could not find base '{}': {}", expected_base, e))
948            })?;
949            reference.target().ok_or_else(|| {
950                CascadeError::branch(format!("Base '{}' has no target commit", expected_base))
951            })?
952        };
953
954        let expected_base_hash = expected_base_oid.to_string();
955
956        tracing::debug!(
957            "Checking if commit {} is based on {}: parent={}, expected={}",
958            &commit_hash[..8],
959            expected_base,
960            &parent_hash[..8],
961            &expected_base_hash[..8]
962        );
963
964        Ok(parent_hash == expected_base_hash)
965    }
966
967    /// Check whether `descendant` commit contains `ancestor` in its history
968    pub fn is_descendant_of(&self, descendant: &str, ancestor: &str) -> Result<bool> {
969        let descendant_oid = Oid::from_str(descendant).map_err(|e| {
970            CascadeError::branch(format!(
971                "Invalid commit hash '{}' for descendant check: {}",
972                descendant, e
973            ))
974        })?;
975        let ancestor_oid = Oid::from_str(ancestor).map_err(|e| {
976            CascadeError::branch(format!(
977                "Invalid commit hash '{}' for descendant check: {}",
978                ancestor, e
979            ))
980        })?;
981
982        self.repo
983            .graph_descendant_of(descendant_oid, ancestor_oid)
984            .map_err(CascadeError::Git)
985    }
986
987    /// Get the HEAD commit object
988    pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
989        let head = self
990            .repo
991            .head()
992            .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
993        head.peel_to_commit()
994            .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
995    }
996
997    /// Get a commit object by hash
998    pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
999        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1000
1001        self.repo.find_commit(oid).map_err(CascadeError::Git)
1002    }
1003
1004    /// Get the commit hash at the head of a branch
1005    pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
1006        let branch = self
1007            .repo
1008            .find_branch(branch_name, git2::BranchType::Local)
1009            .map_err(|e| {
1010                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
1011            })?;
1012
1013        let commit = branch.get().peel_to_commit().map_err(|e| {
1014            CascadeError::branch(format!(
1015                "Could not get commit for branch '{branch_name}': {e}"
1016            ))
1017        })?;
1018
1019        Ok(commit.id().to_string())
1020    }
1021
1022    /// Get the commit hash at the head of a remote branch
1023    pub fn get_remote_branch_head(&self, branch_name: &str) -> Result<String> {
1024        let refname = format!("refs/remotes/origin/{branch_name}");
1025        let reference = self.repo.find_reference(&refname).map_err(|e| {
1026            CascadeError::branch(format!("Remote branch '{branch_name}' not found: {e}"))
1027        })?;
1028
1029        let target = reference.target().ok_or_else(|| {
1030            CascadeError::branch(format!(
1031                "Remote branch '{branch_name}' does not have a target commit"
1032            ))
1033        })?;
1034
1035        Ok(target.to_string())
1036    }
1037
1038    /// Validate git user configuration is properly set
1039    pub fn validate_git_user_config(&self) -> Result<()> {
1040        if let Ok(config) = self.repo.config() {
1041            let name_result = config.get_string("user.name");
1042            let email_result = config.get_string("user.email");
1043
1044            if let (Ok(name), Ok(email)) = (name_result, email_result) {
1045                if !name.trim().is_empty() && !email.trim().is_empty() {
1046                    tracing::debug!("Git user config validated: {} <{}>", name, email);
1047                    return Ok(());
1048                }
1049            }
1050        }
1051
1052        // Check if this is a CI environment where validation can be skipped
1053        let is_ci = std::env::var("CI").is_ok();
1054
1055        if is_ci {
1056            tracing::debug!("CI environment - skipping git user config validation");
1057            return Ok(());
1058        }
1059
1060        Output::warning("Git user configuration missing or incomplete");
1061        Output::info("This can cause cherry-pick and commit operations to fail");
1062        Output::info("Please configure git user information:");
1063        Output::bullet("git config user.name \"Your Name\"".to_string());
1064        Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1065        Output::info("Or set globally with the --global flag");
1066
1067        // Don't fail - let operations continue with fallback signature
1068        // This preserves backward compatibility while providing guidance
1069        Ok(())
1070    }
1071
1072    /// Read the configured git user name and email from git config
1073    pub fn get_user_info(&self) -> (Option<String>, Option<String>) {
1074        let config = match self.repo.config() {
1075            Ok(c) => c,
1076            Err(_) => return (None, None),
1077        };
1078        let name = config.get_string("user.name").ok();
1079        let email = config.get_string("user.email").ok();
1080        (name, email)
1081    }
1082
1083    /// Get a signature for commits with comprehensive fallback and validation
1084    fn get_signature(&self) -> Result<Signature<'_>> {
1085        // Try to get signature from Git config first
1086        if let Ok(config) = self.repo.config() {
1087            // Try global/system config first
1088            let name_result = config.get_string("user.name");
1089            let email_result = config.get_string("user.email");
1090
1091            if let (Ok(name), Ok(email)) = (name_result, email_result) {
1092                if !name.trim().is_empty() && !email.trim().is_empty() {
1093                    tracing::debug!("Using git config: {} <{}>", name, email);
1094                    return Signature::now(&name, &email).map_err(CascadeError::Git);
1095                }
1096            } else {
1097                tracing::debug!("Git user config incomplete or missing");
1098            }
1099        }
1100
1101        // Check if this is a CI environment where fallback is acceptable
1102        let is_ci = std::env::var("CI").is_ok();
1103
1104        if is_ci {
1105            tracing::debug!("CI environment detected, using fallback signature");
1106            return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
1107        }
1108
1109        // Interactive environment - provide helpful guidance
1110        tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
1111
1112        // Try fallback signature, but warn about the issue
1113        match Signature::now("Cascade CLI", "cascade@example.com") {
1114            Ok(sig) => {
1115                Output::warning("Git user not configured - using fallback signature");
1116                Output::info("For better git history, run:");
1117                Output::bullet("git config user.name \"Your Name\"".to_string());
1118                Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1119                Output::info("Or set it globally with --global flag");
1120                Ok(sig)
1121            }
1122            Err(e) => {
1123                Err(CascadeError::branch(format!(
1124                    "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\""
1125                )))
1126            }
1127        }
1128    }
1129
1130    /// Configure remote callbacks with SSL settings
1131    /// Priority: Cascade SSL config > Git config > Default
1132    fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
1133        self.configure_remote_callbacks_with_fallback(false)
1134    }
1135
1136    /// Determine if we should retry with DefaultCredentials based on git2 error classification
1137    fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
1138        match error.class() {
1139            // Authentication errors that might be resolved with DefaultCredentials
1140            git2::ErrorClass::Http => {
1141                // HTTP errors often indicate authentication issues in corporate environments
1142                match error.code() {
1143                    git2::ErrorCode::Auth => true,
1144                    _ => {
1145                        // Check for specific HTTP authentication replay errors
1146                        let error_string = error.to_string();
1147                        error_string.contains("too many redirects")
1148                            || error_string.contains("authentication replays")
1149                            || error_string.contains("authentication required")
1150                    }
1151                }
1152            }
1153            git2::ErrorClass::Net => {
1154                // Network errors that might be authentication-related
1155                let error_string = error.to_string();
1156                error_string.contains("authentication")
1157                    || error_string.contains("unauthorized")
1158                    || error_string.contains("forbidden")
1159            }
1160            _ => false,
1161        }
1162    }
1163
1164    /// Determine if we should fallback to git CLI based on git2 error classification
1165    fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
1166        match error.class() {
1167            // SSL/TLS errors that git CLI handles better
1168            git2::ErrorClass::Ssl => true,
1169
1170            // Certificate errors
1171            git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
1172
1173            // SSH errors that might need git CLI
1174            git2::ErrorClass::Ssh => {
1175                let error_string = error.to_string();
1176                error_string.contains("no callback set")
1177                    || error_string.contains("authentication required")
1178            }
1179
1180            // Network errors that might be proxy/firewall related
1181            git2::ErrorClass::Net => {
1182                let error_string = error.to_string();
1183                error_string.contains("TLS stream")
1184                    || error_string.contains("SSL")
1185                    || error_string.contains("proxy")
1186                    || error_string.contains("firewall")
1187            }
1188
1189            // General HTTP errors not handled by DefaultCredentials retry
1190            git2::ErrorClass::Http => {
1191                let error_string = error.to_string();
1192                error_string.contains("TLS stream")
1193                    || error_string.contains("SSL")
1194                    || error_string.contains("proxy")
1195            }
1196
1197            _ => false,
1198        }
1199    }
1200
1201    fn configure_remote_callbacks_with_fallback(
1202        &self,
1203        use_default_first: bool,
1204    ) -> Result<git2::RemoteCallbacks<'_>> {
1205        let mut callbacks = git2::RemoteCallbacks::new();
1206
1207        // Configure authentication with comprehensive credential support
1208        let bitbucket_credentials = self.bitbucket_credentials.clone();
1209        callbacks.credentials(move |url, username_from_url, allowed_types| {
1210            tracing::debug!(
1211                "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
1212                url,
1213                username_from_url,
1214                allowed_types
1215            );
1216
1217            // For SSH URLs with username
1218            if allowed_types.contains(git2::CredentialType::SSH_KEY) {
1219                if let Some(username) = username_from_url {
1220                    tracing::debug!("Trying SSH key authentication for user: {}", username);
1221                    return git2::Cred::ssh_key_from_agent(username);
1222                }
1223            }
1224
1225            // For HTTPS URLs, try multiple authentication methods in sequence
1226            if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
1227                // If we're in corporate network fallback mode, try DefaultCredentials first
1228                if use_default_first {
1229                    tracing::debug!("Corporate network mode: trying DefaultCredentials first");
1230                    return git2::Cred::default();
1231                }
1232
1233                if url.contains("bitbucket") {
1234                    if let Some(creds) = &bitbucket_credentials {
1235                        // Method 1: Username + Token (common for Bitbucket)
1236                        if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
1237                            tracing::debug!("Trying Bitbucket username + token authentication");
1238                            return git2::Cred::userpass_plaintext(username, token);
1239                        }
1240
1241                        // Method 2: Token as username, empty password (alternate Bitbucket format)
1242                        if let Some(token) = &creds.token {
1243                            tracing::debug!("Trying Bitbucket token-as-username authentication");
1244                            return git2::Cred::userpass_plaintext(token, "");
1245                        }
1246
1247                        // Method 3: Just username (will prompt for password or use credential helper)
1248                        if let Some(username) = &creds.username {
1249                            tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1250                            return git2::Cred::username(username);
1251                        }
1252                    }
1253                }
1254
1255                // Method 4: Default credential helper for all HTTPS URLs
1256                tracing::debug!("Trying default credential helper for HTTPS authentication");
1257                return git2::Cred::default();
1258            }
1259
1260            // Fallback to default for any other cases
1261            tracing::debug!("Using default credential fallback");
1262            git2::Cred::default()
1263        });
1264
1265        // Configure SSL certificate checking with system certificates by default
1266        // This matches what tools like Graphite, Sapling, and Phabricator do
1267        // Priority: 1. Use system certificates (default), 2. Manual overrides only if needed
1268
1269        let mut ssl_configured = false;
1270
1271        // Check for manual SSL overrides first (only when user explicitly needs them)
1272        if let Some(ssl_config) = &self.ssl_config {
1273            if ssl_config.accept_invalid_certs {
1274                Output::warning(
1275                    "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1276                );
1277                callbacks.certificate_check(|_cert, _host| {
1278                    tracing::debug!("⚠️  Accepting invalid certificate for host: {}", _host);
1279                    Ok(git2::CertificateCheckStatus::CertificateOk)
1280                });
1281                ssl_configured = true;
1282            } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1283                Output::info(format!(
1284                    "Using custom CA bundle from Cascade config: {ca_path}"
1285                ));
1286                callbacks.certificate_check(|_cert, host| {
1287                    tracing::debug!("Using custom CA bundle for host: {}", host);
1288                    Ok(git2::CertificateCheckStatus::CertificateOk)
1289                });
1290                ssl_configured = true;
1291            }
1292        }
1293
1294        // Check git config for manual overrides
1295        if !ssl_configured {
1296            if let Ok(config) = self.repo.config() {
1297                let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1298
1299                if !ssl_verify {
1300                    Output::warning(
1301                        "SSL certificate verification DISABLED via git config - this is insecure!",
1302                    );
1303                    callbacks.certificate_check(|_cert, host| {
1304                        tracing::debug!("⚠️  Bypassing SSL verification for host: {}", host);
1305                        Ok(git2::CertificateCheckStatus::CertificateOk)
1306                    });
1307                    ssl_configured = true;
1308                } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1309                    Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1310                    callbacks.certificate_check(|_cert, host| {
1311                        tracing::debug!("Using git config CA bundle for host: {}", host);
1312                        Ok(git2::CertificateCheckStatus::CertificateOk)
1313                    });
1314                    ssl_configured = true;
1315                }
1316            }
1317        }
1318
1319        // DEFAULT BEHAVIOR: Use system certificates (like git CLI and other modern tools)
1320        // This should work out-of-the-box in corporate environments
1321        if !ssl_configured {
1322            tracing::debug!(
1323                "Using system certificate store for SSL verification (default behavior)"
1324            );
1325
1326            // For macOS with SecureTransport backend, try default certificate validation first
1327            if cfg!(target_os = "macos") {
1328                tracing::debug!("macOS detected - using default certificate validation");
1329                // Don't set any certificate callback - let git2 use its default behavior
1330                // This often works better with SecureTransport backend on macOS
1331            } else {
1332                // Use CertificatePassthrough for other platforms
1333                callbacks.certificate_check(|_cert, host| {
1334                    tracing::debug!("System certificate validation for host: {}", host);
1335                    Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1336                });
1337            }
1338        }
1339
1340        Ok(callbacks)
1341    }
1342
1343    /// Get the tree ID from the current index
1344    fn get_index_tree(&self) -> Result<Oid> {
1345        let mut index = self.repo.index().map_err(CascadeError::Git)?;
1346
1347        index.write_tree().map_err(CascadeError::Git)
1348    }
1349
1350    /// Get repository status
1351    pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1352        self.repo.statuses(None).map_err(CascadeError::Git)
1353    }
1354
1355    /// Get a summary of repository status
1356    pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1357        let statuses = self.get_status()?;
1358
1359        let mut staged_files = 0;
1360        let mut unstaged_files = 0;
1361        let mut untracked_files = 0;
1362
1363        for status in statuses.iter() {
1364            let flags = status.status();
1365
1366            if flags.intersects(
1367                git2::Status::INDEX_MODIFIED
1368                    | git2::Status::INDEX_NEW
1369                    | git2::Status::INDEX_DELETED
1370                    | git2::Status::INDEX_RENAMED
1371                    | git2::Status::INDEX_TYPECHANGE,
1372            ) {
1373                staged_files += 1;
1374            }
1375
1376            if flags.intersects(
1377                git2::Status::WT_MODIFIED
1378                    | git2::Status::WT_DELETED
1379                    | git2::Status::WT_TYPECHANGE
1380                    | git2::Status::WT_RENAMED,
1381            ) {
1382                unstaged_files += 1;
1383            }
1384
1385            if flags.intersects(git2::Status::WT_NEW) {
1386                untracked_files += 1;
1387            }
1388        }
1389
1390        Ok(GitStatusSummary {
1391            staged_files,
1392            unstaged_files,
1393            untracked_files,
1394        })
1395    }
1396
1397    /// Get the current commit hash (alias for get_head_commit_hash)
1398    pub fn get_current_commit_hash(&self) -> Result<String> {
1399        self.get_head_commit_hash()
1400    }
1401
1402    /// Get the count of commits between two commits
1403    pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1404        let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1405        let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1406
1407        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1408        revwalk.push(to_oid).map_err(CascadeError::Git)?;
1409        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1410
1411        Ok(revwalk.count())
1412    }
1413
1414    /// Get remote URL for a given remote name
1415    pub fn get_remote_url(&self, name: &str) -> Result<String> {
1416        let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1417        Ok(remote.url().unwrap_or("unknown").to_string())
1418    }
1419
1420    /// Cherry-pick a specific commit to the current branch
1421    pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1422        tracing::debug!("Cherry-picking commit {}", commit_hash);
1423
1424        // Validate git user configuration before attempting commit operations
1425        self.validate_git_user_config()?;
1426
1427        let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1428        let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1429
1430        // Get the commit's tree
1431        let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1432
1433        // Get parent tree for merge base
1434        let parent_commit = if commit.parent_count() > 0 {
1435            commit.parent(0).map_err(CascadeError::Git)?
1436        } else {
1437            // Root commit - use empty tree
1438            let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1439            let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1440            let sig = self.get_signature()?;
1441            return self
1442                .repo
1443                .commit(
1444                    Some("HEAD"),
1445                    &sig,
1446                    &sig,
1447                    commit.message().unwrap_or("Cherry-picked commit"),
1448                    &empty_tree,
1449                    &[],
1450                )
1451                .map(|oid| oid.to_string())
1452                .map_err(CascadeError::Git);
1453        };
1454
1455        let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1456
1457        // Get current HEAD tree for 3-way merge
1458        let head_commit = self.get_head_commit()?;
1459        let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1460
1461        // Perform 3-way merge
1462        let mut index = self
1463            .repo
1464            .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1465            .map_err(CascadeError::Git)?;
1466
1467        // Check for conflicts
1468        if index.has_conflicts() {
1469            // CRITICAL: Write the conflicted state to disk so auto-resolve can see it!
1470            // Without this, conflicts only exist in memory and Git's index stays clean
1471            debug!("Cherry-pick has conflicts - writing conflicted state to disk for resolution");
1472
1473            // The merge_trees() index is in-memory only. We need to:
1474            // 1. Get the repository's actual index
1475            // 2. Read entries from the merge result into it
1476            // 3. Write the repository index to disk
1477
1478            let mut repo_index = self.repo.index().map_err(CascadeError::Git)?;
1479
1480            // Clear the current index and read from the merge result
1481            repo_index.clear().map_err(CascadeError::Git)?;
1482            repo_index
1483                .read_tree(&head_tree)
1484                .map_err(CascadeError::Git)?;
1485
1486            // Now merge the commit tree into the repo index (this will create conflicts)
1487            repo_index
1488                .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
1489                .map_err(CascadeError::Git)?;
1490
1491            // Use git CLI to do the actual cherry-pick with conflicts
1492            // This is more reliable than trying to manually construct the conflicted index
1493
1494            // First, ensure our libgit2 index is closed so git CLI can work
1495            drop(repo_index);
1496            self.ensure_index_closed()?;
1497
1498            let cherry_pick_output = std::process::Command::new("git")
1499                .args(["cherry-pick", commit_hash])
1500                .current_dir(self.path())
1501                .output()
1502                .map_err(CascadeError::Io)?;
1503
1504            if !cherry_pick_output.status.success() {
1505                debug!("Git CLI cherry-pick failed as expected (has conflicts)");
1506                // This is expected - the cherry-pick failed due to conflicts
1507                // The conflicts are now in the working directory and index
1508            }
1509
1510            // CRITICAL: Reload the index from disk so libgit2 sees the conflicts
1511            // Git CLI wrote the conflicts to disk, but our in-memory index doesn't know yet
1512            self.repo
1513                .index()
1514                .and_then(|mut idx| idx.read(true).map(|_| ()))
1515                .map_err(CascadeError::Git)?;
1516
1517            debug!("Conflicted state written and index reloaded - auto-resolve can now process conflicts");
1518
1519            return Err(CascadeError::branch(format!(
1520                "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1521            )));
1522        }
1523
1524        // Write merged tree
1525        let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1526        let merged_tree = self
1527            .repo
1528            .find_tree(merged_tree_oid)
1529            .map_err(CascadeError::Git)?;
1530
1531        // Create new commit with original message (preserve it exactly)
1532        let signature = self.get_signature()?;
1533        let message = commit.message().unwrap_or("Cherry-picked commit");
1534
1535        let new_commit_oid = self
1536            .repo
1537            .commit(
1538                Some("HEAD"),
1539                &signature,
1540                &signature,
1541                message,
1542                &merged_tree,
1543                &[&head_commit],
1544            )
1545            .map_err(CascadeError::Git)?;
1546
1547        // Update working directory to reflect the new commit
1548        let new_commit = self
1549            .repo
1550            .find_commit(new_commit_oid)
1551            .map_err(CascadeError::Git)?;
1552        let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1553
1554        self.repo
1555            .checkout_tree(
1556                new_tree.as_object(),
1557                Some(git2::build::CheckoutBuilder::new().force()),
1558            )
1559            .map_err(CascadeError::Git)?;
1560
1561        tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1562        Ok(new_commit_oid.to_string())
1563    }
1564
1565    /// Check for merge conflicts in the index
1566    pub fn has_conflicts(&self) -> Result<bool> {
1567        let index = self.repo.index().map_err(CascadeError::Git)?;
1568        Ok(index.has_conflicts())
1569    }
1570
1571    /// Get list of conflicted files
1572    pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1573        let index = self.repo.index().map_err(CascadeError::Git)?;
1574
1575        let mut conflicts = Vec::new();
1576
1577        // Iterate through index conflicts
1578        let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1579
1580        for conflict in conflict_iter {
1581            let conflict = conflict.map_err(CascadeError::Git)?;
1582            if let Some(our) = conflict.our {
1583                if let Ok(path) = std::str::from_utf8(&our.path) {
1584                    conflicts.push(path.to_string());
1585                }
1586            } else if let Some(their) = conflict.their {
1587                if let Ok(path) = std::str::from_utf8(&their.path) {
1588                    conflicts.push(path.to_string());
1589                }
1590            }
1591        }
1592
1593        Ok(conflicts)
1594    }
1595
1596    /// Fetch from remote origin
1597    pub fn fetch(&self) -> Result<()> {
1598        tracing::debug!("Fetching from origin");
1599
1600        // CRITICAL: Ensure index is closed before fetch operation
1601        // This prevents "index is locked" errors when fetch is called after cherry-pick/commit
1602        self.ensure_index_closed()?;
1603
1604        let mut remote = self
1605            .repo
1606            .find_remote("origin")
1607            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1608
1609        // Configure callbacks with SSL settings from git config
1610        let callbacks = self.configure_remote_callbacks()?;
1611
1612        // Fetch options with authentication and SSL config
1613        let mut fetch_options = git2::FetchOptions::new();
1614        fetch_options.remote_callbacks(callbacks);
1615
1616        // Fetch with authentication
1617        match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1618            Ok(_) => {
1619                tracing::debug!("Fetch completed successfully");
1620                Ok(())
1621            }
1622            Err(e) => {
1623                if self.should_retry_with_default_credentials(&e) {
1624                    tracing::debug!(
1625                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1626                        e.class(), e.code(), e
1627                    );
1628
1629                    // Retry with DefaultCredentials for corporate networks
1630                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1631                    let mut fetch_options = git2::FetchOptions::new();
1632                    fetch_options.remote_callbacks(callbacks);
1633
1634                    match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1635                        Ok(_) => {
1636                            tracing::debug!("Fetch succeeded with DefaultCredentials");
1637                            return Ok(());
1638                        }
1639                        Err(retry_error) => {
1640                            tracing::debug!(
1641                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1642                                retry_error
1643                            );
1644                            return self.fetch_with_git_cli();
1645                        }
1646                    }
1647                }
1648
1649                if self.should_fallback_to_git_cli(&e) {
1650                    tracing::debug!(
1651                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1652                        e.class(), e.code(), e
1653                    );
1654                    return self.fetch_with_git_cli();
1655                }
1656                Err(CascadeError::Git(e))
1657            }
1658        }
1659    }
1660
1661    /// Fetch from remote with exponential backoff retry logic
1662    /// This is critical for force push safety checks to prevent data loss from stale refs
1663    pub fn fetch_with_retry(&self) -> Result<()> {
1664        const MAX_RETRIES: u32 = 3;
1665        const BASE_DELAY_MS: u64 = 500;
1666
1667        let mut last_error = None;
1668
1669        for attempt in 0..MAX_RETRIES {
1670            match self.fetch() {
1671                Ok(_) => return Ok(()),
1672                Err(e) => {
1673                    last_error = Some(e);
1674
1675                    if attempt < MAX_RETRIES - 1 {
1676                        let delay_ms = BASE_DELAY_MS * 2_u64.pow(attempt);
1677                        debug!(
1678                            "Fetch attempt {} failed, retrying in {}ms...",
1679                            attempt + 1,
1680                            delay_ms
1681                        );
1682                        std::thread::sleep(std::time::Duration::from_millis(delay_ms));
1683                    }
1684                }
1685            }
1686        }
1687
1688        // All retries failed - this is CRITICAL for force push safety
1689        Err(CascadeError::Git(git2::Error::from_str(&format!(
1690            "Critical: Failed to fetch remote refs after {} attempts. Cannot safely proceed with force push - \
1691             stale remote refs could cause data loss. Error: {}. Please check network connection.",
1692            MAX_RETRIES,
1693            last_error.unwrap()
1694        ))))
1695    }
1696
1697    /// Pull changes from remote (fetch + merge)
1698    pub fn pull(&self, branch: &str) -> Result<()> {
1699        tracing::debug!("Pulling branch: {}", branch);
1700
1701        // First fetch - this now includes TLS fallback
1702        match self.fetch() {
1703            Ok(_) => {}
1704            Err(e) => {
1705                // If fetch failed even with CLI fallback, try full git pull as last resort
1706                let error_string = e.to_string();
1707                if error_string.contains("TLS stream") || error_string.contains("SSL") {
1708                    tracing::warn!(
1709                        "git2 error detected: {}, falling back to git CLI for pull operation",
1710                        e
1711                    );
1712                    return self.pull_with_git_cli(branch);
1713                }
1714                return Err(e);
1715            }
1716        }
1717
1718        // Get remote tracking branch
1719        let remote_branch_name = format!("origin/{branch}");
1720        let remote_oid = self
1721            .repo
1722            .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1723            .map_err(|e| {
1724                CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1725            })?;
1726
1727        let remote_commit = self
1728            .repo
1729            .find_commit(remote_oid)
1730            .map_err(CascadeError::Git)?;
1731
1732        // Get current HEAD
1733        let head_commit = self.get_head_commit()?;
1734
1735        // Check if already up to date
1736        if head_commit.id() == remote_commit.id() {
1737            tracing::debug!("Already up to date");
1738            return Ok(());
1739        }
1740
1741        // Check if we can fast-forward (local is ancestor of remote)
1742        let merge_base_oid = self
1743            .repo
1744            .merge_base(head_commit.id(), remote_commit.id())
1745            .map_err(CascadeError::Git)?;
1746
1747        if merge_base_oid == head_commit.id() {
1748            // Fast-forward: local is direct ancestor of remote, just move pointer
1749            tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1750
1751            // Update the branch reference to point to remote commit
1752            let refname = format!("refs/heads/{}", branch);
1753            self.repo
1754                .reference(&refname, remote_oid, true, "pull: Fast-forward")
1755                .map_err(CascadeError::Git)?;
1756
1757            // Update HEAD to point to the new commit
1758            self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1759
1760            // Checkout the new commit (update working directory)
1761            self.repo
1762                .checkout_head(Some(
1763                    git2::build::CheckoutBuilder::new()
1764                        .force()
1765                        .remove_untracked(false),
1766                ))
1767                .map_err(CascadeError::Git)?;
1768
1769            tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1770            return Ok(());
1771        }
1772
1773        // If we can't fast-forward, the local branch has diverged
1774        // This should NOT happen on protected branches!
1775        Err(CascadeError::branch(format!(
1776            "Branch '{}' has diverged from remote. Local has commits not in remote. \
1777             Protected branches should not have local commits. \
1778             Try: git reset --hard origin/{}",
1779            branch, branch
1780        )))
1781    }
1782
1783    /// Push current branch to remote
1784    pub fn push(&self, branch: &str) -> Result<()> {
1785        // Pushing branch to remote
1786
1787        let mut remote = self
1788            .repo
1789            .find_remote("origin")
1790            .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1791
1792        let remote_url = remote.url().unwrap_or("unknown").to_string();
1793        tracing::debug!("Remote URL: {}", remote_url);
1794
1795        let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1796        tracing::debug!("Push refspec: {}", refspec);
1797
1798        // Configure callbacks with enhanced SSL settings and error handling
1799        let mut callbacks = self.configure_remote_callbacks()?;
1800
1801        // Add enhanced progress and error callbacks for better debugging
1802        callbacks.push_update_reference(|refname, status| {
1803            if let Some(msg) = status {
1804                tracing::debug!("Push failed for ref {}: {}", refname, msg);
1805                return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1806            }
1807            tracing::debug!("Push succeeded for ref: {}", refname);
1808            Ok(())
1809        });
1810
1811        // Push options with authentication and SSL config
1812        let mut push_options = git2::PushOptions::new();
1813        push_options.remote_callbacks(callbacks);
1814
1815        // Attempt push with enhanced error reporting
1816        match remote.push(&[&refspec], Some(&mut push_options)) {
1817            Ok(_) => {
1818                tracing::debug!("Push completed successfully for branch: {}", branch);
1819                Ok(())
1820            }
1821            Err(e) => {
1822                tracing::debug!(
1823                    "git2 push error: {} (class: {:?}, code: {:?})",
1824                    e,
1825                    e.class(),
1826                    e.code()
1827                );
1828
1829                if self.should_retry_with_default_credentials(&e) {
1830                    tracing::debug!(
1831                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1832                        e.class(), e.code(), e
1833                    );
1834
1835                    // Retry with DefaultCredentials for corporate networks
1836                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1837                    let mut push_options = git2::PushOptions::new();
1838                    push_options.remote_callbacks(callbacks);
1839
1840                    match remote.push(&[&refspec], Some(&mut push_options)) {
1841                        Ok(_) => {
1842                            tracing::debug!("Push succeeded with DefaultCredentials");
1843                            return Ok(());
1844                        }
1845                        Err(retry_error) => {
1846                            tracing::debug!(
1847                                "DefaultCredentials retry failed: {}, falling back to git CLI",
1848                                retry_error
1849                            );
1850                            return self.push_with_git_cli(branch);
1851                        }
1852                    }
1853                }
1854
1855                if self.should_fallback_to_git_cli(&e) {
1856                    tracing::debug!(
1857                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1858                        e.class(), e.code(), e
1859                    );
1860                    return self.push_with_git_cli(branch);
1861                }
1862
1863                // Create concise error message
1864                let error_msg = if e.to_string().contains("authentication") {
1865                    format!(
1866                        "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1867                    )
1868                } else {
1869                    format!("Failed to push branch '{branch}': {e}")
1870                };
1871
1872                Err(CascadeError::branch(error_msg))
1873            }
1874        }
1875    }
1876
1877    /// Fallback push method using git CLI instead of git2
1878    /// This is used when git2 has TLS/SSL or auth issues but git CLI works fine
1879    fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1880        // Ensure index is closed before CLI command
1881        self.ensure_index_closed()?;
1882
1883        let output = std::process::Command::new("git")
1884            .args(["push", "origin", branch])
1885            .current_dir(&self.path)
1886            .output()
1887            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1888
1889        if output.status.success() {
1890            // Silent success - no need to log when fallback works
1891            Ok(())
1892        } else {
1893            let stderr = String::from_utf8_lossy(&output.stderr);
1894            let _stdout = String::from_utf8_lossy(&output.stdout);
1895            // Extract the most relevant error message
1896            let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1897                "Network error: Unable to connect to repository (VPN may be required)".to_string()
1898            } else if stderr.contains("repository") && stderr.contains("not found") {
1899                "Repository not found - check your Bitbucket configuration".to_string()
1900            } else if stderr.contains("authentication") || stderr.contains("403") {
1901                "Authentication failed - check your credentials".to_string()
1902            } else {
1903                // For other errors, just show the stderr without the verbose prefix
1904                stderr.trim().to_string()
1905            };
1906            Err(CascadeError::branch(error_msg))
1907        }
1908    }
1909
1910    /// Fallback fetch method using git CLI instead of git2
1911    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1912    fn fetch_with_git_cli(&self) -> Result<()> {
1913        tracing::debug!("Using git CLI fallback for fetch operation");
1914
1915        // Ensure index is closed before CLI command
1916        self.ensure_index_closed()?;
1917
1918        let output = std::process::Command::new("git")
1919            .args(["fetch", "origin"])
1920            .current_dir(&self.path)
1921            .output()
1922            .map_err(|e| {
1923                CascadeError::Git(git2::Error::from_str(&format!(
1924                    "Failed to execute git command: {e}"
1925                )))
1926            })?;
1927
1928        if output.status.success() {
1929            tracing::debug!("Git CLI fetch succeeded");
1930            Ok(())
1931        } else {
1932            let stderr = String::from_utf8_lossy(&output.stderr);
1933            let stdout = String::from_utf8_lossy(&output.stdout);
1934            let error_msg = format!(
1935                "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1936                output.status, stdout, stderr
1937            );
1938            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1939        }
1940    }
1941
1942    /// Fallback pull method using git CLI instead of git2
1943    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1944    fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1945        tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1946
1947        // Ensure index is closed before CLI command
1948        self.ensure_index_closed()?;
1949
1950        let output = std::process::Command::new("git")
1951            .args(["pull", "origin", branch])
1952            .current_dir(&self.path)
1953            .output()
1954            .map_err(|e| {
1955                CascadeError::Git(git2::Error::from_str(&format!(
1956                    "Failed to execute git command: {e}"
1957                )))
1958            })?;
1959
1960        if output.status.success() {
1961            tracing::debug!("Git CLI pull succeeded for branch: {}", branch);
1962            Ok(())
1963        } else {
1964            let stderr = String::from_utf8_lossy(&output.stderr);
1965            let stdout = String::from_utf8_lossy(&output.stdout);
1966            let error_msg = format!(
1967                "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1968                branch, output.status, stdout, stderr
1969            );
1970            Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1971        }
1972    }
1973
1974    /// Fallback force push method using git CLI instead of git2
1975    /// This is used when git2 has TLS/SSL issues but git CLI works fine
1976    fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1977        tracing::debug!(
1978            "Using git CLI fallback for force push operation: {}",
1979            branch
1980        );
1981
1982        let output = std::process::Command::new("git")
1983            .args(["push", "--force", "origin", branch])
1984            .current_dir(&self.path)
1985            .output()
1986            .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1987
1988        if output.status.success() {
1989            tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
1990            Ok(())
1991        } else {
1992            let stderr = String::from_utf8_lossy(&output.stderr);
1993            let stdout = String::from_utf8_lossy(&output.stdout);
1994            let error_msg = format!(
1995                "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1996                branch, output.status, stdout, stderr
1997            );
1998            Err(CascadeError::branch(error_msg))
1999        }
2000    }
2001
2002    /// Delete a local branch
2003    pub fn delete_branch(&self, name: &str) -> Result<()> {
2004        self.delete_branch_with_options(name, false)
2005    }
2006
2007    /// Delete a local branch with force option to bypass safety checks
2008    pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
2009        self.delete_branch_with_options(name, true)
2010    }
2011
2012    /// Internal branch deletion implementation with safety options
2013    fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
2014        debug!("Attempting to delete branch: {}", name);
2015
2016        // Enhanced safety check: Detect unpushed commits before deletion
2017        if !force_unsafe {
2018            let safety_result = self.check_branch_deletion_safety(name)?;
2019            if let Some(safety_info) = safety_result {
2020                // Branch has unpushed commits, get user confirmation
2021                self.handle_branch_deletion_confirmation(name, &safety_info)?;
2022            }
2023        }
2024
2025        let mut branch = self
2026            .repo
2027            .find_branch(name, git2::BranchType::Local)
2028            .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
2029
2030        branch
2031            .delete()
2032            .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
2033
2034        debug!("Successfully deleted branch '{}'", name);
2035        Ok(())
2036    }
2037
2038    /// Get commits between two references
2039    pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
2040        let from_oid = self
2041            .repo
2042            .refname_to_id(&format!("refs/heads/{from}"))
2043            .or_else(|_| Oid::from_str(from))
2044            .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
2045
2046        let to_oid = self
2047            .repo
2048            .refname_to_id(&format!("refs/heads/{to}"))
2049            .or_else(|_| Oid::from_str(to))
2050            .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
2051
2052        let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2053
2054        revwalk.push(to_oid).map_err(CascadeError::Git)?;
2055        revwalk.hide(from_oid).map_err(CascadeError::Git)?;
2056
2057        let mut commits = Vec::new();
2058        for oid in revwalk {
2059            let oid = oid.map_err(CascadeError::Git)?;
2060            let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
2061            commits.push(commit);
2062        }
2063
2064        Ok(commits)
2065    }
2066
2067    /// Force push one branch's content to another branch name
2068    /// This is used to preserve PR history while updating branch contents after rebase
2069    pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2070        self.force_push_branch_with_options(target_branch, source_branch, false)
2071    }
2072
2073    /// Force push with explicit force flag to bypass safety checks
2074    pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
2075        self.force_push_branch_with_options(target_branch, source_branch, true)
2076    }
2077
2078    /// Internal force push implementation with safety options
2079    fn force_push_branch_with_options(
2080        &self,
2081        target_branch: &str,
2082        source_branch: &str,
2083        force_unsafe: bool,
2084    ) -> Result<()> {
2085        debug!(
2086            "Force pushing {} content to {} to preserve PR history",
2087            source_branch, target_branch
2088        );
2089
2090        // Enhanced safety check: Detect potential data loss and get user confirmation
2091        if !force_unsafe {
2092            let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
2093            if let Some(backup_info) = safety_result {
2094                // Create backup branch before force push
2095                self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
2096                Output::sub_item(format!(
2097                    "Created backup branch: {}",
2098                    backup_info.backup_branch_name
2099                ));
2100            }
2101        }
2102
2103        // First, ensure we have the latest changes for the source branch
2104        let source_ref = self
2105            .repo
2106            .find_reference(&format!("refs/heads/{source_branch}"))
2107            .map_err(|e| {
2108                CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
2109            })?;
2110        let _source_commit = source_ref.peel_to_commit().map_err(|e| {
2111            CascadeError::config(format!(
2112                "Failed to get commit for source branch {source_branch}: {e}"
2113            ))
2114        })?;
2115
2116        // Force push to remote without modifying local target branch
2117        let mut remote = self
2118            .repo
2119            .find_remote("origin")
2120            .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
2121
2122        // Push source branch content to remote target branch
2123        let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
2124
2125        // Configure callbacks with SSL settings from git config
2126        let callbacks = self.configure_remote_callbacks()?;
2127
2128        // Push options for force push with SSL config
2129        let mut push_options = git2::PushOptions::new();
2130        push_options.remote_callbacks(callbacks);
2131
2132        match remote.push(&[&refspec], Some(&mut push_options)) {
2133            Ok(_) => {}
2134            Err(e) => {
2135                if self.should_retry_with_default_credentials(&e) {
2136                    tracing::debug!(
2137                        "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
2138                        e.class(), e.code(), e
2139                    );
2140
2141                    // Retry with DefaultCredentials for corporate networks
2142                    let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
2143                    let mut push_options = git2::PushOptions::new();
2144                    push_options.remote_callbacks(callbacks);
2145
2146                    match remote.push(&[&refspec], Some(&mut push_options)) {
2147                        Ok(_) => {
2148                            tracing::debug!("Force push succeeded with DefaultCredentials");
2149                            // Success - continue to normal success path
2150                        }
2151                        Err(retry_error) => {
2152                            tracing::debug!(
2153                                "DefaultCredentials retry failed: {}, falling back to git CLI",
2154                                retry_error
2155                            );
2156                            return self.force_push_with_git_cli(target_branch);
2157                        }
2158                    }
2159                } else if self.should_fallback_to_git_cli(&e) {
2160                    tracing::debug!(
2161                        "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
2162                        e.class(), e.code(), e
2163                    );
2164                    return self.force_push_with_git_cli(target_branch);
2165                } else {
2166                    return Err(CascadeError::config(format!(
2167                        "Failed to force push {target_branch}: {e}"
2168                    )));
2169                }
2170            }
2171        }
2172
2173        tracing::debug!(
2174            "Successfully force pushed {} to preserve PR history",
2175            target_branch
2176        );
2177        Ok(())
2178    }
2179
2180    /// Enhanced safety check for force push operations with user confirmation
2181    /// Returns backup info if data would be lost and user confirms
2182    fn check_force_push_safety_enhanced(
2183        &self,
2184        target_branch: &str,
2185    ) -> Result<Option<ForceBackupInfo>> {
2186        // First fetch latest remote changes to ensure we have up-to-date information
2187        match self.fetch() {
2188            Ok(_) => {}
2189            Err(e) => {
2190                // If fetch fails, warn but don't block the operation
2191                debug!("Could not fetch latest changes for safety check: {}", e);
2192            }
2193        }
2194
2195        // Check if there are commits on the remote that would be lost
2196        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2197        let local_ref = format!("refs/heads/{target_branch}");
2198
2199        // Try to find both local and remote references
2200        let local_commit = match self.repo.find_reference(&local_ref) {
2201            Ok(reference) => reference.peel_to_commit().ok(),
2202            Err(_) => None,
2203        };
2204
2205        let remote_commit = match self.repo.find_reference(&remote_ref) {
2206            Ok(reference) => reference.peel_to_commit().ok(),
2207            Err(_) => None,
2208        };
2209
2210        // If we have both commits, check for divergence
2211        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2212            if local.id() != remote.id() {
2213                // Check if the remote has commits that the local doesn't have
2214                let merge_base_oid = self
2215                    .repo
2216                    .merge_base(local.id(), remote.id())
2217                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2218
2219                // If merge base != remote commit, remote has commits that would be lost
2220                if merge_base_oid != remote.id() {
2221                    let commits_to_lose = self.count_commits_between(
2222                        &merge_base_oid.to_string(),
2223                        &remote.id().to_string(),
2224                    )?;
2225
2226                    // Create backup branch name with timestamp
2227                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2228                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2229
2230                    debug!(
2231                        "Force push to '{}' would overwrite {} commits on remote",
2232                        target_branch, commits_to_lose
2233                    );
2234
2235                    // Check if we're in a non-interactive environment (CI/testing)
2236                    if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2237                    {
2238                        info!(
2239                            "Non-interactive environment detected, proceeding with backup creation"
2240                        );
2241                        return Ok(Some(ForceBackupInfo {
2242                            backup_branch_name,
2243                            remote_commit_id: remote.id().to_string(),
2244                            commits_that_would_be_lost: commits_to_lose,
2245                        }));
2246                    }
2247
2248                    // Automatically create backup - this is normal stacked diff workflow
2249                    return Ok(Some(ForceBackupInfo {
2250                        backup_branch_name,
2251                        remote_commit_id: remote.id().to_string(),
2252                        commits_that_would_be_lost: commits_to_lose,
2253                    }));
2254                }
2255            }
2256        }
2257
2258        Ok(None)
2259    }
2260
2261    /// Check force push safety without user confirmation (auto-creates backup)
2262    /// Used for automated operations like sync where user already confirmed the operation
2263    ///
2264    /// When skip_fetch=false: Fetches latest remote state before checking (default behavior)
2265    /// When skip_fetch=true: Assumes fetch already done (batch operations)
2266    fn check_force_push_safety_auto_no_fetch(
2267        &self,
2268        target_branch: &str,
2269    ) -> Result<Option<ForceBackupInfo>> {
2270        // Check if there are commits on the remote that would be lost
2271        let remote_ref = format!("refs/remotes/origin/{target_branch}");
2272        let local_ref = format!("refs/heads/{target_branch}");
2273
2274        // Try to find both local and remote references
2275        let local_commit = match self.repo.find_reference(&local_ref) {
2276            Ok(reference) => reference.peel_to_commit().ok(),
2277            Err(_) => None,
2278        };
2279
2280        let remote_commit = match self.repo.find_reference(&remote_ref) {
2281            Ok(reference) => reference.peel_to_commit().ok(),
2282            Err(_) => None,
2283        };
2284
2285        // If we have both commits, check for divergence
2286        if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2287            if local.id() != remote.id() {
2288                // Check if the remote has commits that the local doesn't have
2289                let merge_base_oid = self
2290                    .repo
2291                    .merge_base(local.id(), remote.id())
2292                    .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2293
2294                // If merge base != remote commit, remote has commits that would be lost
2295                if merge_base_oid != remote.id() {
2296                    let commits_to_lose = self.count_commits_between(
2297                        &merge_base_oid.to_string(),
2298                        &remote.id().to_string(),
2299                    )?;
2300
2301                    // Create backup branch name with timestamp
2302                    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2303                    let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2304
2305                    tracing::debug!(
2306                        "Auto-creating backup '{}' for force push to '{}' (would overwrite {} commits)",
2307                        backup_branch_name, target_branch, commits_to_lose
2308                    );
2309
2310                    // Automatically create backup without confirmation
2311                    return Ok(Some(ForceBackupInfo {
2312                        backup_branch_name,
2313                        remote_commit_id: remote.id().to_string(),
2314                        commits_that_would_be_lost: commits_to_lose,
2315                    }));
2316                }
2317            }
2318        }
2319
2320        Ok(None)
2321    }
2322
2323    /// Create a backup branch pointing to the remote commit that would be lost
2324    fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2325        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2326        let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2327
2328        // Parse the commit ID
2329        let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2330            CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2331        })?;
2332
2333        // Find the commit
2334        let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2335            CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2336        })?;
2337
2338        // Create the backup branch
2339        self.repo
2340            .branch(&backup_branch_name, &commit, false)
2341            .map_err(|e| {
2342                CascadeError::config(format!(
2343                    "Failed to create backup branch {backup_branch_name}: {e}"
2344                ))
2345            })?;
2346
2347        debug!(
2348            "Created backup branch '{}' pointing to {}",
2349            backup_branch_name,
2350            &remote_commit_id[..8]
2351        );
2352        Ok(())
2353    }
2354
2355    /// Check if branch deletion is safe by detecting unpushed commits
2356    /// Returns safety info if there are concerns that need user attention
2357    fn check_branch_deletion_safety(
2358        &self,
2359        branch_name: &str,
2360    ) -> Result<Option<BranchDeletionSafety>> {
2361        // First, try to fetch latest remote changes
2362        match self.fetch() {
2363            Ok(_) => {}
2364            Err(e) => {
2365                warn!(
2366                    "Could not fetch latest changes for branch deletion safety check: {}",
2367                    e
2368                );
2369            }
2370        }
2371
2372        // Find the branch
2373        let branch = self
2374            .repo
2375            .find_branch(branch_name, git2::BranchType::Local)
2376            .map_err(|e| {
2377                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2378            })?;
2379
2380        let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2381            CascadeError::branch(format!(
2382                "Could not get commit for branch '{branch_name}': {e}"
2383            ))
2384        })?;
2385
2386        // Determine the main branch (try common names)
2387        let main_branch_name = self.detect_main_branch()?;
2388
2389        // Check if branch is merged to main
2390        let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2391
2392        // Find the upstream/remote tracking branch
2393        let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2394
2395        let mut unpushed_commits = Vec::new();
2396
2397        // Check for unpushed commits compared to remote tracking branch
2398        if let Some(ref remote_branch) = remote_tracking_branch {
2399            match self.get_commits_between(remote_branch, branch_name) {
2400                Ok(commits) => {
2401                    unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2402                }
2403                Err(_) => {
2404                    // If we can't compare with remote, check against main branch
2405                    if !is_merged_to_main {
2406                        if let Ok(commits) =
2407                            self.get_commits_between(&main_branch_name, branch_name)
2408                        {
2409                            unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2410                        }
2411                    }
2412                }
2413            }
2414        } else if !is_merged_to_main {
2415            // No remote tracking branch, check against main
2416            if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2417                unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2418            }
2419        }
2420
2421        // If there are concerns, return safety info
2422        if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2423        {
2424            Ok(Some(BranchDeletionSafety {
2425                unpushed_commits,
2426                remote_tracking_branch,
2427                is_merged_to_main,
2428                main_branch_name,
2429            }))
2430        } else {
2431            Ok(None)
2432        }
2433    }
2434
2435    /// Handle user confirmation for branch deletion with safety concerns
2436    fn handle_branch_deletion_confirmation(
2437        &self,
2438        branch_name: &str,
2439        safety_info: &BranchDeletionSafety,
2440    ) -> Result<()> {
2441        // Check if we're in a non-interactive environment
2442        if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2443            return Err(CascadeError::branch(
2444                format!(
2445                    "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2446                    safety_info.unpushed_commits.len()
2447                )
2448            ));
2449        }
2450
2451        // Interactive warning and confirmation
2452        println!();
2453        Output::warning("BRANCH DELETION WARNING");
2454        println!("Branch '{branch_name}' has potential issues:");
2455
2456        if !safety_info.unpushed_commits.is_empty() {
2457            println!(
2458                "\n🔍 Unpushed commits ({} total):",
2459                safety_info.unpushed_commits.len()
2460            );
2461
2462            // Show details of unpushed commits
2463            for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2464                if let Ok(oid) = Oid::from_str(commit_id) {
2465                    if let Ok(commit) = self.repo.find_commit(oid) {
2466                        let short_hash = &commit_id[..8];
2467                        let summary = commit.summary().unwrap_or("<no message>");
2468                        println!("  {}. {} - {}", i + 1, short_hash, summary);
2469                    }
2470                }
2471            }
2472
2473            if safety_info.unpushed_commits.len() > 5 {
2474                println!(
2475                    "  ... and {} more commits",
2476                    safety_info.unpushed_commits.len() - 5
2477                );
2478            }
2479        }
2480
2481        if !safety_info.is_merged_to_main {
2482            println!();
2483            crate::cli::output::Output::section("Branch status");
2484            crate::cli::output::Output::bullet(format!(
2485                "Not merged to '{}'",
2486                safety_info.main_branch_name
2487            ));
2488            if let Some(ref remote) = safety_info.remote_tracking_branch {
2489                crate::cli::output::Output::bullet(format!("Remote tracking branch: {remote}"));
2490            } else {
2491                crate::cli::output::Output::bullet("No remote tracking branch");
2492            }
2493        }
2494
2495        println!();
2496        crate::cli::output::Output::section("Safer alternatives");
2497        if !safety_info.unpushed_commits.is_empty() {
2498            if let Some(ref _remote) = safety_info.remote_tracking_branch {
2499                println!("  • Push commits first: git push origin {branch_name}");
2500            } else {
2501                println!("  • Create and push to remote: git push -u origin {branch_name}");
2502            }
2503        }
2504        if !safety_info.is_merged_to_main {
2505            println!(
2506                "  • Merge to {} first: git checkout {} && git merge {branch_name}",
2507                safety_info.main_branch_name, safety_info.main_branch_name
2508            );
2509        }
2510
2511        let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2512            .with_prompt("Do you want to proceed with deleting this branch?")
2513            .default(false)
2514            .interact()
2515            .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2516
2517        if !confirmed {
2518            return Err(CascadeError::branch(
2519                "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2520            ));
2521        }
2522
2523        Ok(())
2524    }
2525
2526    /// Detect the main branch name (main, master, develop)
2527    pub fn detect_main_branch(&self) -> Result<String> {
2528        let main_candidates = ["main", "master", "develop", "trunk"];
2529
2530        for candidate in &main_candidates {
2531            if self
2532                .repo
2533                .find_branch(candidate, git2::BranchType::Local)
2534                .is_ok()
2535            {
2536                return Ok(candidate.to_string());
2537            }
2538        }
2539
2540        // Fallback to HEAD's target if it's a symbolic reference
2541        if let Ok(head) = self.repo.head() {
2542            if let Some(name) = head.shorthand() {
2543                return Ok(name.to_string());
2544            }
2545        }
2546
2547        // Final fallback
2548        Ok("main".to_string())
2549    }
2550
2551    /// Check if a branch is merged to the main branch
2552    fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2553        // Get the commits between main and the branch
2554        match self.get_commits_between(main_branch, branch_name) {
2555            Ok(commits) => Ok(commits.is_empty()),
2556            Err(_) => {
2557                // If we can't determine, assume not merged for safety
2558                Ok(false)
2559            }
2560        }
2561    }
2562
2563    /// Get the remote tracking branch for a local branch
2564    fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2565        // Try common remote tracking branch patterns
2566        let remote_candidates = [
2567            format!("origin/{branch_name}"),
2568            format!("remotes/origin/{branch_name}"),
2569        ];
2570
2571        for candidate in &remote_candidates {
2572            if self
2573                .repo
2574                .find_reference(&format!(
2575                    "refs/remotes/{}",
2576                    candidate.replace("remotes/", "")
2577                ))
2578                .is_ok()
2579            {
2580                return Some(candidate.clone());
2581            }
2582        }
2583
2584        None
2585    }
2586
2587    /// Check if checkout operation is safe
2588    fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2589        // Check if there are uncommitted changes
2590        let is_dirty = self.is_dirty()?;
2591        if !is_dirty {
2592            // No uncommitted changes, checkout is safe
2593            return Ok(None);
2594        }
2595
2596        // Get current branch for context
2597        let current_branch = self.get_current_branch().ok();
2598
2599        // Get detailed information about uncommitted changes
2600        let modified_files = self.get_modified_files()?;
2601        let staged_files = self.get_staged_files()?;
2602        let untracked_files = self.get_untracked_files()?;
2603
2604        let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2605
2606        if has_uncommitted_changes || !untracked_files.is_empty() {
2607            return Ok(Some(CheckoutSafety {
2608                has_uncommitted_changes,
2609                modified_files,
2610                staged_files,
2611                untracked_files,
2612                stash_created: None,
2613                current_branch,
2614            }));
2615        }
2616
2617        Ok(None)
2618    }
2619
2620    /// Handle user confirmation for checkout operations with uncommitted changes
2621    fn handle_checkout_confirmation(
2622        &self,
2623        target: &str,
2624        safety_info: &CheckoutSafety,
2625    ) -> Result<()> {
2626        // Check if we're in a non-interactive environment FIRST (before any output)
2627        let is_ci = std::env::var("CI").is_ok();
2628        let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2629        let is_non_interactive = is_ci || no_confirm;
2630
2631        if is_non_interactive {
2632            return Err(CascadeError::branch(
2633                format!(
2634                    "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2635                )
2636            ));
2637        }
2638
2639        // Interactive warning and confirmation
2640        println!("\nCHECKOUT WARNING");
2641        println!("Attempting to checkout: {}", target);
2642        println!("You have uncommitted changes that could be lost:");
2643
2644        if !safety_info.modified_files.is_empty() {
2645            println!("\nModified files ({}):", safety_info.modified_files.len());
2646            for file in safety_info.modified_files.iter().take(10) {
2647                println!("   - {file}");
2648            }
2649            if safety_info.modified_files.len() > 10 {
2650                println!("   ... and {} more", safety_info.modified_files.len() - 10);
2651            }
2652        }
2653
2654        if !safety_info.staged_files.is_empty() {
2655            println!("\nStaged files ({}):", safety_info.staged_files.len());
2656            for file in safety_info.staged_files.iter().take(10) {
2657                println!("   - {file}");
2658            }
2659            if safety_info.staged_files.len() > 10 {
2660                println!("   ... and {} more", safety_info.staged_files.len() - 10);
2661            }
2662        }
2663
2664        if !safety_info.untracked_files.is_empty() {
2665            println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2666            for file in safety_info.untracked_files.iter().take(5) {
2667                println!("   - {file}");
2668            }
2669            if safety_info.untracked_files.len() > 5 {
2670                println!("   ... and {} more", safety_info.untracked_files.len() - 5);
2671            }
2672        }
2673
2674        println!("\nOptions:");
2675        println!("1. Stash changes and checkout (recommended)");
2676        println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2677        println!("3. Cancel checkout");
2678
2679        // Use proper selection dialog instead of y/n confirmation
2680        let selection = Select::with_theme(&ColorfulTheme::default())
2681            .with_prompt("Choose an action")
2682            .items(&[
2683                "Stash changes and checkout (recommended)",
2684                "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2685                "Cancel checkout",
2686            ])
2687            .default(0)
2688            .interact()
2689            .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2690
2691        match selection {
2692            0 => {
2693                // Option 1: Stash changes and checkout
2694                let stash_message = format!(
2695                    "Auto-stash before checkout to {} at {}",
2696                    target,
2697                    chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2698                );
2699
2700                match self.create_stash(&stash_message) {
2701                    Ok(stash_id) => {
2702                        crate::cli::output::Output::success(format!(
2703                            "Created stash: {stash_message} ({stash_id})"
2704                        ));
2705                        crate::cli::output::Output::tip("You can restore with: git stash pop");
2706                    }
2707                    Err(e) => {
2708                        crate::cli::output::Output::error(format!("Failed to create stash: {e}"));
2709
2710                        // If stash failed, provide better options
2711                        use dialoguer::Select;
2712                        let stash_failed_options = vec![
2713                            "Commit staged changes and proceed",
2714                            "Force checkout (WILL LOSE CHANGES)",
2715                            "Cancel and handle manually",
2716                        ];
2717
2718                        let stash_selection = Select::with_theme(&ColorfulTheme::default())
2719                            .with_prompt("Stash failed. What would you like to do?")
2720                            .items(&stash_failed_options)
2721                            .default(0)
2722                            .interact()
2723                            .map_err(|e| {
2724                                CascadeError::branch(format!("Could not get user selection: {e}"))
2725                            })?;
2726
2727                        match stash_selection {
2728                            0 => {
2729                                // Try to commit staged changes
2730                                let staged_files = self.get_staged_files()?;
2731                                if !staged_files.is_empty() {
2732                                    println!(
2733                                        "📝 Committing {} staged files...",
2734                                        staged_files.len()
2735                                    );
2736                                    match self
2737                                        .commit_staged_changes("WIP: Auto-commit before checkout")
2738                                    {
2739                                        Ok(Some(commit_hash)) => {
2740                                            crate::cli::output::Output::success(format!(
2741                                                "Committed staged changes as {}",
2742                                                &commit_hash[..8]
2743                                            ));
2744                                            crate::cli::output::Output::tip(
2745                                                "You can undo with: git reset HEAD~1",
2746                                            );
2747                                        }
2748                                        Ok(None) => {
2749                                            crate::cli::output::Output::info(
2750                                                "No staged changes found to commit",
2751                                            );
2752                                        }
2753                                        Err(commit_err) => {
2754                                            println!(
2755                                                "❌ Failed to commit staged changes: {commit_err}"
2756                                            );
2757                                            return Err(CascadeError::branch(
2758                                                "Could not commit staged changes".to_string(),
2759                                            ));
2760                                        }
2761                                    }
2762                                } else {
2763                                    println!("No staged changes to commit");
2764                                }
2765                            }
2766                            1 => {
2767                                // Force checkout anyway
2768                                Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2769                            }
2770                            2 => {
2771                                // Cancel
2772                                return Err(CascadeError::branch(
2773                                    "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2774                                ));
2775                            }
2776                            _ => unreachable!(),
2777                        }
2778                    }
2779                }
2780            }
2781            1 => {
2782                // Option 2: Force checkout (lose changes)
2783                Output::warning(
2784                    "Proceeding with force checkout - uncommitted changes will be lost!",
2785                );
2786            }
2787            2 => {
2788                // Option 3: Cancel
2789                return Err(CascadeError::branch(
2790                    "Checkout cancelled by user".to_string(),
2791                ));
2792            }
2793            _ => unreachable!(),
2794        }
2795
2796        Ok(())
2797    }
2798
2799    /// Create a stash with uncommitted changes
2800    fn create_stash(&self, message: &str) -> Result<String> {
2801        use crate::cli::output::Output;
2802
2803        tracing::debug!("Creating stash: {}", message);
2804
2805        // Use git CLI for stashing since git2 stashing is complex and unreliable
2806        let output = std::process::Command::new("git")
2807            .args(["stash", "push", "-m", message])
2808            .current_dir(&self.path)
2809            .output()
2810            .map_err(|e| {
2811                CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2812            })?;
2813
2814        if output.status.success() {
2815            let stdout = String::from_utf8_lossy(&output.stdout);
2816
2817            // Extract stash hash if available (git stash outputs like "Saved working directory and index state WIP on branch: message")
2818            let stash_id = if stdout.contains("Saved working directory") {
2819                // Get the most recent stash ID
2820                let stash_list_output = std::process::Command::new("git")
2821                    .args(["stash", "list", "-n", "1", "--format=%H"])
2822                    .current_dir(&self.path)
2823                    .output()
2824                    .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2825
2826                if stash_list_output.status.success() {
2827                    String::from_utf8_lossy(&stash_list_output.stdout)
2828                        .trim()
2829                        .to_string()
2830                } else {
2831                    "stash@{0}".to_string() // fallback
2832                }
2833            } else {
2834                "stash@{0}".to_string() // fallback
2835            };
2836
2837            Output::success(format!("Created stash: {} ({})", message, stash_id));
2838            Output::tip("You can restore with: git stash pop");
2839            Ok(stash_id)
2840        } else {
2841            let stderr = String::from_utf8_lossy(&output.stderr);
2842            let stdout = String::from_utf8_lossy(&output.stdout);
2843
2844            // Check for common stash failure reasons
2845            if stderr.contains("No local changes to save")
2846                || stdout.contains("No local changes to save")
2847            {
2848                return Err(CascadeError::branch("No local changes to save".to_string()));
2849            }
2850
2851            Err(CascadeError::branch(format!(
2852                "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2853                output.status, stderr, stdout
2854            )))
2855        }
2856    }
2857
2858    /// Get modified files in working directory
2859    fn get_modified_files(&self) -> Result<Vec<String>> {
2860        let mut opts = git2::StatusOptions::new();
2861        opts.include_untracked(false).include_ignored(false);
2862
2863        let statuses = self
2864            .repo
2865            .statuses(Some(&mut opts))
2866            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2867
2868        let mut modified_files = Vec::new();
2869        for status in statuses.iter() {
2870            let flags = status.status();
2871            if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2872            {
2873                if let Some(path) = status.path() {
2874                    modified_files.push(path.to_string());
2875                }
2876            }
2877        }
2878
2879        Ok(modified_files)
2880    }
2881
2882    /// Get staged files in index
2883    pub fn get_staged_files(&self) -> Result<Vec<String>> {
2884        let mut opts = git2::StatusOptions::new();
2885        opts.include_untracked(false).include_ignored(false);
2886
2887        let statuses = self
2888            .repo
2889            .statuses(Some(&mut opts))
2890            .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2891
2892        let mut staged_files = Vec::new();
2893        for status in statuses.iter() {
2894            let flags = status.status();
2895            if flags.contains(git2::Status::INDEX_MODIFIED)
2896                || flags.contains(git2::Status::INDEX_NEW)
2897                || flags.contains(git2::Status::INDEX_DELETED)
2898            {
2899                if let Some(path) = status.path() {
2900                    staged_files.push(path.to_string());
2901                }
2902            }
2903        }
2904
2905        Ok(staged_files)
2906    }
2907
2908    /// Count commits between two references
2909    fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2910        let commits = self.get_commits_between(from, to)?;
2911        Ok(commits.len())
2912    }
2913
2914    /// Resolve a reference (branch name, tag, or commit hash) to a commit
2915    pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2916        // Try to parse as commit hash first
2917        if let Ok(oid) = Oid::from_str(reference) {
2918            if let Ok(commit) = self.repo.find_commit(oid) {
2919                return Ok(commit);
2920            }
2921        }
2922
2923        // Try to resolve as a reference (branch, tag, etc.)
2924        let obj = self.repo.revparse_single(reference).map_err(|e| {
2925            CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2926        })?;
2927
2928        obj.peel_to_commit().map_err(|e| {
2929            CascadeError::branch(format!(
2930                "Reference '{reference}' does not point to a commit: {e}"
2931            ))
2932        })
2933    }
2934
2935    /// Reset HEAD to a specific reference (soft reset)
2936    pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2937        let target_commit = self.resolve_reference(target_ref)?;
2938
2939        self.repo
2940            .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2941            .map_err(CascadeError::Git)?;
2942
2943        Ok(())
2944    }
2945
2946    /// Reset working directory and index to match HEAD (hard reset)
2947    /// This clears all uncommitted changes and staged files
2948    pub fn reset_to_head(&self) -> Result<()> {
2949        tracing::debug!("Resetting working directory and index to HEAD");
2950
2951        let repo_path = self.path();
2952
2953        // Use lock retry wrapper to handle stale locks automatically
2954        crate::utils::git_lock::with_lock_retry(repo_path, || {
2955            let head = self.repo.head()?;
2956            let head_commit = head.peel_to_commit()?;
2957
2958            // Hard reset: resets index and working tree
2959            let mut checkout_builder = git2::build::CheckoutBuilder::new();
2960            checkout_builder.force(); // Force checkout to overwrite any local changes
2961            checkout_builder.remove_untracked(false); // Don't remove untracked files
2962
2963            self.repo.reset(
2964                head_commit.as_object(),
2965                git2::ResetType::Hard,
2966                Some(&mut checkout_builder),
2967            )?;
2968
2969            Ok(())
2970        })?;
2971
2972        tracing::debug!("Successfully reset working directory to HEAD");
2973        Ok(())
2974    }
2975
2976    /// Find which branch contains a specific commit
2977    pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2978        let oid = Oid::from_str(commit_hash).map_err(|e| {
2979            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2980        })?;
2981
2982        // Get all local branches
2983        let branches = self
2984            .repo
2985            .branches(Some(git2::BranchType::Local))
2986            .map_err(CascadeError::Git)?;
2987
2988        for branch_result in branches {
2989            let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2990
2991            if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2992                // Check if this branch contains the commit
2993                if let Ok(branch_head) = branch.get().peel_to_commit() {
2994                    // Walk the commit history from this branch's HEAD
2995                    let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2996                    revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2997
2998                    for commit_oid in revwalk {
2999                        let commit_oid = commit_oid.map_err(CascadeError::Git)?;
3000                        if commit_oid == oid {
3001                            return Ok(branch_name.to_string());
3002                        }
3003                    }
3004                }
3005            }
3006        }
3007
3008        // If not found in any branch, might be on current HEAD
3009        Err(CascadeError::branch(format!(
3010            "Commit {commit_hash} not found in any local branch"
3011        )))
3012    }
3013
3014    // Async wrappers for potentially blocking operations
3015
3016    /// Fetch from remote origin (async)
3017    pub async fn fetch_async(&self) -> Result<()> {
3018        let repo_path = self.path.clone();
3019        crate::utils::async_ops::run_git_operation(move || {
3020            let repo = GitRepository::open(&repo_path)?;
3021            repo.fetch()
3022        })
3023        .await
3024    }
3025
3026    /// Pull changes from remote (async)
3027    pub async fn pull_async(&self, branch: &str) -> Result<()> {
3028        let repo_path = self.path.clone();
3029        let branch_name = branch.to_string();
3030        crate::utils::async_ops::run_git_operation(move || {
3031            let repo = GitRepository::open(&repo_path)?;
3032            repo.pull(&branch_name)
3033        })
3034        .await
3035    }
3036
3037    /// Push branch to remote (async)
3038    pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
3039        let repo_path = self.path.clone();
3040        let branch = branch_name.to_string();
3041        crate::utils::async_ops::run_git_operation(move || {
3042            let repo = GitRepository::open(&repo_path)?;
3043            repo.push(&branch)
3044        })
3045        .await
3046    }
3047
3048    /// Cherry-pick commit (async)
3049    pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
3050        let repo_path = self.path.clone();
3051        let hash = commit_hash.to_string();
3052        crate::utils::async_ops::run_git_operation(move || {
3053            let repo = GitRepository::open(&repo_path)?;
3054            repo.cherry_pick(&hash)
3055        })
3056        .await
3057    }
3058
3059    /// Get commit hashes between two refs (async)
3060    pub async fn get_commit_hashes_between_async(
3061        &self,
3062        from: &str,
3063        to: &str,
3064    ) -> Result<Vec<String>> {
3065        let repo_path = self.path.clone();
3066        let from_str = from.to_string();
3067        let to_str = to.to_string();
3068        crate::utils::async_ops::run_git_operation(move || {
3069            let repo = GitRepository::open(&repo_path)?;
3070            let commits = repo.get_commits_between(&from_str, &to_str)?;
3071            Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
3072        })
3073        .await
3074    }
3075
3076    /// Reset a branch to point to a specific commit
3077    pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
3078        info!(
3079            "Resetting branch '{}' to commit {}",
3080            branch_name,
3081            &commit_hash[..8]
3082        );
3083
3084        // Find the target commit
3085        let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
3086            CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3087        })?;
3088
3089        let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
3090            CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
3091        })?;
3092
3093        // Find the branch
3094        let _branch = self
3095            .repo
3096            .find_branch(branch_name, git2::BranchType::Local)
3097            .map_err(|e| {
3098                CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3099            })?;
3100
3101        // Update the branch reference to point to the target commit
3102        let branch_ref_name = format!("refs/heads/{branch_name}");
3103        self.repo
3104            .reference(
3105                &branch_ref_name,
3106                target_oid,
3107                true,
3108                &format!("Reset {branch_name} to {commit_hash}"),
3109            )
3110            .map_err(|e| {
3111                CascadeError::branch(format!(
3112                    "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3113                ))
3114            })?;
3115
3116        tracing::info!(
3117            "Successfully reset branch '{}' to commit {}",
3118            branch_name,
3119            &commit_hash[..8]
3120        );
3121        Ok(())
3122    }
3123
3124    /// Detect the parent branch of the current branch using multiple strategies
3125    pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3126        let current_branch = self.get_current_branch()?;
3127
3128        // Strategy 1: Check if current branch has an upstream tracking branch
3129        if let Ok(Some(upstream)) = self.get_upstream_branch(&current_branch) {
3130            // Extract the branch name from "origin/branch-name" format
3131            if let Some(branch_name) = upstream.split('/').nth(1) {
3132                if self.branch_exists(branch_name) {
3133                    tracing::debug!(
3134                        "Detected parent branch '{}' from upstream tracking",
3135                        branch_name
3136                    );
3137                    return Ok(Some(branch_name.to_string()));
3138                }
3139            }
3140        }
3141
3142        // Strategy 2: Use git's default branch detection
3143        if let Ok(default_branch) = self.detect_main_branch() {
3144            // Don't suggest the current branch as its own parent
3145            if current_branch != default_branch {
3146                tracing::debug!(
3147                    "Detected parent branch '{}' as repository default",
3148                    default_branch
3149                );
3150                return Ok(Some(default_branch));
3151            }
3152        }
3153
3154        // Strategy 3: Find the branch with the most recent common ancestor
3155        // Get all local branches and find the one with the shortest commit distance
3156        if let Ok(branches) = self.list_branches() {
3157            let current_commit = self.get_head_commit()?;
3158            let current_commit_hash = current_commit.id().to_string();
3159            let current_oid = current_commit.id();
3160
3161            let mut best_candidate = None;
3162            let mut best_distance = usize::MAX;
3163
3164            for branch in branches {
3165                // Skip the current branch and any branches that look like version branches
3166                if branch == current_branch
3167                    || branch.contains("-v")
3168                    || branch.ends_with("-v2")
3169                    || branch.ends_with("-v3")
3170                {
3171                    continue;
3172                }
3173
3174                if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3175                    if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3176                        // Find merge base between current branch and this branch
3177                        if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3178                            // Count commits from merge base to current head
3179                            if let Ok(distance) = self.count_commits_between(
3180                                &merge_base_oid.to_string(),
3181                                &current_commit_hash,
3182                            ) {
3183                                // Prefer branches with shorter distances (more recent common ancestor)
3184                                // Also prefer branches that look like base branches
3185                                let is_likely_base = self.is_likely_base_branch(&branch);
3186                                let adjusted_distance = if is_likely_base {
3187                                    distance
3188                                } else {
3189                                    distance + 1000
3190                                };
3191
3192                                if adjusted_distance < best_distance {
3193                                    best_distance = adjusted_distance;
3194                                    best_candidate = Some(branch.clone());
3195                                }
3196                            }
3197                        }
3198                    }
3199                }
3200            }
3201
3202            if let Some(ref candidate) = best_candidate {
3203                tracing::debug!(
3204                    "Detected parent branch '{}' with distance {}",
3205                    candidate,
3206                    best_distance
3207                );
3208            }
3209
3210            return Ok(best_candidate);
3211        }
3212
3213        tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3214        Ok(None)
3215    }
3216
3217    /// Check if a branch name looks like a typical base branch
3218    fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3219        let base_patterns = [
3220            "main",
3221            "master",
3222            "develop",
3223            "dev",
3224            "development",
3225            "staging",
3226            "stage",
3227            "release",
3228            "production",
3229            "prod",
3230        ];
3231
3232        base_patterns.contains(&branch_name)
3233    }
3234}
3235
3236#[cfg(test)]
3237mod tests {
3238    use super::*;
3239    use std::process::Command;
3240    use tempfile::TempDir;
3241
3242    fn create_test_repo() -> (TempDir, PathBuf) {
3243        let temp_dir = TempDir::new().unwrap();
3244        let repo_path = temp_dir.path().to_path_buf();
3245
3246        // Initialize git repository
3247        Command::new("git")
3248            .args(["init"])
3249            .current_dir(&repo_path)
3250            .output()
3251            .unwrap();
3252        Command::new("git")
3253            .args(["config", "user.name", "Test"])
3254            .current_dir(&repo_path)
3255            .output()
3256            .unwrap();
3257        Command::new("git")
3258            .args(["config", "user.email", "test@test.com"])
3259            .current_dir(&repo_path)
3260            .output()
3261            .unwrap();
3262
3263        // Create initial commit
3264        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3265        Command::new("git")
3266            .args(["add", "."])
3267            .current_dir(&repo_path)
3268            .output()
3269            .unwrap();
3270        Command::new("git")
3271            .args(["commit", "-m", "Initial commit"])
3272            .current_dir(&repo_path)
3273            .output()
3274            .unwrap();
3275
3276        (temp_dir, repo_path)
3277    }
3278
3279    fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3280        let file_path = repo_path.join(filename);
3281        std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3282
3283        Command::new("git")
3284            .args(["add", filename])
3285            .current_dir(repo_path)
3286            .output()
3287            .unwrap();
3288        Command::new("git")
3289            .args(["commit", "-m", message])
3290            .current_dir(repo_path)
3291            .output()
3292            .unwrap();
3293    }
3294
3295    #[test]
3296    fn test_repository_info() {
3297        let (_temp_dir, repo_path) = create_test_repo();
3298        let repo = GitRepository::open(&repo_path).unwrap();
3299
3300        let info = repo.get_info().unwrap();
3301        assert!(!info.is_dirty); // Should be clean after commit
3302        assert!(
3303            info.head_branch == Some("master".to_string())
3304                || info.head_branch == Some("main".to_string()),
3305            "Expected default branch to be 'master' or 'main', got {:?}",
3306            info.head_branch
3307        );
3308        assert!(info.head_commit.is_some()); // Just check it exists
3309        assert!(info.untracked_files.is_empty()); // Should be empty after commit
3310    }
3311
3312    #[test]
3313    fn test_force_push_branch_basic() {
3314        let (_temp_dir, repo_path) = create_test_repo();
3315        let repo = GitRepository::open(&repo_path).unwrap();
3316
3317        // Get the actual default branch name
3318        let default_branch = repo.get_current_branch().unwrap();
3319
3320        // Create source branch with commits
3321        create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3322        Command::new("git")
3323            .args(["checkout", "-b", "source-branch"])
3324            .current_dir(&repo_path)
3325            .output()
3326            .unwrap();
3327        create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3328
3329        // Create target branch
3330        Command::new("git")
3331            .args(["checkout", &default_branch])
3332            .current_dir(&repo_path)
3333            .output()
3334            .unwrap();
3335        Command::new("git")
3336            .args(["checkout", "-b", "target-branch"])
3337            .current_dir(&repo_path)
3338            .output()
3339            .unwrap();
3340        create_commit(&repo_path, "Target commit", "target.rs");
3341
3342        // Test force push from source to target
3343        let result = repo.force_push_branch("target-branch", "source-branch");
3344
3345        // Should succeed in test environment (even though it doesn't actually push to remote)
3346        // The important thing is that the function doesn't panic and handles the git2 operations
3347        assert!(result.is_ok() || result.is_err()); // Either is acceptable for unit test
3348    }
3349
3350    #[test]
3351    fn test_force_push_branch_nonexistent_branches() {
3352        let (_temp_dir, repo_path) = create_test_repo();
3353        let repo = GitRepository::open(&repo_path).unwrap();
3354
3355        // Get the actual default branch name
3356        let default_branch = repo.get_current_branch().unwrap();
3357
3358        // Test force push with nonexistent source branch
3359        let result = repo.force_push_branch("target", "nonexistent-source");
3360        assert!(result.is_err());
3361
3362        // Test force push with nonexistent target branch
3363        let result = repo.force_push_branch("nonexistent-target", &default_branch);
3364        assert!(result.is_err());
3365    }
3366
3367    #[test]
3368    fn test_force_push_workflow_simulation() {
3369        let (_temp_dir, repo_path) = create_test_repo();
3370        let repo = GitRepository::open(&repo_path).unwrap();
3371
3372        // Simulate the smart force push workflow:
3373        // 1. Original branch exists with PR
3374        Command::new("git")
3375            .args(["checkout", "-b", "feature-auth"])
3376            .current_dir(&repo_path)
3377            .output()
3378            .unwrap();
3379        create_commit(&repo_path, "Add authentication", "auth.rs");
3380
3381        // 2. Rebase creates versioned branch
3382        Command::new("git")
3383            .args(["checkout", "-b", "feature-auth-v2"])
3384            .current_dir(&repo_path)
3385            .output()
3386            .unwrap();
3387        create_commit(&repo_path, "Fix auth validation", "auth.rs");
3388
3389        // 3. Smart force push: update original branch from versioned branch
3390        let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3391
3392        // Verify the operation is handled properly (success or expected error)
3393        match result {
3394            Ok(_) => {
3395                // Force push succeeded - verify branch state if possible
3396                Command::new("git")
3397                    .args(["checkout", "feature-auth"])
3398                    .current_dir(&repo_path)
3399                    .output()
3400                    .unwrap();
3401                let log_output = Command::new("git")
3402                    .args(["log", "--oneline", "-2"])
3403                    .current_dir(&repo_path)
3404                    .output()
3405                    .unwrap();
3406                let log_str = String::from_utf8_lossy(&log_output.stdout);
3407                assert!(
3408                    log_str.contains("Fix auth validation")
3409                        || log_str.contains("Add authentication")
3410                );
3411            }
3412            Err(_) => {
3413                // Expected in test environment without remote - that's fine
3414                // The important thing is we tested the code path without panicking
3415            }
3416        }
3417    }
3418
3419    #[test]
3420    fn test_branch_operations() {
3421        let (_temp_dir, repo_path) = create_test_repo();
3422        let repo = GitRepository::open(&repo_path).unwrap();
3423
3424        // Test get current branch - accept either main or master
3425        let current = repo.get_current_branch().unwrap();
3426        assert!(
3427            current == "master" || current == "main",
3428            "Expected default branch to be 'master' or 'main', got '{current}'"
3429        );
3430
3431        // Test create branch
3432        Command::new("git")
3433            .args(["checkout", "-b", "test-branch"])
3434            .current_dir(&repo_path)
3435            .output()
3436            .unwrap();
3437        let current = repo.get_current_branch().unwrap();
3438        assert_eq!(current, "test-branch");
3439    }
3440
3441    #[test]
3442    fn test_commit_operations() {
3443        let (_temp_dir, repo_path) = create_test_repo();
3444        let repo = GitRepository::open(&repo_path).unwrap();
3445
3446        // Test get head commit
3447        let head = repo.get_head_commit().unwrap();
3448        assert_eq!(head.message().unwrap().trim(), "Initial commit");
3449
3450        // Test get commit by hash
3451        let hash = head.id().to_string();
3452        let same_commit = repo.get_commit(&hash).unwrap();
3453        assert_eq!(head.id(), same_commit.id());
3454    }
3455
3456    #[test]
3457    fn test_checkout_safety_clean_repo() {
3458        let (_temp_dir, repo_path) = create_test_repo();
3459        let repo = GitRepository::open(&repo_path).unwrap();
3460
3461        // Create a test branch
3462        create_commit(&repo_path, "Second commit", "test.txt");
3463        Command::new("git")
3464            .args(["checkout", "-b", "test-branch"])
3465            .current_dir(&repo_path)
3466            .output()
3467            .unwrap();
3468
3469        // Test checkout safety with clean repo
3470        let safety_result = repo.check_checkout_safety("main");
3471        assert!(safety_result.is_ok());
3472        assert!(safety_result.unwrap().is_none()); // Clean repo should return None
3473    }
3474
3475    #[test]
3476    fn test_checkout_safety_with_modified_files() {
3477        let (_temp_dir, repo_path) = create_test_repo();
3478        let repo = GitRepository::open(&repo_path).unwrap();
3479
3480        // Create a test branch
3481        Command::new("git")
3482            .args(["checkout", "-b", "test-branch"])
3483            .current_dir(&repo_path)
3484            .output()
3485            .unwrap();
3486
3487        // Modify a file to create uncommitted changes
3488        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3489
3490        // Test checkout safety with modified files
3491        let safety_result = repo.check_checkout_safety("main");
3492        assert!(safety_result.is_ok());
3493        let safety_info = safety_result.unwrap();
3494        assert!(safety_info.is_some());
3495
3496        let info = safety_info.unwrap();
3497        assert!(!info.modified_files.is_empty());
3498        assert!(info.modified_files.contains(&"README.md".to_string()));
3499    }
3500
3501    #[test]
3502    fn test_unsafe_checkout_methods() {
3503        let (_temp_dir, repo_path) = create_test_repo();
3504        let repo = GitRepository::open(&repo_path).unwrap();
3505
3506        // Create a test branch
3507        create_commit(&repo_path, "Second commit", "test.txt");
3508        Command::new("git")
3509            .args(["checkout", "-b", "test-branch"])
3510            .current_dir(&repo_path)
3511            .output()
3512            .unwrap();
3513
3514        // Modify a file to create uncommitted changes
3515        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3516
3517        // Test unsafe checkout methods bypass safety checks
3518        let _result = repo.checkout_branch_unsafe("main");
3519        // Note: This might still fail due to git2 restrictions, but shouldn't hit our safety code
3520        // The important thing is that it doesn't trigger our safety confirmation
3521
3522        // Test unsafe commit checkout
3523        let head_commit = repo.get_head_commit().unwrap();
3524        let commit_hash = head_commit.id().to_string();
3525        let _result = repo.checkout_commit_unsafe(&commit_hash);
3526        // Similar to above - testing that safety is bypassed
3527    }
3528
3529    #[test]
3530    fn test_get_modified_files() {
3531        let (_temp_dir, repo_path) = create_test_repo();
3532        let repo = GitRepository::open(&repo_path).unwrap();
3533
3534        // Initially should have no modified files
3535        let modified = repo.get_modified_files().unwrap();
3536        assert!(modified.is_empty());
3537
3538        // Modify a file
3539        std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3540
3541        // Should now detect the modified file
3542        let modified = repo.get_modified_files().unwrap();
3543        assert_eq!(modified.len(), 1);
3544        assert!(modified.contains(&"README.md".to_string()));
3545    }
3546
3547    #[test]
3548    fn test_get_staged_files() {
3549        let (_temp_dir, repo_path) = create_test_repo();
3550        let repo = GitRepository::open(&repo_path).unwrap();
3551
3552        // Initially should have no staged files
3553        let staged = repo.get_staged_files().unwrap();
3554        assert!(staged.is_empty());
3555
3556        // Create and stage a new file
3557        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3558        Command::new("git")
3559            .args(["add", "staged.txt"])
3560            .current_dir(&repo_path)
3561            .output()
3562            .unwrap();
3563
3564        // Should now detect the staged file
3565        let staged = repo.get_staged_files().unwrap();
3566        assert_eq!(staged.len(), 1);
3567        assert!(staged.contains(&"staged.txt".to_string()));
3568    }
3569
3570    #[test]
3571    fn test_create_stash_fallback() {
3572        let (_temp_dir, repo_path) = create_test_repo();
3573        let repo = GitRepository::open(&repo_path).unwrap();
3574
3575        // Test stash creation - newer git versions allow empty stashes
3576        let result = repo.create_stash("test stash");
3577
3578        // Either succeeds (newer git with empty stash) or fails with helpful message
3579        match result {
3580            Ok(stash_id) => {
3581                // Modern git allows empty stashes, verify we got a stash ID
3582                assert!(!stash_id.is_empty());
3583                assert!(stash_id.contains("stash") || stash_id.len() >= 7); // SHA or stash@{n}
3584            }
3585            Err(error) => {
3586                // Older git should fail with helpful message
3587                let error_msg = error.to_string();
3588                assert!(
3589                    error_msg.contains("No local changes to save")
3590                        || error_msg.contains("git stash push")
3591                );
3592            }
3593        }
3594    }
3595
3596    #[test]
3597    fn test_delete_branch_unsafe() {
3598        let (_temp_dir, repo_path) = create_test_repo();
3599        let repo = GitRepository::open(&repo_path).unwrap();
3600
3601        // Create a test branch
3602        create_commit(&repo_path, "Second commit", "test.txt");
3603        Command::new("git")
3604            .args(["checkout", "-b", "test-branch"])
3605            .current_dir(&repo_path)
3606            .output()
3607            .unwrap();
3608
3609        // Add another commit to the test branch to make it different from main
3610        create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3611
3612        // Go back to main
3613        Command::new("git")
3614            .args(["checkout", "main"])
3615            .current_dir(&repo_path)
3616            .output()
3617            .unwrap();
3618
3619        // Test unsafe delete bypasses safety checks
3620        // Note: This may still fail if the branch has unpushed commits, but it should bypass our safety confirmation
3621        let result = repo.delete_branch_unsafe("test-branch");
3622        // Even if it fails, the key is that it didn't prompt for user confirmation
3623        // So we just check that it attempted the operation without interactive prompts
3624        let _ = result; // Don't assert success since delete may fail for git reasons
3625    }
3626
3627    #[test]
3628    fn test_force_push_unsafe() {
3629        let (_temp_dir, repo_path) = create_test_repo();
3630        let repo = GitRepository::open(&repo_path).unwrap();
3631
3632        // Create a test branch
3633        create_commit(&repo_path, "Second commit", "test.txt");
3634        Command::new("git")
3635            .args(["checkout", "-b", "test-branch"])
3636            .current_dir(&repo_path)
3637            .output()
3638            .unwrap();
3639
3640        // Test unsafe force push bypasses safety checks
3641        // Note: This will likely fail due to no remote, but it tests the safety bypass
3642        let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3643        // The key is that it doesn't trigger safety confirmation dialogs
3644    }
3645
3646    #[test]
3647    fn test_cherry_pick_basic() {
3648        let (_temp_dir, repo_path) = create_test_repo();
3649        let repo = GitRepository::open(&repo_path).unwrap();
3650
3651        // Create a branch with a commit to cherry-pick
3652        repo.create_branch("source", None).unwrap();
3653        repo.checkout_branch("source").unwrap();
3654
3655        std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3656        Command::new("git")
3657            .args(["add", "."])
3658            .current_dir(&repo_path)
3659            .output()
3660            .unwrap();
3661
3662        Command::new("git")
3663            .args(["commit", "-m", "Cherry commit"])
3664            .current_dir(&repo_path)
3665            .output()
3666            .unwrap();
3667
3668        let cherry_commit = repo.get_head_commit_hash().unwrap();
3669
3670        // Switch back to previous branch (where source was created from)
3671        // Using `git checkout -` is environment-agnostic
3672        Command::new("git")
3673            .args(["checkout", "-"])
3674            .current_dir(&repo_path)
3675            .output()
3676            .unwrap();
3677
3678        repo.create_branch("target", None).unwrap();
3679        repo.checkout_branch("target").unwrap();
3680
3681        // Cherry-pick the commit
3682        let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3683
3684        // Verify cherry-pick succeeded (commit exists)
3685        repo.repo
3686            .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3687            .unwrap();
3688
3689        // Verify file exists on target branch
3690        assert!(
3691            repo_path.join("cherry.txt").exists(),
3692            "Cherry-picked file should exist"
3693        );
3694
3695        // Verify source branch is unchanged
3696        repo.checkout_branch("source").unwrap();
3697        let source_head = repo.get_head_commit_hash().unwrap();
3698        assert_eq!(
3699            source_head, cherry_commit,
3700            "Source branch should be unchanged"
3701        );
3702    }
3703
3704    #[test]
3705    fn test_cherry_pick_preserves_commit_message() {
3706        let (_temp_dir, repo_path) = create_test_repo();
3707        let repo = GitRepository::open(&repo_path).unwrap();
3708
3709        // Create commit with specific message
3710        repo.create_branch("msg-test", None).unwrap();
3711        repo.checkout_branch("msg-test").unwrap();
3712
3713        std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3714        Command::new("git")
3715            .args(["add", "."])
3716            .current_dir(&repo_path)
3717            .output()
3718            .unwrap();
3719
3720        let commit_msg = "Test: Special commit message\n\nWith body";
3721        Command::new("git")
3722            .args(["commit", "-m", commit_msg])
3723            .current_dir(&repo_path)
3724            .output()
3725            .unwrap();
3726
3727        let original_commit = repo.get_head_commit_hash().unwrap();
3728
3729        // Cherry-pick to another branch (use previous branch via git checkout -)
3730        Command::new("git")
3731            .args(["checkout", "-"])
3732            .current_dir(&repo_path)
3733            .output()
3734            .unwrap();
3735        let new_commit = repo.cherry_pick(&original_commit).unwrap();
3736
3737        // Get commit message of new commit
3738        let output = Command::new("git")
3739            .args(["log", "-1", "--format=%B", &new_commit])
3740            .current_dir(&repo_path)
3741            .output()
3742            .unwrap();
3743
3744        let new_msg = String::from_utf8_lossy(&output.stdout);
3745        assert!(
3746            new_msg.contains("Special commit message"),
3747            "Should preserve commit message"
3748        );
3749    }
3750
3751    #[test]
3752    fn test_cherry_pick_handles_conflicts() {
3753        let (_temp_dir, repo_path) = create_test_repo();
3754        let repo = GitRepository::open(&repo_path).unwrap();
3755
3756        // Create conflicting content
3757        std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3758        Command::new("git")
3759            .args(["add", "."])
3760            .current_dir(&repo_path)
3761            .output()
3762            .unwrap();
3763
3764        Command::new("git")
3765            .args(["commit", "-m", "Add conflict file"])
3766            .current_dir(&repo_path)
3767            .output()
3768            .unwrap();
3769
3770        // Create branch with different content
3771        repo.create_branch("conflict-branch", None).unwrap();
3772        repo.checkout_branch("conflict-branch").unwrap();
3773
3774        std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3775        Command::new("git")
3776            .args(["add", "."])
3777            .current_dir(&repo_path)
3778            .output()
3779            .unwrap();
3780
3781        Command::new("git")
3782            .args(["commit", "-m", "Modify conflict file"])
3783            .current_dir(&repo_path)
3784            .output()
3785            .unwrap();
3786
3787        let conflict_commit = repo.get_head_commit_hash().unwrap();
3788
3789        // Try to cherry-pick (should fail due to conflict)
3790        // Go back to previous branch
3791        Command::new("git")
3792            .args(["checkout", "-"])
3793            .current_dir(&repo_path)
3794            .output()
3795            .unwrap();
3796        std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3797        Command::new("git")
3798            .args(["add", "."])
3799            .current_dir(&repo_path)
3800            .output()
3801            .unwrap();
3802
3803        Command::new("git")
3804            .args(["commit", "-m", "Different change"])
3805            .current_dir(&repo_path)
3806            .output()
3807            .unwrap();
3808
3809        // Cherry-pick should fail with conflict
3810        let result = repo.cherry_pick(&conflict_commit);
3811        assert!(result.is_err(), "Cherry-pick with conflict should fail");
3812    }
3813
3814    #[test]
3815    fn test_reset_to_head_clears_staged_files() {
3816        let (_temp_dir, repo_path) = create_test_repo();
3817        let repo = GitRepository::open(&repo_path).unwrap();
3818
3819        // Create and stage some files
3820        std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3821        std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3822
3823        Command::new("git")
3824            .args(["add", "staged1.txt", "staged2.txt"])
3825            .current_dir(&repo_path)
3826            .output()
3827            .unwrap();
3828
3829        // Verify files are staged
3830        let staged_before = repo.get_staged_files().unwrap();
3831        assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3832
3833        // Reset to HEAD
3834        repo.reset_to_head().unwrap();
3835
3836        // Verify no files are staged after reset
3837        let staged_after = repo.get_staged_files().unwrap();
3838        assert_eq!(
3839            staged_after.len(),
3840            0,
3841            "Should have no staged files after reset"
3842        );
3843    }
3844
3845    #[test]
3846    fn test_reset_to_head_clears_modified_files() {
3847        let (_temp_dir, repo_path) = create_test_repo();
3848        let repo = GitRepository::open(&repo_path).unwrap();
3849
3850        // Modify an existing file
3851        std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3852
3853        // Stage the modification
3854        Command::new("git")
3855            .args(["add", "README.md"])
3856            .current_dir(&repo_path)
3857            .output()
3858            .unwrap();
3859
3860        // Verify file is modified and staged
3861        assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3862
3863        // Reset to HEAD
3864        repo.reset_to_head().unwrap();
3865
3866        // Verify repo is clean
3867        assert!(
3868            !repo.is_dirty().unwrap(),
3869            "Repo should be clean after reset"
3870        );
3871
3872        // Verify file content is restored
3873        let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3874        assert_eq!(
3875            content, "# Test",
3876            "File should be restored to original content"
3877        );
3878    }
3879
3880    #[test]
3881    fn test_reset_to_head_preserves_untracked_files() {
3882        let (_temp_dir, repo_path) = create_test_repo();
3883        let repo = GitRepository::open(&repo_path).unwrap();
3884
3885        // Create untracked file
3886        std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3887
3888        // Stage some other file
3889        std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3890        Command::new("git")
3891            .args(["add", "staged.txt"])
3892            .current_dir(&repo_path)
3893            .output()
3894            .unwrap();
3895
3896        // Reset to HEAD
3897        repo.reset_to_head().unwrap();
3898
3899        // Verify untracked file still exists
3900        assert!(
3901            repo_path.join("untracked.txt").exists(),
3902            "Untracked file should be preserved"
3903        );
3904
3905        // Verify staged file was removed (since it was never committed)
3906        assert!(
3907            !repo_path.join("staged.txt").exists(),
3908            "Staged but uncommitted file should be removed"
3909        );
3910    }
3911
3912    #[test]
3913    fn test_cherry_pick_does_not_modify_source() {
3914        let (_temp_dir, repo_path) = create_test_repo();
3915        let repo = GitRepository::open(&repo_path).unwrap();
3916
3917        // Create source branch with multiple commits
3918        repo.create_branch("feature", None).unwrap();
3919        repo.checkout_branch("feature").unwrap();
3920
3921        // Add multiple commits
3922        for i in 1..=3 {
3923            std::fs::write(
3924                repo_path.join(format!("file{i}.txt")),
3925                format!("Content {i}"),
3926            )
3927            .unwrap();
3928            Command::new("git")
3929                .args(["add", "."])
3930                .current_dir(&repo_path)
3931                .output()
3932                .unwrap();
3933
3934            Command::new("git")
3935                .args(["commit", "-m", &format!("Commit {i}")])
3936                .current_dir(&repo_path)
3937                .output()
3938                .unwrap();
3939        }
3940
3941        // Get source branch state
3942        let source_commits = Command::new("git")
3943            .args(["log", "--format=%H", "feature"])
3944            .current_dir(&repo_path)
3945            .output()
3946            .unwrap();
3947        let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3948
3949        // Cherry-pick middle commit to another branch
3950        let commits: Vec<&str> = source_state.lines().collect();
3951        let middle_commit = commits[1];
3952
3953        // Go back to previous branch
3954        Command::new("git")
3955            .args(["checkout", "-"])
3956            .current_dir(&repo_path)
3957            .output()
3958            .unwrap();
3959        repo.create_branch("target", None).unwrap();
3960        repo.checkout_branch("target").unwrap();
3961
3962        repo.cherry_pick(middle_commit).unwrap();
3963
3964        // Verify source branch is completely unchanged
3965        let after_commits = Command::new("git")
3966            .args(["log", "--format=%H", "feature"])
3967            .current_dir(&repo_path)
3968            .output()
3969            .unwrap();
3970        let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3971
3972        assert_eq!(
3973            source_state, after_state,
3974            "Source branch should be completely unchanged after cherry-pick"
3975        );
3976    }
3977
3978    #[test]
3979    fn test_detect_parent_branch() {
3980        let (_temp_dir, repo_path) = create_test_repo();
3981        let repo = GitRepository::open(&repo_path).unwrap();
3982
3983        // Create a custom base branch (not just main/master)
3984        repo.create_branch("dev123", None).unwrap();
3985        repo.checkout_branch("dev123").unwrap();
3986        create_commit(&repo_path, "Base commit on dev123", "base.txt");
3987
3988        // Create feature branch from dev123
3989        repo.create_branch("feature-branch", None).unwrap();
3990        repo.checkout_branch("feature-branch").unwrap();
3991        create_commit(&repo_path, "Feature commit", "feature.txt");
3992
3993        // Should detect dev123 as parent since it's the most recent common ancestor
3994        let detected_parent = repo.detect_parent_branch().unwrap();
3995
3996        // The algorithm should find dev123 through either Strategy 2 (default branch)
3997        // or Strategy 3 (common ancestor analysis)
3998        assert!(detected_parent.is_some(), "Should detect a parent branch");
3999
4000        // Since we can't guarantee which strategy will work in the test environment,
4001        // just verify it returns something reasonable
4002        let parent = detected_parent.unwrap();
4003        assert!(
4004            parent == "dev123" || parent == "main" || parent == "master",
4005            "Parent should be dev123, main, or master, got: {parent}"
4006        );
4007    }
4008}