1use crate::cli::output::Output;
2use crate::errors::{CascadeError, Result};
3use chrono;
4use dialoguer::{theme::ColorfulTheme, Confirm, Select};
5use git2::{Oid, Repository, Signature};
6use std::path::{Path, PathBuf};
7use tracing::{debug, info, warn};
8
9#[derive(Debug, Clone)]
11pub struct RepositoryInfo {
12 pub path: PathBuf,
13 pub head_branch: Option<String>,
14 pub head_commit: Option<String>,
15 pub is_dirty: bool,
16 pub untracked_files: Vec<String>,
17}
18
19#[derive(Debug, Clone)]
21struct ForceBackupInfo {
22 pub backup_branch_name: String,
23 pub remote_commit_id: String,
24 #[allow(dead_code)] pub commits_that_would_be_lost: usize,
26}
27
28#[derive(Debug, Clone)]
30struct BranchDeletionSafety {
31 pub unpushed_commits: Vec<String>,
32 pub remote_tracking_branch: Option<String>,
33 pub is_merged_to_main: bool,
34 pub main_branch_name: String,
35}
36
37#[derive(Debug, Clone)]
39struct CheckoutSafety {
40 #[allow(dead_code)] pub has_uncommitted_changes: bool,
42 pub modified_files: Vec<String>,
43 pub staged_files: Vec<String>,
44 pub untracked_files: Vec<String>,
45 #[allow(dead_code)] pub stash_created: Option<String>,
47 #[allow(dead_code)] pub current_branch: Option<String>,
49}
50
51#[derive(Debug, Clone)]
53pub struct GitSslConfig {
54 pub accept_invalid_certs: bool,
55 pub ca_bundle_path: Option<String>,
56}
57
58#[derive(Debug, Clone)]
60pub struct GitStatusSummary {
61 staged_files: usize,
62 unstaged_files: usize,
63 untracked_files: usize,
64}
65
66impl GitStatusSummary {
67 pub fn is_clean(&self) -> bool {
68 self.staged_files == 0 && self.unstaged_files == 0 && self.untracked_files == 0
69 }
70
71 pub fn has_staged_changes(&self) -> bool {
72 self.staged_files > 0
73 }
74
75 pub fn has_unstaged_changes(&self) -> bool {
76 self.unstaged_files > 0
77 }
78
79 pub fn has_untracked_files(&self) -> bool {
80 self.untracked_files > 0
81 }
82
83 pub fn staged_count(&self) -> usize {
84 self.staged_files
85 }
86
87 pub fn unstaged_count(&self) -> usize {
88 self.unstaged_files
89 }
90
91 pub fn untracked_count(&self) -> usize {
92 self.untracked_files
93 }
94}
95
96pub struct GitRepository {
102 repo: Repository,
103 path: PathBuf,
104 ssl_config: Option<GitSslConfig>,
105 bitbucket_credentials: Option<BitbucketCredentials>,
106}
107
108#[derive(Debug, Clone)]
109struct BitbucketCredentials {
110 username: Option<String>,
111 token: Option<String>,
112}
113
114impl GitRepository {
115 pub fn open(path: &Path) -> Result<Self> {
118 let repo = Repository::discover(path)
119 .map_err(|e| CascadeError::config(format!("Not a git repository: {e}")))?;
120
121 let workdir = repo
122 .workdir()
123 .ok_or_else(|| CascadeError::config("Repository has no working directory"))?
124 .to_path_buf();
125
126 let ssl_config = Self::load_ssl_config_from_cascade(&workdir);
128 let bitbucket_credentials = Self::load_bitbucket_credentials_from_cascade(&workdir);
129
130 Ok(Self {
131 repo,
132 path: workdir,
133 ssl_config,
134 bitbucket_credentials,
135 })
136 }
137
138 fn load_ssl_config_from_cascade(repo_path: &Path) -> Option<GitSslConfig> {
140 let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
142 let config_path = config_dir.join("config.json");
143 let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
144
145 if settings.bitbucket.accept_invalid_certs.is_some()
147 || settings.bitbucket.ca_bundle_path.is_some()
148 {
149 Some(GitSslConfig {
150 accept_invalid_certs: settings.bitbucket.accept_invalid_certs.unwrap_or(false),
151 ca_bundle_path: settings.bitbucket.ca_bundle_path,
152 })
153 } else {
154 None
155 }
156 }
157
158 fn load_bitbucket_credentials_from_cascade(repo_path: &Path) -> Option<BitbucketCredentials> {
160 let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
162 let config_path = config_dir.join("config.json");
163 let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
164
165 if settings.bitbucket.username.is_some() || settings.bitbucket.token.is_some() {
167 Some(BitbucketCredentials {
168 username: settings.bitbucket.username.clone(),
169 token: settings.bitbucket.token.clone(),
170 })
171 } else {
172 None
173 }
174 }
175
176 pub fn get_info(&self) -> Result<RepositoryInfo> {
178 let head_branch = self.get_current_branch().ok();
179 let head_commit = self.get_head_commit_hash().ok();
180 let is_dirty = self.is_dirty()?;
181 let untracked_files = self.get_untracked_files()?;
182
183 Ok(RepositoryInfo {
184 path: self.path.clone(),
185 head_branch,
186 head_commit,
187 is_dirty,
188 untracked_files,
189 })
190 }
191
192 pub fn get_current_branch(&self) -> Result<String> {
194 let head = self
195 .repo
196 .head()
197 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
198
199 if let Some(name) = head.shorthand() {
200 Ok(name.to_string())
201 } else {
202 let commit = head
204 .peel_to_commit()
205 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
206 Ok(format!("HEAD@{}", commit.id()))
207 }
208 }
209
210 pub fn get_head_commit_hash(&self) -> Result<String> {
212 let head = self
213 .repo
214 .head()
215 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
216
217 let commit = head
218 .peel_to_commit()
219 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
220
221 Ok(commit.id().to_string())
222 }
223
224 pub fn is_dirty(&self) -> Result<bool> {
226 let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
227
228 for status in statuses.iter() {
229 let flags = status.status();
230
231 if flags.intersects(
233 git2::Status::INDEX_MODIFIED
234 | git2::Status::INDEX_NEW
235 | git2::Status::INDEX_DELETED
236 | git2::Status::WT_MODIFIED
237 | git2::Status::WT_NEW
238 | git2::Status::WT_DELETED,
239 ) {
240 return Ok(true);
241 }
242 }
243
244 Ok(false)
245 }
246
247 pub fn get_untracked_files(&self) -> Result<Vec<String>> {
249 let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
250
251 let mut untracked = Vec::new();
252 for status in statuses.iter() {
253 if status.status().contains(git2::Status::WT_NEW) {
254 if let Some(path) = status.path() {
255 untracked.push(path.to_string());
256 }
257 }
258 }
259
260 Ok(untracked)
261 }
262
263 pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
265 let target_commit = if let Some(target) = target {
266 let target_obj = self.repo.revparse_single(target).map_err(|e| {
268 CascadeError::branch(format!("Could not find target '{target}': {e}"))
269 })?;
270 target_obj.peel_to_commit().map_err(|e| {
271 CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
272 })?
273 } else {
274 let head = self
276 .repo
277 .head()
278 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
279 head.peel_to_commit()
280 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
281 };
282
283 self.repo
284 .branch(name, &target_commit, false)
285 .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;
286
287 Ok(())
289 }
290
291 pub fn update_branch_to_commit(&self, branch_name: &str, commit_id: &str) -> Result<()> {
294 let commit_oid = Oid::from_str(commit_id).map_err(|e| {
295 CascadeError::branch(format!("Invalid commit ID '{}': {}", commit_id, e))
296 })?;
297
298 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
299 CascadeError::branch(format!("Commit '{}' not found: {}", commit_id, e))
300 })?;
301
302 if self
304 .repo
305 .find_branch(branch_name, git2::BranchType::Local)
306 .is_ok()
307 {
308 let refname = format!("refs/heads/{}", branch_name);
310 self.repo
311 .reference(
312 &refname,
313 commit_oid,
314 true,
315 "update branch to rebased commit",
316 )
317 .map_err(|e| {
318 CascadeError::branch(format!(
319 "Failed to update branch '{}': {}",
320 branch_name, e
321 ))
322 })?;
323 } else {
324 self.repo.branch(branch_name, &commit, false).map_err(|e| {
326 CascadeError::branch(format!("Failed to create branch '{}': {}", branch_name, e))
327 })?;
328 }
329
330 Ok(())
331 }
332
333 pub fn force_push_single_branch(&self, branch_name: &str) -> Result<()> {
335 self.force_push_single_branch_with_options(branch_name, false)
336 }
337
338 pub fn force_push_single_branch_auto(&self, branch_name: &str) -> Result<()> {
340 self.force_push_single_branch_with_options(branch_name, true)
341 }
342
343 fn force_push_single_branch_with_options(
344 &self,
345 branch_name: &str,
346 auto_confirm: bool,
347 ) -> Result<()> {
348 if self.get_branch_commit_hash(branch_name).is_err() {
351 return Err(CascadeError::branch(format!(
352 "Cannot push '{}': branch does not exist locally",
353 branch_name
354 )));
355 }
356
357 if let Err(e) = self.fetch() {
359 tracing::warn!("Could not fetch before force push: {}", e);
360 }
361
362 let safety_result = if auto_confirm {
364 self.check_force_push_safety_auto(branch_name)?
365 } else {
366 self.check_force_push_safety_enhanced(branch_name)?
367 };
368
369 if let Some(backup_info) = safety_result {
370 self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
371 }
372
373 self.ensure_index_closed()?;
375
376 let output = std::process::Command::new("git")
379 .args(["push", "--force", "origin", branch_name])
380 .env("CASCADE_INTERNAL_PUSH", "1")
381 .current_dir(&self.path)
382 .output()
383 .map_err(|e| CascadeError::branch(format!("Failed to execute git push: {}", e)))?;
384
385 if !output.status.success() {
386 let stderr = String::from_utf8_lossy(&output.stderr);
387 let stdout = String::from_utf8_lossy(&output.stdout);
388
389 let full_error = if !stdout.is_empty() {
391 format!("{}\n{}", stderr.trim(), stdout.trim())
392 } else {
393 stderr.trim().to_string()
394 };
395
396 return Err(CascadeError::branch(format!(
397 "Force push failed for '{}':\n{}",
398 branch_name, full_error
399 )));
400 }
401
402 Ok(())
403 }
404
405 pub fn checkout_branch(&self, name: &str) -> Result<()> {
407 self.checkout_branch_with_options(name, false, true)
408 }
409
410 pub fn checkout_branch_silent(&self, name: &str) -> Result<()> {
412 self.checkout_branch_with_options(name, false, false)
413 }
414
415 pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
417 self.checkout_branch_with_options(name, true, false)
418 }
419
420 fn checkout_branch_with_options(
422 &self,
423 name: &str,
424 force_unsafe: bool,
425 show_output: bool,
426 ) -> Result<()> {
427 debug!("Attempting to checkout branch: {}", name);
428
429 if !force_unsafe {
431 let safety_result = self.check_checkout_safety(name)?;
432 if let Some(safety_info) = safety_result {
433 self.handle_checkout_confirmation(name, &safety_info)?;
435 }
436 }
437
438 let branch = self
440 .repo
441 .find_branch(name, git2::BranchType::Local)
442 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
443
444 let branch_ref = branch.get();
445 let tree = branch_ref.peel_to_tree().map_err(|e| {
446 CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
447 })?;
448
449 self.repo
451 .checkout_tree(tree.as_object(), None)
452 .map_err(|e| {
453 CascadeError::branch(format!("Could not checkout branch '{name}': {e}"))
454 })?;
455
456 self.repo
458 .set_head(&format!("refs/heads/{name}"))
459 .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
460
461 if show_output {
462 Output::success(format!("Switched to branch '{name}'"));
463 }
464 Ok(())
465 }
466
467 pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
469 self.checkout_commit_with_options(commit_hash, false)
470 }
471
472 pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
474 self.checkout_commit_with_options(commit_hash, true)
475 }
476
477 fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
479 debug!("Attempting to checkout commit: {}", commit_hash);
480
481 if !force_unsafe {
483 let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
484 if let Some(safety_info) = safety_result {
485 self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
487 }
488 }
489
490 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
491
492 let commit = self.repo.find_commit(oid).map_err(|e| {
493 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
494 })?;
495
496 let tree = commit.tree().map_err(|e| {
497 CascadeError::branch(format!(
498 "Could not get tree for commit '{commit_hash}': {e}"
499 ))
500 })?;
501
502 self.repo
504 .checkout_tree(tree.as_object(), None)
505 .map_err(|e| {
506 CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
507 })?;
508
509 self.repo.set_head_detached(oid).map_err(|e| {
511 CascadeError::branch(format!(
512 "Could not update HEAD to commit '{commit_hash}': {e}"
513 ))
514 })?;
515
516 Output::success(format!(
517 "Checked out commit '{commit_hash}' (detached HEAD)"
518 ));
519 Ok(())
520 }
521
522 pub fn branch_exists(&self, name: &str) -> bool {
524 self.repo.find_branch(name, git2::BranchType::Local).is_ok()
525 }
526
527 pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
529 if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
531 return Ok(true);
532 }
533
534 println!("🔍 Branch '{name}' not found locally, trying to fetch from remote...");
536
537 use std::process::Command;
538
539 let fetch_result = Command::new("git")
541 .args(["fetch", "origin", &format!("{name}:{name}")])
542 .current_dir(&self.path)
543 .output();
544
545 match fetch_result {
546 Ok(output) => {
547 if output.status.success() {
548 println!("✅ Successfully fetched '{name}' from origin");
549 return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
551 } else {
552 let stderr = String::from_utf8_lossy(&output.stderr);
553 tracing::debug!("Failed to fetch branch '{name}': {stderr}");
554 }
555 }
556 Err(e) => {
557 tracing::debug!("Git fetch command failed: {e}");
558 }
559 }
560
561 if name.contains('/') {
563 println!("🔍 Trying alternative fetch patterns...");
564
565 let fetch_all_result = Command::new("git")
567 .args(["fetch", "origin"])
568 .current_dir(&self.path)
569 .output();
570
571 if let Ok(output) = fetch_all_result {
572 if output.status.success() {
573 let checkout_result = Command::new("git")
575 .args(["checkout", "-b", name, &format!("origin/{name}")])
576 .current_dir(&self.path)
577 .output();
578
579 if let Ok(checkout_output) = checkout_result {
580 if checkout_output.status.success() {
581 println!(
582 "✅ Successfully created local branch '{name}' from origin/{name}"
583 );
584 return Ok(true);
585 }
586 }
587 }
588 }
589 }
590
591 Ok(false)
593 }
594
595 pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
597 let branch = self
598 .repo
599 .find_branch(branch_name, git2::BranchType::Local)
600 .map_err(|e| {
601 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
602 })?;
603
604 let commit = branch.get().peel_to_commit().map_err(|e| {
605 CascadeError::branch(format!(
606 "Could not get commit for branch '{branch_name}': {e}"
607 ))
608 })?;
609
610 Ok(commit.id().to_string())
611 }
612
613 pub fn list_branches(&self) -> Result<Vec<String>> {
615 let branches = self
616 .repo
617 .branches(Some(git2::BranchType::Local))
618 .map_err(CascadeError::Git)?;
619
620 let mut branch_names = Vec::new();
621 for branch in branches {
622 let (branch, _) = branch.map_err(CascadeError::Git)?;
623 if let Some(name) = branch.name().map_err(CascadeError::Git)? {
624 branch_names.push(name.to_string());
625 }
626 }
627
628 Ok(branch_names)
629 }
630
631 pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
633 let config = self.repo.config().map_err(CascadeError::Git)?;
635
636 let remote_key = format!("branch.{branch_name}.remote");
638 let merge_key = format!("branch.{branch_name}.merge");
639
640 if let (Ok(remote), Ok(merge_ref)) = (
641 config.get_string(&remote_key),
642 config.get_string(&merge_key),
643 ) {
644 if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
646 return Ok(Some(format!("{remote}/{branch_part}")));
647 }
648 }
649
650 let potential_upstream = format!("origin/{branch_name}");
652 if self
653 .repo
654 .find_reference(&format!("refs/remotes/{potential_upstream}"))
655 .is_ok()
656 {
657 return Ok(Some(potential_upstream));
658 }
659
660 Ok(None)
661 }
662
663 pub fn get_ahead_behind_counts(
665 &self,
666 local_branch: &str,
667 upstream_branch: &str,
668 ) -> Result<(usize, usize)> {
669 let local_ref = self
671 .repo
672 .find_reference(&format!("refs/heads/{local_branch}"))
673 .map_err(|_| {
674 CascadeError::config(format!("Local branch '{local_branch}' not found"))
675 })?;
676 let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;
677
678 let upstream_ref = self
679 .repo
680 .find_reference(&format!("refs/remotes/{upstream_branch}"))
681 .map_err(|_| {
682 CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
683 })?;
684 let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;
685
686 let (ahead, behind) = self
688 .repo
689 .graph_ahead_behind(local_commit.id(), upstream_commit.id())
690 .map_err(CascadeError::Git)?;
691
692 Ok((ahead, behind))
693 }
694
695 pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
697 let mut config = self.repo.config().map_err(CascadeError::Git)?;
698
699 let remote_key = format!("branch.{branch_name}.remote");
701 config
702 .set_str(&remote_key, remote)
703 .map_err(CascadeError::Git)?;
704
705 let merge_key = format!("branch.{branch_name}.merge");
707 let merge_value = format!("refs/heads/{remote_branch}");
708 config
709 .set_str(&merge_key, &merge_value)
710 .map_err(CascadeError::Git)?;
711
712 Ok(())
713 }
714
715 pub fn commit(&self, message: &str) -> Result<String> {
717 self.validate_git_user_config()?;
719
720 let signature = self.get_signature()?;
721 let tree_id = self.get_index_tree()?;
722 let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
723
724 let head = self.repo.head().map_err(CascadeError::Git)?;
726 let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
727
728 let commit_id = self
729 .repo
730 .commit(
731 Some("HEAD"),
732 &signature,
733 &signature,
734 message,
735 &tree,
736 &[&parent_commit],
737 )
738 .map_err(CascadeError::Git)?;
739
740 Output::success(format!("Created commit: {commit_id} - {message}"));
741 Ok(commit_id.to_string())
742 }
743
744 pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
746 let staged_files = self.get_staged_files()?;
748 if staged_files.is_empty() {
749 tracing::debug!("No staged changes to commit");
750 return Ok(None);
751 }
752
753 tracing::info!("Committing {} staged files", staged_files.len());
754 let commit_hash = self.commit(default_message)?;
755 Ok(Some(commit_hash))
756 }
757
758 pub fn stage_all(&self) -> Result<()> {
760 let mut index = self.repo.index().map_err(CascadeError::Git)?;
761
762 index
763 .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
764 .map_err(CascadeError::Git)?;
765
766 index.write().map_err(CascadeError::Git)?;
767
768 tracing::debug!("Staged all changes");
769 Ok(())
770 }
771
772 fn ensure_index_closed(&self) -> Result<()> {
775 let mut index = self.repo.index().map_err(CascadeError::Git)?;
778 index.write().map_err(CascadeError::Git)?;
779 drop(index); std::thread::sleep(std::time::Duration::from_millis(10));
785
786 Ok(())
787 }
788
789 pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
791 if file_paths.is_empty() {
792 tracing::debug!("No files to stage");
793 return Ok(());
794 }
795
796 let mut index = self.repo.index().map_err(CascadeError::Git)?;
797
798 for file_path in file_paths {
799 index
800 .add_path(std::path::Path::new(file_path))
801 .map_err(CascadeError::Git)?;
802 }
803
804 index.write().map_err(CascadeError::Git)?;
805
806 tracing::debug!(
807 "Staged {} specific files: {:?}",
808 file_paths.len(),
809 file_paths
810 );
811 Ok(())
812 }
813
814 pub fn stage_conflict_resolved_files(&self) -> Result<()> {
816 let conflicted_files = self.get_conflicted_files()?;
817 if conflicted_files.is_empty() {
818 tracing::debug!("No conflicted files to stage");
819 return Ok(());
820 }
821
822 let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
823 self.stage_files(&file_paths)?;
824
825 tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
826 Ok(())
827 }
828
829 pub fn path(&self) -> &Path {
831 &self.path
832 }
833
834 pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
836 match Oid::from_str(commit_hash) {
837 Ok(oid) => match self.repo.find_commit(oid) {
838 Ok(_) => Ok(true),
839 Err(_) => Ok(false),
840 },
841 Err(_) => Ok(false),
842 }
843 }
844
845 pub fn is_commit_based_on(&self, commit_hash: &str, expected_base: &str) -> Result<bool> {
848 let commit_oid = Oid::from_str(commit_hash).map_err(|e| {
849 CascadeError::branch(format!("Invalid commit hash '{}': {}", commit_hash, e))
850 })?;
851
852 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
853 CascadeError::branch(format!("Commit '{}' not found: {}", commit_hash, e))
854 })?;
855
856 if commit.parent_count() == 0 {
858 return Ok(false);
860 }
861
862 let parent = commit.parent(0).map_err(|e| {
863 CascadeError::branch(format!(
864 "Could not get parent of commit '{}': {}",
865 commit_hash, e
866 ))
867 })?;
868 let parent_hash = parent.id().to_string();
869
870 let expected_base_oid = if let Ok(oid) = Oid::from_str(expected_base) {
872 oid
873 } else {
874 let branch_ref = format!("refs/heads/{}", expected_base);
876 let reference = self.repo.find_reference(&branch_ref).map_err(|e| {
877 CascadeError::branch(format!("Could not find base '{}': {}", expected_base, e))
878 })?;
879 reference.target().ok_or_else(|| {
880 CascadeError::branch(format!("Base '{}' has no target commit", expected_base))
881 })?
882 };
883
884 let expected_base_hash = expected_base_oid.to_string();
885
886 tracing::debug!(
887 "Checking if commit {} is based on {}: parent={}, expected={}",
888 &commit_hash[..8],
889 expected_base,
890 &parent_hash[..8],
891 &expected_base_hash[..8]
892 );
893
894 Ok(parent_hash == expected_base_hash)
895 }
896
897 pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
899 let head = self
900 .repo
901 .head()
902 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
903 head.peel_to_commit()
904 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
905 }
906
907 pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
909 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
910
911 self.repo.find_commit(oid).map_err(CascadeError::Git)
912 }
913
914 pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
916 let branch = self
917 .repo
918 .find_branch(branch_name, git2::BranchType::Local)
919 .map_err(|e| {
920 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
921 })?;
922
923 let commit = branch.get().peel_to_commit().map_err(|e| {
924 CascadeError::branch(format!(
925 "Could not get commit for branch '{branch_name}': {e}"
926 ))
927 })?;
928
929 Ok(commit.id().to_string())
930 }
931
932 pub fn validate_git_user_config(&self) -> Result<()> {
934 if let Ok(config) = self.repo.config() {
935 let name_result = config.get_string("user.name");
936 let email_result = config.get_string("user.email");
937
938 if let (Ok(name), Ok(email)) = (name_result, email_result) {
939 if !name.trim().is_empty() && !email.trim().is_empty() {
940 tracing::debug!("Git user config validated: {} <{}>", name, email);
941 return Ok(());
942 }
943 }
944 }
945
946 let is_ci = std::env::var("CI").is_ok();
948
949 if is_ci {
950 tracing::debug!("CI environment - skipping git user config validation");
951 return Ok(());
952 }
953
954 Output::warning("Git user configuration missing or incomplete");
955 Output::info("This can cause cherry-pick and commit operations to fail");
956 Output::info("Please configure git user information:");
957 Output::bullet("git config user.name \"Your Name\"".to_string());
958 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
959 Output::info("Or set globally with the --global flag");
960
961 Ok(())
964 }
965
966 fn get_signature(&self) -> Result<Signature<'_>> {
968 if let Ok(config) = self.repo.config() {
970 let name_result = config.get_string("user.name");
972 let email_result = config.get_string("user.email");
973
974 if let (Ok(name), Ok(email)) = (name_result, email_result) {
975 if !name.trim().is_empty() && !email.trim().is_empty() {
976 tracing::debug!("Using git config: {} <{}>", name, email);
977 return Signature::now(&name, &email).map_err(CascadeError::Git);
978 }
979 } else {
980 tracing::debug!("Git user config incomplete or missing");
981 }
982 }
983
984 let is_ci = std::env::var("CI").is_ok();
986
987 if is_ci {
988 tracing::debug!("CI environment detected, using fallback signature");
989 return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
990 }
991
992 tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
994
995 match Signature::now("Cascade CLI", "cascade@example.com") {
997 Ok(sig) => {
998 Output::warning("Git user not configured - using fallback signature");
999 Output::info("For better git history, run:");
1000 Output::bullet("git config user.name \"Your Name\"".to_string());
1001 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
1002 Output::info("Or set it globally with --global flag");
1003 Ok(sig)
1004 }
1005 Err(e) => {
1006 Err(CascadeError::branch(format!(
1007 "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\""
1008 )))
1009 }
1010 }
1011 }
1012
1013 fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
1016 self.configure_remote_callbacks_with_fallback(false)
1017 }
1018
1019 fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
1021 match error.class() {
1022 git2::ErrorClass::Http => {
1024 match error.code() {
1026 git2::ErrorCode::Auth => true,
1027 _ => {
1028 let error_string = error.to_string();
1030 error_string.contains("too many redirects")
1031 || error_string.contains("authentication replays")
1032 || error_string.contains("authentication required")
1033 }
1034 }
1035 }
1036 git2::ErrorClass::Net => {
1037 let error_string = error.to_string();
1039 error_string.contains("authentication")
1040 || error_string.contains("unauthorized")
1041 || error_string.contains("forbidden")
1042 }
1043 _ => false,
1044 }
1045 }
1046
1047 fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
1049 match error.class() {
1050 git2::ErrorClass::Ssl => true,
1052
1053 git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
1055
1056 git2::ErrorClass::Ssh => {
1058 let error_string = error.to_string();
1059 error_string.contains("no callback set")
1060 || error_string.contains("authentication required")
1061 }
1062
1063 git2::ErrorClass::Net => {
1065 let error_string = error.to_string();
1066 error_string.contains("TLS stream")
1067 || error_string.contains("SSL")
1068 || error_string.contains("proxy")
1069 || error_string.contains("firewall")
1070 }
1071
1072 git2::ErrorClass::Http => {
1074 let error_string = error.to_string();
1075 error_string.contains("TLS stream")
1076 || error_string.contains("SSL")
1077 || error_string.contains("proxy")
1078 }
1079
1080 _ => false,
1081 }
1082 }
1083
1084 fn configure_remote_callbacks_with_fallback(
1085 &self,
1086 use_default_first: bool,
1087 ) -> Result<git2::RemoteCallbacks<'_>> {
1088 let mut callbacks = git2::RemoteCallbacks::new();
1089
1090 let bitbucket_credentials = self.bitbucket_credentials.clone();
1092 callbacks.credentials(move |url, username_from_url, allowed_types| {
1093 tracing::debug!(
1094 "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
1095 url,
1096 username_from_url,
1097 allowed_types
1098 );
1099
1100 if allowed_types.contains(git2::CredentialType::SSH_KEY) {
1102 if let Some(username) = username_from_url {
1103 tracing::debug!("Trying SSH key authentication for user: {}", username);
1104 return git2::Cred::ssh_key_from_agent(username);
1105 }
1106 }
1107
1108 if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
1110 if use_default_first {
1112 tracing::debug!("Corporate network mode: trying DefaultCredentials first");
1113 return git2::Cred::default();
1114 }
1115
1116 if url.contains("bitbucket") {
1117 if let Some(creds) = &bitbucket_credentials {
1118 if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
1120 tracing::debug!("Trying Bitbucket username + token authentication");
1121 return git2::Cred::userpass_plaintext(username, token);
1122 }
1123
1124 if let Some(token) = &creds.token {
1126 tracing::debug!("Trying Bitbucket token-as-username authentication");
1127 return git2::Cred::userpass_plaintext(token, "");
1128 }
1129
1130 if let Some(username) = &creds.username {
1132 tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1133 return git2::Cred::username(username);
1134 }
1135 }
1136 }
1137
1138 tracing::debug!("Trying default credential helper for HTTPS authentication");
1140 return git2::Cred::default();
1141 }
1142
1143 tracing::debug!("Using default credential fallback");
1145 git2::Cred::default()
1146 });
1147
1148 let mut ssl_configured = false;
1153
1154 if let Some(ssl_config) = &self.ssl_config {
1156 if ssl_config.accept_invalid_certs {
1157 Output::warning(
1158 "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1159 );
1160 callbacks.certificate_check(|_cert, _host| {
1161 tracing::debug!("⚠️ Accepting invalid certificate for host: {}", _host);
1162 Ok(git2::CertificateCheckStatus::CertificateOk)
1163 });
1164 ssl_configured = true;
1165 } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1166 Output::info(format!(
1167 "Using custom CA bundle from Cascade config: {ca_path}"
1168 ));
1169 callbacks.certificate_check(|_cert, host| {
1170 tracing::debug!("Using custom CA bundle for host: {}", host);
1171 Ok(git2::CertificateCheckStatus::CertificateOk)
1172 });
1173 ssl_configured = true;
1174 }
1175 }
1176
1177 if !ssl_configured {
1179 if let Ok(config) = self.repo.config() {
1180 let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1181
1182 if !ssl_verify {
1183 Output::warning(
1184 "SSL certificate verification DISABLED via git config - this is insecure!",
1185 );
1186 callbacks.certificate_check(|_cert, host| {
1187 tracing::debug!("⚠️ Bypassing SSL verification for host: {}", host);
1188 Ok(git2::CertificateCheckStatus::CertificateOk)
1189 });
1190 ssl_configured = true;
1191 } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1192 Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1193 callbacks.certificate_check(|_cert, host| {
1194 tracing::debug!("Using git config CA bundle for host: {}", host);
1195 Ok(git2::CertificateCheckStatus::CertificateOk)
1196 });
1197 ssl_configured = true;
1198 }
1199 }
1200 }
1201
1202 if !ssl_configured {
1205 tracing::debug!(
1206 "Using system certificate store for SSL verification (default behavior)"
1207 );
1208
1209 if cfg!(target_os = "macos") {
1211 tracing::debug!("macOS detected - using default certificate validation");
1212 } else {
1215 callbacks.certificate_check(|_cert, host| {
1217 tracing::debug!("System certificate validation for host: {}", host);
1218 Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1219 });
1220 }
1221 }
1222
1223 Ok(callbacks)
1224 }
1225
1226 fn get_index_tree(&self) -> Result<Oid> {
1228 let mut index = self.repo.index().map_err(CascadeError::Git)?;
1229
1230 index.write_tree().map_err(CascadeError::Git)
1231 }
1232
1233 pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1235 self.repo.statuses(None).map_err(CascadeError::Git)
1236 }
1237
1238 pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1240 let statuses = self.get_status()?;
1241
1242 let mut staged_files = 0;
1243 let mut unstaged_files = 0;
1244 let mut untracked_files = 0;
1245
1246 for status in statuses.iter() {
1247 let flags = status.status();
1248
1249 if flags.intersects(
1250 git2::Status::INDEX_MODIFIED
1251 | git2::Status::INDEX_NEW
1252 | git2::Status::INDEX_DELETED
1253 | git2::Status::INDEX_RENAMED
1254 | git2::Status::INDEX_TYPECHANGE,
1255 ) {
1256 staged_files += 1;
1257 }
1258
1259 if flags.intersects(
1260 git2::Status::WT_MODIFIED
1261 | git2::Status::WT_DELETED
1262 | git2::Status::WT_TYPECHANGE
1263 | git2::Status::WT_RENAMED,
1264 ) {
1265 unstaged_files += 1;
1266 }
1267
1268 if flags.intersects(git2::Status::WT_NEW) {
1269 untracked_files += 1;
1270 }
1271 }
1272
1273 Ok(GitStatusSummary {
1274 staged_files,
1275 unstaged_files,
1276 untracked_files,
1277 })
1278 }
1279
1280 pub fn get_current_commit_hash(&self) -> Result<String> {
1282 self.get_head_commit_hash()
1283 }
1284
1285 pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1287 let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1288 let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1289
1290 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1291 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1292 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1293
1294 Ok(revwalk.count())
1295 }
1296
1297 pub fn get_remote_url(&self, name: &str) -> Result<String> {
1299 let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1300 Ok(remote.url().unwrap_or("unknown").to_string())
1301 }
1302
1303 pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1305 tracing::debug!("Cherry-picking commit {}", commit_hash);
1306
1307 self.validate_git_user_config()?;
1309
1310 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1311 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1312
1313 let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1315
1316 let parent_commit = if commit.parent_count() > 0 {
1318 commit.parent(0).map_err(CascadeError::Git)?
1319 } else {
1320 let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1322 let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1323 let sig = self.get_signature()?;
1324 return self
1325 .repo
1326 .commit(
1327 Some("HEAD"),
1328 &sig,
1329 &sig,
1330 commit.message().unwrap_or("Cherry-picked commit"),
1331 &empty_tree,
1332 &[],
1333 )
1334 .map(|oid| oid.to_string())
1335 .map_err(CascadeError::Git);
1336 };
1337
1338 let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1339
1340 let head_commit = self.get_head_commit()?;
1342 let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1343
1344 let mut index = self
1346 .repo
1347 .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1348 .map_err(CascadeError::Git)?;
1349
1350 if index.has_conflicts() {
1352 debug!("Cherry-pick has conflicts - writing conflicted state to disk for resolution");
1355
1356 let mut repo_index = self.repo.index().map_err(CascadeError::Git)?;
1362
1363 repo_index.clear().map_err(CascadeError::Git)?;
1365 repo_index
1366 .read_tree(&head_tree)
1367 .map_err(CascadeError::Git)?;
1368
1369 repo_index
1371 .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
1372 .map_err(CascadeError::Git)?;
1373
1374 drop(repo_index);
1379 self.ensure_index_closed()?;
1380
1381 let cherry_pick_output = std::process::Command::new("git")
1382 .args(["cherry-pick", commit_hash])
1383 .current_dir(self.path())
1384 .output()
1385 .map_err(CascadeError::Io)?;
1386
1387 if !cherry_pick_output.status.success() {
1388 debug!("Git CLI cherry-pick failed as expected (has conflicts)");
1389 }
1392
1393 self.repo
1396 .index()
1397 .and_then(|mut idx| idx.read(true).map(|_| ()))
1398 .map_err(CascadeError::Git)?;
1399
1400 debug!("Conflicted state written and index reloaded - auto-resolve can now process conflicts");
1401
1402 return Err(CascadeError::branch(format!(
1403 "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1404 )));
1405 }
1406
1407 let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1409 let merged_tree = self
1410 .repo
1411 .find_tree(merged_tree_oid)
1412 .map_err(CascadeError::Git)?;
1413
1414 let signature = self.get_signature()?;
1416 let message = commit.message().unwrap_or("Cherry-picked commit");
1417
1418 let new_commit_oid = self
1419 .repo
1420 .commit(
1421 Some("HEAD"),
1422 &signature,
1423 &signature,
1424 message,
1425 &merged_tree,
1426 &[&head_commit],
1427 )
1428 .map_err(CascadeError::Git)?;
1429
1430 let new_commit = self
1432 .repo
1433 .find_commit(new_commit_oid)
1434 .map_err(CascadeError::Git)?;
1435 let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1436
1437 self.repo
1438 .checkout_tree(
1439 new_tree.as_object(),
1440 Some(git2::build::CheckoutBuilder::new().force()),
1441 )
1442 .map_err(CascadeError::Git)?;
1443
1444 tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1445 Ok(new_commit_oid.to_string())
1446 }
1447
1448 pub fn has_conflicts(&self) -> Result<bool> {
1450 let index = self.repo.index().map_err(CascadeError::Git)?;
1451 Ok(index.has_conflicts())
1452 }
1453
1454 pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1456 let index = self.repo.index().map_err(CascadeError::Git)?;
1457
1458 let mut conflicts = Vec::new();
1459
1460 let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1462
1463 for conflict in conflict_iter {
1464 let conflict = conflict.map_err(CascadeError::Git)?;
1465 if let Some(our) = conflict.our {
1466 if let Ok(path) = std::str::from_utf8(&our.path) {
1467 conflicts.push(path.to_string());
1468 }
1469 } else if let Some(their) = conflict.their {
1470 if let Ok(path) = std::str::from_utf8(&their.path) {
1471 conflicts.push(path.to_string());
1472 }
1473 }
1474 }
1475
1476 Ok(conflicts)
1477 }
1478
1479 pub fn fetch(&self) -> Result<()> {
1481 tracing::debug!("Fetching from origin");
1482
1483 let mut remote = self
1484 .repo
1485 .find_remote("origin")
1486 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1487
1488 let callbacks = self.configure_remote_callbacks()?;
1490
1491 let mut fetch_options = git2::FetchOptions::new();
1493 fetch_options.remote_callbacks(callbacks);
1494
1495 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1497 Ok(_) => {
1498 tracing::debug!("Fetch completed successfully");
1499 Ok(())
1500 }
1501 Err(e) => {
1502 if self.should_retry_with_default_credentials(&e) {
1503 tracing::debug!(
1504 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1505 e.class(), e.code(), e
1506 );
1507
1508 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1510 let mut fetch_options = git2::FetchOptions::new();
1511 fetch_options.remote_callbacks(callbacks);
1512
1513 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1514 Ok(_) => {
1515 tracing::debug!("Fetch succeeded with DefaultCredentials");
1516 return Ok(());
1517 }
1518 Err(retry_error) => {
1519 tracing::debug!(
1520 "DefaultCredentials retry failed: {}, falling back to git CLI",
1521 retry_error
1522 );
1523 return self.fetch_with_git_cli();
1524 }
1525 }
1526 }
1527
1528 if self.should_fallback_to_git_cli(&e) {
1529 tracing::debug!(
1530 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1531 e.class(), e.code(), e
1532 );
1533 return self.fetch_with_git_cli();
1534 }
1535 Err(CascadeError::Git(e))
1536 }
1537 }
1538 }
1539
1540 pub fn pull(&self, branch: &str) -> Result<()> {
1542 tracing::debug!("Pulling branch: {}", branch);
1543
1544 match self.fetch() {
1546 Ok(_) => {}
1547 Err(e) => {
1548 let error_string = e.to_string();
1550 if error_string.contains("TLS stream") || error_string.contains("SSL") {
1551 tracing::warn!(
1552 "git2 error detected: {}, falling back to git CLI for pull operation",
1553 e
1554 );
1555 return self.pull_with_git_cli(branch);
1556 }
1557 return Err(e);
1558 }
1559 }
1560
1561 let remote_branch_name = format!("origin/{branch}");
1563 let remote_oid = self
1564 .repo
1565 .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1566 .map_err(|e| {
1567 CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1568 })?;
1569
1570 let remote_commit = self
1571 .repo
1572 .find_commit(remote_oid)
1573 .map_err(CascadeError::Git)?;
1574
1575 let head_commit = self.get_head_commit()?;
1577
1578 if head_commit.id() == remote_commit.id() {
1580 tracing::debug!("Already up to date");
1581 return Ok(());
1582 }
1583
1584 let merge_base_oid = self
1586 .repo
1587 .merge_base(head_commit.id(), remote_commit.id())
1588 .map_err(CascadeError::Git)?;
1589
1590 if merge_base_oid == head_commit.id() {
1591 tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1593
1594 let refname = format!("refs/heads/{}", branch);
1596 self.repo
1597 .reference(&refname, remote_oid, true, "pull: Fast-forward")
1598 .map_err(CascadeError::Git)?;
1599
1600 self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1602
1603 self.repo
1605 .checkout_head(Some(
1606 git2::build::CheckoutBuilder::new()
1607 .force()
1608 .remove_untracked(false),
1609 ))
1610 .map_err(CascadeError::Git)?;
1611
1612 tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1613 return Ok(());
1614 }
1615
1616 Err(CascadeError::branch(format!(
1619 "Branch '{}' has diverged from remote. Local has commits not in remote. \
1620 Protected branches should not have local commits. \
1621 Try: git reset --hard origin/{}",
1622 branch, branch
1623 )))
1624 }
1625
1626 pub fn push(&self, branch: &str) -> Result<()> {
1628 let mut remote = self
1631 .repo
1632 .find_remote("origin")
1633 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1634
1635 let remote_url = remote.url().unwrap_or("unknown").to_string();
1636 tracing::debug!("Remote URL: {}", remote_url);
1637
1638 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1639 tracing::debug!("Push refspec: {}", refspec);
1640
1641 let mut callbacks = self.configure_remote_callbacks()?;
1643
1644 callbacks.push_update_reference(|refname, status| {
1646 if let Some(msg) = status {
1647 tracing::error!("Push failed for ref {}: {}", refname, msg);
1648 return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1649 }
1650 tracing::debug!("Push succeeded for ref: {}", refname);
1651 Ok(())
1652 });
1653
1654 let mut push_options = git2::PushOptions::new();
1656 push_options.remote_callbacks(callbacks);
1657
1658 match remote.push(&[&refspec], Some(&mut push_options)) {
1660 Ok(_) => {
1661 tracing::info!("Push completed successfully for branch: {}", branch);
1662 Ok(())
1663 }
1664 Err(e) => {
1665 tracing::debug!(
1666 "git2 push error: {} (class: {:?}, code: {:?})",
1667 e,
1668 e.class(),
1669 e.code()
1670 );
1671
1672 if self.should_retry_with_default_credentials(&e) {
1673 tracing::debug!(
1674 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1675 e.class(), e.code(), e
1676 );
1677
1678 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1680 let mut push_options = git2::PushOptions::new();
1681 push_options.remote_callbacks(callbacks);
1682
1683 match remote.push(&[&refspec], Some(&mut push_options)) {
1684 Ok(_) => {
1685 tracing::debug!("Push succeeded with DefaultCredentials");
1686 return Ok(());
1687 }
1688 Err(retry_error) => {
1689 tracing::debug!(
1690 "DefaultCredentials retry failed: {}, falling back to git CLI",
1691 retry_error
1692 );
1693 return self.push_with_git_cli(branch);
1694 }
1695 }
1696 }
1697
1698 if self.should_fallback_to_git_cli(&e) {
1699 tracing::debug!(
1700 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1701 e.class(), e.code(), e
1702 );
1703 return self.push_with_git_cli(branch);
1704 }
1705
1706 let error_msg = if e.to_string().contains("authentication") {
1708 format!(
1709 "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1710 )
1711 } else {
1712 format!("Failed to push branch '{branch}': {e}")
1713 };
1714
1715 tracing::error!("{}", error_msg);
1716 Err(CascadeError::branch(error_msg))
1717 }
1718 }
1719 }
1720
1721 fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1724 self.ensure_index_closed()?;
1726
1727 let output = std::process::Command::new("git")
1728 .args(["push", "origin", branch])
1729 .current_dir(&self.path)
1730 .output()
1731 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1732
1733 if output.status.success() {
1734 Ok(())
1736 } else {
1737 let stderr = String::from_utf8_lossy(&output.stderr);
1738 let _stdout = String::from_utf8_lossy(&output.stdout);
1739 let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1741 "Network error: Unable to connect to repository (VPN may be required)".to_string()
1742 } else if stderr.contains("repository") && stderr.contains("not found") {
1743 "Repository not found - check your Bitbucket configuration".to_string()
1744 } else if stderr.contains("authentication") || stderr.contains("403") {
1745 "Authentication failed - check your credentials".to_string()
1746 } else {
1747 stderr.trim().to_string()
1749 };
1750 tracing::error!("{}", error_msg);
1751 Err(CascadeError::branch(error_msg))
1752 }
1753 }
1754
1755 fn fetch_with_git_cli(&self) -> Result<()> {
1758 tracing::debug!("Using git CLI fallback for fetch operation");
1759
1760 self.ensure_index_closed()?;
1762
1763 let output = std::process::Command::new("git")
1764 .args(["fetch", "origin"])
1765 .current_dir(&self.path)
1766 .output()
1767 .map_err(|e| {
1768 CascadeError::Git(git2::Error::from_str(&format!(
1769 "Failed to execute git command: {e}"
1770 )))
1771 })?;
1772
1773 if output.status.success() {
1774 tracing::debug!("Git CLI fetch succeeded");
1775 Ok(())
1776 } else {
1777 let stderr = String::from_utf8_lossy(&output.stderr);
1778 let stdout = String::from_utf8_lossy(&output.stdout);
1779 let error_msg = format!(
1780 "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1781 output.status, stdout, stderr
1782 );
1783 tracing::error!("{}", error_msg);
1784 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1785 }
1786 }
1787
1788 fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1791 tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1792
1793 self.ensure_index_closed()?;
1795
1796 let output = std::process::Command::new("git")
1797 .args(["pull", "origin", branch])
1798 .current_dir(&self.path)
1799 .output()
1800 .map_err(|e| {
1801 CascadeError::Git(git2::Error::from_str(&format!(
1802 "Failed to execute git command: {e}"
1803 )))
1804 })?;
1805
1806 if output.status.success() {
1807 tracing::info!("✅ Git CLI pull succeeded for branch: {}", branch);
1808 Ok(())
1809 } else {
1810 let stderr = String::from_utf8_lossy(&output.stderr);
1811 let stdout = String::from_utf8_lossy(&output.stdout);
1812 let error_msg = format!(
1813 "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1814 branch, output.status, stdout, stderr
1815 );
1816 tracing::error!("{}", error_msg);
1817 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1818 }
1819 }
1820
1821 fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1824 tracing::debug!(
1825 "Using git CLI fallback for force push operation: {}",
1826 branch
1827 );
1828
1829 let output = std::process::Command::new("git")
1830 .args(["push", "--force", "origin", branch])
1831 .current_dir(&self.path)
1832 .output()
1833 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1834
1835 if output.status.success() {
1836 tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
1837 Ok(())
1838 } else {
1839 let stderr = String::from_utf8_lossy(&output.stderr);
1840 let stdout = String::from_utf8_lossy(&output.stdout);
1841 let error_msg = format!(
1842 "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1843 branch, output.status, stdout, stderr
1844 );
1845 tracing::error!("{}", error_msg);
1846 Err(CascadeError::branch(error_msg))
1847 }
1848 }
1849
1850 pub fn delete_branch(&self, name: &str) -> Result<()> {
1852 self.delete_branch_with_options(name, false)
1853 }
1854
1855 pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1857 self.delete_branch_with_options(name, true)
1858 }
1859
1860 fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1862 debug!("Attempting to delete branch: {}", name);
1863
1864 if !force_unsafe {
1866 let safety_result = self.check_branch_deletion_safety(name)?;
1867 if let Some(safety_info) = safety_result {
1868 self.handle_branch_deletion_confirmation(name, &safety_info)?;
1870 }
1871 }
1872
1873 let mut branch = self
1874 .repo
1875 .find_branch(name, git2::BranchType::Local)
1876 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1877
1878 branch
1879 .delete()
1880 .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1881
1882 debug!("Successfully deleted branch '{}'", name);
1883 Ok(())
1884 }
1885
1886 pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1888 let from_oid = self
1889 .repo
1890 .refname_to_id(&format!("refs/heads/{from}"))
1891 .or_else(|_| Oid::from_str(from))
1892 .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1893
1894 let to_oid = self
1895 .repo
1896 .refname_to_id(&format!("refs/heads/{to}"))
1897 .or_else(|_| Oid::from_str(to))
1898 .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1899
1900 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1901
1902 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1903 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1904
1905 let mut commits = Vec::new();
1906 for oid in revwalk {
1907 let oid = oid.map_err(CascadeError::Git)?;
1908 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1909 commits.push(commit);
1910 }
1911
1912 Ok(commits)
1913 }
1914
1915 pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1918 self.force_push_branch_with_options(target_branch, source_branch, false)
1919 }
1920
1921 pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1923 self.force_push_branch_with_options(target_branch, source_branch, true)
1924 }
1925
1926 fn force_push_branch_with_options(
1928 &self,
1929 target_branch: &str,
1930 source_branch: &str,
1931 force_unsafe: bool,
1932 ) -> Result<()> {
1933 debug!(
1934 "Force pushing {} content to {} to preserve PR history",
1935 source_branch, target_branch
1936 );
1937
1938 if !force_unsafe {
1940 let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1941 if let Some(backup_info) = safety_result {
1942 self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1944 debug!("Created backup branch: {}", backup_info.backup_branch_name);
1945 }
1946 }
1947
1948 let source_ref = self
1950 .repo
1951 .find_reference(&format!("refs/heads/{source_branch}"))
1952 .map_err(|e| {
1953 CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1954 })?;
1955 let _source_commit = source_ref.peel_to_commit().map_err(|e| {
1956 CascadeError::config(format!(
1957 "Failed to get commit for source branch {source_branch}: {e}"
1958 ))
1959 })?;
1960
1961 let mut remote = self
1963 .repo
1964 .find_remote("origin")
1965 .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1966
1967 let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
1969
1970 let callbacks = self.configure_remote_callbacks()?;
1972
1973 let mut push_options = git2::PushOptions::new();
1975 push_options.remote_callbacks(callbacks);
1976
1977 match remote.push(&[&refspec], Some(&mut push_options)) {
1978 Ok(_) => {}
1979 Err(e) => {
1980 if self.should_retry_with_default_credentials(&e) {
1981 tracing::debug!(
1982 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1983 e.class(), e.code(), e
1984 );
1985
1986 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1988 let mut push_options = git2::PushOptions::new();
1989 push_options.remote_callbacks(callbacks);
1990
1991 match remote.push(&[&refspec], Some(&mut push_options)) {
1992 Ok(_) => {
1993 tracing::debug!("Force push succeeded with DefaultCredentials");
1994 }
1996 Err(retry_error) => {
1997 tracing::debug!(
1998 "DefaultCredentials retry failed: {}, falling back to git CLI",
1999 retry_error
2000 );
2001 return self.force_push_with_git_cli(target_branch);
2002 }
2003 }
2004 } else if self.should_fallback_to_git_cli(&e) {
2005 tracing::debug!(
2006 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
2007 e.class(), e.code(), e
2008 );
2009 return self.force_push_with_git_cli(target_branch);
2010 } else {
2011 return Err(CascadeError::config(format!(
2012 "Failed to force push {target_branch}: {e}"
2013 )));
2014 }
2015 }
2016 }
2017
2018 info!(
2019 "✅ Successfully force pushed {} to preserve PR history",
2020 target_branch
2021 );
2022 Ok(())
2023 }
2024
2025 fn check_force_push_safety_enhanced(
2028 &self,
2029 target_branch: &str,
2030 ) -> Result<Option<ForceBackupInfo>> {
2031 match self.fetch() {
2033 Ok(_) => {}
2034 Err(e) => {
2035 warn!("Could not fetch latest changes for safety check: {}", e);
2037 }
2038 }
2039
2040 let remote_ref = format!("refs/remotes/origin/{target_branch}");
2042 let local_ref = format!("refs/heads/{target_branch}");
2043
2044 let local_commit = match self.repo.find_reference(&local_ref) {
2046 Ok(reference) => reference.peel_to_commit().ok(),
2047 Err(_) => None,
2048 };
2049
2050 let remote_commit = match self.repo.find_reference(&remote_ref) {
2051 Ok(reference) => reference.peel_to_commit().ok(),
2052 Err(_) => None,
2053 };
2054
2055 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2057 if local.id() != remote.id() {
2058 let merge_base_oid = self
2060 .repo
2061 .merge_base(local.id(), remote.id())
2062 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2063
2064 if merge_base_oid != remote.id() {
2066 let commits_to_lose = self.count_commits_between(
2067 &merge_base_oid.to_string(),
2068 &remote.id().to_string(),
2069 )?;
2070
2071 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2073 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2074
2075 debug!(
2076 "Force push to '{}' would overwrite {} commits on remote",
2077 target_branch, commits_to_lose
2078 );
2079
2080 if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2082 {
2083 info!(
2084 "Non-interactive environment detected, proceeding with backup creation"
2085 );
2086 return Ok(Some(ForceBackupInfo {
2087 backup_branch_name,
2088 remote_commit_id: remote.id().to_string(),
2089 commits_that_would_be_lost: commits_to_lose,
2090 }));
2091 }
2092
2093 println!();
2095 Output::warning("FORCE PUSH WARNING");
2096 println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
2097
2098 match self
2100 .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
2101 {
2102 Ok(commits) => {
2103 println!();
2104 println!("Commits that would be lost:");
2105 for (i, commit) in commits.iter().take(5).enumerate() {
2106 let short_hash = &commit.id().to_string()[..8];
2107 let summary = commit.summary().unwrap_or("<no message>");
2108 println!(" {}. {} - {}", i + 1, short_hash, summary);
2109 }
2110 if commits.len() > 5 {
2111 println!(" ... and {} more commits", commits.len() - 5);
2112 }
2113 }
2114 Err(_) => {
2115 println!(" (Unable to retrieve commit details)");
2116 }
2117 }
2118
2119 println!();
2120 Output::info(format!(
2121 "A backup branch '{backup_branch_name}' will be created before proceeding."
2122 ));
2123
2124 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2125 .with_prompt("Do you want to proceed with the force push?")
2126 .default(false)
2127 .interact()
2128 .map_err(|e| {
2129 CascadeError::config(format!("Failed to get user confirmation: {e}"))
2130 })?;
2131
2132 if !confirmed {
2133 return Err(CascadeError::config(
2134 "Force push cancelled by user. Use --force to bypass this check."
2135 .to_string(),
2136 ));
2137 }
2138
2139 return Ok(Some(ForceBackupInfo {
2140 backup_branch_name,
2141 remote_commit_id: remote.id().to_string(),
2142 commits_that_would_be_lost: commits_to_lose,
2143 }));
2144 }
2145 }
2146 }
2147
2148 Ok(None)
2149 }
2150
2151 fn is_likely_rebase_scenario(&self, local_oid: &str, remote_oid: &str) -> bool {
2154 let local_oid_parsed = match git2::Oid::from_str(local_oid) {
2156 Ok(oid) => oid,
2157 Err(_) => return false,
2158 };
2159
2160 let remote_oid_parsed = match git2::Oid::from_str(remote_oid) {
2161 Ok(oid) => oid,
2162 Err(_) => return false,
2163 };
2164
2165 let local_commit = match self.repo.find_commit(local_oid_parsed) {
2166 Ok(c) => c,
2167 Err(_) => return false,
2168 };
2169
2170 let remote_commit = match self.repo.find_commit(remote_oid_parsed) {
2171 Ok(c) => c,
2172 Err(_) => return false,
2173 };
2174
2175 let local_msg = local_commit.message().unwrap_or("");
2177 let remote_msg = remote_commit.message().unwrap_or("");
2178
2179 if local_msg == remote_msg {
2181 return true;
2182 }
2183
2184 let local_count = local_commit.parent_count();
2187 let remote_count = remote_commit.parent_count();
2188
2189 if local_count == remote_count && local_count > 0 {
2190 let mut local_walker = match self.repo.revwalk() {
2192 Ok(w) => w,
2193 Err(_) => return false,
2194 };
2195 let mut remote_walker = match self.repo.revwalk() {
2196 Ok(w) => w,
2197 Err(_) => return false,
2198 };
2199
2200 if local_walker.push(local_commit.id()).is_err() {
2201 return false;
2202 }
2203 if remote_walker.push(remote_commit.id()).is_err() {
2204 return false;
2205 }
2206
2207 let local_messages: Vec<String> = local_walker
2208 .take(5) .filter_map(|oid| {
2210 self.repo
2211 .find_commit(oid.ok()?)
2212 .ok()?
2213 .message()
2214 .map(|s| s.to_string())
2215 })
2216 .collect();
2217
2218 let remote_messages: Vec<String> = remote_walker
2219 .take(5)
2220 .filter_map(|oid| {
2221 self.repo
2222 .find_commit(oid.ok()?)
2223 .ok()?
2224 .message()
2225 .map(|s| s.to_string())
2226 })
2227 .collect();
2228
2229 let matches = local_messages
2231 .iter()
2232 .zip(remote_messages.iter())
2233 .filter(|(l, r)| l == r)
2234 .count();
2235
2236 return matches >= local_messages.len() / 2;
2237 }
2238
2239 false
2240 }
2241
2242 fn check_force_push_safety_auto(&self, target_branch: &str) -> Result<Option<ForceBackupInfo>> {
2245 match self.fetch() {
2247 Ok(_) => {}
2248 Err(e) => {
2249 warn!("Could not fetch latest changes for safety check: {}", e);
2250 }
2251 }
2252
2253 let remote_ref = format!("refs/remotes/origin/{target_branch}");
2255 let local_ref = format!("refs/heads/{target_branch}");
2256
2257 let local_commit = match self.repo.find_reference(&local_ref) {
2259 Ok(reference) => reference.peel_to_commit().ok(),
2260 Err(_) => None,
2261 };
2262
2263 let remote_commit = match self.repo.find_reference(&remote_ref) {
2264 Ok(reference) => reference.peel_to_commit().ok(),
2265 Err(_) => None,
2266 };
2267
2268 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2270 if local.id() != remote.id() {
2271 let merge_base_oid = self
2273 .repo
2274 .merge_base(local.id(), remote.id())
2275 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2276
2277 if merge_base_oid != remote.id() {
2279 let is_likely_rebase = self.is_likely_rebase_scenario(
2282 &local.id().to_string(),
2283 &remote.id().to_string(),
2284 );
2285
2286 if is_likely_rebase {
2287 debug!(
2288 "Detected rebase scenario for '{}' - skipping backup (commit content preserved)",
2289 target_branch
2290 );
2291 return Ok(None);
2293 }
2294
2295 let commits_to_lose = self.count_commits_between(
2296 &merge_base_oid.to_string(),
2297 &remote.id().to_string(),
2298 )?;
2299
2300 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2302 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2303
2304 debug!(
2305 "Auto-creating backup for force push to '{}' (would overwrite {} commits)",
2306 target_branch, commits_to_lose
2307 );
2308
2309 return Ok(Some(ForceBackupInfo {
2311 backup_branch_name,
2312 remote_commit_id: remote.id().to_string(),
2313 commits_that_would_be_lost: commits_to_lose,
2314 }));
2315 }
2316 }
2317 }
2318
2319 Ok(None)
2320 }
2321
2322 fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2324 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2325 let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2326
2327 let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2329 CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2330 })?;
2331
2332 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2334 CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2335 })?;
2336
2337 self.repo
2339 .branch(&backup_branch_name, &commit, false)
2340 .map_err(|e| {
2341 CascadeError::config(format!(
2342 "Failed to create backup branch {backup_branch_name}: {e}"
2343 ))
2344 })?;
2345
2346 debug!(
2347 "Created backup branch '{}' pointing to {}",
2348 backup_branch_name,
2349 &remote_commit_id[..8]
2350 );
2351 Ok(())
2352 }
2353
2354 fn check_branch_deletion_safety(
2357 &self,
2358 branch_name: &str,
2359 ) -> Result<Option<BranchDeletionSafety>> {
2360 match self.fetch() {
2362 Ok(_) => {}
2363 Err(e) => {
2364 warn!(
2365 "Could not fetch latest changes for branch deletion safety check: {}",
2366 e
2367 );
2368 }
2369 }
2370
2371 let branch = self
2373 .repo
2374 .find_branch(branch_name, git2::BranchType::Local)
2375 .map_err(|e| {
2376 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2377 })?;
2378
2379 let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2380 CascadeError::branch(format!(
2381 "Could not get commit for branch '{branch_name}': {e}"
2382 ))
2383 })?;
2384
2385 let main_branch_name = self.detect_main_branch()?;
2387
2388 let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2390
2391 let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2393
2394 let mut unpushed_commits = Vec::new();
2395
2396 if let Some(ref remote_branch) = remote_tracking_branch {
2398 match self.get_commits_between(remote_branch, branch_name) {
2399 Ok(commits) => {
2400 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2401 }
2402 Err(_) => {
2403 if !is_merged_to_main {
2405 if let Ok(commits) =
2406 self.get_commits_between(&main_branch_name, branch_name)
2407 {
2408 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2409 }
2410 }
2411 }
2412 }
2413 } else if !is_merged_to_main {
2414 if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2416 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2417 }
2418 }
2419
2420 if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2422 {
2423 Ok(Some(BranchDeletionSafety {
2424 unpushed_commits,
2425 remote_tracking_branch,
2426 is_merged_to_main,
2427 main_branch_name,
2428 }))
2429 } else {
2430 Ok(None)
2431 }
2432 }
2433
2434 fn handle_branch_deletion_confirmation(
2436 &self,
2437 branch_name: &str,
2438 safety_info: &BranchDeletionSafety,
2439 ) -> Result<()> {
2440 if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2442 return Err(CascadeError::branch(
2443 format!(
2444 "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2445 safety_info.unpushed_commits.len()
2446 )
2447 ));
2448 }
2449
2450 println!();
2452 Output::warning("BRANCH DELETION WARNING");
2453 println!("Branch '{branch_name}' has potential issues:");
2454
2455 if !safety_info.unpushed_commits.is_empty() {
2456 println!(
2457 "\n🔍 Unpushed commits ({} total):",
2458 safety_info.unpushed_commits.len()
2459 );
2460
2461 for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2463 if let Ok(oid) = Oid::from_str(commit_id) {
2464 if let Ok(commit) = self.repo.find_commit(oid) {
2465 let short_hash = &commit_id[..8];
2466 let summary = commit.summary().unwrap_or("<no message>");
2467 println!(" {}. {} - {}", i + 1, short_hash, summary);
2468 }
2469 }
2470 }
2471
2472 if safety_info.unpushed_commits.len() > 5 {
2473 println!(
2474 " ... and {} more commits",
2475 safety_info.unpushed_commits.len() - 5
2476 );
2477 }
2478 }
2479
2480 if !safety_info.is_merged_to_main {
2481 println!("\n📋 Branch status:");
2482 println!(" • Not merged to '{}'", safety_info.main_branch_name);
2483 if let Some(ref remote) = safety_info.remote_tracking_branch {
2484 println!(" • Remote tracking branch: {remote}");
2485 } else {
2486 println!(" • No remote tracking branch");
2487 }
2488 }
2489
2490 println!("\n💡 Safer alternatives:");
2491 if !safety_info.unpushed_commits.is_empty() {
2492 if let Some(ref _remote) = safety_info.remote_tracking_branch {
2493 println!(" • Push commits first: git push origin {branch_name}");
2494 } else {
2495 println!(" • Create and push to remote: git push -u origin {branch_name}");
2496 }
2497 }
2498 if !safety_info.is_merged_to_main {
2499 println!(
2500 " • Merge to {} first: git checkout {} && git merge {branch_name}",
2501 safety_info.main_branch_name, safety_info.main_branch_name
2502 );
2503 }
2504
2505 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2506 .with_prompt("Do you want to proceed with deleting this branch?")
2507 .default(false)
2508 .interact()
2509 .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2510
2511 if !confirmed {
2512 return Err(CascadeError::branch(
2513 "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2514 ));
2515 }
2516
2517 Ok(())
2518 }
2519
2520 pub fn detect_main_branch(&self) -> Result<String> {
2522 let main_candidates = ["main", "master", "develop", "trunk"];
2523
2524 for candidate in &main_candidates {
2525 if self
2526 .repo
2527 .find_branch(candidate, git2::BranchType::Local)
2528 .is_ok()
2529 {
2530 return Ok(candidate.to_string());
2531 }
2532 }
2533
2534 if let Ok(head) = self.repo.head() {
2536 if let Some(name) = head.shorthand() {
2537 return Ok(name.to_string());
2538 }
2539 }
2540
2541 Ok("main".to_string())
2543 }
2544
2545 fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2547 match self.get_commits_between(main_branch, branch_name) {
2549 Ok(commits) => Ok(commits.is_empty()),
2550 Err(_) => {
2551 Ok(false)
2553 }
2554 }
2555 }
2556
2557 fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2559 let remote_candidates = [
2561 format!("origin/{branch_name}"),
2562 format!("remotes/origin/{branch_name}"),
2563 ];
2564
2565 for candidate in &remote_candidates {
2566 if self
2567 .repo
2568 .find_reference(&format!(
2569 "refs/remotes/{}",
2570 candidate.replace("remotes/", "")
2571 ))
2572 .is_ok()
2573 {
2574 return Some(candidate.clone());
2575 }
2576 }
2577
2578 None
2579 }
2580
2581 fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2583 let is_dirty = self.is_dirty()?;
2585 if !is_dirty {
2586 return Ok(None);
2588 }
2589
2590 let current_branch = self.get_current_branch().ok();
2592
2593 let modified_files = self.get_modified_files()?;
2595 let staged_files = self.get_staged_files()?;
2596 let untracked_files = self.get_untracked_files()?;
2597
2598 let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2599
2600 if has_uncommitted_changes || !untracked_files.is_empty() {
2601 return Ok(Some(CheckoutSafety {
2602 has_uncommitted_changes,
2603 modified_files,
2604 staged_files,
2605 untracked_files,
2606 stash_created: None,
2607 current_branch,
2608 }));
2609 }
2610
2611 Ok(None)
2612 }
2613
2614 fn handle_checkout_confirmation(
2616 &self,
2617 target: &str,
2618 safety_info: &CheckoutSafety,
2619 ) -> Result<()> {
2620 let is_ci = std::env::var("CI").is_ok();
2622 let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2623 let is_non_interactive = is_ci || no_confirm;
2624
2625 if is_non_interactive {
2626 return Err(CascadeError::branch(
2627 format!(
2628 "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2629 )
2630 ));
2631 }
2632
2633 println!("\nCHECKOUT WARNING");
2635 println!("Attempting to checkout: {}", target);
2636 println!("You have uncommitted changes that could be lost:");
2637
2638 if !safety_info.modified_files.is_empty() {
2639 println!("\nModified files ({}):", safety_info.modified_files.len());
2640 for file in safety_info.modified_files.iter().take(10) {
2641 println!(" - {file}");
2642 }
2643 if safety_info.modified_files.len() > 10 {
2644 println!(" ... and {} more", safety_info.modified_files.len() - 10);
2645 }
2646 }
2647
2648 if !safety_info.staged_files.is_empty() {
2649 println!("\nStaged files ({}):", safety_info.staged_files.len());
2650 for file in safety_info.staged_files.iter().take(10) {
2651 println!(" - {file}");
2652 }
2653 if safety_info.staged_files.len() > 10 {
2654 println!(" ... and {} more", safety_info.staged_files.len() - 10);
2655 }
2656 }
2657
2658 if !safety_info.untracked_files.is_empty() {
2659 println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2660 for file in safety_info.untracked_files.iter().take(5) {
2661 println!(" - {file}");
2662 }
2663 if safety_info.untracked_files.len() > 5 {
2664 println!(" ... and {} more", safety_info.untracked_files.len() - 5);
2665 }
2666 }
2667
2668 println!("\nOptions:");
2669 println!("1. Stash changes and checkout (recommended)");
2670 println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2671 println!("3. Cancel checkout");
2672
2673 let selection = Select::with_theme(&ColorfulTheme::default())
2675 .with_prompt("Choose an action")
2676 .items(&[
2677 "Stash changes and checkout (recommended)",
2678 "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2679 "Cancel checkout",
2680 ])
2681 .default(0)
2682 .interact()
2683 .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2684
2685 match selection {
2686 0 => {
2687 let stash_message = format!(
2689 "Auto-stash before checkout to {} at {}",
2690 target,
2691 chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2692 );
2693
2694 match self.create_stash(&stash_message) {
2695 Ok(stash_id) => {
2696 println!("✅ Created stash: {stash_message} ({stash_id})");
2697 println!("💡 You can restore with: git stash pop");
2698 }
2699 Err(e) => {
2700 println!("❌ Failed to create stash: {e}");
2701
2702 use dialoguer::Select;
2704 let stash_failed_options = vec![
2705 "Commit staged changes and proceed",
2706 "Force checkout (WILL LOSE CHANGES)",
2707 "Cancel and handle manually",
2708 ];
2709
2710 let stash_selection = Select::with_theme(&ColorfulTheme::default())
2711 .with_prompt("Stash failed. What would you like to do?")
2712 .items(&stash_failed_options)
2713 .default(0)
2714 .interact()
2715 .map_err(|e| {
2716 CascadeError::branch(format!("Could not get user selection: {e}"))
2717 })?;
2718
2719 match stash_selection {
2720 0 => {
2721 let staged_files = self.get_staged_files()?;
2723 if !staged_files.is_empty() {
2724 println!(
2725 "📝 Committing {} staged files...",
2726 staged_files.len()
2727 );
2728 match self
2729 .commit_staged_changes("WIP: Auto-commit before checkout")
2730 {
2731 Ok(Some(commit_hash)) => {
2732 println!(
2733 "✅ Committed staged changes as {}",
2734 &commit_hash[..8]
2735 );
2736 println!("💡 You can undo with: git reset HEAD~1");
2737 }
2738 Ok(None) => {
2739 println!("No staged changes found to commit");
2740 }
2741 Err(commit_err) => {
2742 println!(
2743 "❌ Failed to commit staged changes: {commit_err}"
2744 );
2745 return Err(CascadeError::branch(
2746 "Could not commit staged changes".to_string(),
2747 ));
2748 }
2749 }
2750 } else {
2751 println!("No staged changes to commit");
2752 }
2753 }
2754 1 => {
2755 Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2757 }
2758 2 => {
2759 return Err(CascadeError::branch(
2761 "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2762 ));
2763 }
2764 _ => unreachable!(),
2765 }
2766 }
2767 }
2768 }
2769 1 => {
2770 Output::warning(
2772 "Proceeding with force checkout - uncommitted changes will be lost!",
2773 );
2774 }
2775 2 => {
2776 return Err(CascadeError::branch(
2778 "Checkout cancelled by user".to_string(),
2779 ));
2780 }
2781 _ => unreachable!(),
2782 }
2783
2784 Ok(())
2785 }
2786
2787 fn create_stash(&self, message: &str) -> Result<String> {
2789 tracing::info!("Creating stash: {}", message);
2790
2791 let output = std::process::Command::new("git")
2793 .args(["stash", "push", "-m", message])
2794 .current_dir(&self.path)
2795 .output()
2796 .map_err(|e| {
2797 CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2798 })?;
2799
2800 if output.status.success() {
2801 let stdout = String::from_utf8_lossy(&output.stdout);
2802
2803 let stash_id = if stdout.contains("Saved working directory") {
2805 let stash_list_output = std::process::Command::new("git")
2807 .args(["stash", "list", "-n", "1", "--format=%H"])
2808 .current_dir(&self.path)
2809 .output()
2810 .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2811
2812 if stash_list_output.status.success() {
2813 String::from_utf8_lossy(&stash_list_output.stdout)
2814 .trim()
2815 .to_string()
2816 } else {
2817 "stash@{0}".to_string() }
2819 } else {
2820 "stash@{0}".to_string() };
2822
2823 tracing::info!("✅ Created stash: {} ({})", message, stash_id);
2824 Ok(stash_id)
2825 } else {
2826 let stderr = String::from_utf8_lossy(&output.stderr);
2827 let stdout = String::from_utf8_lossy(&output.stdout);
2828
2829 if stderr.contains("No local changes to save")
2831 || stdout.contains("No local changes to save")
2832 {
2833 return Err(CascadeError::branch("No local changes to save".to_string()));
2834 }
2835
2836 Err(CascadeError::branch(format!(
2837 "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2838 output.status, stderr, stdout
2839 )))
2840 }
2841 }
2842
2843 fn get_modified_files(&self) -> Result<Vec<String>> {
2845 let mut opts = git2::StatusOptions::new();
2846 opts.include_untracked(false).include_ignored(false);
2847
2848 let statuses = self
2849 .repo
2850 .statuses(Some(&mut opts))
2851 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2852
2853 let mut modified_files = Vec::new();
2854 for status in statuses.iter() {
2855 let flags = status.status();
2856 if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2857 {
2858 if let Some(path) = status.path() {
2859 modified_files.push(path.to_string());
2860 }
2861 }
2862 }
2863
2864 Ok(modified_files)
2865 }
2866
2867 pub fn get_staged_files(&self) -> Result<Vec<String>> {
2869 let mut opts = git2::StatusOptions::new();
2870 opts.include_untracked(false).include_ignored(false);
2871
2872 let statuses = self
2873 .repo
2874 .statuses(Some(&mut opts))
2875 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2876
2877 let mut staged_files = Vec::new();
2878 for status in statuses.iter() {
2879 let flags = status.status();
2880 if flags.contains(git2::Status::INDEX_MODIFIED)
2881 || flags.contains(git2::Status::INDEX_NEW)
2882 || flags.contains(git2::Status::INDEX_DELETED)
2883 {
2884 if let Some(path) = status.path() {
2885 staged_files.push(path.to_string());
2886 }
2887 }
2888 }
2889
2890 Ok(staged_files)
2891 }
2892
2893 fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2895 let commits = self.get_commits_between(from, to)?;
2896 Ok(commits.len())
2897 }
2898
2899 pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2901 if let Ok(oid) = Oid::from_str(reference) {
2903 if let Ok(commit) = self.repo.find_commit(oid) {
2904 return Ok(commit);
2905 }
2906 }
2907
2908 let obj = self.repo.revparse_single(reference).map_err(|e| {
2910 CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2911 })?;
2912
2913 obj.peel_to_commit().map_err(|e| {
2914 CascadeError::branch(format!(
2915 "Reference '{reference}' does not point to a commit: {e}"
2916 ))
2917 })
2918 }
2919
2920 pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2922 let target_commit = self.resolve_reference(target_ref)?;
2923
2924 self.repo
2925 .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2926 .map_err(CascadeError::Git)?;
2927
2928 Ok(())
2929 }
2930
2931 pub fn reset_to_head(&self) -> Result<()> {
2934 tracing::debug!("Resetting working directory and index to HEAD");
2935
2936 let head = self.repo.head().map_err(CascadeError::Git)?;
2937 let head_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
2938
2939 let mut checkout_builder = git2::build::CheckoutBuilder::new();
2941 checkout_builder.force(); checkout_builder.remove_untracked(false); self.repo
2945 .reset(
2946 head_commit.as_object(),
2947 git2::ResetType::Hard,
2948 Some(&mut checkout_builder),
2949 )
2950 .map_err(CascadeError::Git)?;
2951
2952 tracing::debug!("Successfully reset working directory to HEAD");
2953 Ok(())
2954 }
2955
2956 pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2958 let oid = Oid::from_str(commit_hash).map_err(|e| {
2959 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2960 })?;
2961
2962 let branches = self
2964 .repo
2965 .branches(Some(git2::BranchType::Local))
2966 .map_err(CascadeError::Git)?;
2967
2968 for branch_result in branches {
2969 let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2970
2971 if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2972 if let Ok(branch_head) = branch.get().peel_to_commit() {
2974 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2976 revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2977
2978 for commit_oid in revwalk {
2979 let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2980 if commit_oid == oid {
2981 return Ok(branch_name.to_string());
2982 }
2983 }
2984 }
2985 }
2986 }
2987
2988 Err(CascadeError::branch(format!(
2990 "Commit {commit_hash} not found in any local branch"
2991 )))
2992 }
2993
2994 pub async fn fetch_async(&self) -> Result<()> {
2998 let repo_path = self.path.clone();
2999 crate::utils::async_ops::run_git_operation(move || {
3000 let repo = GitRepository::open(&repo_path)?;
3001 repo.fetch()
3002 })
3003 .await
3004 }
3005
3006 pub async fn pull_async(&self, branch: &str) -> Result<()> {
3008 let repo_path = self.path.clone();
3009 let branch_name = branch.to_string();
3010 crate::utils::async_ops::run_git_operation(move || {
3011 let repo = GitRepository::open(&repo_path)?;
3012 repo.pull(&branch_name)
3013 })
3014 .await
3015 }
3016
3017 pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
3019 let repo_path = self.path.clone();
3020 let branch = branch_name.to_string();
3021 crate::utils::async_ops::run_git_operation(move || {
3022 let repo = GitRepository::open(&repo_path)?;
3023 repo.push(&branch)
3024 })
3025 .await
3026 }
3027
3028 pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
3030 let repo_path = self.path.clone();
3031 let hash = commit_hash.to_string();
3032 crate::utils::async_ops::run_git_operation(move || {
3033 let repo = GitRepository::open(&repo_path)?;
3034 repo.cherry_pick(&hash)
3035 })
3036 .await
3037 }
3038
3039 pub async fn get_commit_hashes_between_async(
3041 &self,
3042 from: &str,
3043 to: &str,
3044 ) -> Result<Vec<String>> {
3045 let repo_path = self.path.clone();
3046 let from_str = from.to_string();
3047 let to_str = to.to_string();
3048 crate::utils::async_ops::run_git_operation(move || {
3049 let repo = GitRepository::open(&repo_path)?;
3050 let commits = repo.get_commits_between(&from_str, &to_str)?;
3051 Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
3052 })
3053 .await
3054 }
3055
3056 pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
3058 info!(
3059 "Resetting branch '{}' to commit {}",
3060 branch_name,
3061 &commit_hash[..8]
3062 );
3063
3064 let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
3066 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3067 })?;
3068
3069 let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
3070 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
3071 })?;
3072
3073 let _branch = self
3075 .repo
3076 .find_branch(branch_name, git2::BranchType::Local)
3077 .map_err(|e| {
3078 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3079 })?;
3080
3081 let branch_ref_name = format!("refs/heads/{branch_name}");
3083 self.repo
3084 .reference(
3085 &branch_ref_name,
3086 target_oid,
3087 true,
3088 &format!("Reset {branch_name} to {commit_hash}"),
3089 )
3090 .map_err(|e| {
3091 CascadeError::branch(format!(
3092 "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3093 ))
3094 })?;
3095
3096 tracing::info!(
3097 "Successfully reset branch '{}' to commit {}",
3098 branch_name,
3099 &commit_hash[..8]
3100 );
3101 Ok(())
3102 }
3103
3104 pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3106 let current_branch = self.get_current_branch()?;
3107
3108 if let Ok(Some(upstream)) = self.get_upstream_branch(¤t_branch) {
3110 if let Some(branch_name) = upstream.split('/').nth(1) {
3112 if self.branch_exists(branch_name) {
3113 tracing::debug!(
3114 "Detected parent branch '{}' from upstream tracking",
3115 branch_name
3116 );
3117 return Ok(Some(branch_name.to_string()));
3118 }
3119 }
3120 }
3121
3122 if let Ok(default_branch) = self.detect_main_branch() {
3124 if current_branch != default_branch {
3126 tracing::debug!(
3127 "Detected parent branch '{}' as repository default",
3128 default_branch
3129 );
3130 return Ok(Some(default_branch));
3131 }
3132 }
3133
3134 if let Ok(branches) = self.list_branches() {
3137 let current_commit = self.get_head_commit()?;
3138 let current_commit_hash = current_commit.id().to_string();
3139 let current_oid = current_commit.id();
3140
3141 let mut best_candidate = None;
3142 let mut best_distance = usize::MAX;
3143
3144 for branch in branches {
3145 if branch == current_branch
3147 || branch.contains("-v")
3148 || branch.ends_with("-v2")
3149 || branch.ends_with("-v3")
3150 {
3151 continue;
3152 }
3153
3154 if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3155 if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3156 if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3158 if let Ok(distance) = self.count_commits_between(
3160 &merge_base_oid.to_string(),
3161 ¤t_commit_hash,
3162 ) {
3163 let is_likely_base = self.is_likely_base_branch(&branch);
3166 let adjusted_distance = if is_likely_base {
3167 distance
3168 } else {
3169 distance + 1000
3170 };
3171
3172 if adjusted_distance < best_distance {
3173 best_distance = adjusted_distance;
3174 best_candidate = Some(branch.clone());
3175 }
3176 }
3177 }
3178 }
3179 }
3180 }
3181
3182 if let Some(ref candidate) = best_candidate {
3183 tracing::debug!(
3184 "Detected parent branch '{}' with distance {}",
3185 candidate,
3186 best_distance
3187 );
3188 }
3189
3190 return Ok(best_candidate);
3191 }
3192
3193 tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3194 Ok(None)
3195 }
3196
3197 fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3199 let base_patterns = [
3200 "main",
3201 "master",
3202 "develop",
3203 "dev",
3204 "development",
3205 "staging",
3206 "stage",
3207 "release",
3208 "production",
3209 "prod",
3210 ];
3211
3212 base_patterns.contains(&branch_name)
3213 }
3214}
3215
3216#[cfg(test)]
3217mod tests {
3218 use super::*;
3219 use std::process::Command;
3220 use tempfile::TempDir;
3221
3222 fn create_test_repo() -> (TempDir, PathBuf) {
3223 let temp_dir = TempDir::new().unwrap();
3224 let repo_path = temp_dir.path().to_path_buf();
3225
3226 Command::new("git")
3228 .args(["init"])
3229 .current_dir(&repo_path)
3230 .output()
3231 .unwrap();
3232 Command::new("git")
3233 .args(["config", "user.name", "Test"])
3234 .current_dir(&repo_path)
3235 .output()
3236 .unwrap();
3237 Command::new("git")
3238 .args(["config", "user.email", "test@test.com"])
3239 .current_dir(&repo_path)
3240 .output()
3241 .unwrap();
3242
3243 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3245 Command::new("git")
3246 .args(["add", "."])
3247 .current_dir(&repo_path)
3248 .output()
3249 .unwrap();
3250 Command::new("git")
3251 .args(["commit", "-m", "Initial commit"])
3252 .current_dir(&repo_path)
3253 .output()
3254 .unwrap();
3255
3256 (temp_dir, repo_path)
3257 }
3258
3259 fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3260 let file_path = repo_path.join(filename);
3261 std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3262
3263 Command::new("git")
3264 .args(["add", filename])
3265 .current_dir(repo_path)
3266 .output()
3267 .unwrap();
3268 Command::new("git")
3269 .args(["commit", "-m", message])
3270 .current_dir(repo_path)
3271 .output()
3272 .unwrap();
3273 }
3274
3275 #[test]
3276 fn test_repository_info() {
3277 let (_temp_dir, repo_path) = create_test_repo();
3278 let repo = GitRepository::open(&repo_path).unwrap();
3279
3280 let info = repo.get_info().unwrap();
3281 assert!(!info.is_dirty); assert!(
3283 info.head_branch == Some("master".to_string())
3284 || info.head_branch == Some("main".to_string()),
3285 "Expected default branch to be 'master' or 'main', got {:?}",
3286 info.head_branch
3287 );
3288 assert!(info.head_commit.is_some()); assert!(info.untracked_files.is_empty()); }
3291
3292 #[test]
3293 fn test_force_push_branch_basic() {
3294 let (_temp_dir, repo_path) = create_test_repo();
3295 let repo = GitRepository::open(&repo_path).unwrap();
3296
3297 let default_branch = repo.get_current_branch().unwrap();
3299
3300 create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3302 Command::new("git")
3303 .args(["checkout", "-b", "source-branch"])
3304 .current_dir(&repo_path)
3305 .output()
3306 .unwrap();
3307 create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3308
3309 Command::new("git")
3311 .args(["checkout", &default_branch])
3312 .current_dir(&repo_path)
3313 .output()
3314 .unwrap();
3315 Command::new("git")
3316 .args(["checkout", "-b", "target-branch"])
3317 .current_dir(&repo_path)
3318 .output()
3319 .unwrap();
3320 create_commit(&repo_path, "Target commit", "target.rs");
3321
3322 let result = repo.force_push_branch("target-branch", "source-branch");
3324
3325 assert!(result.is_ok() || result.is_err()); }
3329
3330 #[test]
3331 fn test_force_push_branch_nonexistent_branches() {
3332 let (_temp_dir, repo_path) = create_test_repo();
3333 let repo = GitRepository::open(&repo_path).unwrap();
3334
3335 let default_branch = repo.get_current_branch().unwrap();
3337
3338 let result = repo.force_push_branch("target", "nonexistent-source");
3340 assert!(result.is_err());
3341
3342 let result = repo.force_push_branch("nonexistent-target", &default_branch);
3344 assert!(result.is_err());
3345 }
3346
3347 #[test]
3348 fn test_force_push_workflow_simulation() {
3349 let (_temp_dir, repo_path) = create_test_repo();
3350 let repo = GitRepository::open(&repo_path).unwrap();
3351
3352 Command::new("git")
3355 .args(["checkout", "-b", "feature-auth"])
3356 .current_dir(&repo_path)
3357 .output()
3358 .unwrap();
3359 create_commit(&repo_path, "Add authentication", "auth.rs");
3360
3361 Command::new("git")
3363 .args(["checkout", "-b", "feature-auth-v2"])
3364 .current_dir(&repo_path)
3365 .output()
3366 .unwrap();
3367 create_commit(&repo_path, "Fix auth validation", "auth.rs");
3368
3369 let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3371
3372 match result {
3374 Ok(_) => {
3375 Command::new("git")
3377 .args(["checkout", "feature-auth"])
3378 .current_dir(&repo_path)
3379 .output()
3380 .unwrap();
3381 let log_output = Command::new("git")
3382 .args(["log", "--oneline", "-2"])
3383 .current_dir(&repo_path)
3384 .output()
3385 .unwrap();
3386 let log_str = String::from_utf8_lossy(&log_output.stdout);
3387 assert!(
3388 log_str.contains("Fix auth validation")
3389 || log_str.contains("Add authentication")
3390 );
3391 }
3392 Err(_) => {
3393 }
3396 }
3397 }
3398
3399 #[test]
3400 fn test_branch_operations() {
3401 let (_temp_dir, repo_path) = create_test_repo();
3402 let repo = GitRepository::open(&repo_path).unwrap();
3403
3404 let current = repo.get_current_branch().unwrap();
3406 assert!(
3407 current == "master" || current == "main",
3408 "Expected default branch to be 'master' or 'main', got '{current}'"
3409 );
3410
3411 Command::new("git")
3413 .args(["checkout", "-b", "test-branch"])
3414 .current_dir(&repo_path)
3415 .output()
3416 .unwrap();
3417 let current = repo.get_current_branch().unwrap();
3418 assert_eq!(current, "test-branch");
3419 }
3420
3421 #[test]
3422 fn test_commit_operations() {
3423 let (_temp_dir, repo_path) = create_test_repo();
3424 let repo = GitRepository::open(&repo_path).unwrap();
3425
3426 let head = repo.get_head_commit().unwrap();
3428 assert_eq!(head.message().unwrap().trim(), "Initial commit");
3429
3430 let hash = head.id().to_string();
3432 let same_commit = repo.get_commit(&hash).unwrap();
3433 assert_eq!(head.id(), same_commit.id());
3434 }
3435
3436 #[test]
3437 fn test_checkout_safety_clean_repo() {
3438 let (_temp_dir, repo_path) = create_test_repo();
3439 let repo = GitRepository::open(&repo_path).unwrap();
3440
3441 create_commit(&repo_path, "Second commit", "test.txt");
3443 Command::new("git")
3444 .args(["checkout", "-b", "test-branch"])
3445 .current_dir(&repo_path)
3446 .output()
3447 .unwrap();
3448
3449 let safety_result = repo.check_checkout_safety("main");
3451 assert!(safety_result.is_ok());
3452 assert!(safety_result.unwrap().is_none()); }
3454
3455 #[test]
3456 fn test_checkout_safety_with_modified_files() {
3457 let (_temp_dir, repo_path) = create_test_repo();
3458 let repo = GitRepository::open(&repo_path).unwrap();
3459
3460 Command::new("git")
3462 .args(["checkout", "-b", "test-branch"])
3463 .current_dir(&repo_path)
3464 .output()
3465 .unwrap();
3466
3467 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3469
3470 let safety_result = repo.check_checkout_safety("main");
3472 assert!(safety_result.is_ok());
3473 let safety_info = safety_result.unwrap();
3474 assert!(safety_info.is_some());
3475
3476 let info = safety_info.unwrap();
3477 assert!(!info.modified_files.is_empty());
3478 assert!(info.modified_files.contains(&"README.md".to_string()));
3479 }
3480
3481 #[test]
3482 fn test_unsafe_checkout_methods() {
3483 let (_temp_dir, repo_path) = create_test_repo();
3484 let repo = GitRepository::open(&repo_path).unwrap();
3485
3486 create_commit(&repo_path, "Second commit", "test.txt");
3488 Command::new("git")
3489 .args(["checkout", "-b", "test-branch"])
3490 .current_dir(&repo_path)
3491 .output()
3492 .unwrap();
3493
3494 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3496
3497 let _result = repo.checkout_branch_unsafe("main");
3499 let head_commit = repo.get_head_commit().unwrap();
3504 let commit_hash = head_commit.id().to_string();
3505 let _result = repo.checkout_commit_unsafe(&commit_hash);
3506 }
3508
3509 #[test]
3510 fn test_get_modified_files() {
3511 let (_temp_dir, repo_path) = create_test_repo();
3512 let repo = GitRepository::open(&repo_path).unwrap();
3513
3514 let modified = repo.get_modified_files().unwrap();
3516 assert!(modified.is_empty());
3517
3518 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3520
3521 let modified = repo.get_modified_files().unwrap();
3523 assert_eq!(modified.len(), 1);
3524 assert!(modified.contains(&"README.md".to_string()));
3525 }
3526
3527 #[test]
3528 fn test_get_staged_files() {
3529 let (_temp_dir, repo_path) = create_test_repo();
3530 let repo = GitRepository::open(&repo_path).unwrap();
3531
3532 let staged = repo.get_staged_files().unwrap();
3534 assert!(staged.is_empty());
3535
3536 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3538 Command::new("git")
3539 .args(["add", "staged.txt"])
3540 .current_dir(&repo_path)
3541 .output()
3542 .unwrap();
3543
3544 let staged = repo.get_staged_files().unwrap();
3546 assert_eq!(staged.len(), 1);
3547 assert!(staged.contains(&"staged.txt".to_string()));
3548 }
3549
3550 #[test]
3551 fn test_create_stash_fallback() {
3552 let (_temp_dir, repo_path) = create_test_repo();
3553 let repo = GitRepository::open(&repo_path).unwrap();
3554
3555 let result = repo.create_stash("test stash");
3557
3558 match result {
3560 Ok(stash_id) => {
3561 assert!(!stash_id.is_empty());
3563 assert!(stash_id.contains("stash") || stash_id.len() >= 7); }
3565 Err(error) => {
3566 let error_msg = error.to_string();
3568 assert!(
3569 error_msg.contains("No local changes to save")
3570 || error_msg.contains("git stash push")
3571 );
3572 }
3573 }
3574 }
3575
3576 #[test]
3577 fn test_delete_branch_unsafe() {
3578 let (_temp_dir, repo_path) = create_test_repo();
3579 let repo = GitRepository::open(&repo_path).unwrap();
3580
3581 create_commit(&repo_path, "Second commit", "test.txt");
3583 Command::new("git")
3584 .args(["checkout", "-b", "test-branch"])
3585 .current_dir(&repo_path)
3586 .output()
3587 .unwrap();
3588
3589 create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3591
3592 Command::new("git")
3594 .args(["checkout", "main"])
3595 .current_dir(&repo_path)
3596 .output()
3597 .unwrap();
3598
3599 let result = repo.delete_branch_unsafe("test-branch");
3602 let _ = result; }
3606
3607 #[test]
3608 fn test_force_push_unsafe() {
3609 let (_temp_dir, repo_path) = create_test_repo();
3610 let repo = GitRepository::open(&repo_path).unwrap();
3611
3612 create_commit(&repo_path, "Second commit", "test.txt");
3614 Command::new("git")
3615 .args(["checkout", "-b", "test-branch"])
3616 .current_dir(&repo_path)
3617 .output()
3618 .unwrap();
3619
3620 let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3623 }
3625
3626 #[test]
3627 fn test_cherry_pick_basic() {
3628 let (_temp_dir, repo_path) = create_test_repo();
3629 let repo = GitRepository::open(&repo_path).unwrap();
3630
3631 repo.create_branch("source", None).unwrap();
3633 repo.checkout_branch("source").unwrap();
3634
3635 std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3636 Command::new("git")
3637 .args(["add", "."])
3638 .current_dir(&repo_path)
3639 .output()
3640 .unwrap();
3641
3642 Command::new("git")
3643 .args(["commit", "-m", "Cherry commit"])
3644 .current_dir(&repo_path)
3645 .output()
3646 .unwrap();
3647
3648 let cherry_commit = repo.get_head_commit_hash().unwrap();
3649
3650 Command::new("git")
3653 .args(["checkout", "-"])
3654 .current_dir(&repo_path)
3655 .output()
3656 .unwrap();
3657
3658 repo.create_branch("target", None).unwrap();
3659 repo.checkout_branch("target").unwrap();
3660
3661 let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3663
3664 repo.repo
3666 .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3667 .unwrap();
3668
3669 assert!(
3671 repo_path.join("cherry.txt").exists(),
3672 "Cherry-picked file should exist"
3673 );
3674
3675 repo.checkout_branch("source").unwrap();
3677 let source_head = repo.get_head_commit_hash().unwrap();
3678 assert_eq!(
3679 source_head, cherry_commit,
3680 "Source branch should be unchanged"
3681 );
3682 }
3683
3684 #[test]
3685 fn test_cherry_pick_preserves_commit_message() {
3686 let (_temp_dir, repo_path) = create_test_repo();
3687 let repo = GitRepository::open(&repo_path).unwrap();
3688
3689 repo.create_branch("msg-test", None).unwrap();
3691 repo.checkout_branch("msg-test").unwrap();
3692
3693 std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3694 Command::new("git")
3695 .args(["add", "."])
3696 .current_dir(&repo_path)
3697 .output()
3698 .unwrap();
3699
3700 let commit_msg = "Test: Special commit message\n\nWith body";
3701 Command::new("git")
3702 .args(["commit", "-m", commit_msg])
3703 .current_dir(&repo_path)
3704 .output()
3705 .unwrap();
3706
3707 let original_commit = repo.get_head_commit_hash().unwrap();
3708
3709 Command::new("git")
3711 .args(["checkout", "-"])
3712 .current_dir(&repo_path)
3713 .output()
3714 .unwrap();
3715 let new_commit = repo.cherry_pick(&original_commit).unwrap();
3716
3717 let output = Command::new("git")
3719 .args(["log", "-1", "--format=%B", &new_commit])
3720 .current_dir(&repo_path)
3721 .output()
3722 .unwrap();
3723
3724 let new_msg = String::from_utf8_lossy(&output.stdout);
3725 assert!(
3726 new_msg.contains("Special commit message"),
3727 "Should preserve commit message"
3728 );
3729 }
3730
3731 #[test]
3732 fn test_cherry_pick_handles_conflicts() {
3733 let (_temp_dir, repo_path) = create_test_repo();
3734 let repo = GitRepository::open(&repo_path).unwrap();
3735
3736 std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3738 Command::new("git")
3739 .args(["add", "."])
3740 .current_dir(&repo_path)
3741 .output()
3742 .unwrap();
3743
3744 Command::new("git")
3745 .args(["commit", "-m", "Add conflict file"])
3746 .current_dir(&repo_path)
3747 .output()
3748 .unwrap();
3749
3750 repo.create_branch("conflict-branch", None).unwrap();
3752 repo.checkout_branch("conflict-branch").unwrap();
3753
3754 std::fs::write(repo_path.join("conflict.txt"), "Modified").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", "Modify conflict file"])
3763 .current_dir(&repo_path)
3764 .output()
3765 .unwrap();
3766
3767 let conflict_commit = repo.get_head_commit_hash().unwrap();
3768
3769 Command::new("git")
3772 .args(["checkout", "-"])
3773 .current_dir(&repo_path)
3774 .output()
3775 .unwrap();
3776 std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3777 Command::new("git")
3778 .args(["add", "."])
3779 .current_dir(&repo_path)
3780 .output()
3781 .unwrap();
3782
3783 Command::new("git")
3784 .args(["commit", "-m", "Different change"])
3785 .current_dir(&repo_path)
3786 .output()
3787 .unwrap();
3788
3789 let result = repo.cherry_pick(&conflict_commit);
3791 assert!(result.is_err(), "Cherry-pick with conflict should fail");
3792 }
3793
3794 #[test]
3795 fn test_reset_to_head_clears_staged_files() {
3796 let (_temp_dir, repo_path) = create_test_repo();
3797 let repo = GitRepository::open(&repo_path).unwrap();
3798
3799 std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3801 std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3802
3803 Command::new("git")
3804 .args(["add", "staged1.txt", "staged2.txt"])
3805 .current_dir(&repo_path)
3806 .output()
3807 .unwrap();
3808
3809 let staged_before = repo.get_staged_files().unwrap();
3811 assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3812
3813 repo.reset_to_head().unwrap();
3815
3816 let staged_after = repo.get_staged_files().unwrap();
3818 assert_eq!(
3819 staged_after.len(),
3820 0,
3821 "Should have no staged files after reset"
3822 );
3823 }
3824
3825 #[test]
3826 fn test_reset_to_head_clears_modified_files() {
3827 let (_temp_dir, repo_path) = create_test_repo();
3828 let repo = GitRepository::open(&repo_path).unwrap();
3829
3830 std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3832
3833 Command::new("git")
3835 .args(["add", "README.md"])
3836 .current_dir(&repo_path)
3837 .output()
3838 .unwrap();
3839
3840 assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3842
3843 repo.reset_to_head().unwrap();
3845
3846 assert!(
3848 !repo.is_dirty().unwrap(),
3849 "Repo should be clean after reset"
3850 );
3851
3852 let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3854 assert_eq!(
3855 content, "# Test",
3856 "File should be restored to original content"
3857 );
3858 }
3859
3860 #[test]
3861 fn test_reset_to_head_preserves_untracked_files() {
3862 let (_temp_dir, repo_path) = create_test_repo();
3863 let repo = GitRepository::open(&repo_path).unwrap();
3864
3865 std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3867
3868 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3870 Command::new("git")
3871 .args(["add", "staged.txt"])
3872 .current_dir(&repo_path)
3873 .output()
3874 .unwrap();
3875
3876 repo.reset_to_head().unwrap();
3878
3879 assert!(
3881 repo_path.join("untracked.txt").exists(),
3882 "Untracked file should be preserved"
3883 );
3884
3885 assert!(
3887 !repo_path.join("staged.txt").exists(),
3888 "Staged but uncommitted file should be removed"
3889 );
3890 }
3891
3892 #[test]
3893 fn test_cherry_pick_does_not_modify_source() {
3894 let (_temp_dir, repo_path) = create_test_repo();
3895 let repo = GitRepository::open(&repo_path).unwrap();
3896
3897 repo.create_branch("feature", None).unwrap();
3899 repo.checkout_branch("feature").unwrap();
3900
3901 for i in 1..=3 {
3903 std::fs::write(
3904 repo_path.join(format!("file{i}.txt")),
3905 format!("Content {i}"),
3906 )
3907 .unwrap();
3908 Command::new("git")
3909 .args(["add", "."])
3910 .current_dir(&repo_path)
3911 .output()
3912 .unwrap();
3913
3914 Command::new("git")
3915 .args(["commit", "-m", &format!("Commit {i}")])
3916 .current_dir(&repo_path)
3917 .output()
3918 .unwrap();
3919 }
3920
3921 let source_commits = Command::new("git")
3923 .args(["log", "--format=%H", "feature"])
3924 .current_dir(&repo_path)
3925 .output()
3926 .unwrap();
3927 let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3928
3929 let commits: Vec<&str> = source_state.lines().collect();
3931 let middle_commit = commits[1];
3932
3933 Command::new("git")
3935 .args(["checkout", "-"])
3936 .current_dir(&repo_path)
3937 .output()
3938 .unwrap();
3939 repo.create_branch("target", None).unwrap();
3940 repo.checkout_branch("target").unwrap();
3941
3942 repo.cherry_pick(middle_commit).unwrap();
3943
3944 let after_commits = Command::new("git")
3946 .args(["log", "--format=%H", "feature"])
3947 .current_dir(&repo_path)
3948 .output()
3949 .unwrap();
3950 let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3951
3952 assert_eq!(
3953 source_state, after_state,
3954 "Source branch should be completely unchanged after cherry-pick"
3955 );
3956 }
3957
3958 #[test]
3959 fn test_detect_parent_branch() {
3960 let (_temp_dir, repo_path) = create_test_repo();
3961 let repo = GitRepository::open(&repo_path).unwrap();
3962
3963 repo.create_branch("dev123", None).unwrap();
3965 repo.checkout_branch("dev123").unwrap();
3966 create_commit(&repo_path, "Base commit on dev123", "base.txt");
3967
3968 repo.create_branch("feature-branch", None).unwrap();
3970 repo.checkout_branch("feature-branch").unwrap();
3971 create_commit(&repo_path, "Feature commit", "feature.txt");
3972
3973 let detected_parent = repo.detect_parent_branch().unwrap();
3975
3976 assert!(detected_parent.is_some(), "Should detect a parent branch");
3979
3980 let parent = detected_parent.unwrap();
3983 assert!(
3984 parent == "dev123" || parent == "main" || parent == "master",
3985 "Parent should be dev123, main, or master, got: {parent}"
3986 );
3987 }
3988}