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