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