cascade_cli/git/
repository.rs

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