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