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