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