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