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, true)
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 get_head_commit(&self) -> Result<git2::Commit<'_>> {
847 let head = self
848 .repo
849 .head()
850 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
851 head.peel_to_commit()
852 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
853 }
854
855 pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
857 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
858
859 self.repo.find_commit(oid).map_err(CascadeError::Git)
860 }
861
862 pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
864 let branch = self
865 .repo
866 .find_branch(branch_name, git2::BranchType::Local)
867 .map_err(|e| {
868 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
869 })?;
870
871 let commit = branch.get().peel_to_commit().map_err(|e| {
872 CascadeError::branch(format!(
873 "Could not get commit for branch '{branch_name}': {e}"
874 ))
875 })?;
876
877 Ok(commit.id().to_string())
878 }
879
880 pub fn validate_git_user_config(&self) -> Result<()> {
882 if let Ok(config) = self.repo.config() {
883 let name_result = config.get_string("user.name");
884 let email_result = config.get_string("user.email");
885
886 if let (Ok(name), Ok(email)) = (name_result, email_result) {
887 if !name.trim().is_empty() && !email.trim().is_empty() {
888 tracing::debug!("Git user config validated: {} <{}>", name, email);
889 return Ok(());
890 }
891 }
892 }
893
894 let is_ci = std::env::var("CI").is_ok();
896
897 if is_ci {
898 tracing::debug!("CI environment - skipping git user config validation");
899 return Ok(());
900 }
901
902 Output::warning("Git user configuration missing or incomplete");
903 Output::info("This can cause cherry-pick and commit operations to fail");
904 Output::info("Please configure git user information:");
905 Output::bullet("git config user.name \"Your Name\"".to_string());
906 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
907 Output::info("Or set globally with the --global flag");
908
909 Ok(())
912 }
913
914 fn get_signature(&self) -> Result<Signature<'_>> {
916 if let Ok(config) = self.repo.config() {
918 let name_result = config.get_string("user.name");
920 let email_result = config.get_string("user.email");
921
922 if let (Ok(name), Ok(email)) = (name_result, email_result) {
923 if !name.trim().is_empty() && !email.trim().is_empty() {
924 tracing::debug!("Using git config: {} <{}>", name, email);
925 return Signature::now(&name, &email).map_err(CascadeError::Git);
926 }
927 } else {
928 tracing::debug!("Git user config incomplete or missing");
929 }
930 }
931
932 let is_ci = std::env::var("CI").is_ok();
934
935 if is_ci {
936 tracing::debug!("CI environment detected, using fallback signature");
937 return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
938 }
939
940 tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
942
943 match Signature::now("Cascade CLI", "cascade@example.com") {
945 Ok(sig) => {
946 Output::warning("Git user not configured - using fallback signature");
947 Output::info("For better git history, run:");
948 Output::bullet("git config user.name \"Your Name\"".to_string());
949 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
950 Output::info("Or set it globally with --global flag");
951 Ok(sig)
952 }
953 Err(e) => {
954 Err(CascadeError::branch(format!(
955 "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\""
956 )))
957 }
958 }
959 }
960
961 fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
964 self.configure_remote_callbacks_with_fallback(false)
965 }
966
967 fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
969 match error.class() {
970 git2::ErrorClass::Http => {
972 match error.code() {
974 git2::ErrorCode::Auth => true,
975 _ => {
976 let error_string = error.to_string();
978 error_string.contains("too many redirects")
979 || error_string.contains("authentication replays")
980 || error_string.contains("authentication required")
981 }
982 }
983 }
984 git2::ErrorClass::Net => {
985 let error_string = error.to_string();
987 error_string.contains("authentication")
988 || error_string.contains("unauthorized")
989 || error_string.contains("forbidden")
990 }
991 _ => false,
992 }
993 }
994
995 fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
997 match error.class() {
998 git2::ErrorClass::Ssl => true,
1000
1001 git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
1003
1004 git2::ErrorClass::Ssh => {
1006 let error_string = error.to_string();
1007 error_string.contains("no callback set")
1008 || error_string.contains("authentication required")
1009 }
1010
1011 git2::ErrorClass::Net => {
1013 let error_string = error.to_string();
1014 error_string.contains("TLS stream")
1015 || error_string.contains("SSL")
1016 || error_string.contains("proxy")
1017 || error_string.contains("firewall")
1018 }
1019
1020 git2::ErrorClass::Http => {
1022 let error_string = error.to_string();
1023 error_string.contains("TLS stream")
1024 || error_string.contains("SSL")
1025 || error_string.contains("proxy")
1026 }
1027
1028 _ => false,
1029 }
1030 }
1031
1032 fn configure_remote_callbacks_with_fallback(
1033 &self,
1034 use_default_first: bool,
1035 ) -> Result<git2::RemoteCallbacks<'_>> {
1036 let mut callbacks = git2::RemoteCallbacks::new();
1037
1038 let bitbucket_credentials = self.bitbucket_credentials.clone();
1040 callbacks.credentials(move |url, username_from_url, allowed_types| {
1041 tracing::debug!(
1042 "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
1043 url,
1044 username_from_url,
1045 allowed_types
1046 );
1047
1048 if allowed_types.contains(git2::CredentialType::SSH_KEY) {
1050 if let Some(username) = username_from_url {
1051 tracing::debug!("Trying SSH key authentication for user: {}", username);
1052 return git2::Cred::ssh_key_from_agent(username);
1053 }
1054 }
1055
1056 if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
1058 if use_default_first {
1060 tracing::debug!("Corporate network mode: trying DefaultCredentials first");
1061 return git2::Cred::default();
1062 }
1063
1064 if url.contains("bitbucket") {
1065 if let Some(creds) = &bitbucket_credentials {
1066 if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
1068 tracing::debug!("Trying Bitbucket username + token authentication");
1069 return git2::Cred::userpass_plaintext(username, token);
1070 }
1071
1072 if let Some(token) = &creds.token {
1074 tracing::debug!("Trying Bitbucket token-as-username authentication");
1075 return git2::Cred::userpass_plaintext(token, "");
1076 }
1077
1078 if let Some(username) = &creds.username {
1080 tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1081 return git2::Cred::username(username);
1082 }
1083 }
1084 }
1085
1086 tracing::debug!("Trying default credential helper for HTTPS authentication");
1088 return git2::Cred::default();
1089 }
1090
1091 tracing::debug!("Using default credential fallback");
1093 git2::Cred::default()
1094 });
1095
1096 let mut ssl_configured = false;
1101
1102 if let Some(ssl_config) = &self.ssl_config {
1104 if ssl_config.accept_invalid_certs {
1105 Output::warning(
1106 "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1107 );
1108 callbacks.certificate_check(|_cert, _host| {
1109 tracing::debug!("⚠️ Accepting invalid certificate for host: {}", _host);
1110 Ok(git2::CertificateCheckStatus::CertificateOk)
1111 });
1112 ssl_configured = true;
1113 } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1114 Output::info(format!(
1115 "Using custom CA bundle from Cascade config: {ca_path}"
1116 ));
1117 callbacks.certificate_check(|_cert, host| {
1118 tracing::debug!("Using custom CA bundle for host: {}", host);
1119 Ok(git2::CertificateCheckStatus::CertificateOk)
1120 });
1121 ssl_configured = true;
1122 }
1123 }
1124
1125 if !ssl_configured {
1127 if let Ok(config) = self.repo.config() {
1128 let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1129
1130 if !ssl_verify {
1131 Output::warning(
1132 "SSL certificate verification DISABLED via git config - this is insecure!",
1133 );
1134 callbacks.certificate_check(|_cert, host| {
1135 tracing::debug!("⚠️ Bypassing SSL verification for host: {}", host);
1136 Ok(git2::CertificateCheckStatus::CertificateOk)
1137 });
1138 ssl_configured = true;
1139 } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1140 Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1141 callbacks.certificate_check(|_cert, host| {
1142 tracing::debug!("Using git config CA bundle for host: {}", host);
1143 Ok(git2::CertificateCheckStatus::CertificateOk)
1144 });
1145 ssl_configured = true;
1146 }
1147 }
1148 }
1149
1150 if !ssl_configured {
1153 tracing::debug!(
1154 "Using system certificate store for SSL verification (default behavior)"
1155 );
1156
1157 if cfg!(target_os = "macos") {
1159 tracing::debug!("macOS detected - using default certificate validation");
1160 } else {
1163 callbacks.certificate_check(|_cert, host| {
1165 tracing::debug!("System certificate validation for host: {}", host);
1166 Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1167 });
1168 }
1169 }
1170
1171 Ok(callbacks)
1172 }
1173
1174 fn get_index_tree(&self) -> Result<Oid> {
1176 let mut index = self.repo.index().map_err(CascadeError::Git)?;
1177
1178 index.write_tree().map_err(CascadeError::Git)
1179 }
1180
1181 pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1183 self.repo.statuses(None).map_err(CascadeError::Git)
1184 }
1185
1186 pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1188 let statuses = self.get_status()?;
1189
1190 let mut staged_files = 0;
1191 let mut unstaged_files = 0;
1192 let mut untracked_files = 0;
1193
1194 for status in statuses.iter() {
1195 let flags = status.status();
1196
1197 if flags.intersects(
1198 git2::Status::INDEX_MODIFIED
1199 | git2::Status::INDEX_NEW
1200 | git2::Status::INDEX_DELETED
1201 | git2::Status::INDEX_RENAMED
1202 | git2::Status::INDEX_TYPECHANGE,
1203 ) {
1204 staged_files += 1;
1205 }
1206
1207 if flags.intersects(
1208 git2::Status::WT_MODIFIED
1209 | git2::Status::WT_DELETED
1210 | git2::Status::WT_TYPECHANGE
1211 | git2::Status::WT_RENAMED,
1212 ) {
1213 unstaged_files += 1;
1214 }
1215
1216 if flags.intersects(git2::Status::WT_NEW) {
1217 untracked_files += 1;
1218 }
1219 }
1220
1221 Ok(GitStatusSummary {
1222 staged_files,
1223 unstaged_files,
1224 untracked_files,
1225 })
1226 }
1227
1228 pub fn get_current_commit_hash(&self) -> Result<String> {
1230 self.get_head_commit_hash()
1231 }
1232
1233 pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1235 let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1236 let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1237
1238 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1239 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1240 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1241
1242 Ok(revwalk.count())
1243 }
1244
1245 pub fn get_remote_url(&self, name: &str) -> Result<String> {
1247 let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1248 Ok(remote.url().unwrap_or("unknown").to_string())
1249 }
1250
1251 pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1253 tracing::debug!("Cherry-picking commit {}", commit_hash);
1254
1255 self.validate_git_user_config()?;
1257
1258 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1259 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1260
1261 let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1263
1264 let parent_commit = if commit.parent_count() > 0 {
1266 commit.parent(0).map_err(CascadeError::Git)?
1267 } else {
1268 let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1270 let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1271 let sig = self.get_signature()?;
1272 return self
1273 .repo
1274 .commit(
1275 Some("HEAD"),
1276 &sig,
1277 &sig,
1278 commit.message().unwrap_or("Cherry-picked commit"),
1279 &empty_tree,
1280 &[],
1281 )
1282 .map(|oid| oid.to_string())
1283 .map_err(CascadeError::Git);
1284 };
1285
1286 let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1287
1288 let head_commit = self.get_head_commit()?;
1290 let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1291
1292 let mut index = self
1294 .repo
1295 .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1296 .map_err(CascadeError::Git)?;
1297
1298 if index.has_conflicts() {
1300 tracing::warn!(
1303 "Cherry-pick has conflicts - writing conflicted state to disk for resolution"
1304 );
1305
1306 let mut repo_index = self.repo.index().map_err(CascadeError::Git)?;
1312
1313 repo_index.clear().map_err(CascadeError::Git)?;
1315 repo_index.read_tree(&head_tree).map_err(CascadeError::Git)?;
1316
1317 repo_index
1319 .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
1320 .map_err(CascadeError::Git)?;
1321
1322 drop(repo_index);
1327 self.ensure_index_closed()?;
1328
1329 let cherry_pick_output = std::process::Command::new("git")
1330 .args(["cherry-pick", commit_hash])
1331 .current_dir(self.path())
1332 .output()
1333 .map_err(CascadeError::Io)?;
1334
1335 if !cherry_pick_output.status.success() {
1336 tracing::warn!("Git CLI cherry-pick failed as expected (has conflicts)");
1337 }
1340
1341 self.repo.index()
1344 .and_then(|mut idx| idx.read(true).map(|_| ()))
1345 .map_err(CascadeError::Git)?;
1346
1347 tracing::warn!("Conflicted state written and index reloaded - auto-resolve can now process conflicts");
1348
1349 return Err(CascadeError::branch(format!(
1350 "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1351 )));
1352 }
1353
1354 let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1356 let merged_tree = self
1357 .repo
1358 .find_tree(merged_tree_oid)
1359 .map_err(CascadeError::Git)?;
1360
1361 let signature = self.get_signature()?;
1363 let message = commit.message().unwrap_or("Cherry-picked commit");
1364
1365 let new_commit_oid = self
1366 .repo
1367 .commit(
1368 Some("HEAD"),
1369 &signature,
1370 &signature,
1371 message,
1372 &merged_tree,
1373 &[&head_commit],
1374 )
1375 .map_err(CascadeError::Git)?;
1376
1377 let new_commit = self
1379 .repo
1380 .find_commit(new_commit_oid)
1381 .map_err(CascadeError::Git)?;
1382 let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1383
1384 self.repo
1385 .checkout_tree(
1386 new_tree.as_object(),
1387 Some(git2::build::CheckoutBuilder::new().force()),
1388 )
1389 .map_err(CascadeError::Git)?;
1390
1391 tracing::debug!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1392 Ok(new_commit_oid.to_string())
1393 }
1394
1395 pub fn has_conflicts(&self) -> Result<bool> {
1397 let index = self.repo.index().map_err(CascadeError::Git)?;
1398 Ok(index.has_conflicts())
1399 }
1400
1401 pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1403 let index = self.repo.index().map_err(CascadeError::Git)?;
1404
1405 let mut conflicts = Vec::new();
1406
1407 let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1409
1410 for conflict in conflict_iter {
1411 let conflict = conflict.map_err(CascadeError::Git)?;
1412 if let Some(our) = conflict.our {
1413 if let Ok(path) = std::str::from_utf8(&our.path) {
1414 conflicts.push(path.to_string());
1415 }
1416 } else if let Some(their) = conflict.their {
1417 if let Ok(path) = std::str::from_utf8(&their.path) {
1418 conflicts.push(path.to_string());
1419 }
1420 }
1421 }
1422
1423 Ok(conflicts)
1424 }
1425
1426 pub fn fetch(&self) -> Result<()> {
1428 tracing::debug!("Fetching from origin");
1429
1430 let mut remote = self
1431 .repo
1432 .find_remote("origin")
1433 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1434
1435 let callbacks = self.configure_remote_callbacks()?;
1437
1438 let mut fetch_options = git2::FetchOptions::new();
1440 fetch_options.remote_callbacks(callbacks);
1441
1442 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1444 Ok(_) => {
1445 tracing::debug!("Fetch completed successfully");
1446 Ok(())
1447 }
1448 Err(e) => {
1449 if self.should_retry_with_default_credentials(&e) {
1450 tracing::debug!(
1451 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1452 e.class(), e.code(), e
1453 );
1454
1455 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1457 let mut fetch_options = git2::FetchOptions::new();
1458 fetch_options.remote_callbacks(callbacks);
1459
1460 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1461 Ok(_) => {
1462 tracing::debug!("Fetch succeeded with DefaultCredentials");
1463 return Ok(());
1464 }
1465 Err(retry_error) => {
1466 tracing::debug!(
1467 "DefaultCredentials retry failed: {}, falling back to git CLI",
1468 retry_error
1469 );
1470 return self.fetch_with_git_cli();
1471 }
1472 }
1473 }
1474
1475 if self.should_fallback_to_git_cli(&e) {
1476 tracing::debug!(
1477 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1478 e.class(), e.code(), e
1479 );
1480 return self.fetch_with_git_cli();
1481 }
1482 Err(CascadeError::Git(e))
1483 }
1484 }
1485 }
1486
1487 pub fn pull(&self, branch: &str) -> Result<()> {
1489 tracing::debug!("Pulling branch: {}", branch);
1490
1491 match self.fetch() {
1493 Ok(_) => {}
1494 Err(e) => {
1495 let error_string = e.to_string();
1497 if error_string.contains("TLS stream") || error_string.contains("SSL") {
1498 tracing::warn!(
1499 "git2 error detected: {}, falling back to git CLI for pull operation",
1500 e
1501 );
1502 return self.pull_with_git_cli(branch);
1503 }
1504 return Err(e);
1505 }
1506 }
1507
1508 let remote_branch_name = format!("origin/{branch}");
1510 let remote_oid = self
1511 .repo
1512 .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1513 .map_err(|e| {
1514 CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1515 })?;
1516
1517 let remote_commit = self
1518 .repo
1519 .find_commit(remote_oid)
1520 .map_err(CascadeError::Git)?;
1521
1522 let head_commit = self.get_head_commit()?;
1524
1525 if head_commit.id() == remote_commit.id() {
1527 tracing::debug!("Already up to date");
1528 return Ok(());
1529 }
1530
1531 let merge_base_oid = self
1533 .repo
1534 .merge_base(head_commit.id(), remote_commit.id())
1535 .map_err(CascadeError::Git)?;
1536
1537 if merge_base_oid == head_commit.id() {
1538 tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1540
1541 let refname = format!("refs/heads/{}", branch);
1543 self.repo
1544 .reference(&refname, remote_oid, true, "pull: Fast-forward")
1545 .map_err(CascadeError::Git)?;
1546
1547 self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1549
1550 self.repo
1552 .checkout_head(Some(
1553 git2::build::CheckoutBuilder::new()
1554 .force()
1555 .remove_untracked(false),
1556 ))
1557 .map_err(CascadeError::Git)?;
1558
1559 tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1560 return Ok(());
1561 }
1562
1563 Err(CascadeError::branch(format!(
1566 "Branch '{}' has diverged from remote. Local has commits not in remote. \
1567 Protected branches should not have local commits. \
1568 Try: git reset --hard origin/{}",
1569 branch, branch
1570 )))
1571 }
1572
1573 pub fn push(&self, branch: &str) -> Result<()> {
1575 let mut remote = self
1578 .repo
1579 .find_remote("origin")
1580 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1581
1582 let remote_url = remote.url().unwrap_or("unknown").to_string();
1583 tracing::debug!("Remote URL: {}", remote_url);
1584
1585 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1586 tracing::debug!("Push refspec: {}", refspec);
1587
1588 let mut callbacks = self.configure_remote_callbacks()?;
1590
1591 callbacks.push_update_reference(|refname, status| {
1593 if let Some(msg) = status {
1594 tracing::error!("Push failed for ref {}: {}", refname, msg);
1595 return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1596 }
1597 tracing::debug!("Push succeeded for ref: {}", refname);
1598 Ok(())
1599 });
1600
1601 let mut push_options = git2::PushOptions::new();
1603 push_options.remote_callbacks(callbacks);
1604
1605 match remote.push(&[&refspec], Some(&mut push_options)) {
1607 Ok(_) => {
1608 tracing::info!("Push completed successfully for branch: {}", branch);
1609 Ok(())
1610 }
1611 Err(e) => {
1612 tracing::debug!(
1613 "git2 push error: {} (class: {:?}, code: {:?})",
1614 e,
1615 e.class(),
1616 e.code()
1617 );
1618
1619 if self.should_retry_with_default_credentials(&e) {
1620 tracing::debug!(
1621 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1622 e.class(), e.code(), e
1623 );
1624
1625 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1627 let mut push_options = git2::PushOptions::new();
1628 push_options.remote_callbacks(callbacks);
1629
1630 match remote.push(&[&refspec], Some(&mut push_options)) {
1631 Ok(_) => {
1632 tracing::debug!("Push succeeded with DefaultCredentials");
1633 return Ok(());
1634 }
1635 Err(retry_error) => {
1636 tracing::debug!(
1637 "DefaultCredentials retry failed: {}, falling back to git CLI",
1638 retry_error
1639 );
1640 return self.push_with_git_cli(branch);
1641 }
1642 }
1643 }
1644
1645 if self.should_fallback_to_git_cli(&e) {
1646 tracing::debug!(
1647 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1648 e.class(), e.code(), e
1649 );
1650 return self.push_with_git_cli(branch);
1651 }
1652
1653 let error_msg = if e.to_string().contains("authentication") {
1655 format!(
1656 "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1657 )
1658 } else {
1659 format!("Failed to push branch '{branch}': {e}")
1660 };
1661
1662 tracing::error!("{}", error_msg);
1663 Err(CascadeError::branch(error_msg))
1664 }
1665 }
1666 }
1667
1668 fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1671 self.ensure_index_closed()?;
1673
1674 let output = std::process::Command::new("git")
1675 .args(["push", "origin", branch])
1676 .current_dir(&self.path)
1677 .output()
1678 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1679
1680 if output.status.success() {
1681 Ok(())
1683 } else {
1684 let stderr = String::from_utf8_lossy(&output.stderr);
1685 let _stdout = String::from_utf8_lossy(&output.stdout);
1686 let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1688 "Network error: Unable to connect to repository (VPN may be required)".to_string()
1689 } else if stderr.contains("repository") && stderr.contains("not found") {
1690 "Repository not found - check your Bitbucket configuration".to_string()
1691 } else if stderr.contains("authentication") || stderr.contains("403") {
1692 "Authentication failed - check your credentials".to_string()
1693 } else {
1694 stderr.trim().to_string()
1696 };
1697 tracing::error!("{}", error_msg);
1698 Err(CascadeError::branch(error_msg))
1699 }
1700 }
1701
1702 fn fetch_with_git_cli(&self) -> Result<()> {
1705 tracing::debug!("Using git CLI fallback for fetch operation");
1706
1707 self.ensure_index_closed()?;
1709
1710 let output = std::process::Command::new("git")
1711 .args(["fetch", "origin"])
1712 .current_dir(&self.path)
1713 .output()
1714 .map_err(|e| {
1715 CascadeError::Git(git2::Error::from_str(&format!(
1716 "Failed to execute git command: {e}"
1717 )))
1718 })?;
1719
1720 if output.status.success() {
1721 tracing::debug!("Git CLI fetch succeeded");
1722 Ok(())
1723 } else {
1724 let stderr = String::from_utf8_lossy(&output.stderr);
1725 let stdout = String::from_utf8_lossy(&output.stdout);
1726 let error_msg = format!(
1727 "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1728 output.status, stdout, stderr
1729 );
1730 tracing::error!("{}", error_msg);
1731 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1732 }
1733 }
1734
1735 fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1738 tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1739
1740 self.ensure_index_closed()?;
1742
1743 let output = std::process::Command::new("git")
1744 .args(["pull", "origin", branch])
1745 .current_dir(&self.path)
1746 .output()
1747 .map_err(|e| {
1748 CascadeError::Git(git2::Error::from_str(&format!(
1749 "Failed to execute git command: {e}"
1750 )))
1751 })?;
1752
1753 if output.status.success() {
1754 tracing::info!("✅ Git CLI pull succeeded for branch: {}", branch);
1755 Ok(())
1756 } else {
1757 let stderr = String::from_utf8_lossy(&output.stderr);
1758 let stdout = String::from_utf8_lossy(&output.stdout);
1759 let error_msg = format!(
1760 "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1761 branch, output.status, stdout, stderr
1762 );
1763 tracing::error!("{}", error_msg);
1764 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1765 }
1766 }
1767
1768 fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1771 tracing::debug!(
1772 "Using git CLI fallback for force push operation: {}",
1773 branch
1774 );
1775
1776 let output = std::process::Command::new("git")
1777 .args(["push", "--force", "origin", branch])
1778 .current_dir(&self.path)
1779 .output()
1780 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1781
1782 if output.status.success() {
1783 tracing::debug!("Git CLI force push succeeded for branch: {}", branch);
1784 Ok(())
1785 } else {
1786 let stderr = String::from_utf8_lossy(&output.stderr);
1787 let stdout = String::from_utf8_lossy(&output.stdout);
1788 let error_msg = format!(
1789 "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1790 branch, output.status, stdout, stderr
1791 );
1792 tracing::error!("{}", error_msg);
1793 Err(CascadeError::branch(error_msg))
1794 }
1795 }
1796
1797 pub fn delete_branch(&self, name: &str) -> Result<()> {
1799 self.delete_branch_with_options(name, false)
1800 }
1801
1802 pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1804 self.delete_branch_with_options(name, true)
1805 }
1806
1807 fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1809 debug!("Attempting to delete branch: {}", name);
1810
1811 if !force_unsafe {
1813 let safety_result = self.check_branch_deletion_safety(name)?;
1814 if let Some(safety_info) = safety_result {
1815 self.handle_branch_deletion_confirmation(name, &safety_info)?;
1817 }
1818 }
1819
1820 let mut branch = self
1821 .repo
1822 .find_branch(name, git2::BranchType::Local)
1823 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1824
1825 branch
1826 .delete()
1827 .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1828
1829 debug!("Successfully deleted branch '{}'", name);
1830 Ok(())
1831 }
1832
1833 pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1835 let from_oid = self
1836 .repo
1837 .refname_to_id(&format!("refs/heads/{from}"))
1838 .or_else(|_| Oid::from_str(from))
1839 .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1840
1841 let to_oid = self
1842 .repo
1843 .refname_to_id(&format!("refs/heads/{to}"))
1844 .or_else(|_| Oid::from_str(to))
1845 .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1846
1847 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1848
1849 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1850 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1851
1852 let mut commits = Vec::new();
1853 for oid in revwalk {
1854 let oid = oid.map_err(CascadeError::Git)?;
1855 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1856 commits.push(commit);
1857 }
1858
1859 Ok(commits)
1860 }
1861
1862 pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1865 self.force_push_branch_with_options(target_branch, source_branch, false)
1866 }
1867
1868 pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1870 self.force_push_branch_with_options(target_branch, source_branch, true)
1871 }
1872
1873 fn force_push_branch_with_options(
1875 &self,
1876 target_branch: &str,
1877 source_branch: &str,
1878 force_unsafe: bool,
1879 ) -> Result<()> {
1880 debug!(
1881 "Force pushing {} content to {} to preserve PR history",
1882 source_branch, target_branch
1883 );
1884
1885 if !force_unsafe {
1887 let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1888 if let Some(backup_info) = safety_result {
1889 self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1891 debug!("Created backup branch: {}", backup_info.backup_branch_name);
1892 }
1893 }
1894
1895 let source_ref = self
1897 .repo
1898 .find_reference(&format!("refs/heads/{source_branch}"))
1899 .map_err(|e| {
1900 CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1901 })?;
1902 let _source_commit = source_ref.peel_to_commit().map_err(|e| {
1903 CascadeError::config(format!(
1904 "Failed to get commit for source branch {source_branch}: {e}"
1905 ))
1906 })?;
1907
1908 let mut remote = self
1910 .repo
1911 .find_remote("origin")
1912 .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1913
1914 let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
1916
1917 let callbacks = self.configure_remote_callbacks()?;
1919
1920 let mut push_options = git2::PushOptions::new();
1922 push_options.remote_callbacks(callbacks);
1923
1924 match remote.push(&[&refspec], Some(&mut push_options)) {
1925 Ok(_) => {}
1926 Err(e) => {
1927 if self.should_retry_with_default_credentials(&e) {
1928 tracing::debug!(
1929 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1930 e.class(), e.code(), e
1931 );
1932
1933 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1935 let mut push_options = git2::PushOptions::new();
1936 push_options.remote_callbacks(callbacks);
1937
1938 match remote.push(&[&refspec], Some(&mut push_options)) {
1939 Ok(_) => {
1940 tracing::debug!("Force push succeeded with DefaultCredentials");
1941 }
1943 Err(retry_error) => {
1944 tracing::debug!(
1945 "DefaultCredentials retry failed: {}, falling back to git CLI",
1946 retry_error
1947 );
1948 return self.force_push_with_git_cli(target_branch);
1949 }
1950 }
1951 } else if self.should_fallback_to_git_cli(&e) {
1952 tracing::debug!(
1953 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
1954 e.class(), e.code(), e
1955 );
1956 return self.force_push_with_git_cli(target_branch);
1957 } else {
1958 return Err(CascadeError::config(format!(
1959 "Failed to force push {target_branch}: {e}"
1960 )));
1961 }
1962 }
1963 }
1964
1965 info!(
1966 "✅ Successfully force pushed {} to preserve PR history",
1967 target_branch
1968 );
1969 Ok(())
1970 }
1971
1972 fn check_force_push_safety_enhanced(
1975 &self,
1976 target_branch: &str,
1977 ) -> Result<Option<ForceBackupInfo>> {
1978 match self.fetch() {
1980 Ok(_) => {}
1981 Err(e) => {
1982 warn!("Could not fetch latest changes for safety check: {}", e);
1984 }
1985 }
1986
1987 let remote_ref = format!("refs/remotes/origin/{target_branch}");
1989 let local_ref = format!("refs/heads/{target_branch}");
1990
1991 let local_commit = match self.repo.find_reference(&local_ref) {
1993 Ok(reference) => reference.peel_to_commit().ok(),
1994 Err(_) => None,
1995 };
1996
1997 let remote_commit = match self.repo.find_reference(&remote_ref) {
1998 Ok(reference) => reference.peel_to_commit().ok(),
1999 Err(_) => None,
2000 };
2001
2002 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2004 if local.id() != remote.id() {
2005 let merge_base_oid = self
2007 .repo
2008 .merge_base(local.id(), remote.id())
2009 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2010
2011 if merge_base_oid != remote.id() {
2013 let commits_to_lose = self.count_commits_between(
2014 &merge_base_oid.to_string(),
2015 &remote.id().to_string(),
2016 )?;
2017
2018 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2020 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2021
2022 debug!(
2023 "Force push to '{}' would overwrite {} commits on remote",
2024 target_branch, commits_to_lose
2025 );
2026
2027 if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
2029 {
2030 info!(
2031 "Non-interactive environment detected, proceeding with backup creation"
2032 );
2033 return Ok(Some(ForceBackupInfo {
2034 backup_branch_name,
2035 remote_commit_id: remote.id().to_string(),
2036 commits_that_would_be_lost: commits_to_lose,
2037 }));
2038 }
2039
2040 println!();
2042 Output::warning("FORCE PUSH WARNING");
2043 println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
2044
2045 match self
2047 .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
2048 {
2049 Ok(commits) => {
2050 println!();
2051 println!("Commits that would be lost:");
2052 for (i, commit) in commits.iter().take(5).enumerate() {
2053 let short_hash = &commit.id().to_string()[..8];
2054 let summary = commit.summary().unwrap_or("<no message>");
2055 println!(" {}. {} - {}", i + 1, short_hash, summary);
2056 }
2057 if commits.len() > 5 {
2058 println!(" ... and {} more commits", commits.len() - 5);
2059 }
2060 }
2061 Err(_) => {
2062 println!(" (Unable to retrieve commit details)");
2063 }
2064 }
2065
2066 println!();
2067 Output::info(format!(
2068 "A backup branch '{backup_branch_name}' will be created before proceeding."
2069 ));
2070
2071 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2072 .with_prompt("Do you want to proceed with the force push?")
2073 .default(false)
2074 .interact()
2075 .map_err(|e| {
2076 CascadeError::config(format!("Failed to get user confirmation: {e}"))
2077 })?;
2078
2079 if !confirmed {
2080 return Err(CascadeError::config(
2081 "Force push cancelled by user. Use --force to bypass this check."
2082 .to_string(),
2083 ));
2084 }
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 }
2094
2095 Ok(None)
2096 }
2097
2098 fn is_likely_rebase_scenario(&self, local_oid: &str, remote_oid: &str) -> bool {
2101 let local_oid_parsed = match git2::Oid::from_str(local_oid) {
2103 Ok(oid) => oid,
2104 Err(_) => return false,
2105 };
2106
2107 let remote_oid_parsed = match git2::Oid::from_str(remote_oid) {
2108 Ok(oid) => oid,
2109 Err(_) => return false,
2110 };
2111
2112 let local_commit = match self.repo.find_commit(local_oid_parsed) {
2113 Ok(c) => c,
2114 Err(_) => return false,
2115 };
2116
2117 let remote_commit = match self.repo.find_commit(remote_oid_parsed) {
2118 Ok(c) => c,
2119 Err(_) => return false,
2120 };
2121
2122 let local_msg = local_commit.message().unwrap_or("");
2124 let remote_msg = remote_commit.message().unwrap_or("");
2125
2126 if local_msg == remote_msg {
2128 return true;
2129 }
2130
2131 let local_count = local_commit.parent_count();
2134 let remote_count = remote_commit.parent_count();
2135
2136 if local_count == remote_count && local_count > 0 {
2137 let mut local_walker = match self.repo.revwalk() {
2139 Ok(w) => w,
2140 Err(_) => return false,
2141 };
2142 let mut remote_walker = match self.repo.revwalk() {
2143 Ok(w) => w,
2144 Err(_) => return false,
2145 };
2146
2147 if local_walker.push(local_commit.id()).is_err() {
2148 return false;
2149 }
2150 if remote_walker.push(remote_commit.id()).is_err() {
2151 return false;
2152 }
2153
2154 let local_messages: Vec<String> = local_walker
2155 .take(5) .filter_map(|oid| {
2157 self.repo
2158 .find_commit(oid.ok()?)
2159 .ok()?
2160 .message()
2161 .map(|s| s.to_string())
2162 })
2163 .collect();
2164
2165 let remote_messages: Vec<String> = remote_walker
2166 .take(5)
2167 .filter_map(|oid| {
2168 self.repo
2169 .find_commit(oid.ok()?)
2170 .ok()?
2171 .message()
2172 .map(|s| s.to_string())
2173 })
2174 .collect();
2175
2176 let matches = local_messages
2178 .iter()
2179 .zip(remote_messages.iter())
2180 .filter(|(l, r)| l == r)
2181 .count();
2182
2183 return matches >= local_messages.len() / 2;
2184 }
2185
2186 false
2187 }
2188
2189 fn check_force_push_safety_auto(&self, target_branch: &str) -> Result<Option<ForceBackupInfo>> {
2192 match self.fetch() {
2194 Ok(_) => {}
2195 Err(e) => {
2196 warn!("Could not fetch latest changes for safety check: {}", e);
2197 }
2198 }
2199
2200 let remote_ref = format!("refs/remotes/origin/{target_branch}");
2202 let local_ref = format!("refs/heads/{target_branch}");
2203
2204 let local_commit = match self.repo.find_reference(&local_ref) {
2206 Ok(reference) => reference.peel_to_commit().ok(),
2207 Err(_) => None,
2208 };
2209
2210 let remote_commit = match self.repo.find_reference(&remote_ref) {
2211 Ok(reference) => reference.peel_to_commit().ok(),
2212 Err(_) => None,
2213 };
2214
2215 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
2217 if local.id() != remote.id() {
2218 let merge_base_oid = self
2220 .repo
2221 .merge_base(local.id(), remote.id())
2222 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
2223
2224 if merge_base_oid != remote.id() {
2226 let is_likely_rebase = self.is_likely_rebase_scenario(
2229 &local.id().to_string(),
2230 &remote.id().to_string(),
2231 );
2232
2233 if is_likely_rebase {
2234 debug!(
2235 "Detected rebase scenario for '{}' - skipping backup (commit content preserved)",
2236 target_branch
2237 );
2238 return Ok(None);
2240 }
2241
2242 let commits_to_lose = self.count_commits_between(
2243 &merge_base_oid.to_string(),
2244 &remote.id().to_string(),
2245 )?;
2246
2247 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2249 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
2250
2251 debug!(
2252 "Auto-creating backup for force push to '{}' (would overwrite {} commits)",
2253 target_branch, commits_to_lose
2254 );
2255
2256 return Ok(Some(ForceBackupInfo {
2258 backup_branch_name,
2259 remote_commit_id: remote.id().to_string(),
2260 commits_that_would_be_lost: commits_to_lose,
2261 }));
2262 }
2263 }
2264 }
2265
2266 Ok(None)
2267 }
2268
2269 fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
2271 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
2272 let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
2273
2274 let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
2276 CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
2277 })?;
2278
2279 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
2281 CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
2282 })?;
2283
2284 self.repo
2286 .branch(&backup_branch_name, &commit, false)
2287 .map_err(|e| {
2288 CascadeError::config(format!(
2289 "Failed to create backup branch {backup_branch_name}: {e}"
2290 ))
2291 })?;
2292
2293 debug!(
2294 "Created backup branch '{}' pointing to {}",
2295 backup_branch_name,
2296 &remote_commit_id[..8]
2297 );
2298 Ok(())
2299 }
2300
2301 fn check_branch_deletion_safety(
2304 &self,
2305 branch_name: &str,
2306 ) -> Result<Option<BranchDeletionSafety>> {
2307 match self.fetch() {
2309 Ok(_) => {}
2310 Err(e) => {
2311 warn!(
2312 "Could not fetch latest changes for branch deletion safety check: {}",
2313 e
2314 );
2315 }
2316 }
2317
2318 let branch = self
2320 .repo
2321 .find_branch(branch_name, git2::BranchType::Local)
2322 .map_err(|e| {
2323 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2324 })?;
2325
2326 let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2327 CascadeError::branch(format!(
2328 "Could not get commit for branch '{branch_name}': {e}"
2329 ))
2330 })?;
2331
2332 let main_branch_name = self.detect_main_branch()?;
2334
2335 let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2337
2338 let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2340
2341 let mut unpushed_commits = Vec::new();
2342
2343 if let Some(ref remote_branch) = remote_tracking_branch {
2345 match self.get_commits_between(remote_branch, branch_name) {
2346 Ok(commits) => {
2347 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2348 }
2349 Err(_) => {
2350 if !is_merged_to_main {
2352 if let Ok(commits) =
2353 self.get_commits_between(&main_branch_name, branch_name)
2354 {
2355 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2356 }
2357 }
2358 }
2359 }
2360 } else if !is_merged_to_main {
2361 if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2363 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2364 }
2365 }
2366
2367 if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2369 {
2370 Ok(Some(BranchDeletionSafety {
2371 unpushed_commits,
2372 remote_tracking_branch,
2373 is_merged_to_main,
2374 main_branch_name,
2375 }))
2376 } else {
2377 Ok(None)
2378 }
2379 }
2380
2381 fn handle_branch_deletion_confirmation(
2383 &self,
2384 branch_name: &str,
2385 safety_info: &BranchDeletionSafety,
2386 ) -> Result<()> {
2387 if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2389 return Err(CascadeError::branch(
2390 format!(
2391 "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2392 safety_info.unpushed_commits.len()
2393 )
2394 ));
2395 }
2396
2397 println!();
2399 Output::warning("BRANCH DELETION WARNING");
2400 println!("Branch '{branch_name}' has potential issues:");
2401
2402 if !safety_info.unpushed_commits.is_empty() {
2403 println!(
2404 "\n🔍 Unpushed commits ({} total):",
2405 safety_info.unpushed_commits.len()
2406 );
2407
2408 for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2410 if let Ok(oid) = Oid::from_str(commit_id) {
2411 if let Ok(commit) = self.repo.find_commit(oid) {
2412 let short_hash = &commit_id[..8];
2413 let summary = commit.summary().unwrap_or("<no message>");
2414 println!(" {}. {} - {}", i + 1, short_hash, summary);
2415 }
2416 }
2417 }
2418
2419 if safety_info.unpushed_commits.len() > 5 {
2420 println!(
2421 " ... and {} more commits",
2422 safety_info.unpushed_commits.len() - 5
2423 );
2424 }
2425 }
2426
2427 if !safety_info.is_merged_to_main {
2428 println!("\n📋 Branch status:");
2429 println!(" • Not merged to '{}'", safety_info.main_branch_name);
2430 if let Some(ref remote) = safety_info.remote_tracking_branch {
2431 println!(" • Remote tracking branch: {remote}");
2432 } else {
2433 println!(" • No remote tracking branch");
2434 }
2435 }
2436
2437 println!("\n💡 Safer alternatives:");
2438 if !safety_info.unpushed_commits.is_empty() {
2439 if let Some(ref _remote) = safety_info.remote_tracking_branch {
2440 println!(" • Push commits first: git push origin {branch_name}");
2441 } else {
2442 println!(" • Create and push to remote: git push -u origin {branch_name}");
2443 }
2444 }
2445 if !safety_info.is_merged_to_main {
2446 println!(
2447 " • Merge to {} first: git checkout {} && git merge {branch_name}",
2448 safety_info.main_branch_name, safety_info.main_branch_name
2449 );
2450 }
2451
2452 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2453 .with_prompt("Do you want to proceed with deleting this branch?")
2454 .default(false)
2455 .interact()
2456 .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2457
2458 if !confirmed {
2459 return Err(CascadeError::branch(
2460 "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2461 ));
2462 }
2463
2464 Ok(())
2465 }
2466
2467 pub fn detect_main_branch(&self) -> Result<String> {
2469 let main_candidates = ["main", "master", "develop", "trunk"];
2470
2471 for candidate in &main_candidates {
2472 if self
2473 .repo
2474 .find_branch(candidate, git2::BranchType::Local)
2475 .is_ok()
2476 {
2477 return Ok(candidate.to_string());
2478 }
2479 }
2480
2481 if let Ok(head) = self.repo.head() {
2483 if let Some(name) = head.shorthand() {
2484 return Ok(name.to_string());
2485 }
2486 }
2487
2488 Ok("main".to_string())
2490 }
2491
2492 fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2494 match self.get_commits_between(main_branch, branch_name) {
2496 Ok(commits) => Ok(commits.is_empty()),
2497 Err(_) => {
2498 Ok(false)
2500 }
2501 }
2502 }
2503
2504 fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2506 let remote_candidates = [
2508 format!("origin/{branch_name}"),
2509 format!("remotes/origin/{branch_name}"),
2510 ];
2511
2512 for candidate in &remote_candidates {
2513 if self
2514 .repo
2515 .find_reference(&format!(
2516 "refs/remotes/{}",
2517 candidate.replace("remotes/", "")
2518 ))
2519 .is_ok()
2520 {
2521 return Some(candidate.clone());
2522 }
2523 }
2524
2525 None
2526 }
2527
2528 fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2530 let is_dirty = self.is_dirty()?;
2532 if !is_dirty {
2533 return Ok(None);
2535 }
2536
2537 let current_branch = self.get_current_branch().ok();
2539
2540 let modified_files = self.get_modified_files()?;
2542 let staged_files = self.get_staged_files()?;
2543 let untracked_files = self.get_untracked_files()?;
2544
2545 let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2546
2547 if has_uncommitted_changes || !untracked_files.is_empty() {
2548 return Ok(Some(CheckoutSafety {
2549 has_uncommitted_changes,
2550 modified_files,
2551 staged_files,
2552 untracked_files,
2553 stash_created: None,
2554 current_branch,
2555 }));
2556 }
2557
2558 Ok(None)
2559 }
2560
2561 fn handle_checkout_confirmation(
2563 &self,
2564 target: &str,
2565 safety_info: &CheckoutSafety,
2566 ) -> Result<()> {
2567 let is_ci = std::env::var("CI").is_ok();
2569 let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2570 let is_non_interactive = is_ci || no_confirm;
2571
2572 if is_non_interactive {
2573 return Err(CascadeError::branch(
2574 format!(
2575 "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2576 )
2577 ));
2578 }
2579
2580 println!("\nCHECKOUT WARNING");
2582 println!("Attempting to checkout: {}", target);
2583 println!("You have uncommitted changes that could be lost:");
2584
2585 if !safety_info.modified_files.is_empty() {
2586 println!("\nModified files ({}):", safety_info.modified_files.len());
2587 for file in safety_info.modified_files.iter().take(10) {
2588 println!(" - {file}");
2589 }
2590 if safety_info.modified_files.len() > 10 {
2591 println!(" ... and {} more", safety_info.modified_files.len() - 10);
2592 }
2593 }
2594
2595 if !safety_info.staged_files.is_empty() {
2596 println!("\nStaged files ({}):", safety_info.staged_files.len());
2597 for file in safety_info.staged_files.iter().take(10) {
2598 println!(" - {file}");
2599 }
2600 if safety_info.staged_files.len() > 10 {
2601 println!(" ... and {} more", safety_info.staged_files.len() - 10);
2602 }
2603 }
2604
2605 if !safety_info.untracked_files.is_empty() {
2606 println!("\nUntracked files ({}):", safety_info.untracked_files.len());
2607 for file in safety_info.untracked_files.iter().take(5) {
2608 println!(" - {file}");
2609 }
2610 if safety_info.untracked_files.len() > 5 {
2611 println!(" ... and {} more", safety_info.untracked_files.len() - 5);
2612 }
2613 }
2614
2615 println!("\nOptions:");
2616 println!("1. Stash changes and checkout (recommended)");
2617 println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2618 println!("3. Cancel checkout");
2619
2620 let selection = Select::with_theme(&ColorfulTheme::default())
2622 .with_prompt("Choose an action")
2623 .items(&[
2624 "Stash changes and checkout (recommended)",
2625 "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2626 "Cancel checkout",
2627 ])
2628 .default(0)
2629 .interact()
2630 .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2631
2632 match selection {
2633 0 => {
2634 let stash_message = format!(
2636 "Auto-stash before checkout to {} at {}",
2637 target,
2638 chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2639 );
2640
2641 match self.create_stash(&stash_message) {
2642 Ok(stash_id) => {
2643 println!("✅ Created stash: {stash_message} ({stash_id})");
2644 println!("💡 You can restore with: git stash pop");
2645 }
2646 Err(e) => {
2647 println!("❌ Failed to create stash: {e}");
2648
2649 use dialoguer::Select;
2651 let stash_failed_options = vec![
2652 "Commit staged changes and proceed",
2653 "Force checkout (WILL LOSE CHANGES)",
2654 "Cancel and handle manually",
2655 ];
2656
2657 let stash_selection = Select::with_theme(&ColorfulTheme::default())
2658 .with_prompt("Stash failed. What would you like to do?")
2659 .items(&stash_failed_options)
2660 .default(0)
2661 .interact()
2662 .map_err(|e| {
2663 CascadeError::branch(format!("Could not get user selection: {e}"))
2664 })?;
2665
2666 match stash_selection {
2667 0 => {
2668 let staged_files = self.get_staged_files()?;
2670 if !staged_files.is_empty() {
2671 println!(
2672 "📝 Committing {} staged files...",
2673 staged_files.len()
2674 );
2675 match self
2676 .commit_staged_changes("WIP: Auto-commit before checkout")
2677 {
2678 Ok(Some(commit_hash)) => {
2679 println!(
2680 "✅ Committed staged changes as {}",
2681 &commit_hash[..8]
2682 );
2683 println!("💡 You can undo with: git reset HEAD~1");
2684 }
2685 Ok(None) => {
2686 println!("ℹ️ No staged changes found to commit");
2687 }
2688 Err(commit_err) => {
2689 println!(
2690 "❌ Failed to commit staged changes: {commit_err}"
2691 );
2692 return Err(CascadeError::branch(
2693 "Could not commit staged changes".to_string(),
2694 ));
2695 }
2696 }
2697 } else {
2698 println!("ℹ️ No staged changes to commit");
2699 }
2700 }
2701 1 => {
2702 Output::warning("Proceeding with force checkout - uncommitted changes will be lost!");
2704 }
2705 2 => {
2706 return Err(CascadeError::branch(
2708 "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2709 ));
2710 }
2711 _ => unreachable!(),
2712 }
2713 }
2714 }
2715 }
2716 1 => {
2717 Output::warning(
2719 "Proceeding with force checkout - uncommitted changes will be lost!",
2720 );
2721 }
2722 2 => {
2723 return Err(CascadeError::branch(
2725 "Checkout cancelled by user".to_string(),
2726 ));
2727 }
2728 _ => unreachable!(),
2729 }
2730
2731 Ok(())
2732 }
2733
2734 fn create_stash(&self, message: &str) -> Result<String> {
2736 tracing::info!("Creating stash: {}", message);
2737
2738 let output = std::process::Command::new("git")
2740 .args(["stash", "push", "-m", message])
2741 .current_dir(&self.path)
2742 .output()
2743 .map_err(|e| {
2744 CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2745 })?;
2746
2747 if output.status.success() {
2748 let stdout = String::from_utf8_lossy(&output.stdout);
2749
2750 let stash_id = if stdout.contains("Saved working directory") {
2752 let stash_list_output = std::process::Command::new("git")
2754 .args(["stash", "list", "-n", "1", "--format=%H"])
2755 .current_dir(&self.path)
2756 .output()
2757 .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2758
2759 if stash_list_output.status.success() {
2760 String::from_utf8_lossy(&stash_list_output.stdout)
2761 .trim()
2762 .to_string()
2763 } else {
2764 "stash@{0}".to_string() }
2766 } else {
2767 "stash@{0}".to_string() };
2769
2770 tracing::info!("✅ Created stash: {} ({})", message, stash_id);
2771 Ok(stash_id)
2772 } else {
2773 let stderr = String::from_utf8_lossy(&output.stderr);
2774 let stdout = String::from_utf8_lossy(&output.stdout);
2775
2776 if stderr.contains("No local changes to save")
2778 || stdout.contains("No local changes to save")
2779 {
2780 return Err(CascadeError::branch("No local changes to save".to_string()));
2781 }
2782
2783 Err(CascadeError::branch(format!(
2784 "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2785 output.status, stderr, stdout
2786 )))
2787 }
2788 }
2789
2790 fn get_modified_files(&self) -> Result<Vec<String>> {
2792 let mut opts = git2::StatusOptions::new();
2793 opts.include_untracked(false).include_ignored(false);
2794
2795 let statuses = self
2796 .repo
2797 .statuses(Some(&mut opts))
2798 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2799
2800 let mut modified_files = Vec::new();
2801 for status in statuses.iter() {
2802 let flags = status.status();
2803 if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2804 {
2805 if let Some(path) = status.path() {
2806 modified_files.push(path.to_string());
2807 }
2808 }
2809 }
2810
2811 Ok(modified_files)
2812 }
2813
2814 pub fn get_staged_files(&self) -> Result<Vec<String>> {
2816 let mut opts = git2::StatusOptions::new();
2817 opts.include_untracked(false).include_ignored(false);
2818
2819 let statuses = self
2820 .repo
2821 .statuses(Some(&mut opts))
2822 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2823
2824 let mut staged_files = Vec::new();
2825 for status in statuses.iter() {
2826 let flags = status.status();
2827 if flags.contains(git2::Status::INDEX_MODIFIED)
2828 || flags.contains(git2::Status::INDEX_NEW)
2829 || flags.contains(git2::Status::INDEX_DELETED)
2830 {
2831 if let Some(path) = status.path() {
2832 staged_files.push(path.to_string());
2833 }
2834 }
2835 }
2836
2837 Ok(staged_files)
2838 }
2839
2840 fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2842 let commits = self.get_commits_between(from, to)?;
2843 Ok(commits.len())
2844 }
2845
2846 pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2848 if let Ok(oid) = Oid::from_str(reference) {
2850 if let Ok(commit) = self.repo.find_commit(oid) {
2851 return Ok(commit);
2852 }
2853 }
2854
2855 let obj = self.repo.revparse_single(reference).map_err(|e| {
2857 CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2858 })?;
2859
2860 obj.peel_to_commit().map_err(|e| {
2861 CascadeError::branch(format!(
2862 "Reference '{reference}' does not point to a commit: {e}"
2863 ))
2864 })
2865 }
2866
2867 pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2869 let target_commit = self.resolve_reference(target_ref)?;
2870
2871 self.repo
2872 .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2873 .map_err(CascadeError::Git)?;
2874
2875 Ok(())
2876 }
2877
2878 pub fn reset_to_head(&self) -> Result<()> {
2881 tracing::debug!("Resetting working directory and index to HEAD");
2882
2883 let head = self.repo.head().map_err(CascadeError::Git)?;
2884 let head_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
2885
2886 let mut checkout_builder = git2::build::CheckoutBuilder::new();
2888 checkout_builder.force(); checkout_builder.remove_untracked(false); self.repo
2892 .reset(
2893 head_commit.as_object(),
2894 git2::ResetType::Hard,
2895 Some(&mut checkout_builder),
2896 )
2897 .map_err(CascadeError::Git)?;
2898
2899 tracing::debug!("Successfully reset working directory to HEAD");
2900 Ok(())
2901 }
2902
2903 pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2905 let oid = Oid::from_str(commit_hash).map_err(|e| {
2906 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2907 })?;
2908
2909 let branches = self
2911 .repo
2912 .branches(Some(git2::BranchType::Local))
2913 .map_err(CascadeError::Git)?;
2914
2915 for branch_result in branches {
2916 let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2917
2918 if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2919 if let Ok(branch_head) = branch.get().peel_to_commit() {
2921 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2923 revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2924
2925 for commit_oid in revwalk {
2926 let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2927 if commit_oid == oid {
2928 return Ok(branch_name.to_string());
2929 }
2930 }
2931 }
2932 }
2933 }
2934
2935 Err(CascadeError::branch(format!(
2937 "Commit {commit_hash} not found in any local branch"
2938 )))
2939 }
2940
2941 pub async fn fetch_async(&self) -> Result<()> {
2945 let repo_path = self.path.clone();
2946 crate::utils::async_ops::run_git_operation(move || {
2947 let repo = GitRepository::open(&repo_path)?;
2948 repo.fetch()
2949 })
2950 .await
2951 }
2952
2953 pub async fn pull_async(&self, branch: &str) -> Result<()> {
2955 let repo_path = self.path.clone();
2956 let branch_name = branch.to_string();
2957 crate::utils::async_ops::run_git_operation(move || {
2958 let repo = GitRepository::open(&repo_path)?;
2959 repo.pull(&branch_name)
2960 })
2961 .await
2962 }
2963
2964 pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
2966 let repo_path = self.path.clone();
2967 let branch = branch_name.to_string();
2968 crate::utils::async_ops::run_git_operation(move || {
2969 let repo = GitRepository::open(&repo_path)?;
2970 repo.push(&branch)
2971 })
2972 .await
2973 }
2974
2975 pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
2977 let repo_path = self.path.clone();
2978 let hash = commit_hash.to_string();
2979 crate::utils::async_ops::run_git_operation(move || {
2980 let repo = GitRepository::open(&repo_path)?;
2981 repo.cherry_pick(&hash)
2982 })
2983 .await
2984 }
2985
2986 pub async fn get_commit_hashes_between_async(
2988 &self,
2989 from: &str,
2990 to: &str,
2991 ) -> Result<Vec<String>> {
2992 let repo_path = self.path.clone();
2993 let from_str = from.to_string();
2994 let to_str = to.to_string();
2995 crate::utils::async_ops::run_git_operation(move || {
2996 let repo = GitRepository::open(&repo_path)?;
2997 let commits = repo.get_commits_between(&from_str, &to_str)?;
2998 Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
2999 })
3000 .await
3001 }
3002
3003 pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
3005 info!(
3006 "Resetting branch '{}' to commit {}",
3007 branch_name,
3008 &commit_hash[..8]
3009 );
3010
3011 let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
3013 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
3014 })?;
3015
3016 let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
3017 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
3018 })?;
3019
3020 let _branch = self
3022 .repo
3023 .find_branch(branch_name, git2::BranchType::Local)
3024 .map_err(|e| {
3025 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
3026 })?;
3027
3028 let branch_ref_name = format!("refs/heads/{branch_name}");
3030 self.repo
3031 .reference(
3032 &branch_ref_name,
3033 target_oid,
3034 true,
3035 &format!("Reset {branch_name} to {commit_hash}"),
3036 )
3037 .map_err(|e| {
3038 CascadeError::branch(format!(
3039 "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
3040 ))
3041 })?;
3042
3043 tracing::info!(
3044 "Successfully reset branch '{}' to commit {}",
3045 branch_name,
3046 &commit_hash[..8]
3047 );
3048 Ok(())
3049 }
3050
3051 pub fn detect_parent_branch(&self) -> Result<Option<String>> {
3053 let current_branch = self.get_current_branch()?;
3054
3055 if let Ok(Some(upstream)) = self.get_upstream_branch(¤t_branch) {
3057 if let Some(branch_name) = upstream.split('/').nth(1) {
3059 if self.branch_exists(branch_name) {
3060 tracing::debug!(
3061 "Detected parent branch '{}' from upstream tracking",
3062 branch_name
3063 );
3064 return Ok(Some(branch_name.to_string()));
3065 }
3066 }
3067 }
3068
3069 if let Ok(default_branch) = self.detect_main_branch() {
3071 if current_branch != default_branch {
3073 tracing::debug!(
3074 "Detected parent branch '{}' as repository default",
3075 default_branch
3076 );
3077 return Ok(Some(default_branch));
3078 }
3079 }
3080
3081 if let Ok(branches) = self.list_branches() {
3084 let current_commit = self.get_head_commit()?;
3085 let current_commit_hash = current_commit.id().to_string();
3086 let current_oid = current_commit.id();
3087
3088 let mut best_candidate = None;
3089 let mut best_distance = usize::MAX;
3090
3091 for branch in branches {
3092 if branch == current_branch
3094 || branch.contains("-v")
3095 || branch.ends_with("-v2")
3096 || branch.ends_with("-v3")
3097 {
3098 continue;
3099 }
3100
3101 if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
3102 if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
3103 if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
3105 if let Ok(distance) = self.count_commits_between(
3107 &merge_base_oid.to_string(),
3108 ¤t_commit_hash,
3109 ) {
3110 let is_likely_base = self.is_likely_base_branch(&branch);
3113 let adjusted_distance = if is_likely_base {
3114 distance
3115 } else {
3116 distance + 1000
3117 };
3118
3119 if adjusted_distance < best_distance {
3120 best_distance = adjusted_distance;
3121 best_candidate = Some(branch.clone());
3122 }
3123 }
3124 }
3125 }
3126 }
3127 }
3128
3129 if let Some(ref candidate) = best_candidate {
3130 tracing::debug!(
3131 "Detected parent branch '{}' with distance {}",
3132 candidate,
3133 best_distance
3134 );
3135 }
3136
3137 return Ok(best_candidate);
3138 }
3139
3140 tracing::debug!("Could not detect parent branch for '{}'", current_branch);
3141 Ok(None)
3142 }
3143
3144 fn is_likely_base_branch(&self, branch_name: &str) -> bool {
3146 let base_patterns = [
3147 "main",
3148 "master",
3149 "develop",
3150 "dev",
3151 "development",
3152 "staging",
3153 "stage",
3154 "release",
3155 "production",
3156 "prod",
3157 ];
3158
3159 base_patterns.contains(&branch_name)
3160 }
3161}
3162
3163#[cfg(test)]
3164mod tests {
3165 use super::*;
3166 use std::process::Command;
3167 use tempfile::TempDir;
3168
3169 fn create_test_repo() -> (TempDir, PathBuf) {
3170 let temp_dir = TempDir::new().unwrap();
3171 let repo_path = temp_dir.path().to_path_buf();
3172
3173 Command::new("git")
3175 .args(["init"])
3176 .current_dir(&repo_path)
3177 .output()
3178 .unwrap();
3179 Command::new("git")
3180 .args(["config", "user.name", "Test"])
3181 .current_dir(&repo_path)
3182 .output()
3183 .unwrap();
3184 Command::new("git")
3185 .args(["config", "user.email", "test@test.com"])
3186 .current_dir(&repo_path)
3187 .output()
3188 .unwrap();
3189
3190 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
3192 Command::new("git")
3193 .args(["add", "."])
3194 .current_dir(&repo_path)
3195 .output()
3196 .unwrap();
3197 Command::new("git")
3198 .args(["commit", "-m", "Initial commit"])
3199 .current_dir(&repo_path)
3200 .output()
3201 .unwrap();
3202
3203 (temp_dir, repo_path)
3204 }
3205
3206 fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
3207 let file_path = repo_path.join(filename);
3208 std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
3209
3210 Command::new("git")
3211 .args(["add", filename])
3212 .current_dir(repo_path)
3213 .output()
3214 .unwrap();
3215 Command::new("git")
3216 .args(["commit", "-m", message])
3217 .current_dir(repo_path)
3218 .output()
3219 .unwrap();
3220 }
3221
3222 #[test]
3223 fn test_repository_info() {
3224 let (_temp_dir, repo_path) = create_test_repo();
3225 let repo = GitRepository::open(&repo_path).unwrap();
3226
3227 let info = repo.get_info().unwrap();
3228 assert!(!info.is_dirty); assert!(
3230 info.head_branch == Some("master".to_string())
3231 || info.head_branch == Some("main".to_string()),
3232 "Expected default branch to be 'master' or 'main', got {:?}",
3233 info.head_branch
3234 );
3235 assert!(info.head_commit.is_some()); assert!(info.untracked_files.is_empty()); }
3238
3239 #[test]
3240 fn test_force_push_branch_basic() {
3241 let (_temp_dir, repo_path) = create_test_repo();
3242 let repo = GitRepository::open(&repo_path).unwrap();
3243
3244 let default_branch = repo.get_current_branch().unwrap();
3246
3247 create_commit(&repo_path, "Feature commit 1", "feature1.rs");
3249 Command::new("git")
3250 .args(["checkout", "-b", "source-branch"])
3251 .current_dir(&repo_path)
3252 .output()
3253 .unwrap();
3254 create_commit(&repo_path, "Feature commit 2", "feature2.rs");
3255
3256 Command::new("git")
3258 .args(["checkout", &default_branch])
3259 .current_dir(&repo_path)
3260 .output()
3261 .unwrap();
3262 Command::new("git")
3263 .args(["checkout", "-b", "target-branch"])
3264 .current_dir(&repo_path)
3265 .output()
3266 .unwrap();
3267 create_commit(&repo_path, "Target commit", "target.rs");
3268
3269 let result = repo.force_push_branch("target-branch", "source-branch");
3271
3272 assert!(result.is_ok() || result.is_err()); }
3276
3277 #[test]
3278 fn test_force_push_branch_nonexistent_branches() {
3279 let (_temp_dir, repo_path) = create_test_repo();
3280 let repo = GitRepository::open(&repo_path).unwrap();
3281
3282 let default_branch = repo.get_current_branch().unwrap();
3284
3285 let result = repo.force_push_branch("target", "nonexistent-source");
3287 assert!(result.is_err());
3288
3289 let result = repo.force_push_branch("nonexistent-target", &default_branch);
3291 assert!(result.is_err());
3292 }
3293
3294 #[test]
3295 fn test_force_push_workflow_simulation() {
3296 let (_temp_dir, repo_path) = create_test_repo();
3297 let repo = GitRepository::open(&repo_path).unwrap();
3298
3299 Command::new("git")
3302 .args(["checkout", "-b", "feature-auth"])
3303 .current_dir(&repo_path)
3304 .output()
3305 .unwrap();
3306 create_commit(&repo_path, "Add authentication", "auth.rs");
3307
3308 Command::new("git")
3310 .args(["checkout", "-b", "feature-auth-v2"])
3311 .current_dir(&repo_path)
3312 .output()
3313 .unwrap();
3314 create_commit(&repo_path, "Fix auth validation", "auth.rs");
3315
3316 let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3318
3319 match result {
3321 Ok(_) => {
3322 Command::new("git")
3324 .args(["checkout", "feature-auth"])
3325 .current_dir(&repo_path)
3326 .output()
3327 .unwrap();
3328 let log_output = Command::new("git")
3329 .args(["log", "--oneline", "-2"])
3330 .current_dir(&repo_path)
3331 .output()
3332 .unwrap();
3333 let log_str = String::from_utf8_lossy(&log_output.stdout);
3334 assert!(
3335 log_str.contains("Fix auth validation")
3336 || log_str.contains("Add authentication")
3337 );
3338 }
3339 Err(_) => {
3340 }
3343 }
3344 }
3345
3346 #[test]
3347 fn test_branch_operations() {
3348 let (_temp_dir, repo_path) = create_test_repo();
3349 let repo = GitRepository::open(&repo_path).unwrap();
3350
3351 let current = repo.get_current_branch().unwrap();
3353 assert!(
3354 current == "master" || current == "main",
3355 "Expected default branch to be 'master' or 'main', got '{current}'"
3356 );
3357
3358 Command::new("git")
3360 .args(["checkout", "-b", "test-branch"])
3361 .current_dir(&repo_path)
3362 .output()
3363 .unwrap();
3364 let current = repo.get_current_branch().unwrap();
3365 assert_eq!(current, "test-branch");
3366 }
3367
3368 #[test]
3369 fn test_commit_operations() {
3370 let (_temp_dir, repo_path) = create_test_repo();
3371 let repo = GitRepository::open(&repo_path).unwrap();
3372
3373 let head = repo.get_head_commit().unwrap();
3375 assert_eq!(head.message().unwrap().trim(), "Initial commit");
3376
3377 let hash = head.id().to_string();
3379 let same_commit = repo.get_commit(&hash).unwrap();
3380 assert_eq!(head.id(), same_commit.id());
3381 }
3382
3383 #[test]
3384 fn test_checkout_safety_clean_repo() {
3385 let (_temp_dir, repo_path) = create_test_repo();
3386 let repo = GitRepository::open(&repo_path).unwrap();
3387
3388 create_commit(&repo_path, "Second commit", "test.txt");
3390 Command::new("git")
3391 .args(["checkout", "-b", "test-branch"])
3392 .current_dir(&repo_path)
3393 .output()
3394 .unwrap();
3395
3396 let safety_result = repo.check_checkout_safety("main");
3398 assert!(safety_result.is_ok());
3399 assert!(safety_result.unwrap().is_none()); }
3401
3402 #[test]
3403 fn test_checkout_safety_with_modified_files() {
3404 let (_temp_dir, repo_path) = create_test_repo();
3405 let repo = GitRepository::open(&repo_path).unwrap();
3406
3407 Command::new("git")
3409 .args(["checkout", "-b", "test-branch"])
3410 .current_dir(&repo_path)
3411 .output()
3412 .unwrap();
3413
3414 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3416
3417 let safety_result = repo.check_checkout_safety("main");
3419 assert!(safety_result.is_ok());
3420 let safety_info = safety_result.unwrap();
3421 assert!(safety_info.is_some());
3422
3423 let info = safety_info.unwrap();
3424 assert!(!info.modified_files.is_empty());
3425 assert!(info.modified_files.contains(&"README.md".to_string()));
3426 }
3427
3428 #[test]
3429 fn test_unsafe_checkout_methods() {
3430 let (_temp_dir, repo_path) = create_test_repo();
3431 let repo = GitRepository::open(&repo_path).unwrap();
3432
3433 create_commit(&repo_path, "Second commit", "test.txt");
3435 Command::new("git")
3436 .args(["checkout", "-b", "test-branch"])
3437 .current_dir(&repo_path)
3438 .output()
3439 .unwrap();
3440
3441 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3443
3444 let _result = repo.checkout_branch_unsafe("main");
3446 let head_commit = repo.get_head_commit().unwrap();
3451 let commit_hash = head_commit.id().to_string();
3452 let _result = repo.checkout_commit_unsafe(&commit_hash);
3453 }
3455
3456 #[test]
3457 fn test_get_modified_files() {
3458 let (_temp_dir, repo_path) = create_test_repo();
3459 let repo = GitRepository::open(&repo_path).unwrap();
3460
3461 let modified = repo.get_modified_files().unwrap();
3463 assert!(modified.is_empty());
3464
3465 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3467
3468 let modified = repo.get_modified_files().unwrap();
3470 assert_eq!(modified.len(), 1);
3471 assert!(modified.contains(&"README.md".to_string()));
3472 }
3473
3474 #[test]
3475 fn test_get_staged_files() {
3476 let (_temp_dir, repo_path) = create_test_repo();
3477 let repo = GitRepository::open(&repo_path).unwrap();
3478
3479 let staged = repo.get_staged_files().unwrap();
3481 assert!(staged.is_empty());
3482
3483 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3485 Command::new("git")
3486 .args(["add", "staged.txt"])
3487 .current_dir(&repo_path)
3488 .output()
3489 .unwrap();
3490
3491 let staged = repo.get_staged_files().unwrap();
3493 assert_eq!(staged.len(), 1);
3494 assert!(staged.contains(&"staged.txt".to_string()));
3495 }
3496
3497 #[test]
3498 fn test_create_stash_fallback() {
3499 let (_temp_dir, repo_path) = create_test_repo();
3500 let repo = GitRepository::open(&repo_path).unwrap();
3501
3502 let result = repo.create_stash("test stash");
3504
3505 match result {
3507 Ok(stash_id) => {
3508 assert!(!stash_id.is_empty());
3510 assert!(stash_id.contains("stash") || stash_id.len() >= 7); }
3512 Err(error) => {
3513 let error_msg = error.to_string();
3515 assert!(
3516 error_msg.contains("No local changes to save")
3517 || error_msg.contains("git stash push")
3518 );
3519 }
3520 }
3521 }
3522
3523 #[test]
3524 fn test_delete_branch_unsafe() {
3525 let (_temp_dir, repo_path) = create_test_repo();
3526 let repo = GitRepository::open(&repo_path).unwrap();
3527
3528 create_commit(&repo_path, "Second commit", "test.txt");
3530 Command::new("git")
3531 .args(["checkout", "-b", "test-branch"])
3532 .current_dir(&repo_path)
3533 .output()
3534 .unwrap();
3535
3536 create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3538
3539 Command::new("git")
3541 .args(["checkout", "main"])
3542 .current_dir(&repo_path)
3543 .output()
3544 .unwrap();
3545
3546 let result = repo.delete_branch_unsafe("test-branch");
3549 let _ = result; }
3553
3554 #[test]
3555 fn test_force_push_unsafe() {
3556 let (_temp_dir, repo_path) = create_test_repo();
3557 let repo = GitRepository::open(&repo_path).unwrap();
3558
3559 create_commit(&repo_path, "Second commit", "test.txt");
3561 Command::new("git")
3562 .args(["checkout", "-b", "test-branch"])
3563 .current_dir(&repo_path)
3564 .output()
3565 .unwrap();
3566
3567 let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3570 }
3572
3573 #[test]
3574 fn test_cherry_pick_basic() {
3575 let (_temp_dir, repo_path) = create_test_repo();
3576 let repo = GitRepository::open(&repo_path).unwrap();
3577
3578 repo.create_branch("source", None).unwrap();
3580 repo.checkout_branch("source").unwrap();
3581
3582 std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3583 Command::new("git")
3584 .args(["add", "."])
3585 .current_dir(&repo_path)
3586 .output()
3587 .unwrap();
3588
3589 Command::new("git")
3590 .args(["commit", "-m", "Cherry commit"])
3591 .current_dir(&repo_path)
3592 .output()
3593 .unwrap();
3594
3595 let cherry_commit = repo.get_head_commit_hash().unwrap();
3596
3597 Command::new("git")
3600 .args(["checkout", "-"])
3601 .current_dir(&repo_path)
3602 .output()
3603 .unwrap();
3604
3605 repo.create_branch("target", None).unwrap();
3606 repo.checkout_branch("target").unwrap();
3607
3608 let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3610
3611 repo.repo
3613 .find_commit(git2::Oid::from_str(&new_commit).unwrap())
3614 .unwrap();
3615
3616 assert!(
3618 repo_path.join("cherry.txt").exists(),
3619 "Cherry-picked file should exist"
3620 );
3621
3622 repo.checkout_branch("source").unwrap();
3624 let source_head = repo.get_head_commit_hash().unwrap();
3625 assert_eq!(
3626 source_head, cherry_commit,
3627 "Source branch should be unchanged"
3628 );
3629 }
3630
3631 #[test]
3632 fn test_cherry_pick_preserves_commit_message() {
3633 let (_temp_dir, repo_path) = create_test_repo();
3634 let repo = GitRepository::open(&repo_path).unwrap();
3635
3636 repo.create_branch("msg-test", None).unwrap();
3638 repo.checkout_branch("msg-test").unwrap();
3639
3640 std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3641 Command::new("git")
3642 .args(["add", "."])
3643 .current_dir(&repo_path)
3644 .output()
3645 .unwrap();
3646
3647 let commit_msg = "Test: Special commit message\n\nWith body";
3648 Command::new("git")
3649 .args(["commit", "-m", commit_msg])
3650 .current_dir(&repo_path)
3651 .output()
3652 .unwrap();
3653
3654 let original_commit = repo.get_head_commit_hash().unwrap();
3655
3656 Command::new("git")
3658 .args(["checkout", "-"])
3659 .current_dir(&repo_path)
3660 .output()
3661 .unwrap();
3662 let new_commit = repo.cherry_pick(&original_commit).unwrap();
3663
3664 let output = Command::new("git")
3666 .args(["log", "-1", "--format=%B", &new_commit])
3667 .current_dir(&repo_path)
3668 .output()
3669 .unwrap();
3670
3671 let new_msg = String::from_utf8_lossy(&output.stdout);
3672 assert!(
3673 new_msg.contains("Special commit message"),
3674 "Should preserve commit message"
3675 );
3676 }
3677
3678 #[test]
3679 fn test_cherry_pick_handles_conflicts() {
3680 let (_temp_dir, repo_path) = create_test_repo();
3681 let repo = GitRepository::open(&repo_path).unwrap();
3682
3683 std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3685 Command::new("git")
3686 .args(["add", "."])
3687 .current_dir(&repo_path)
3688 .output()
3689 .unwrap();
3690
3691 Command::new("git")
3692 .args(["commit", "-m", "Add conflict file"])
3693 .current_dir(&repo_path)
3694 .output()
3695 .unwrap();
3696
3697 repo.create_branch("conflict-branch", None).unwrap();
3699 repo.checkout_branch("conflict-branch").unwrap();
3700
3701 std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3702 Command::new("git")
3703 .args(["add", "."])
3704 .current_dir(&repo_path)
3705 .output()
3706 .unwrap();
3707
3708 Command::new("git")
3709 .args(["commit", "-m", "Modify conflict file"])
3710 .current_dir(&repo_path)
3711 .output()
3712 .unwrap();
3713
3714 let conflict_commit = repo.get_head_commit_hash().unwrap();
3715
3716 Command::new("git")
3719 .args(["checkout", "-"])
3720 .current_dir(&repo_path)
3721 .output()
3722 .unwrap();
3723 std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3724 Command::new("git")
3725 .args(["add", "."])
3726 .current_dir(&repo_path)
3727 .output()
3728 .unwrap();
3729
3730 Command::new("git")
3731 .args(["commit", "-m", "Different change"])
3732 .current_dir(&repo_path)
3733 .output()
3734 .unwrap();
3735
3736 let result = repo.cherry_pick(&conflict_commit);
3738 assert!(result.is_err(), "Cherry-pick with conflict should fail");
3739 }
3740
3741 #[test]
3742 fn test_reset_to_head_clears_staged_files() {
3743 let (_temp_dir, repo_path) = create_test_repo();
3744 let repo = GitRepository::open(&repo_path).unwrap();
3745
3746 std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3748 std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3749
3750 Command::new("git")
3751 .args(["add", "staged1.txt", "staged2.txt"])
3752 .current_dir(&repo_path)
3753 .output()
3754 .unwrap();
3755
3756 let staged_before = repo.get_staged_files().unwrap();
3758 assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3759
3760 repo.reset_to_head().unwrap();
3762
3763 let staged_after = repo.get_staged_files().unwrap();
3765 assert_eq!(
3766 staged_after.len(),
3767 0,
3768 "Should have no staged files after reset"
3769 );
3770 }
3771
3772 #[test]
3773 fn test_reset_to_head_clears_modified_files() {
3774 let (_temp_dir, repo_path) = create_test_repo();
3775 let repo = GitRepository::open(&repo_path).unwrap();
3776
3777 std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3779
3780 Command::new("git")
3782 .args(["add", "README.md"])
3783 .current_dir(&repo_path)
3784 .output()
3785 .unwrap();
3786
3787 assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3789
3790 repo.reset_to_head().unwrap();
3792
3793 assert!(
3795 !repo.is_dirty().unwrap(),
3796 "Repo should be clean after reset"
3797 );
3798
3799 let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3801 assert_eq!(
3802 content, "# Test",
3803 "File should be restored to original content"
3804 );
3805 }
3806
3807 #[test]
3808 fn test_reset_to_head_preserves_untracked_files() {
3809 let (_temp_dir, repo_path) = create_test_repo();
3810 let repo = GitRepository::open(&repo_path).unwrap();
3811
3812 std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3814
3815 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3817 Command::new("git")
3818 .args(["add", "staged.txt"])
3819 .current_dir(&repo_path)
3820 .output()
3821 .unwrap();
3822
3823 repo.reset_to_head().unwrap();
3825
3826 assert!(
3828 repo_path.join("untracked.txt").exists(),
3829 "Untracked file should be preserved"
3830 );
3831
3832 assert!(
3834 !repo_path.join("staged.txt").exists(),
3835 "Staged but uncommitted file should be removed"
3836 );
3837 }
3838
3839 #[test]
3840 fn test_cherry_pick_does_not_modify_source() {
3841 let (_temp_dir, repo_path) = create_test_repo();
3842 let repo = GitRepository::open(&repo_path).unwrap();
3843
3844 repo.create_branch("feature", None).unwrap();
3846 repo.checkout_branch("feature").unwrap();
3847
3848 for i in 1..=3 {
3850 std::fs::write(
3851 repo_path.join(format!("file{i}.txt")),
3852 format!("Content {i}"),
3853 )
3854 .unwrap();
3855 Command::new("git")
3856 .args(["add", "."])
3857 .current_dir(&repo_path)
3858 .output()
3859 .unwrap();
3860
3861 Command::new("git")
3862 .args(["commit", "-m", &format!("Commit {i}")])
3863 .current_dir(&repo_path)
3864 .output()
3865 .unwrap();
3866 }
3867
3868 let source_commits = Command::new("git")
3870 .args(["log", "--format=%H", "feature"])
3871 .current_dir(&repo_path)
3872 .output()
3873 .unwrap();
3874 let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3875
3876 let commits: Vec<&str> = source_state.lines().collect();
3878 let middle_commit = commits[1];
3879
3880 Command::new("git")
3882 .args(["checkout", "-"])
3883 .current_dir(&repo_path)
3884 .output()
3885 .unwrap();
3886 repo.create_branch("target", None).unwrap();
3887 repo.checkout_branch("target").unwrap();
3888
3889 repo.cherry_pick(middle_commit).unwrap();
3890
3891 let after_commits = Command::new("git")
3893 .args(["log", "--format=%H", "feature"])
3894 .current_dir(&repo_path)
3895 .output()
3896 .unwrap();
3897 let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3898
3899 assert_eq!(
3900 source_state, after_state,
3901 "Source branch should be completely unchanged after cherry-pick"
3902 );
3903 }
3904
3905 #[test]
3906 fn test_detect_parent_branch() {
3907 let (_temp_dir, repo_path) = create_test_repo();
3908 let repo = GitRepository::open(&repo_path).unwrap();
3909
3910 repo.create_branch("dev123", None).unwrap();
3912 repo.checkout_branch("dev123").unwrap();
3913 create_commit(&repo_path, "Base commit on dev123", "base.txt");
3914
3915 repo.create_branch("feature-branch", None).unwrap();
3917 repo.checkout_branch("feature-branch").unwrap();
3918 create_commit(&repo_path, "Feature commit", "feature.txt");
3919
3920 let detected_parent = repo.detect_parent_branch().unwrap();
3922
3923 assert!(detected_parent.is_some(), "Should detect a parent branch");
3926
3927 let parent = detected_parent.unwrap();
3930 assert!(
3931 parent == "dev123" || parent == "main" || parent == "master",
3932 "Parent should be dev123, main, or master, got: {parent}"
3933 );
3934 }
3935}