1use crate::cli::output::Output;
2use crate::errors::{CascadeError, Result};
3use chrono;
4use dialoguer::{theme::ColorfulTheme, Confirm, Select};
5use git2::{Oid, Repository, Signature};
6use std::path::{Path, PathBuf};
7use tracing::{debug, info, warn};
8
9#[derive(Debug, Clone)]
11pub struct RepositoryInfo {
12 pub path: PathBuf,
13 pub head_branch: Option<String>,
14 pub head_commit: Option<String>,
15 pub is_dirty: bool,
16 pub untracked_files: Vec<String>,
17}
18
19#[derive(Debug, Clone)]
21struct ForceBackupInfo {
22 pub backup_branch_name: String,
23 pub remote_commit_id: String,
24 #[allow(dead_code)] pub commits_that_would_be_lost: usize,
26}
27
28#[derive(Debug, Clone)]
30struct BranchDeletionSafety {
31 pub unpushed_commits: Vec<String>,
32 pub remote_tracking_branch: Option<String>,
33 pub is_merged_to_main: bool,
34 pub main_branch_name: String,
35}
36
37#[derive(Debug, Clone)]
39struct CheckoutSafety {
40 #[allow(dead_code)] pub has_uncommitted_changes: bool,
42 pub modified_files: Vec<String>,
43 pub staged_files: Vec<String>,
44 pub untracked_files: Vec<String>,
45 #[allow(dead_code)] pub stash_created: Option<String>,
47 #[allow(dead_code)] pub current_branch: Option<String>,
49}
50
51#[derive(Debug, Clone)]
53pub struct GitSslConfig {
54 pub accept_invalid_certs: bool,
55 pub ca_bundle_path: Option<String>,
56}
57
58#[derive(Debug, Clone)]
60pub struct GitStatusSummary {
61 staged_files: usize,
62 unstaged_files: usize,
63 untracked_files: usize,
64}
65
66impl GitStatusSummary {
67 pub fn is_clean(&self) -> bool {
68 self.staged_files == 0 && self.unstaged_files == 0 && self.untracked_files == 0
69 }
70
71 pub fn has_staged_changes(&self) -> bool {
72 self.staged_files > 0
73 }
74
75 pub fn has_unstaged_changes(&self) -> bool {
76 self.unstaged_files > 0
77 }
78
79 pub fn has_untracked_files(&self) -> bool {
80 self.untracked_files > 0
81 }
82
83 pub fn staged_count(&self) -> usize {
84 self.staged_files
85 }
86
87 pub fn unstaged_count(&self) -> usize {
88 self.unstaged_files
89 }
90
91 pub fn untracked_count(&self) -> usize {
92 self.untracked_files
93 }
94}
95
96pub struct GitRepository {
102 repo: Repository,
103 path: PathBuf,
104 ssl_config: Option<GitSslConfig>,
105 bitbucket_credentials: Option<BitbucketCredentials>,
106}
107
108#[derive(Debug, Clone)]
109struct BitbucketCredentials {
110 username: Option<String>,
111 token: Option<String>,
112}
113
114impl GitRepository {
115 pub fn open(path: &Path) -> Result<Self> {
118 let repo = Repository::discover(path)
119 .map_err(|e| CascadeError::config(format!("Not a git repository: {e}")))?;
120
121 let workdir = repo
122 .workdir()
123 .ok_or_else(|| CascadeError::config("Repository has no working directory"))?
124 .to_path_buf();
125
126 let ssl_config = Self::load_ssl_config_from_cascade(&workdir);
128 let bitbucket_credentials = Self::load_bitbucket_credentials_from_cascade(&workdir);
129
130 Ok(Self {
131 repo,
132 path: workdir,
133 ssl_config,
134 bitbucket_credentials,
135 })
136 }
137
138 fn load_ssl_config_from_cascade(repo_path: &Path) -> Option<GitSslConfig> {
140 let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
142 let config_path = config_dir.join("config.json");
143 let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
144
145 if settings.bitbucket.accept_invalid_certs.is_some()
147 || settings.bitbucket.ca_bundle_path.is_some()
148 {
149 Some(GitSslConfig {
150 accept_invalid_certs: settings.bitbucket.accept_invalid_certs.unwrap_or(false),
151 ca_bundle_path: settings.bitbucket.ca_bundle_path,
152 })
153 } else {
154 None
155 }
156 }
157
158 fn load_bitbucket_credentials_from_cascade(repo_path: &Path) -> Option<BitbucketCredentials> {
160 let config_dir = crate::config::get_repo_config_dir(repo_path).ok()?;
162 let config_path = config_dir.join("config.json");
163 let settings = crate::config::Settings::load_from_file(&config_path).ok()?;
164
165 if settings.bitbucket.username.is_some() || settings.bitbucket.token.is_some() {
167 Some(BitbucketCredentials {
168 username: settings.bitbucket.username.clone(),
169 token: settings.bitbucket.token.clone(),
170 })
171 } else {
172 None
173 }
174 }
175
176 pub fn get_info(&self) -> Result<RepositoryInfo> {
178 let head_branch = self.get_current_branch().ok();
179 let head_commit = self.get_head_commit_hash().ok();
180 let is_dirty = self.is_dirty()?;
181 let untracked_files = self.get_untracked_files()?;
182
183 Ok(RepositoryInfo {
184 path: self.path.clone(),
185 head_branch,
186 head_commit,
187 is_dirty,
188 untracked_files,
189 })
190 }
191
192 pub fn get_current_branch(&self) -> Result<String> {
194 let head = self
195 .repo
196 .head()
197 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
198
199 if let Some(name) = head.shorthand() {
200 Ok(name.to_string())
201 } else {
202 let commit = head
204 .peel_to_commit()
205 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
206 Ok(format!("HEAD@{}", commit.id()))
207 }
208 }
209
210 pub fn get_head_commit_hash(&self) -> Result<String> {
212 let head = self
213 .repo
214 .head()
215 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
216
217 let commit = head
218 .peel_to_commit()
219 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?;
220
221 Ok(commit.id().to_string())
222 }
223
224 pub fn is_dirty(&self) -> Result<bool> {
226 let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
227
228 for status in statuses.iter() {
229 let flags = status.status();
230
231 if flags.intersects(
233 git2::Status::INDEX_MODIFIED
234 | git2::Status::INDEX_NEW
235 | git2::Status::INDEX_DELETED
236 | git2::Status::WT_MODIFIED
237 | git2::Status::WT_NEW
238 | git2::Status::WT_DELETED,
239 ) {
240 return Ok(true);
241 }
242 }
243
244 Ok(false)
245 }
246
247 pub fn get_untracked_files(&self) -> Result<Vec<String>> {
249 let statuses = self.repo.statuses(None).map_err(CascadeError::Git)?;
250
251 let mut untracked = Vec::new();
252 for status in statuses.iter() {
253 if status.status().contains(git2::Status::WT_NEW) {
254 if let Some(path) = status.path() {
255 untracked.push(path.to_string());
256 }
257 }
258 }
259
260 Ok(untracked)
261 }
262
263 pub fn create_branch(&self, name: &str, target: Option<&str>) -> Result<()> {
265 let target_commit = if let Some(target) = target {
266 let target_obj = self.repo.revparse_single(target).map_err(|e| {
268 CascadeError::branch(format!("Could not find target '{target}': {e}"))
269 })?;
270 target_obj.peel_to_commit().map_err(|e| {
271 CascadeError::branch(format!("Target '{target}' is not a commit: {e}"))
272 })?
273 } else {
274 let head = self
276 .repo
277 .head()
278 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
279 head.peel_to_commit()
280 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))?
281 };
282
283 self.repo
284 .branch(name, &target_commit, false)
285 .map_err(|e| CascadeError::branch(format!("Could not create branch '{name}': {e}")))?;
286
287 Ok(())
289 }
290
291 pub fn update_branch_to_commit(&self, branch_name: &str, commit_id: &str) -> Result<()> {
294 let commit_oid = Oid::from_str(commit_id).map_err(|e| {
295 CascadeError::branch(format!("Invalid commit ID '{}': {}", commit_id, e))
296 })?;
297
298 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
299 CascadeError::branch(format!("Commit '{}' not found: {}", commit_id, e))
300 })?;
301
302 if self
304 .repo
305 .find_branch(branch_name, git2::BranchType::Local)
306 .is_ok()
307 {
308 let refname = format!("refs/heads/{}", branch_name);
310 self.repo
311 .reference(
312 &refname,
313 commit_oid,
314 true,
315 "update branch to rebased commit",
316 )
317 .map_err(|e| {
318 CascadeError::branch(format!(
319 "Failed to update branch '{}': {}",
320 branch_name, e
321 ))
322 })?;
323 } else {
324 self.repo.branch(branch_name, &commit, false).map_err(|e| {
326 CascadeError::branch(format!("Failed to create branch '{}': {}", branch_name, e))
327 })?;
328 }
329
330 Ok(())
331 }
332
333 pub fn force_push_single_branch(&self, branch_name: &str) -> Result<()> {
335 if let Err(e) = self.fetch() {
337 tracing::warn!("Could not fetch before force push: {}", e);
338 }
339
340 let safety_result = self.check_force_push_safety_enhanced(branch_name)?;
342 if let Some(backup_info) = safety_result {
343 self.create_backup_branch(branch_name, &backup_info.remote_commit_id)?;
344 }
345
346 let output = std::process::Command::new("git")
348 .args(["push", "--force", "origin", branch_name])
349 .current_dir(&self.path)
350 .output()
351 .map_err(|e| CascadeError::branch(format!("Failed to execute git push: {}", e)))?;
352
353 if !output.status.success() {
354 let stderr = String::from_utf8_lossy(&output.stderr);
355 return Err(CascadeError::branch(format!(
356 "Force push failed for '{}': {}",
357 branch_name, stderr
358 )));
359 }
360
361 Ok(())
362 }
363
364 pub fn checkout_branch(&self, name: &str) -> Result<()> {
366 self.checkout_branch_with_options(name, false)
367 }
368
369 pub fn checkout_branch_unsafe(&self, name: &str) -> Result<()> {
371 self.checkout_branch_with_options(name, true)
372 }
373
374 fn checkout_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
376 debug!("Attempting to checkout branch: {}", name);
377
378 if !force_unsafe {
380 let safety_result = self.check_checkout_safety(name)?;
381 if let Some(safety_info) = safety_result {
382 self.handle_checkout_confirmation(name, &safety_info)?;
384 }
385 }
386
387 let branch = self
389 .repo
390 .find_branch(name, git2::BranchType::Local)
391 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
392
393 let branch_ref = branch.get();
394 let tree = branch_ref.peel_to_tree().map_err(|e| {
395 CascadeError::branch(format!("Could not get tree for branch '{name}': {e}"))
396 })?;
397
398 self.repo
400 .checkout_tree(tree.as_object(), None)
401 .map_err(|e| {
402 CascadeError::branch(format!("Could not checkout branch '{name}': {e}"))
403 })?;
404
405 self.repo
407 .set_head(&format!("refs/heads/{name}"))
408 .map_err(|e| CascadeError::branch(format!("Could not update HEAD to '{name}': {e}")))?;
409
410 Output::success(format!("Switched to branch '{name}'"));
411 Ok(())
412 }
413
414 pub fn checkout_commit(&self, commit_hash: &str) -> Result<()> {
416 self.checkout_commit_with_options(commit_hash, false)
417 }
418
419 pub fn checkout_commit_unsafe(&self, commit_hash: &str) -> Result<()> {
421 self.checkout_commit_with_options(commit_hash, true)
422 }
423
424 fn checkout_commit_with_options(&self, commit_hash: &str, force_unsafe: bool) -> Result<()> {
426 debug!("Attempting to checkout commit: {}", commit_hash);
427
428 if !force_unsafe {
430 let safety_result = self.check_checkout_safety(&format!("commit:{commit_hash}"))?;
431 if let Some(safety_info) = safety_result {
432 self.handle_checkout_confirmation(&format!("commit {commit_hash}"), &safety_info)?;
434 }
435 }
436
437 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
438
439 let commit = self.repo.find_commit(oid).map_err(|e| {
440 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
441 })?;
442
443 let tree = commit.tree().map_err(|e| {
444 CascadeError::branch(format!(
445 "Could not get tree for commit '{commit_hash}': {e}"
446 ))
447 })?;
448
449 self.repo
451 .checkout_tree(tree.as_object(), None)
452 .map_err(|e| {
453 CascadeError::branch(format!("Could not checkout commit '{commit_hash}': {e}"))
454 })?;
455
456 self.repo.set_head_detached(oid).map_err(|e| {
458 CascadeError::branch(format!(
459 "Could not update HEAD to commit '{commit_hash}': {e}"
460 ))
461 })?;
462
463 Output::success(format!(
464 "Checked out commit '{commit_hash}' (detached HEAD)"
465 ));
466 Ok(())
467 }
468
469 pub fn branch_exists(&self, name: &str) -> bool {
471 self.repo.find_branch(name, git2::BranchType::Local).is_ok()
472 }
473
474 pub fn branch_exists_or_fetch(&self, name: &str) -> Result<bool> {
476 if self.repo.find_branch(name, git2::BranchType::Local).is_ok() {
478 return Ok(true);
479 }
480
481 println!("🔍 Branch '{name}' not found locally, trying to fetch from remote...");
483
484 use std::process::Command;
485
486 let fetch_result = Command::new("git")
488 .args(["fetch", "origin", &format!("{name}:{name}")])
489 .current_dir(&self.path)
490 .output();
491
492 match fetch_result {
493 Ok(output) => {
494 if output.status.success() {
495 println!("✅ Successfully fetched '{name}' from origin");
496 return Ok(self.repo.find_branch(name, git2::BranchType::Local).is_ok());
498 } else {
499 let stderr = String::from_utf8_lossy(&output.stderr);
500 tracing::debug!("Failed to fetch branch '{name}': {stderr}");
501 }
502 }
503 Err(e) => {
504 tracing::debug!("Git fetch command failed: {e}");
505 }
506 }
507
508 if name.contains('/') {
510 println!("🔍 Trying alternative fetch patterns...");
511
512 let fetch_all_result = Command::new("git")
514 .args(["fetch", "origin"])
515 .current_dir(&self.path)
516 .output();
517
518 if let Ok(output) = fetch_all_result {
519 if output.status.success() {
520 let checkout_result = Command::new("git")
522 .args(["checkout", "-b", name, &format!("origin/{name}")])
523 .current_dir(&self.path)
524 .output();
525
526 if let Ok(checkout_output) = checkout_result {
527 if checkout_output.status.success() {
528 println!(
529 "✅ Successfully created local branch '{name}' from origin/{name}"
530 );
531 return Ok(true);
532 }
533 }
534 }
535 }
536 }
537
538 Ok(false)
540 }
541
542 pub fn get_branch_commit_hash(&self, branch_name: &str) -> Result<String> {
544 let branch = self
545 .repo
546 .find_branch(branch_name, git2::BranchType::Local)
547 .map_err(|e| {
548 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
549 })?;
550
551 let commit = branch.get().peel_to_commit().map_err(|e| {
552 CascadeError::branch(format!(
553 "Could not get commit for branch '{branch_name}': {e}"
554 ))
555 })?;
556
557 Ok(commit.id().to_string())
558 }
559
560 pub fn list_branches(&self) -> Result<Vec<String>> {
562 let branches = self
563 .repo
564 .branches(Some(git2::BranchType::Local))
565 .map_err(CascadeError::Git)?;
566
567 let mut branch_names = Vec::new();
568 for branch in branches {
569 let (branch, _) = branch.map_err(CascadeError::Git)?;
570 if let Some(name) = branch.name().map_err(CascadeError::Git)? {
571 branch_names.push(name.to_string());
572 }
573 }
574
575 Ok(branch_names)
576 }
577
578 pub fn get_upstream_branch(&self, branch_name: &str) -> Result<Option<String>> {
580 let config = self.repo.config().map_err(CascadeError::Git)?;
582
583 let remote_key = format!("branch.{branch_name}.remote");
585 let merge_key = format!("branch.{branch_name}.merge");
586
587 if let (Ok(remote), Ok(merge_ref)) = (
588 config.get_string(&remote_key),
589 config.get_string(&merge_key),
590 ) {
591 if let Some(branch_part) = merge_ref.strip_prefix("refs/heads/") {
593 return Ok(Some(format!("{remote}/{branch_part}")));
594 }
595 }
596
597 let potential_upstream = format!("origin/{branch_name}");
599 if self
600 .repo
601 .find_reference(&format!("refs/remotes/{potential_upstream}"))
602 .is_ok()
603 {
604 return Ok(Some(potential_upstream));
605 }
606
607 Ok(None)
608 }
609
610 pub fn get_ahead_behind_counts(
612 &self,
613 local_branch: &str,
614 upstream_branch: &str,
615 ) -> Result<(usize, usize)> {
616 let local_ref = self
618 .repo
619 .find_reference(&format!("refs/heads/{local_branch}"))
620 .map_err(|_| {
621 CascadeError::config(format!("Local branch '{local_branch}' not found"))
622 })?;
623 let local_commit = local_ref.peel_to_commit().map_err(CascadeError::Git)?;
624
625 let upstream_ref = self
626 .repo
627 .find_reference(&format!("refs/remotes/{upstream_branch}"))
628 .map_err(|_| {
629 CascadeError::config(format!("Upstream branch '{upstream_branch}' not found"))
630 })?;
631 let upstream_commit = upstream_ref.peel_to_commit().map_err(CascadeError::Git)?;
632
633 let (ahead, behind) = self
635 .repo
636 .graph_ahead_behind(local_commit.id(), upstream_commit.id())
637 .map_err(CascadeError::Git)?;
638
639 Ok((ahead, behind))
640 }
641
642 pub fn set_upstream(&self, branch_name: &str, remote: &str, remote_branch: &str) -> Result<()> {
644 let mut config = self.repo.config().map_err(CascadeError::Git)?;
645
646 let remote_key = format!("branch.{branch_name}.remote");
648 config
649 .set_str(&remote_key, remote)
650 .map_err(CascadeError::Git)?;
651
652 let merge_key = format!("branch.{branch_name}.merge");
654 let merge_value = format!("refs/heads/{remote_branch}");
655 config
656 .set_str(&merge_key, &merge_value)
657 .map_err(CascadeError::Git)?;
658
659 Ok(())
660 }
661
662 pub fn commit(&self, message: &str) -> Result<String> {
664 self.validate_git_user_config()?;
666
667 let signature = self.get_signature()?;
668 let tree_id = self.get_index_tree()?;
669 let tree = self.repo.find_tree(tree_id).map_err(CascadeError::Git)?;
670
671 let head = self.repo.head().map_err(CascadeError::Git)?;
673 let parent_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
674
675 let commit_id = self
676 .repo
677 .commit(
678 Some("HEAD"),
679 &signature,
680 &signature,
681 message,
682 &tree,
683 &[&parent_commit],
684 )
685 .map_err(CascadeError::Git)?;
686
687 Output::success(format!("Created commit: {commit_id} - {message}"));
688 Ok(commit_id.to_string())
689 }
690
691 pub fn commit_staged_changes(&self, default_message: &str) -> Result<Option<String>> {
693 let staged_files = self.get_staged_files()?;
695 if staged_files.is_empty() {
696 tracing::debug!("No staged changes to commit");
697 return Ok(None);
698 }
699
700 tracing::info!("Committing {} staged files", staged_files.len());
701 let commit_hash = self.commit(default_message)?;
702 Ok(Some(commit_hash))
703 }
704
705 pub fn stage_all(&self) -> Result<()> {
707 let mut index = self.repo.index().map_err(CascadeError::Git)?;
708
709 index
710 .add_all(["*"].iter(), git2::IndexAddOption::DEFAULT, None)
711 .map_err(CascadeError::Git)?;
712
713 index.write().map_err(CascadeError::Git)?;
714
715 tracing::debug!("Staged all changes");
716 Ok(())
717 }
718
719 pub fn stage_files(&self, file_paths: &[&str]) -> Result<()> {
721 if file_paths.is_empty() {
722 tracing::debug!("No files to stage");
723 return Ok(());
724 }
725
726 let mut index = self.repo.index().map_err(CascadeError::Git)?;
727
728 for file_path in file_paths {
729 index
730 .add_path(std::path::Path::new(file_path))
731 .map_err(CascadeError::Git)?;
732 }
733
734 index.write().map_err(CascadeError::Git)?;
735
736 tracing::debug!(
737 "Staged {} specific files: {:?}",
738 file_paths.len(),
739 file_paths
740 );
741 Ok(())
742 }
743
744 pub fn stage_conflict_resolved_files(&self) -> Result<()> {
746 let conflicted_files = self.get_conflicted_files()?;
747 if conflicted_files.is_empty() {
748 tracing::debug!("No conflicted files to stage");
749 return Ok(());
750 }
751
752 let file_paths: Vec<&str> = conflicted_files.iter().map(|s| s.as_str()).collect();
753 self.stage_files(&file_paths)?;
754
755 tracing::debug!("Staged {} conflict-resolved files", conflicted_files.len());
756 Ok(())
757 }
758
759 pub fn path(&self) -> &Path {
761 &self.path
762 }
763
764 pub fn commit_exists(&self, commit_hash: &str) -> Result<bool> {
766 match Oid::from_str(commit_hash) {
767 Ok(oid) => match self.repo.find_commit(oid) {
768 Ok(_) => Ok(true),
769 Err(_) => Ok(false),
770 },
771 Err(_) => Ok(false),
772 }
773 }
774
775 pub fn get_head_commit(&self) -> Result<git2::Commit<'_>> {
777 let head = self
778 .repo
779 .head()
780 .map_err(|e| CascadeError::branch(format!("Could not get HEAD: {e}")))?;
781 head.peel_to_commit()
782 .map_err(|e| CascadeError::branch(format!("Could not get HEAD commit: {e}")))
783 }
784
785 pub fn get_commit(&self, commit_hash: &str) -> Result<git2::Commit<'_>> {
787 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
788
789 self.repo.find_commit(oid).map_err(CascadeError::Git)
790 }
791
792 pub fn get_branch_head(&self, branch_name: &str) -> Result<String> {
794 let branch = self
795 .repo
796 .find_branch(branch_name, git2::BranchType::Local)
797 .map_err(|e| {
798 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
799 })?;
800
801 let commit = branch.get().peel_to_commit().map_err(|e| {
802 CascadeError::branch(format!(
803 "Could not get commit for branch '{branch_name}': {e}"
804 ))
805 })?;
806
807 Ok(commit.id().to_string())
808 }
809
810 pub fn validate_git_user_config(&self) -> Result<()> {
812 if let Ok(config) = self.repo.config() {
813 let name_result = config.get_string("user.name");
814 let email_result = config.get_string("user.email");
815
816 if let (Ok(name), Ok(email)) = (name_result, email_result) {
817 if !name.trim().is_empty() && !email.trim().is_empty() {
818 tracing::debug!("Git user config validated: {} <{}>", name, email);
819 return Ok(());
820 }
821 }
822 }
823
824 let is_ci = std::env::var("CI").is_ok();
826
827 if is_ci {
828 tracing::debug!("CI environment - skipping git user config validation");
829 return Ok(());
830 }
831
832 Output::warning("Git user configuration missing or incomplete");
833 Output::info("This can cause cherry-pick and commit operations to fail");
834 Output::info("Please configure git user information:");
835 Output::bullet("git config user.name \"Your Name\"".to_string());
836 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
837 Output::info("Or set globally with the --global flag");
838
839 Ok(())
842 }
843
844 fn get_signature(&self) -> Result<Signature<'_>> {
846 if let Ok(config) = self.repo.config() {
848 let name_result = config.get_string("user.name");
850 let email_result = config.get_string("user.email");
851
852 if let (Ok(name), Ok(email)) = (name_result, email_result) {
853 if !name.trim().is_empty() && !email.trim().is_empty() {
854 tracing::debug!("Using git config: {} <{}>", name, email);
855 return Signature::now(&name, &email).map_err(CascadeError::Git);
856 }
857 } else {
858 tracing::debug!("Git user config incomplete or missing");
859 }
860 }
861
862 let is_ci = std::env::var("CI").is_ok();
864
865 if is_ci {
866 tracing::debug!("CI environment detected, using fallback signature");
867 return Signature::now("Cascade CLI", "cascade@example.com").map_err(CascadeError::Git);
868 }
869
870 tracing::warn!("Git user configuration missing - this can cause commit operations to fail");
872
873 match Signature::now("Cascade CLI", "cascade@example.com") {
875 Ok(sig) => {
876 Output::warning("Git user not configured - using fallback signature");
877 Output::info("For better git history, run:");
878 Output::bullet("git config user.name \"Your Name\"".to_string());
879 Output::bullet("git config user.email \"your.email@example.com\"".to_string());
880 Output::info("Or set it globally with --global flag");
881 Ok(sig)
882 }
883 Err(e) => {
884 Err(CascadeError::branch(format!(
885 "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\""
886 )))
887 }
888 }
889 }
890
891 fn configure_remote_callbacks(&self) -> Result<git2::RemoteCallbacks<'_>> {
894 self.configure_remote_callbacks_with_fallback(false)
895 }
896
897 fn should_retry_with_default_credentials(&self, error: &git2::Error) -> bool {
899 match error.class() {
900 git2::ErrorClass::Http => {
902 match error.code() {
904 git2::ErrorCode::Auth => true,
905 _ => {
906 let error_string = error.to_string();
908 error_string.contains("too many redirects")
909 || error_string.contains("authentication replays")
910 || error_string.contains("authentication required")
911 }
912 }
913 }
914 git2::ErrorClass::Net => {
915 let error_string = error.to_string();
917 error_string.contains("authentication")
918 || error_string.contains("unauthorized")
919 || error_string.contains("forbidden")
920 }
921 _ => false,
922 }
923 }
924
925 fn should_fallback_to_git_cli(&self, error: &git2::Error) -> bool {
927 match error.class() {
928 git2::ErrorClass::Ssl => true,
930
931 git2::ErrorClass::Http if error.code() == git2::ErrorCode::Certificate => true,
933
934 git2::ErrorClass::Ssh => {
936 let error_string = error.to_string();
937 error_string.contains("no callback set")
938 || error_string.contains("authentication required")
939 }
940
941 git2::ErrorClass::Net => {
943 let error_string = error.to_string();
944 error_string.contains("TLS stream")
945 || error_string.contains("SSL")
946 || error_string.contains("proxy")
947 || error_string.contains("firewall")
948 }
949
950 git2::ErrorClass::Http => {
952 let error_string = error.to_string();
953 error_string.contains("TLS stream")
954 || error_string.contains("SSL")
955 || error_string.contains("proxy")
956 }
957
958 _ => false,
959 }
960 }
961
962 fn configure_remote_callbacks_with_fallback(
963 &self,
964 use_default_first: bool,
965 ) -> Result<git2::RemoteCallbacks<'_>> {
966 let mut callbacks = git2::RemoteCallbacks::new();
967
968 let bitbucket_credentials = self.bitbucket_credentials.clone();
970 callbacks.credentials(move |url, username_from_url, allowed_types| {
971 tracing::debug!(
972 "Authentication requested for URL: {}, username: {:?}, allowed_types: {:?}",
973 url,
974 username_from_url,
975 allowed_types
976 );
977
978 if allowed_types.contains(git2::CredentialType::SSH_KEY) {
980 if let Some(username) = username_from_url {
981 tracing::debug!("Trying SSH key authentication for user: {}", username);
982 return git2::Cred::ssh_key_from_agent(username);
983 }
984 }
985
986 if allowed_types.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
988 if use_default_first {
990 tracing::debug!("Corporate network mode: trying DefaultCredentials first");
991 return git2::Cred::default();
992 }
993
994 if url.contains("bitbucket") {
995 if let Some(creds) = &bitbucket_credentials {
996 if let (Some(username), Some(token)) = (&creds.username, &creds.token) {
998 tracing::debug!("Trying Bitbucket username + token authentication");
999 return git2::Cred::userpass_plaintext(username, token);
1000 }
1001
1002 if let Some(token) = &creds.token {
1004 tracing::debug!("Trying Bitbucket token-as-username authentication");
1005 return git2::Cred::userpass_plaintext(token, "");
1006 }
1007
1008 if let Some(username) = &creds.username {
1010 tracing::debug!("Trying Bitbucket username authentication (will use credential helper)");
1011 return git2::Cred::username(username);
1012 }
1013 }
1014 }
1015
1016 tracing::debug!("Trying default credential helper for HTTPS authentication");
1018 return git2::Cred::default();
1019 }
1020
1021 tracing::debug!("Using default credential fallback");
1023 git2::Cred::default()
1024 });
1025
1026 let mut ssl_configured = false;
1031
1032 if let Some(ssl_config) = &self.ssl_config {
1034 if ssl_config.accept_invalid_certs {
1035 Output::warning(
1036 "SSL certificate verification DISABLED via Cascade config - this is insecure!",
1037 );
1038 callbacks.certificate_check(|_cert, _host| {
1039 tracing::debug!("⚠️ Accepting invalid certificate for host: {}", _host);
1040 Ok(git2::CertificateCheckStatus::CertificateOk)
1041 });
1042 ssl_configured = true;
1043 } else if let Some(ca_path) = &ssl_config.ca_bundle_path {
1044 Output::info(format!(
1045 "Using custom CA bundle from Cascade config: {ca_path}"
1046 ));
1047 callbacks.certificate_check(|_cert, host| {
1048 tracing::debug!("Using custom CA bundle for host: {}", host);
1049 Ok(git2::CertificateCheckStatus::CertificateOk)
1050 });
1051 ssl_configured = true;
1052 }
1053 }
1054
1055 if !ssl_configured {
1057 if let Ok(config) = self.repo.config() {
1058 let ssl_verify = config.get_bool("http.sslVerify").unwrap_or(true);
1059
1060 if !ssl_verify {
1061 Output::warning(
1062 "SSL certificate verification DISABLED via git config - this is insecure!",
1063 );
1064 callbacks.certificate_check(|_cert, host| {
1065 tracing::debug!("⚠️ Bypassing SSL verification for host: {}", host);
1066 Ok(git2::CertificateCheckStatus::CertificateOk)
1067 });
1068 ssl_configured = true;
1069 } else if let Ok(ca_path) = config.get_string("http.sslCAInfo") {
1070 Output::info(format!("Using custom CA bundle from git config: {ca_path}"));
1071 callbacks.certificate_check(|_cert, host| {
1072 tracing::debug!("Using git config CA bundle for host: {}", host);
1073 Ok(git2::CertificateCheckStatus::CertificateOk)
1074 });
1075 ssl_configured = true;
1076 }
1077 }
1078 }
1079
1080 if !ssl_configured {
1083 tracing::debug!(
1084 "Using system certificate store for SSL verification (default behavior)"
1085 );
1086
1087 if cfg!(target_os = "macos") {
1089 tracing::debug!("macOS detected - using default certificate validation");
1090 } else {
1093 callbacks.certificate_check(|_cert, host| {
1095 tracing::debug!("System certificate validation for host: {}", host);
1096 Ok(git2::CertificateCheckStatus::CertificatePassthrough)
1097 });
1098 }
1099 }
1100
1101 Ok(callbacks)
1102 }
1103
1104 fn get_index_tree(&self) -> Result<Oid> {
1106 let mut index = self.repo.index().map_err(CascadeError::Git)?;
1107
1108 index.write_tree().map_err(CascadeError::Git)
1109 }
1110
1111 pub fn get_status(&self) -> Result<git2::Statuses<'_>> {
1113 self.repo.statuses(None).map_err(CascadeError::Git)
1114 }
1115
1116 pub fn get_status_summary(&self) -> Result<GitStatusSummary> {
1118 let statuses = self.get_status()?;
1119
1120 let mut staged_files = 0;
1121 let mut unstaged_files = 0;
1122 let mut untracked_files = 0;
1123
1124 for status in statuses.iter() {
1125 let flags = status.status();
1126
1127 if flags.intersects(
1128 git2::Status::INDEX_MODIFIED
1129 | git2::Status::INDEX_NEW
1130 | git2::Status::INDEX_DELETED
1131 | git2::Status::INDEX_RENAMED
1132 | git2::Status::INDEX_TYPECHANGE,
1133 ) {
1134 staged_files += 1;
1135 }
1136
1137 if flags.intersects(
1138 git2::Status::WT_MODIFIED
1139 | git2::Status::WT_DELETED
1140 | git2::Status::WT_TYPECHANGE
1141 | git2::Status::WT_RENAMED,
1142 ) {
1143 unstaged_files += 1;
1144 }
1145
1146 if flags.intersects(git2::Status::WT_NEW) {
1147 untracked_files += 1;
1148 }
1149 }
1150
1151 Ok(GitStatusSummary {
1152 staged_files,
1153 unstaged_files,
1154 untracked_files,
1155 })
1156 }
1157
1158 pub fn get_current_commit_hash(&self) -> Result<String> {
1160 self.get_head_commit_hash()
1161 }
1162
1163 pub fn get_commit_count_between(&self, from_commit: &str, to_commit: &str) -> Result<usize> {
1165 let from_oid = git2::Oid::from_str(from_commit).map_err(CascadeError::Git)?;
1166 let to_oid = git2::Oid::from_str(to_commit).map_err(CascadeError::Git)?;
1167
1168 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1169 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1170 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1171
1172 Ok(revwalk.count())
1173 }
1174
1175 pub fn get_remote_url(&self, name: &str) -> Result<String> {
1177 let remote = self.repo.find_remote(name).map_err(CascadeError::Git)?;
1178 Ok(remote.url().unwrap_or("unknown").to_string())
1179 }
1180
1181 pub fn cherry_pick(&self, commit_hash: &str) -> Result<String> {
1183 tracing::debug!("Cherry-picking commit {}", commit_hash);
1184
1185 self.validate_git_user_config()?;
1187
1188 let oid = Oid::from_str(commit_hash).map_err(CascadeError::Git)?;
1189 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1190
1191 let commit_tree = commit.tree().map_err(CascadeError::Git)?;
1193
1194 let parent_commit = if commit.parent_count() > 0 {
1196 commit.parent(0).map_err(CascadeError::Git)?
1197 } else {
1198 let empty_tree_oid = self.repo.treebuilder(None)?.write()?;
1200 let empty_tree = self.repo.find_tree(empty_tree_oid)?;
1201 let sig = self.get_signature()?;
1202 return self
1203 .repo
1204 .commit(
1205 Some("HEAD"),
1206 &sig,
1207 &sig,
1208 commit.message().unwrap_or("Cherry-picked commit"),
1209 &empty_tree,
1210 &[],
1211 )
1212 .map(|oid| oid.to_string())
1213 .map_err(CascadeError::Git);
1214 };
1215
1216 let parent_tree = parent_commit.tree().map_err(CascadeError::Git)?;
1217
1218 let head_commit = self.get_head_commit()?;
1220 let head_tree = head_commit.tree().map_err(CascadeError::Git)?;
1221
1222 let mut index = self
1224 .repo
1225 .merge_trees(&parent_tree, &head_tree, &commit_tree, None)
1226 .map_err(CascadeError::Git)?;
1227
1228 if index.has_conflicts() {
1230 return Err(CascadeError::branch(format!(
1231 "Cherry-pick of {commit_hash} has conflicts that need manual resolution"
1232 )));
1233 }
1234
1235 let merged_tree_oid = index.write_tree_to(&self.repo).map_err(CascadeError::Git)?;
1237 let merged_tree = self
1238 .repo
1239 .find_tree(merged_tree_oid)
1240 .map_err(CascadeError::Git)?;
1241
1242 let signature = self.get_signature()?;
1244 let message = format!("Cherry-pick: {}", commit.message().unwrap_or(""));
1245
1246 let new_commit_oid = self
1247 .repo
1248 .commit(
1249 Some("HEAD"),
1250 &signature,
1251 &signature,
1252 &message,
1253 &merged_tree,
1254 &[&head_commit],
1255 )
1256 .map_err(CascadeError::Git)?;
1257
1258 let new_commit = self
1260 .repo
1261 .find_commit(new_commit_oid)
1262 .map_err(CascadeError::Git)?;
1263 let new_tree = new_commit.tree().map_err(CascadeError::Git)?;
1264
1265 self.repo
1266 .checkout_tree(
1267 new_tree.as_object(),
1268 Some(git2::build::CheckoutBuilder::new().force()),
1269 )
1270 .map_err(CascadeError::Git)?;
1271
1272 tracing::info!("Cherry-picked {} -> {}", commit_hash, new_commit_oid);
1273 Ok(new_commit_oid.to_string())
1274 }
1275
1276 pub fn has_conflicts(&self) -> Result<bool> {
1278 let index = self.repo.index().map_err(CascadeError::Git)?;
1279 Ok(index.has_conflicts())
1280 }
1281
1282 pub fn get_conflicted_files(&self) -> Result<Vec<String>> {
1284 let index = self.repo.index().map_err(CascadeError::Git)?;
1285
1286 let mut conflicts = Vec::new();
1287
1288 let conflict_iter = index.conflicts().map_err(CascadeError::Git)?;
1290
1291 for conflict in conflict_iter {
1292 let conflict = conflict.map_err(CascadeError::Git)?;
1293 if let Some(our) = conflict.our {
1294 if let Ok(path) = std::str::from_utf8(&our.path) {
1295 conflicts.push(path.to_string());
1296 }
1297 } else if let Some(their) = conflict.their {
1298 if let Ok(path) = std::str::from_utf8(&their.path) {
1299 conflicts.push(path.to_string());
1300 }
1301 }
1302 }
1303
1304 Ok(conflicts)
1305 }
1306
1307 pub fn fetch(&self) -> Result<()> {
1309 tracing::debug!("Fetching from origin");
1310
1311 let mut remote = self
1312 .repo
1313 .find_remote("origin")
1314 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1315
1316 let callbacks = self.configure_remote_callbacks()?;
1318
1319 let mut fetch_options = git2::FetchOptions::new();
1321 fetch_options.remote_callbacks(callbacks);
1322
1323 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1325 Ok(_) => {
1326 tracing::debug!("Fetch completed successfully");
1327 Ok(())
1328 }
1329 Err(e) => {
1330 if self.should_retry_with_default_credentials(&e) {
1331 tracing::debug!(
1332 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1333 e.class(), e.code(), e
1334 );
1335
1336 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1338 let mut fetch_options = git2::FetchOptions::new();
1339 fetch_options.remote_callbacks(callbacks);
1340
1341 match remote.fetch::<&str>(&[], Some(&mut fetch_options), None) {
1342 Ok(_) => {
1343 tracing::debug!("Fetch succeeded with DefaultCredentials");
1344 return Ok(());
1345 }
1346 Err(retry_error) => {
1347 tracing::debug!(
1348 "DefaultCredentials retry failed: {}, falling back to git CLI",
1349 retry_error
1350 );
1351 return self.fetch_with_git_cli();
1352 }
1353 }
1354 }
1355
1356 if self.should_fallback_to_git_cli(&e) {
1357 tracing::debug!(
1358 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for fetch operation",
1359 e.class(), e.code(), e
1360 );
1361 return self.fetch_with_git_cli();
1362 }
1363 Err(CascadeError::Git(e))
1364 }
1365 }
1366 }
1367
1368 pub fn pull(&self, branch: &str) -> Result<()> {
1370 tracing::debug!("Pulling branch: {}", branch);
1371
1372 match self.fetch() {
1374 Ok(_) => {}
1375 Err(e) => {
1376 let error_string = e.to_string();
1378 if error_string.contains("TLS stream") || error_string.contains("SSL") {
1379 tracing::warn!(
1380 "git2 error detected: {}, falling back to git CLI for pull operation",
1381 e
1382 );
1383 return self.pull_with_git_cli(branch);
1384 }
1385 return Err(e);
1386 }
1387 }
1388
1389 let remote_branch_name = format!("origin/{branch}");
1391 let remote_oid = self
1392 .repo
1393 .refname_to_id(&format!("refs/remotes/{remote_branch_name}"))
1394 .map_err(|e| {
1395 CascadeError::branch(format!("Remote branch {remote_branch_name} not found: {e}"))
1396 })?;
1397
1398 let remote_commit = self
1399 .repo
1400 .find_commit(remote_oid)
1401 .map_err(CascadeError::Git)?;
1402
1403 let head_commit = self.get_head_commit()?;
1405
1406 if head_commit.id() == remote_commit.id() {
1408 tracing::debug!("Already up to date");
1409 return Ok(());
1410 }
1411
1412 let merge_base_oid = self
1414 .repo
1415 .merge_base(head_commit.id(), remote_commit.id())
1416 .map_err(CascadeError::Git)?;
1417
1418 if merge_base_oid == head_commit.id() {
1419 tracing::debug!("Fast-forwarding {} to {}", branch, remote_commit.id());
1421
1422 let refname = format!("refs/heads/{}", branch);
1424 self.repo
1425 .reference(&refname, remote_oid, true, "pull: Fast-forward")
1426 .map_err(CascadeError::Git)?;
1427
1428 self.repo.set_head(&refname).map_err(CascadeError::Git)?;
1430
1431 self.repo
1433 .checkout_head(Some(
1434 git2::build::CheckoutBuilder::new()
1435 .force()
1436 .remove_untracked(false),
1437 ))
1438 .map_err(CascadeError::Git)?;
1439
1440 tracing::debug!("Fast-forwarded to {}", remote_commit.id());
1441 return Ok(());
1442 }
1443
1444 Err(CascadeError::branch(format!(
1447 "Branch '{}' has diverged from remote. Local has commits not in remote. \
1448 Protected branches should not have local commits. \
1449 Try: git reset --hard origin/{}",
1450 branch, branch
1451 )))
1452 }
1453
1454 pub fn push(&self, branch: &str) -> Result<()> {
1456 let mut remote = self
1459 .repo
1460 .find_remote("origin")
1461 .map_err(|e| CascadeError::branch(format!("No remote 'origin' found: {e}")))?;
1462
1463 let remote_url = remote.url().unwrap_or("unknown").to_string();
1464 tracing::debug!("Remote URL: {}", remote_url);
1465
1466 let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
1467 tracing::debug!("Push refspec: {}", refspec);
1468
1469 let mut callbacks = self.configure_remote_callbacks()?;
1471
1472 callbacks.push_update_reference(|refname, status| {
1474 if let Some(msg) = status {
1475 tracing::error!("Push failed for ref {}: {}", refname, msg);
1476 return Err(git2::Error::from_str(&format!("Push failed: {msg}")));
1477 }
1478 tracing::debug!("Push succeeded for ref: {}", refname);
1479 Ok(())
1480 });
1481
1482 let mut push_options = git2::PushOptions::new();
1484 push_options.remote_callbacks(callbacks);
1485
1486 match remote.push(&[&refspec], Some(&mut push_options)) {
1488 Ok(_) => {
1489 tracing::info!("Push completed successfully for branch: {}", branch);
1490 Ok(())
1491 }
1492 Err(e) => {
1493 tracing::debug!(
1494 "git2 push error: {} (class: {:?}, code: {:?})",
1495 e,
1496 e.class(),
1497 e.code()
1498 );
1499
1500 if self.should_retry_with_default_credentials(&e) {
1501 tracing::debug!(
1502 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1503 e.class(), e.code(), e
1504 );
1505
1506 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1508 let mut push_options = git2::PushOptions::new();
1509 push_options.remote_callbacks(callbacks);
1510
1511 match remote.push(&[&refspec], Some(&mut push_options)) {
1512 Ok(_) => {
1513 tracing::debug!("Push succeeded with DefaultCredentials");
1514 return Ok(());
1515 }
1516 Err(retry_error) => {
1517 tracing::debug!(
1518 "DefaultCredentials retry failed: {}, falling back to git CLI",
1519 retry_error
1520 );
1521 return self.push_with_git_cli(branch);
1522 }
1523 }
1524 }
1525
1526 if self.should_fallback_to_git_cli(&e) {
1527 tracing::debug!(
1528 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for push operation",
1529 e.class(), e.code(), e
1530 );
1531 return self.push_with_git_cli(branch);
1532 }
1533
1534 let error_msg = if e.to_string().contains("authentication") {
1536 format!(
1537 "Authentication failed for branch '{branch}'. Try: git push origin {branch}"
1538 )
1539 } else {
1540 format!("Failed to push branch '{branch}': {e}")
1541 };
1542
1543 tracing::error!("{}", error_msg);
1544 Err(CascadeError::branch(error_msg))
1545 }
1546 }
1547 }
1548
1549 fn push_with_git_cli(&self, branch: &str) -> Result<()> {
1552 let output = std::process::Command::new("git")
1553 .args(["push", "origin", branch])
1554 .current_dir(&self.path)
1555 .output()
1556 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1557
1558 if output.status.success() {
1559 Ok(())
1561 } else {
1562 let stderr = String::from_utf8_lossy(&output.stderr);
1563 let _stdout = String::from_utf8_lossy(&output.stdout);
1564 let error_msg = if stderr.contains("SSL_connect") || stderr.contains("SSL_ERROR") {
1566 "Network error: Unable to connect to repository (VPN may be required)".to_string()
1567 } else if stderr.contains("repository") && stderr.contains("not found") {
1568 "Repository not found - check your Bitbucket configuration".to_string()
1569 } else if stderr.contains("authentication") || stderr.contains("403") {
1570 "Authentication failed - check your credentials".to_string()
1571 } else {
1572 stderr.trim().to_string()
1574 };
1575 tracing::error!("{}", error_msg);
1576 Err(CascadeError::branch(error_msg))
1577 }
1578 }
1579
1580 fn fetch_with_git_cli(&self) -> Result<()> {
1583 tracing::debug!("Using git CLI fallback for fetch operation");
1584
1585 let output = std::process::Command::new("git")
1586 .args(["fetch", "origin"])
1587 .current_dir(&self.path)
1588 .output()
1589 .map_err(|e| {
1590 CascadeError::Git(git2::Error::from_str(&format!(
1591 "Failed to execute git command: {e}"
1592 )))
1593 })?;
1594
1595 if output.status.success() {
1596 tracing::debug!("Git CLI fetch succeeded");
1597 Ok(())
1598 } else {
1599 let stderr = String::from_utf8_lossy(&output.stderr);
1600 let stdout = String::from_utf8_lossy(&output.stdout);
1601 let error_msg = format!(
1602 "Git CLI fetch failed: {}\nStdout: {}\nStderr: {}",
1603 output.status, stdout, stderr
1604 );
1605 tracing::error!("{}", error_msg);
1606 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1607 }
1608 }
1609
1610 fn pull_with_git_cli(&self, branch: &str) -> Result<()> {
1613 tracing::debug!("Using git CLI fallback for pull operation: {}", branch);
1614
1615 let output = std::process::Command::new("git")
1616 .args(["pull", "origin", branch])
1617 .current_dir(&self.path)
1618 .output()
1619 .map_err(|e| {
1620 CascadeError::Git(git2::Error::from_str(&format!(
1621 "Failed to execute git command: {e}"
1622 )))
1623 })?;
1624
1625 if output.status.success() {
1626 tracing::info!("✅ Git CLI pull succeeded for branch: {}", branch);
1627 Ok(())
1628 } else {
1629 let stderr = String::from_utf8_lossy(&output.stderr);
1630 let stdout = String::from_utf8_lossy(&output.stdout);
1631 let error_msg = format!(
1632 "Git CLI pull failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1633 branch, output.status, stdout, stderr
1634 );
1635 tracing::error!("{}", error_msg);
1636 Err(CascadeError::Git(git2::Error::from_str(&error_msg)))
1637 }
1638 }
1639
1640 fn force_push_with_git_cli(&self, branch: &str) -> Result<()> {
1643 tracing::debug!(
1644 "Using git CLI fallback for force push operation: {}",
1645 branch
1646 );
1647
1648 let output = std::process::Command::new("git")
1649 .args(["push", "--force", "origin", branch])
1650 .current_dir(&self.path)
1651 .output()
1652 .map_err(|e| CascadeError::branch(format!("Failed to execute git command: {e}")))?;
1653
1654 if output.status.success() {
1655 tracing::info!("✅ Git CLI force push succeeded for branch: {}", branch);
1656 Ok(())
1657 } else {
1658 let stderr = String::from_utf8_lossy(&output.stderr);
1659 let stdout = String::from_utf8_lossy(&output.stdout);
1660 let error_msg = format!(
1661 "Git CLI force push failed for branch '{}': {}\nStdout: {}\nStderr: {}",
1662 branch, output.status, stdout, stderr
1663 );
1664 tracing::error!("{}", error_msg);
1665 Err(CascadeError::branch(error_msg))
1666 }
1667 }
1668
1669 pub fn delete_branch(&self, name: &str) -> Result<()> {
1671 self.delete_branch_with_options(name, false)
1672 }
1673
1674 pub fn delete_branch_unsafe(&self, name: &str) -> Result<()> {
1676 self.delete_branch_with_options(name, true)
1677 }
1678
1679 fn delete_branch_with_options(&self, name: &str, force_unsafe: bool) -> Result<()> {
1681 debug!("Attempting to delete branch: {}", name);
1682
1683 if !force_unsafe {
1685 let safety_result = self.check_branch_deletion_safety(name)?;
1686 if let Some(safety_info) = safety_result {
1687 self.handle_branch_deletion_confirmation(name, &safety_info)?;
1689 }
1690 }
1691
1692 let mut branch = self
1693 .repo
1694 .find_branch(name, git2::BranchType::Local)
1695 .map_err(|e| CascadeError::branch(format!("Could not find branch '{name}': {e}")))?;
1696
1697 branch
1698 .delete()
1699 .map_err(|e| CascadeError::branch(format!("Could not delete branch '{name}': {e}")))?;
1700
1701 debug!("Successfully deleted branch '{}'", name);
1702 Ok(())
1703 }
1704
1705 pub fn get_commits_between(&self, from: &str, to: &str) -> Result<Vec<git2::Commit<'_>>> {
1707 let from_oid = self
1708 .repo
1709 .refname_to_id(&format!("refs/heads/{from}"))
1710 .or_else(|_| Oid::from_str(from))
1711 .map_err(|e| CascadeError::branch(format!("Invalid from reference '{from}': {e}")))?;
1712
1713 let to_oid = self
1714 .repo
1715 .refname_to_id(&format!("refs/heads/{to}"))
1716 .or_else(|_| Oid::from_str(to))
1717 .map_err(|e| CascadeError::branch(format!("Invalid to reference '{to}': {e}")))?;
1718
1719 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
1720
1721 revwalk.push(to_oid).map_err(CascadeError::Git)?;
1722 revwalk.hide(from_oid).map_err(CascadeError::Git)?;
1723
1724 let mut commits = Vec::new();
1725 for oid in revwalk {
1726 let oid = oid.map_err(CascadeError::Git)?;
1727 let commit = self.repo.find_commit(oid).map_err(CascadeError::Git)?;
1728 commits.push(commit);
1729 }
1730
1731 Ok(commits)
1732 }
1733
1734 pub fn force_push_branch(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1737 self.force_push_branch_with_options(target_branch, source_branch, false)
1738 }
1739
1740 pub fn force_push_branch_unsafe(&self, target_branch: &str, source_branch: &str) -> Result<()> {
1742 self.force_push_branch_with_options(target_branch, source_branch, true)
1743 }
1744
1745 fn force_push_branch_with_options(
1747 &self,
1748 target_branch: &str,
1749 source_branch: &str,
1750 force_unsafe: bool,
1751 ) -> Result<()> {
1752 info!(
1753 "Force pushing {} content to {} to preserve PR history",
1754 source_branch, target_branch
1755 );
1756
1757 if !force_unsafe {
1759 let safety_result = self.check_force_push_safety_enhanced(target_branch)?;
1760 if let Some(backup_info) = safety_result {
1761 self.create_backup_branch(target_branch, &backup_info.remote_commit_id)?;
1763 info!(
1764 "✅ Created backup branch: {}",
1765 backup_info.backup_branch_name
1766 );
1767 }
1768 }
1769
1770 let source_ref = self
1772 .repo
1773 .find_reference(&format!("refs/heads/{source_branch}"))
1774 .map_err(|e| {
1775 CascadeError::config(format!("Failed to find source branch {source_branch}: {e}"))
1776 })?;
1777 let _source_commit = source_ref.peel_to_commit().map_err(|e| {
1778 CascadeError::config(format!(
1779 "Failed to get commit for source branch {source_branch}: {e}"
1780 ))
1781 })?;
1782
1783 let mut remote = self
1785 .repo
1786 .find_remote("origin")
1787 .map_err(|e| CascadeError::config(format!("Failed to find origin remote: {e}")))?;
1788
1789 let refspec = format!("+refs/heads/{source_branch}:refs/heads/{target_branch}");
1791
1792 let callbacks = self.configure_remote_callbacks()?;
1794
1795 let mut push_options = git2::PushOptions::new();
1797 push_options.remote_callbacks(callbacks);
1798
1799 match remote.push(&[&refspec], Some(&mut push_options)) {
1800 Ok(_) => {}
1801 Err(e) => {
1802 if self.should_retry_with_default_credentials(&e) {
1803 tracing::debug!(
1804 "Authentication error detected (class: {:?}, code: {:?}): {}, retrying with DefaultCredentials",
1805 e.class(), e.code(), e
1806 );
1807
1808 let callbacks = self.configure_remote_callbacks_with_fallback(true)?;
1810 let mut push_options = git2::PushOptions::new();
1811 push_options.remote_callbacks(callbacks);
1812
1813 match remote.push(&[&refspec], Some(&mut push_options)) {
1814 Ok(_) => {
1815 tracing::debug!("Force push succeeded with DefaultCredentials");
1816 }
1818 Err(retry_error) => {
1819 tracing::debug!(
1820 "DefaultCredentials retry failed: {}, falling back to git CLI",
1821 retry_error
1822 );
1823 return self.force_push_with_git_cli(target_branch);
1824 }
1825 }
1826 } else if self.should_fallback_to_git_cli(&e) {
1827 tracing::debug!(
1828 "Network/SSL error detected (class: {:?}, code: {:?}): {}, falling back to git CLI for force push operation",
1829 e.class(), e.code(), e
1830 );
1831 return self.force_push_with_git_cli(target_branch);
1832 } else {
1833 return Err(CascadeError::config(format!(
1834 "Failed to force push {target_branch}: {e}"
1835 )));
1836 }
1837 }
1838 }
1839
1840 info!(
1841 "✅ Successfully force pushed {} to preserve PR history",
1842 target_branch
1843 );
1844 Ok(())
1845 }
1846
1847 fn check_force_push_safety_enhanced(
1850 &self,
1851 target_branch: &str,
1852 ) -> Result<Option<ForceBackupInfo>> {
1853 match self.fetch() {
1855 Ok(_) => {}
1856 Err(e) => {
1857 warn!("Could not fetch latest changes for safety check: {}", e);
1859 }
1860 }
1861
1862 let remote_ref = format!("refs/remotes/origin/{target_branch}");
1864 let local_ref = format!("refs/heads/{target_branch}");
1865
1866 let local_commit = match self.repo.find_reference(&local_ref) {
1868 Ok(reference) => reference.peel_to_commit().ok(),
1869 Err(_) => None,
1870 };
1871
1872 let remote_commit = match self.repo.find_reference(&remote_ref) {
1873 Ok(reference) => reference.peel_to_commit().ok(),
1874 Err(_) => None,
1875 };
1876
1877 if let (Some(local), Some(remote)) = (local_commit, remote_commit) {
1879 if local.id() != remote.id() {
1880 let merge_base_oid = self
1882 .repo
1883 .merge_base(local.id(), remote.id())
1884 .map_err(|e| CascadeError::config(format!("Failed to find merge base: {e}")))?;
1885
1886 if merge_base_oid != remote.id() {
1888 let commits_to_lose = self.count_commits_between(
1889 &merge_base_oid.to_string(),
1890 &remote.id().to_string(),
1891 )?;
1892
1893 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1895 let backup_branch_name = format!("{target_branch}_backup_{timestamp}");
1896
1897 debug!(
1898 "Force push to '{}' would overwrite {} commits on remote",
1899 target_branch, commits_to_lose
1900 );
1901
1902 if std::env::var("CI").is_ok() || std::env::var("FORCE_PUSH_NO_CONFIRM").is_ok()
1904 {
1905 info!(
1906 "Non-interactive environment detected, proceeding with backup creation"
1907 );
1908 return Ok(Some(ForceBackupInfo {
1909 backup_branch_name,
1910 remote_commit_id: remote.id().to_string(),
1911 commits_that_would_be_lost: commits_to_lose,
1912 }));
1913 }
1914
1915 println!("\n⚠️ FORCE PUSH WARNING ⚠️");
1917 println!("Force push to '{target_branch}' would overwrite {commits_to_lose} commits on remote:");
1918
1919 match self
1921 .get_commits_between(&merge_base_oid.to_string(), &remote.id().to_string())
1922 {
1923 Ok(commits) => {
1924 println!("\nCommits that would be lost:");
1925 for (i, commit) in commits.iter().take(5).enumerate() {
1926 let short_hash = &commit.id().to_string()[..8];
1927 let summary = commit.summary().unwrap_or("<no message>");
1928 println!(" {}. {} - {}", i + 1, short_hash, summary);
1929 }
1930 if commits.len() > 5 {
1931 println!(" ... and {} more commits", commits.len() - 5);
1932 }
1933 }
1934 Err(_) => {
1935 println!(" (Unable to retrieve commit details)");
1936 }
1937 }
1938
1939 println!("\nA backup branch '{backup_branch_name}' will be created before proceeding.");
1940
1941 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
1942 .with_prompt("Do you want to proceed with the force push?")
1943 .default(false)
1944 .interact()
1945 .map_err(|e| {
1946 CascadeError::config(format!("Failed to get user confirmation: {e}"))
1947 })?;
1948
1949 if !confirmed {
1950 return Err(CascadeError::config(
1951 "Force push cancelled by user. Use --force to bypass this check."
1952 .to_string(),
1953 ));
1954 }
1955
1956 return Ok(Some(ForceBackupInfo {
1957 backup_branch_name,
1958 remote_commit_id: remote.id().to_string(),
1959 commits_that_would_be_lost: commits_to_lose,
1960 }));
1961 }
1962 }
1963 }
1964
1965 Ok(None)
1966 }
1967
1968 fn create_backup_branch(&self, original_branch: &str, remote_commit_id: &str) -> Result<()> {
1970 let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
1971 let backup_branch_name = format!("{original_branch}_backup_{timestamp}");
1972
1973 let commit_oid = Oid::from_str(remote_commit_id).map_err(|e| {
1975 CascadeError::config(format!("Invalid commit ID {remote_commit_id}: {e}"))
1976 })?;
1977
1978 let commit = self.repo.find_commit(commit_oid).map_err(|e| {
1980 CascadeError::config(format!("Failed to find commit {remote_commit_id}: {e}"))
1981 })?;
1982
1983 self.repo
1985 .branch(&backup_branch_name, &commit, false)
1986 .map_err(|e| {
1987 CascadeError::config(format!(
1988 "Failed to create backup branch {backup_branch_name}: {e}"
1989 ))
1990 })?;
1991
1992 info!(
1993 "✅ Created backup branch '{}' pointing to {}",
1994 backup_branch_name,
1995 &remote_commit_id[..8]
1996 );
1997 Ok(())
1998 }
1999
2000 fn check_branch_deletion_safety(
2003 &self,
2004 branch_name: &str,
2005 ) -> Result<Option<BranchDeletionSafety>> {
2006 match self.fetch() {
2008 Ok(_) => {}
2009 Err(e) => {
2010 warn!(
2011 "Could not fetch latest changes for branch deletion safety check: {}",
2012 e
2013 );
2014 }
2015 }
2016
2017 let branch = self
2019 .repo
2020 .find_branch(branch_name, git2::BranchType::Local)
2021 .map_err(|e| {
2022 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2023 })?;
2024
2025 let _branch_commit = branch.get().peel_to_commit().map_err(|e| {
2026 CascadeError::branch(format!(
2027 "Could not get commit for branch '{branch_name}': {e}"
2028 ))
2029 })?;
2030
2031 let main_branch_name = self.detect_main_branch()?;
2033
2034 let is_merged_to_main = self.is_branch_merged_to_main(branch_name, &main_branch_name)?;
2036
2037 let remote_tracking_branch = self.get_remote_tracking_branch(branch_name);
2039
2040 let mut unpushed_commits = Vec::new();
2041
2042 if let Some(ref remote_branch) = remote_tracking_branch {
2044 match self.get_commits_between(remote_branch, branch_name) {
2045 Ok(commits) => {
2046 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2047 }
2048 Err(_) => {
2049 if !is_merged_to_main {
2051 if let Ok(commits) =
2052 self.get_commits_between(&main_branch_name, branch_name)
2053 {
2054 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2055 }
2056 }
2057 }
2058 }
2059 } else if !is_merged_to_main {
2060 if let Ok(commits) = self.get_commits_between(&main_branch_name, branch_name) {
2062 unpushed_commits = commits.iter().map(|c| c.id().to_string()).collect();
2063 }
2064 }
2065
2066 if !unpushed_commits.is_empty() || (!is_merged_to_main && remote_tracking_branch.is_none())
2068 {
2069 Ok(Some(BranchDeletionSafety {
2070 unpushed_commits,
2071 remote_tracking_branch,
2072 is_merged_to_main,
2073 main_branch_name,
2074 }))
2075 } else {
2076 Ok(None)
2077 }
2078 }
2079
2080 fn handle_branch_deletion_confirmation(
2082 &self,
2083 branch_name: &str,
2084 safety_info: &BranchDeletionSafety,
2085 ) -> Result<()> {
2086 if std::env::var("CI").is_ok() || std::env::var("BRANCH_DELETE_NO_CONFIRM").is_ok() {
2088 return Err(CascadeError::branch(
2089 format!(
2090 "Branch '{branch_name}' has {} unpushed commits and cannot be deleted in non-interactive mode. Use --force to override.",
2091 safety_info.unpushed_commits.len()
2092 )
2093 ));
2094 }
2095
2096 println!("\n⚠️ BRANCH DELETION WARNING ⚠️");
2098 println!("Branch '{branch_name}' has potential issues:");
2099
2100 if !safety_info.unpushed_commits.is_empty() {
2101 println!(
2102 "\n🔍 Unpushed commits ({} total):",
2103 safety_info.unpushed_commits.len()
2104 );
2105
2106 for (i, commit_id) in safety_info.unpushed_commits.iter().take(5).enumerate() {
2108 if let Ok(oid) = Oid::from_str(commit_id) {
2109 if let Ok(commit) = self.repo.find_commit(oid) {
2110 let short_hash = &commit_id[..8];
2111 let summary = commit.summary().unwrap_or("<no message>");
2112 println!(" {}. {} - {}", i + 1, short_hash, summary);
2113 }
2114 }
2115 }
2116
2117 if safety_info.unpushed_commits.len() > 5 {
2118 println!(
2119 " ... and {} more commits",
2120 safety_info.unpushed_commits.len() - 5
2121 );
2122 }
2123 }
2124
2125 if !safety_info.is_merged_to_main {
2126 println!("\n📋 Branch status:");
2127 println!(" • Not merged to '{}'", safety_info.main_branch_name);
2128 if let Some(ref remote) = safety_info.remote_tracking_branch {
2129 println!(" • Remote tracking branch: {remote}");
2130 } else {
2131 println!(" • No remote tracking branch");
2132 }
2133 }
2134
2135 println!("\n💡 Safer alternatives:");
2136 if !safety_info.unpushed_commits.is_empty() {
2137 if let Some(ref _remote) = safety_info.remote_tracking_branch {
2138 println!(" • Push commits first: git push origin {branch_name}");
2139 } else {
2140 println!(" • Create and push to remote: git push -u origin {branch_name}");
2141 }
2142 }
2143 if !safety_info.is_merged_to_main {
2144 println!(
2145 " • Merge to {} first: git checkout {} && git merge {branch_name}",
2146 safety_info.main_branch_name, safety_info.main_branch_name
2147 );
2148 }
2149
2150 let confirmed = Confirm::with_theme(&ColorfulTheme::default())
2151 .with_prompt("Do you want to proceed with deleting this branch?")
2152 .default(false)
2153 .interact()
2154 .map_err(|e| CascadeError::branch(format!("Failed to get user confirmation: {e}")))?;
2155
2156 if !confirmed {
2157 return Err(CascadeError::branch(
2158 "Branch deletion cancelled by user. Use --force to bypass this check.".to_string(),
2159 ));
2160 }
2161
2162 Ok(())
2163 }
2164
2165 pub fn detect_main_branch(&self) -> Result<String> {
2167 let main_candidates = ["main", "master", "develop", "trunk"];
2168
2169 for candidate in &main_candidates {
2170 if self
2171 .repo
2172 .find_branch(candidate, git2::BranchType::Local)
2173 .is_ok()
2174 {
2175 return Ok(candidate.to_string());
2176 }
2177 }
2178
2179 if let Ok(head) = self.repo.head() {
2181 if let Some(name) = head.shorthand() {
2182 return Ok(name.to_string());
2183 }
2184 }
2185
2186 Ok("main".to_string())
2188 }
2189
2190 fn is_branch_merged_to_main(&self, branch_name: &str, main_branch: &str) -> Result<bool> {
2192 match self.get_commits_between(main_branch, branch_name) {
2194 Ok(commits) => Ok(commits.is_empty()),
2195 Err(_) => {
2196 Ok(false)
2198 }
2199 }
2200 }
2201
2202 fn get_remote_tracking_branch(&self, branch_name: &str) -> Option<String> {
2204 let remote_candidates = [
2206 format!("origin/{branch_name}"),
2207 format!("remotes/origin/{branch_name}"),
2208 ];
2209
2210 for candidate in &remote_candidates {
2211 if self
2212 .repo
2213 .find_reference(&format!(
2214 "refs/remotes/{}",
2215 candidate.replace("remotes/", "")
2216 ))
2217 .is_ok()
2218 {
2219 return Some(candidate.clone());
2220 }
2221 }
2222
2223 None
2224 }
2225
2226 fn check_checkout_safety(&self, _target: &str) -> Result<Option<CheckoutSafety>> {
2228 let is_dirty = self.is_dirty()?;
2230 if !is_dirty {
2231 return Ok(None);
2233 }
2234
2235 let current_branch = self.get_current_branch().ok();
2237
2238 let modified_files = self.get_modified_files()?;
2240 let staged_files = self.get_staged_files()?;
2241 let untracked_files = self.get_untracked_files()?;
2242
2243 let has_uncommitted_changes = !modified_files.is_empty() || !staged_files.is_empty();
2244
2245 if has_uncommitted_changes || !untracked_files.is_empty() {
2246 return Ok(Some(CheckoutSafety {
2247 has_uncommitted_changes,
2248 modified_files,
2249 staged_files,
2250 untracked_files,
2251 stash_created: None,
2252 current_branch,
2253 }));
2254 }
2255
2256 Ok(None)
2257 }
2258
2259 fn handle_checkout_confirmation(
2261 &self,
2262 target: &str,
2263 safety_info: &CheckoutSafety,
2264 ) -> Result<()> {
2265 let is_ci = std::env::var("CI").is_ok();
2267 let no_confirm = std::env::var("CHECKOUT_NO_CONFIRM").is_ok();
2268 let is_non_interactive = is_ci || no_confirm;
2269
2270 if is_non_interactive {
2271 return Err(CascadeError::branch(
2272 format!(
2273 "Cannot checkout '{target}' with uncommitted changes in non-interactive mode. Commit your changes or use stash first."
2274 )
2275 ));
2276 }
2277
2278 println!("\n⚠️ CHECKOUT WARNING ⚠️");
2280 println!("You have uncommitted changes that could be lost:");
2281
2282 if !safety_info.modified_files.is_empty() {
2283 println!(
2284 "\n📝 Modified files ({}):",
2285 safety_info.modified_files.len()
2286 );
2287 for file in safety_info.modified_files.iter().take(10) {
2288 println!(" - {file}");
2289 }
2290 if safety_info.modified_files.len() > 10 {
2291 println!(" ... and {} more", safety_info.modified_files.len() - 10);
2292 }
2293 }
2294
2295 if !safety_info.staged_files.is_empty() {
2296 println!("\n📁 Staged files ({}):", safety_info.staged_files.len());
2297 for file in safety_info.staged_files.iter().take(10) {
2298 println!(" - {file}");
2299 }
2300 if safety_info.staged_files.len() > 10 {
2301 println!(" ... and {} more", safety_info.staged_files.len() - 10);
2302 }
2303 }
2304
2305 if !safety_info.untracked_files.is_empty() {
2306 println!(
2307 "\n❓ Untracked files ({}):",
2308 safety_info.untracked_files.len()
2309 );
2310 for file in safety_info.untracked_files.iter().take(5) {
2311 println!(" - {file}");
2312 }
2313 if safety_info.untracked_files.len() > 5 {
2314 println!(" ... and {} more", safety_info.untracked_files.len() - 5);
2315 }
2316 }
2317
2318 println!("\n🔄 Options:");
2319 println!("1. Stash changes and checkout (recommended)");
2320 println!("2. Force checkout (WILL LOSE UNCOMMITTED CHANGES)");
2321 println!("3. Cancel checkout");
2322
2323 let selection = Select::with_theme(&ColorfulTheme::default())
2325 .with_prompt("Choose an action")
2326 .items(&[
2327 "Stash changes and checkout (recommended)",
2328 "Force checkout (WILL LOSE UNCOMMITTED CHANGES)",
2329 "Cancel checkout",
2330 ])
2331 .default(0)
2332 .interact()
2333 .map_err(|e| CascadeError::branch(format!("Could not get user selection: {e}")))?;
2334
2335 match selection {
2336 0 => {
2337 let stash_message = format!(
2339 "Auto-stash before checkout to {} at {}",
2340 target,
2341 chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
2342 );
2343
2344 match self.create_stash(&stash_message) {
2345 Ok(stash_id) => {
2346 println!("✅ Created stash: {stash_message} ({stash_id})");
2347 println!("💡 You can restore with: git stash pop");
2348 }
2349 Err(e) => {
2350 println!("❌ Failed to create stash: {e}");
2351
2352 use dialoguer::Select;
2354 let stash_failed_options = vec![
2355 "Commit staged changes and proceed",
2356 "Force checkout (WILL LOSE CHANGES)",
2357 "Cancel and handle manually",
2358 ];
2359
2360 let stash_selection = Select::with_theme(&ColorfulTheme::default())
2361 .with_prompt("Stash failed. What would you like to do?")
2362 .items(&stash_failed_options)
2363 .default(0)
2364 .interact()
2365 .map_err(|e| {
2366 CascadeError::branch(format!("Could not get user selection: {e}"))
2367 })?;
2368
2369 match stash_selection {
2370 0 => {
2371 let staged_files = self.get_staged_files()?;
2373 if !staged_files.is_empty() {
2374 println!(
2375 "📝 Committing {} staged files...",
2376 staged_files.len()
2377 );
2378 match self
2379 .commit_staged_changes("WIP: Auto-commit before checkout")
2380 {
2381 Ok(Some(commit_hash)) => {
2382 println!(
2383 "✅ Committed staged changes as {}",
2384 &commit_hash[..8]
2385 );
2386 println!("💡 You can undo with: git reset HEAD~1");
2387 }
2388 Ok(None) => {
2389 println!("ℹ️ No staged changes found to commit");
2390 }
2391 Err(commit_err) => {
2392 println!(
2393 "❌ Failed to commit staged changes: {commit_err}"
2394 );
2395 return Err(CascadeError::branch(
2396 "Could not commit staged changes".to_string(),
2397 ));
2398 }
2399 }
2400 } else {
2401 println!("ℹ️ No staged changes to commit");
2402 }
2403 }
2404 1 => {
2405 println!("⚠️ Proceeding with force checkout - uncommitted changes will be lost!");
2407 }
2408 2 => {
2409 return Err(CascadeError::branch(
2411 "Checkout cancelled. Please handle changes manually and try again.".to_string(),
2412 ));
2413 }
2414 _ => unreachable!(),
2415 }
2416 }
2417 }
2418 }
2419 1 => {
2420 println!("⚠️ Proceeding with force checkout - uncommitted changes will be lost!");
2422 }
2423 2 => {
2424 return Err(CascadeError::branch(
2426 "Checkout cancelled by user".to_string(),
2427 ));
2428 }
2429 _ => unreachable!(),
2430 }
2431
2432 Ok(())
2433 }
2434
2435 fn create_stash(&self, message: &str) -> Result<String> {
2437 tracing::info!("Creating stash: {}", message);
2438
2439 let output = std::process::Command::new("git")
2441 .args(["stash", "push", "-m", message])
2442 .current_dir(&self.path)
2443 .output()
2444 .map_err(|e| {
2445 CascadeError::branch(format!("Failed to execute git stash command: {e}"))
2446 })?;
2447
2448 if output.status.success() {
2449 let stdout = String::from_utf8_lossy(&output.stdout);
2450
2451 let stash_id = if stdout.contains("Saved working directory") {
2453 let stash_list_output = std::process::Command::new("git")
2455 .args(["stash", "list", "-n", "1", "--format=%H"])
2456 .current_dir(&self.path)
2457 .output()
2458 .map_err(|e| CascadeError::branch(format!("Failed to get stash ID: {e}")))?;
2459
2460 if stash_list_output.status.success() {
2461 String::from_utf8_lossy(&stash_list_output.stdout)
2462 .trim()
2463 .to_string()
2464 } else {
2465 "stash@{0}".to_string() }
2467 } else {
2468 "stash@{0}".to_string() };
2470
2471 tracing::info!("✅ Created stash: {} ({})", message, stash_id);
2472 Ok(stash_id)
2473 } else {
2474 let stderr = String::from_utf8_lossy(&output.stderr);
2475 let stdout = String::from_utf8_lossy(&output.stdout);
2476
2477 if stderr.contains("No local changes to save")
2479 || stdout.contains("No local changes to save")
2480 {
2481 return Err(CascadeError::branch("No local changes to save".to_string()));
2482 }
2483
2484 Err(CascadeError::branch(format!(
2485 "Failed to create stash: {}\nStderr: {}\nStdout: {}",
2486 output.status, stderr, stdout
2487 )))
2488 }
2489 }
2490
2491 fn get_modified_files(&self) -> Result<Vec<String>> {
2493 let mut opts = git2::StatusOptions::new();
2494 opts.include_untracked(false).include_ignored(false);
2495
2496 let statuses = self
2497 .repo
2498 .statuses(Some(&mut opts))
2499 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2500
2501 let mut modified_files = Vec::new();
2502 for status in statuses.iter() {
2503 let flags = status.status();
2504 if flags.contains(git2::Status::WT_MODIFIED) || flags.contains(git2::Status::WT_DELETED)
2505 {
2506 if let Some(path) = status.path() {
2507 modified_files.push(path.to_string());
2508 }
2509 }
2510 }
2511
2512 Ok(modified_files)
2513 }
2514
2515 pub fn get_staged_files(&self) -> Result<Vec<String>> {
2517 let mut opts = git2::StatusOptions::new();
2518 opts.include_untracked(false).include_ignored(false);
2519
2520 let statuses = self
2521 .repo
2522 .statuses(Some(&mut opts))
2523 .map_err(|e| CascadeError::branch(format!("Could not get repository status: {e}")))?;
2524
2525 let mut staged_files = Vec::new();
2526 for status in statuses.iter() {
2527 let flags = status.status();
2528 if flags.contains(git2::Status::INDEX_MODIFIED)
2529 || flags.contains(git2::Status::INDEX_NEW)
2530 || flags.contains(git2::Status::INDEX_DELETED)
2531 {
2532 if let Some(path) = status.path() {
2533 staged_files.push(path.to_string());
2534 }
2535 }
2536 }
2537
2538 Ok(staged_files)
2539 }
2540
2541 fn count_commits_between(&self, from: &str, to: &str) -> Result<usize> {
2543 let commits = self.get_commits_between(from, to)?;
2544 Ok(commits.len())
2545 }
2546
2547 pub fn resolve_reference(&self, reference: &str) -> Result<git2::Commit<'_>> {
2549 if let Ok(oid) = Oid::from_str(reference) {
2551 if let Ok(commit) = self.repo.find_commit(oid) {
2552 return Ok(commit);
2553 }
2554 }
2555
2556 let obj = self.repo.revparse_single(reference).map_err(|e| {
2558 CascadeError::branch(format!("Could not resolve reference '{reference}': {e}"))
2559 })?;
2560
2561 obj.peel_to_commit().map_err(|e| {
2562 CascadeError::branch(format!(
2563 "Reference '{reference}' does not point to a commit: {e}"
2564 ))
2565 })
2566 }
2567
2568 pub fn reset_soft(&self, target_ref: &str) -> Result<()> {
2570 let target_commit = self.resolve_reference(target_ref)?;
2571
2572 self.repo
2573 .reset(target_commit.as_object(), git2::ResetType::Soft, None)
2574 .map_err(CascadeError::Git)?;
2575
2576 Ok(())
2577 }
2578
2579 pub fn reset_to_head(&self) -> Result<()> {
2582 tracing::debug!("Resetting working directory and index to HEAD");
2583
2584 let head = self.repo.head().map_err(CascadeError::Git)?;
2585 let head_commit = head.peel_to_commit().map_err(CascadeError::Git)?;
2586
2587 let mut checkout_builder = git2::build::CheckoutBuilder::new();
2589 checkout_builder.force(); checkout_builder.remove_untracked(false); self.repo
2593 .reset(
2594 head_commit.as_object(),
2595 git2::ResetType::Hard,
2596 Some(&mut checkout_builder),
2597 )
2598 .map_err(CascadeError::Git)?;
2599
2600 tracing::debug!("Successfully reset working directory to HEAD");
2601 Ok(())
2602 }
2603
2604 pub fn find_branch_containing_commit(&self, commit_hash: &str) -> Result<String> {
2606 let oid = Oid::from_str(commit_hash).map_err(|e| {
2607 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2608 })?;
2609
2610 let branches = self
2612 .repo
2613 .branches(Some(git2::BranchType::Local))
2614 .map_err(CascadeError::Git)?;
2615
2616 for branch_result in branches {
2617 let (branch, _) = branch_result.map_err(CascadeError::Git)?;
2618
2619 if let Some(branch_name) = branch.name().map_err(CascadeError::Git)? {
2620 if let Ok(branch_head) = branch.get().peel_to_commit() {
2622 let mut revwalk = self.repo.revwalk().map_err(CascadeError::Git)?;
2624 revwalk.push(branch_head.id()).map_err(CascadeError::Git)?;
2625
2626 for commit_oid in revwalk {
2627 let commit_oid = commit_oid.map_err(CascadeError::Git)?;
2628 if commit_oid == oid {
2629 return Ok(branch_name.to_string());
2630 }
2631 }
2632 }
2633 }
2634 }
2635
2636 Err(CascadeError::branch(format!(
2638 "Commit {commit_hash} not found in any local branch"
2639 )))
2640 }
2641
2642 pub async fn fetch_async(&self) -> Result<()> {
2646 let repo_path = self.path.clone();
2647 crate::utils::async_ops::run_git_operation(move || {
2648 let repo = GitRepository::open(&repo_path)?;
2649 repo.fetch()
2650 })
2651 .await
2652 }
2653
2654 pub async fn pull_async(&self, branch: &str) -> Result<()> {
2656 let repo_path = self.path.clone();
2657 let branch_name = branch.to_string();
2658 crate::utils::async_ops::run_git_operation(move || {
2659 let repo = GitRepository::open(&repo_path)?;
2660 repo.pull(&branch_name)
2661 })
2662 .await
2663 }
2664
2665 pub async fn push_branch_async(&self, branch_name: &str) -> Result<()> {
2667 let repo_path = self.path.clone();
2668 let branch = branch_name.to_string();
2669 crate::utils::async_ops::run_git_operation(move || {
2670 let repo = GitRepository::open(&repo_path)?;
2671 repo.push(&branch)
2672 })
2673 .await
2674 }
2675
2676 pub async fn cherry_pick_commit_async(&self, commit_hash: &str) -> Result<String> {
2678 let repo_path = self.path.clone();
2679 let hash = commit_hash.to_string();
2680 crate::utils::async_ops::run_git_operation(move || {
2681 let repo = GitRepository::open(&repo_path)?;
2682 repo.cherry_pick(&hash)
2683 })
2684 .await
2685 }
2686
2687 pub async fn get_commit_hashes_between_async(
2689 &self,
2690 from: &str,
2691 to: &str,
2692 ) -> Result<Vec<String>> {
2693 let repo_path = self.path.clone();
2694 let from_str = from.to_string();
2695 let to_str = to.to_string();
2696 crate::utils::async_ops::run_git_operation(move || {
2697 let repo = GitRepository::open(&repo_path)?;
2698 let commits = repo.get_commits_between(&from_str, &to_str)?;
2699 Ok(commits.into_iter().map(|c| c.id().to_string()).collect())
2700 })
2701 .await
2702 }
2703
2704 pub fn reset_branch_to_commit(&self, branch_name: &str, commit_hash: &str) -> Result<()> {
2706 info!(
2707 "Resetting branch '{}' to commit {}",
2708 branch_name,
2709 &commit_hash[..8]
2710 );
2711
2712 let target_oid = git2::Oid::from_str(commit_hash).map_err(|e| {
2714 CascadeError::branch(format!("Invalid commit hash '{commit_hash}': {e}"))
2715 })?;
2716
2717 let _target_commit = self.repo.find_commit(target_oid).map_err(|e| {
2718 CascadeError::branch(format!("Could not find commit '{commit_hash}': {e}"))
2719 })?;
2720
2721 let _branch = self
2723 .repo
2724 .find_branch(branch_name, git2::BranchType::Local)
2725 .map_err(|e| {
2726 CascadeError::branch(format!("Could not find branch '{branch_name}': {e}"))
2727 })?;
2728
2729 let branch_ref_name = format!("refs/heads/{branch_name}");
2731 self.repo
2732 .reference(
2733 &branch_ref_name,
2734 target_oid,
2735 true,
2736 &format!("Reset {branch_name} to {commit_hash}"),
2737 )
2738 .map_err(|e| {
2739 CascadeError::branch(format!(
2740 "Could not reset branch '{branch_name}' to commit '{commit_hash}': {e}"
2741 ))
2742 })?;
2743
2744 tracing::info!(
2745 "Successfully reset branch '{}' to commit {}",
2746 branch_name,
2747 &commit_hash[..8]
2748 );
2749 Ok(())
2750 }
2751
2752 pub fn detect_parent_branch(&self) -> Result<Option<String>> {
2754 let current_branch = self.get_current_branch()?;
2755
2756 if let Ok(Some(upstream)) = self.get_upstream_branch(¤t_branch) {
2758 if let Some(branch_name) = upstream.split('/').nth(1) {
2760 if self.branch_exists(branch_name) {
2761 tracing::debug!(
2762 "Detected parent branch '{}' from upstream tracking",
2763 branch_name
2764 );
2765 return Ok(Some(branch_name.to_string()));
2766 }
2767 }
2768 }
2769
2770 if let Ok(default_branch) = self.detect_main_branch() {
2772 if current_branch != default_branch {
2774 tracing::debug!(
2775 "Detected parent branch '{}' as repository default",
2776 default_branch
2777 );
2778 return Ok(Some(default_branch));
2779 }
2780 }
2781
2782 if let Ok(branches) = self.list_branches() {
2785 let current_commit = self.get_head_commit()?;
2786 let current_commit_hash = current_commit.id().to_string();
2787 let current_oid = current_commit.id();
2788
2789 let mut best_candidate = None;
2790 let mut best_distance = usize::MAX;
2791
2792 for branch in branches {
2793 if branch == current_branch
2795 || branch.contains("-v")
2796 || branch.ends_with("-v2")
2797 || branch.ends_with("-v3")
2798 {
2799 continue;
2800 }
2801
2802 if let Ok(base_commit_hash) = self.get_branch_commit_hash(&branch) {
2803 if let Ok(base_oid) = git2::Oid::from_str(&base_commit_hash) {
2804 if let Ok(merge_base_oid) = self.repo.merge_base(current_oid, base_oid) {
2806 if let Ok(distance) = self.count_commits_between(
2808 &merge_base_oid.to_string(),
2809 ¤t_commit_hash,
2810 ) {
2811 let is_likely_base = self.is_likely_base_branch(&branch);
2814 let adjusted_distance = if is_likely_base {
2815 distance
2816 } else {
2817 distance + 1000
2818 };
2819
2820 if adjusted_distance < best_distance {
2821 best_distance = adjusted_distance;
2822 best_candidate = Some(branch.clone());
2823 }
2824 }
2825 }
2826 }
2827 }
2828 }
2829
2830 if let Some(ref candidate) = best_candidate {
2831 tracing::debug!(
2832 "Detected parent branch '{}' with distance {}",
2833 candidate,
2834 best_distance
2835 );
2836 }
2837
2838 return Ok(best_candidate);
2839 }
2840
2841 tracing::debug!("Could not detect parent branch for '{}'", current_branch);
2842 Ok(None)
2843 }
2844
2845 fn is_likely_base_branch(&self, branch_name: &str) -> bool {
2847 let base_patterns = [
2848 "main",
2849 "master",
2850 "develop",
2851 "dev",
2852 "development",
2853 "staging",
2854 "stage",
2855 "release",
2856 "production",
2857 "prod",
2858 ];
2859
2860 base_patterns.contains(&branch_name)
2861 }
2862}
2863
2864#[cfg(test)]
2865mod tests {
2866 use super::*;
2867 use std::process::Command;
2868 use tempfile::TempDir;
2869
2870 fn create_test_repo() -> (TempDir, PathBuf) {
2871 let temp_dir = TempDir::new().unwrap();
2872 let repo_path = temp_dir.path().to_path_buf();
2873
2874 Command::new("git")
2876 .args(["init"])
2877 .current_dir(&repo_path)
2878 .output()
2879 .unwrap();
2880 Command::new("git")
2881 .args(["config", "user.name", "Test"])
2882 .current_dir(&repo_path)
2883 .output()
2884 .unwrap();
2885 Command::new("git")
2886 .args(["config", "user.email", "test@test.com"])
2887 .current_dir(&repo_path)
2888 .output()
2889 .unwrap();
2890
2891 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
2893 Command::new("git")
2894 .args(["add", "."])
2895 .current_dir(&repo_path)
2896 .output()
2897 .unwrap();
2898 Command::new("git")
2899 .args(["commit", "-m", "Initial commit"])
2900 .current_dir(&repo_path)
2901 .output()
2902 .unwrap();
2903
2904 (temp_dir, repo_path)
2905 }
2906
2907 fn create_commit(repo_path: &PathBuf, message: &str, filename: &str) {
2908 let file_path = repo_path.join(filename);
2909 std::fs::write(&file_path, format!("Content for {filename}\n")).unwrap();
2910
2911 Command::new("git")
2912 .args(["add", filename])
2913 .current_dir(repo_path)
2914 .output()
2915 .unwrap();
2916 Command::new("git")
2917 .args(["commit", "-m", message])
2918 .current_dir(repo_path)
2919 .output()
2920 .unwrap();
2921 }
2922
2923 #[test]
2924 fn test_repository_info() {
2925 let (_temp_dir, repo_path) = create_test_repo();
2926 let repo = GitRepository::open(&repo_path).unwrap();
2927
2928 let info = repo.get_info().unwrap();
2929 assert!(!info.is_dirty); assert!(
2931 info.head_branch == Some("master".to_string())
2932 || info.head_branch == Some("main".to_string()),
2933 "Expected default branch to be 'master' or 'main', got {:?}",
2934 info.head_branch
2935 );
2936 assert!(info.head_commit.is_some()); assert!(info.untracked_files.is_empty()); }
2939
2940 #[test]
2941 fn test_force_push_branch_basic() {
2942 let (_temp_dir, repo_path) = create_test_repo();
2943 let repo = GitRepository::open(&repo_path).unwrap();
2944
2945 let default_branch = repo.get_current_branch().unwrap();
2947
2948 create_commit(&repo_path, "Feature commit 1", "feature1.rs");
2950 Command::new("git")
2951 .args(["checkout", "-b", "source-branch"])
2952 .current_dir(&repo_path)
2953 .output()
2954 .unwrap();
2955 create_commit(&repo_path, "Feature commit 2", "feature2.rs");
2956
2957 Command::new("git")
2959 .args(["checkout", &default_branch])
2960 .current_dir(&repo_path)
2961 .output()
2962 .unwrap();
2963 Command::new("git")
2964 .args(["checkout", "-b", "target-branch"])
2965 .current_dir(&repo_path)
2966 .output()
2967 .unwrap();
2968 create_commit(&repo_path, "Target commit", "target.rs");
2969
2970 let result = repo.force_push_branch("target-branch", "source-branch");
2972
2973 assert!(result.is_ok() || result.is_err()); }
2977
2978 #[test]
2979 fn test_force_push_branch_nonexistent_branches() {
2980 let (_temp_dir, repo_path) = create_test_repo();
2981 let repo = GitRepository::open(&repo_path).unwrap();
2982
2983 let default_branch = repo.get_current_branch().unwrap();
2985
2986 let result = repo.force_push_branch("target", "nonexistent-source");
2988 assert!(result.is_err());
2989
2990 let result = repo.force_push_branch("nonexistent-target", &default_branch);
2992 assert!(result.is_err());
2993 }
2994
2995 #[test]
2996 fn test_force_push_workflow_simulation() {
2997 let (_temp_dir, repo_path) = create_test_repo();
2998 let repo = GitRepository::open(&repo_path).unwrap();
2999
3000 Command::new("git")
3003 .args(["checkout", "-b", "feature-auth"])
3004 .current_dir(&repo_path)
3005 .output()
3006 .unwrap();
3007 create_commit(&repo_path, "Add authentication", "auth.rs");
3008
3009 Command::new("git")
3011 .args(["checkout", "-b", "feature-auth-v2"])
3012 .current_dir(&repo_path)
3013 .output()
3014 .unwrap();
3015 create_commit(&repo_path, "Fix auth validation", "auth.rs");
3016
3017 let result = repo.force_push_branch("feature-auth", "feature-auth-v2");
3019
3020 match result {
3022 Ok(_) => {
3023 Command::new("git")
3025 .args(["checkout", "feature-auth"])
3026 .current_dir(&repo_path)
3027 .output()
3028 .unwrap();
3029 let log_output = Command::new("git")
3030 .args(["log", "--oneline", "-2"])
3031 .current_dir(&repo_path)
3032 .output()
3033 .unwrap();
3034 let log_str = String::from_utf8_lossy(&log_output.stdout);
3035 assert!(
3036 log_str.contains("Fix auth validation")
3037 || log_str.contains("Add authentication")
3038 );
3039 }
3040 Err(_) => {
3041 }
3044 }
3045 }
3046
3047 #[test]
3048 fn test_branch_operations() {
3049 let (_temp_dir, repo_path) = create_test_repo();
3050 let repo = GitRepository::open(&repo_path).unwrap();
3051
3052 let current = repo.get_current_branch().unwrap();
3054 assert!(
3055 current == "master" || current == "main",
3056 "Expected default branch to be 'master' or 'main', got '{current}'"
3057 );
3058
3059 Command::new("git")
3061 .args(["checkout", "-b", "test-branch"])
3062 .current_dir(&repo_path)
3063 .output()
3064 .unwrap();
3065 let current = repo.get_current_branch().unwrap();
3066 assert_eq!(current, "test-branch");
3067 }
3068
3069 #[test]
3070 fn test_commit_operations() {
3071 let (_temp_dir, repo_path) = create_test_repo();
3072 let repo = GitRepository::open(&repo_path).unwrap();
3073
3074 let head = repo.get_head_commit().unwrap();
3076 assert_eq!(head.message().unwrap().trim(), "Initial commit");
3077
3078 let hash = head.id().to_string();
3080 let same_commit = repo.get_commit(&hash).unwrap();
3081 assert_eq!(head.id(), same_commit.id());
3082 }
3083
3084 #[test]
3085 fn test_checkout_safety_clean_repo() {
3086 let (_temp_dir, repo_path) = create_test_repo();
3087 let repo = GitRepository::open(&repo_path).unwrap();
3088
3089 create_commit(&repo_path, "Second commit", "test.txt");
3091 Command::new("git")
3092 .args(["checkout", "-b", "test-branch"])
3093 .current_dir(&repo_path)
3094 .output()
3095 .unwrap();
3096
3097 let safety_result = repo.check_checkout_safety("main");
3099 assert!(safety_result.is_ok());
3100 assert!(safety_result.unwrap().is_none()); }
3102
3103 #[test]
3104 fn test_checkout_safety_with_modified_files() {
3105 let (_temp_dir, repo_path) = create_test_repo();
3106 let repo = GitRepository::open(&repo_path).unwrap();
3107
3108 Command::new("git")
3110 .args(["checkout", "-b", "test-branch"])
3111 .current_dir(&repo_path)
3112 .output()
3113 .unwrap();
3114
3115 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3117
3118 let safety_result = repo.check_checkout_safety("main");
3120 assert!(safety_result.is_ok());
3121 let safety_info = safety_result.unwrap();
3122 assert!(safety_info.is_some());
3123
3124 let info = safety_info.unwrap();
3125 assert!(!info.modified_files.is_empty());
3126 assert!(info.modified_files.contains(&"README.md".to_string()));
3127 }
3128
3129 #[test]
3130 fn test_unsafe_checkout_methods() {
3131 let (_temp_dir, repo_path) = create_test_repo();
3132 let repo = GitRepository::open(&repo_path).unwrap();
3133
3134 create_commit(&repo_path, "Second commit", "test.txt");
3136 Command::new("git")
3137 .args(["checkout", "-b", "test-branch"])
3138 .current_dir(&repo_path)
3139 .output()
3140 .unwrap();
3141
3142 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3144
3145 let _result = repo.checkout_branch_unsafe("main");
3147 let head_commit = repo.get_head_commit().unwrap();
3152 let commit_hash = head_commit.id().to_string();
3153 let _result = repo.checkout_commit_unsafe(&commit_hash);
3154 }
3156
3157 #[test]
3158 fn test_get_modified_files() {
3159 let (_temp_dir, repo_path) = create_test_repo();
3160 let repo = GitRepository::open(&repo_path).unwrap();
3161
3162 let modified = repo.get_modified_files().unwrap();
3164 assert!(modified.is_empty());
3165
3166 std::fs::write(repo_path.join("README.md"), "Modified content").unwrap();
3168
3169 let modified = repo.get_modified_files().unwrap();
3171 assert_eq!(modified.len(), 1);
3172 assert!(modified.contains(&"README.md".to_string()));
3173 }
3174
3175 #[test]
3176 fn test_get_staged_files() {
3177 let (_temp_dir, repo_path) = create_test_repo();
3178 let repo = GitRepository::open(&repo_path).unwrap();
3179
3180 let staged = repo.get_staged_files().unwrap();
3182 assert!(staged.is_empty());
3183
3184 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3186 Command::new("git")
3187 .args(["add", "staged.txt"])
3188 .current_dir(&repo_path)
3189 .output()
3190 .unwrap();
3191
3192 let staged = repo.get_staged_files().unwrap();
3194 assert_eq!(staged.len(), 1);
3195 assert!(staged.contains(&"staged.txt".to_string()));
3196 }
3197
3198 #[test]
3199 fn test_create_stash_fallback() {
3200 let (_temp_dir, repo_path) = create_test_repo();
3201 let repo = GitRepository::open(&repo_path).unwrap();
3202
3203 let result = repo.create_stash("test stash");
3205
3206 match result {
3208 Ok(stash_id) => {
3209 assert!(!stash_id.is_empty());
3211 assert!(stash_id.contains("stash") || stash_id.len() >= 7); }
3213 Err(error) => {
3214 let error_msg = error.to_string();
3216 assert!(
3217 error_msg.contains("No local changes to save")
3218 || error_msg.contains("git stash push")
3219 );
3220 }
3221 }
3222 }
3223
3224 #[test]
3225 fn test_delete_branch_unsafe() {
3226 let (_temp_dir, repo_path) = create_test_repo();
3227 let repo = GitRepository::open(&repo_path).unwrap();
3228
3229 create_commit(&repo_path, "Second commit", "test.txt");
3231 Command::new("git")
3232 .args(["checkout", "-b", "test-branch"])
3233 .current_dir(&repo_path)
3234 .output()
3235 .unwrap();
3236
3237 create_commit(&repo_path, "Branch-specific commit", "branch.txt");
3239
3240 Command::new("git")
3242 .args(["checkout", "main"])
3243 .current_dir(&repo_path)
3244 .output()
3245 .unwrap();
3246
3247 let result = repo.delete_branch_unsafe("test-branch");
3250 let _ = result; }
3254
3255 #[test]
3256 fn test_force_push_unsafe() {
3257 let (_temp_dir, repo_path) = create_test_repo();
3258 let repo = GitRepository::open(&repo_path).unwrap();
3259
3260 create_commit(&repo_path, "Second commit", "test.txt");
3262 Command::new("git")
3263 .args(["checkout", "-b", "test-branch"])
3264 .current_dir(&repo_path)
3265 .output()
3266 .unwrap();
3267
3268 let _result = repo.force_push_branch_unsafe("test-branch", "test-branch");
3271 }
3273
3274 #[test]
3275 fn test_cherry_pick_basic() {
3276 let (_temp_dir, repo_path) = create_test_repo();
3277 let repo = GitRepository::open(&repo_path).unwrap();
3278
3279 repo.create_branch("source", None).unwrap();
3281 repo.checkout_branch("source").unwrap();
3282
3283 std::fs::write(repo_path.join("cherry.txt"), "Cherry content").unwrap();
3284 Command::new("git")
3285 .args(["add", "."])
3286 .current_dir(&repo_path)
3287 .output()
3288 .unwrap();
3289
3290 Command::new("git")
3291 .args(["commit", "-m", "Cherry commit"])
3292 .current_dir(&repo_path)
3293 .output()
3294 .unwrap();
3295
3296 let cherry_commit = repo.get_head_commit_hash().unwrap();
3297
3298 Command::new("git")
3301 .args(["checkout", "-"])
3302 .current_dir(&repo_path)
3303 .output()
3304 .unwrap();
3305
3306 repo.create_branch("target", None).unwrap();
3307 repo.checkout_branch("target").unwrap();
3308
3309 let new_commit = repo.cherry_pick(&cherry_commit).unwrap();
3311
3312 assert_ne!(new_commit, cherry_commit, "Should create new commit hash");
3314
3315 assert!(
3317 repo_path.join("cherry.txt").exists(),
3318 "Cherry-picked file should exist"
3319 );
3320
3321 repo.checkout_branch("source").unwrap();
3323 let source_head = repo.get_head_commit_hash().unwrap();
3324 assert_eq!(
3325 source_head, cherry_commit,
3326 "Source branch should be unchanged"
3327 );
3328 }
3329
3330 #[test]
3331 fn test_cherry_pick_preserves_commit_message() {
3332 let (_temp_dir, repo_path) = create_test_repo();
3333 let repo = GitRepository::open(&repo_path).unwrap();
3334
3335 repo.create_branch("msg-test", None).unwrap();
3337 repo.checkout_branch("msg-test").unwrap();
3338
3339 std::fs::write(repo_path.join("msg.txt"), "Content").unwrap();
3340 Command::new("git")
3341 .args(["add", "."])
3342 .current_dir(&repo_path)
3343 .output()
3344 .unwrap();
3345
3346 let commit_msg = "Test: Special commit message\n\nWith body";
3347 Command::new("git")
3348 .args(["commit", "-m", commit_msg])
3349 .current_dir(&repo_path)
3350 .output()
3351 .unwrap();
3352
3353 let original_commit = repo.get_head_commit_hash().unwrap();
3354
3355 Command::new("git")
3357 .args(["checkout", "-"])
3358 .current_dir(&repo_path)
3359 .output()
3360 .unwrap();
3361 let new_commit = repo.cherry_pick(&original_commit).unwrap();
3362
3363 let output = Command::new("git")
3365 .args(["log", "-1", "--format=%B", &new_commit])
3366 .current_dir(&repo_path)
3367 .output()
3368 .unwrap();
3369
3370 let new_msg = String::from_utf8_lossy(&output.stdout);
3371 assert!(
3372 new_msg.contains("Special commit message"),
3373 "Should preserve commit message"
3374 );
3375 }
3376
3377 #[test]
3378 fn test_cherry_pick_handles_conflicts() {
3379 let (_temp_dir, repo_path) = create_test_repo();
3380 let repo = GitRepository::open(&repo_path).unwrap();
3381
3382 std::fs::write(repo_path.join("conflict.txt"), "Original").unwrap();
3384 Command::new("git")
3385 .args(["add", "."])
3386 .current_dir(&repo_path)
3387 .output()
3388 .unwrap();
3389
3390 Command::new("git")
3391 .args(["commit", "-m", "Add conflict file"])
3392 .current_dir(&repo_path)
3393 .output()
3394 .unwrap();
3395
3396 repo.create_branch("conflict-branch", None).unwrap();
3398 repo.checkout_branch("conflict-branch").unwrap();
3399
3400 std::fs::write(repo_path.join("conflict.txt"), "Modified").unwrap();
3401 Command::new("git")
3402 .args(["add", "."])
3403 .current_dir(&repo_path)
3404 .output()
3405 .unwrap();
3406
3407 Command::new("git")
3408 .args(["commit", "-m", "Modify conflict file"])
3409 .current_dir(&repo_path)
3410 .output()
3411 .unwrap();
3412
3413 let conflict_commit = repo.get_head_commit_hash().unwrap();
3414
3415 Command::new("git")
3418 .args(["checkout", "-"])
3419 .current_dir(&repo_path)
3420 .output()
3421 .unwrap();
3422 std::fs::write(repo_path.join("conflict.txt"), "Different").unwrap();
3423 Command::new("git")
3424 .args(["add", "."])
3425 .current_dir(&repo_path)
3426 .output()
3427 .unwrap();
3428
3429 Command::new("git")
3430 .args(["commit", "-m", "Different change"])
3431 .current_dir(&repo_path)
3432 .output()
3433 .unwrap();
3434
3435 let result = repo.cherry_pick(&conflict_commit);
3437 assert!(result.is_err(), "Cherry-pick with conflict should fail");
3438 }
3439
3440 #[test]
3441 fn test_reset_to_head_clears_staged_files() {
3442 let (_temp_dir, repo_path) = create_test_repo();
3443 let repo = GitRepository::open(&repo_path).unwrap();
3444
3445 std::fs::write(repo_path.join("staged1.txt"), "Content 1").unwrap();
3447 std::fs::write(repo_path.join("staged2.txt"), "Content 2").unwrap();
3448
3449 Command::new("git")
3450 .args(["add", "staged1.txt", "staged2.txt"])
3451 .current_dir(&repo_path)
3452 .output()
3453 .unwrap();
3454
3455 let staged_before = repo.get_staged_files().unwrap();
3457 assert_eq!(staged_before.len(), 2, "Should have 2 staged files");
3458
3459 repo.reset_to_head().unwrap();
3461
3462 let staged_after = repo.get_staged_files().unwrap();
3464 assert_eq!(
3465 staged_after.len(),
3466 0,
3467 "Should have no staged files after reset"
3468 );
3469 }
3470
3471 #[test]
3472 fn test_reset_to_head_clears_modified_files() {
3473 let (_temp_dir, repo_path) = create_test_repo();
3474 let repo = GitRepository::open(&repo_path).unwrap();
3475
3476 std::fs::write(repo_path.join("README.md"), "# Modified content").unwrap();
3478
3479 Command::new("git")
3481 .args(["add", "README.md"])
3482 .current_dir(&repo_path)
3483 .output()
3484 .unwrap();
3485
3486 assert!(repo.is_dirty().unwrap(), "Repo should be dirty");
3488
3489 repo.reset_to_head().unwrap();
3491
3492 assert!(
3494 !repo.is_dirty().unwrap(),
3495 "Repo should be clean after reset"
3496 );
3497
3498 let content = std::fs::read_to_string(repo_path.join("README.md")).unwrap();
3500 assert_eq!(
3501 content, "# Test",
3502 "File should be restored to original content"
3503 );
3504 }
3505
3506 #[test]
3507 fn test_reset_to_head_preserves_untracked_files() {
3508 let (_temp_dir, repo_path) = create_test_repo();
3509 let repo = GitRepository::open(&repo_path).unwrap();
3510
3511 std::fs::write(repo_path.join("untracked.txt"), "Untracked content").unwrap();
3513
3514 std::fs::write(repo_path.join("staged.txt"), "Staged content").unwrap();
3516 Command::new("git")
3517 .args(["add", "staged.txt"])
3518 .current_dir(&repo_path)
3519 .output()
3520 .unwrap();
3521
3522 repo.reset_to_head().unwrap();
3524
3525 assert!(
3527 repo_path.join("untracked.txt").exists(),
3528 "Untracked file should be preserved"
3529 );
3530
3531 assert!(
3533 !repo_path.join("staged.txt").exists(),
3534 "Staged but uncommitted file should be removed"
3535 );
3536 }
3537
3538 #[test]
3539 fn test_cherry_pick_does_not_modify_source() {
3540 let (_temp_dir, repo_path) = create_test_repo();
3541 let repo = GitRepository::open(&repo_path).unwrap();
3542
3543 repo.create_branch("feature", None).unwrap();
3545 repo.checkout_branch("feature").unwrap();
3546
3547 for i in 1..=3 {
3549 std::fs::write(
3550 repo_path.join(format!("file{i}.txt")),
3551 format!("Content {i}"),
3552 )
3553 .unwrap();
3554 Command::new("git")
3555 .args(["add", "."])
3556 .current_dir(&repo_path)
3557 .output()
3558 .unwrap();
3559
3560 Command::new("git")
3561 .args(["commit", "-m", &format!("Commit {i}")])
3562 .current_dir(&repo_path)
3563 .output()
3564 .unwrap();
3565 }
3566
3567 let source_commits = Command::new("git")
3569 .args(["log", "--format=%H", "feature"])
3570 .current_dir(&repo_path)
3571 .output()
3572 .unwrap();
3573 let source_state = String::from_utf8_lossy(&source_commits.stdout).to_string();
3574
3575 let commits: Vec<&str> = source_state.lines().collect();
3577 let middle_commit = commits[1];
3578
3579 Command::new("git")
3581 .args(["checkout", "-"])
3582 .current_dir(&repo_path)
3583 .output()
3584 .unwrap();
3585 repo.create_branch("target", None).unwrap();
3586 repo.checkout_branch("target").unwrap();
3587
3588 repo.cherry_pick(middle_commit).unwrap();
3589
3590 let after_commits = Command::new("git")
3592 .args(["log", "--format=%H", "feature"])
3593 .current_dir(&repo_path)
3594 .output()
3595 .unwrap();
3596 let after_state = String::from_utf8_lossy(&after_commits.stdout).to_string();
3597
3598 assert_eq!(
3599 source_state, after_state,
3600 "Source branch should be completely unchanged after cherry-pick"
3601 );
3602 }
3603
3604 #[test]
3605 fn test_detect_parent_branch() {
3606 let (_temp_dir, repo_path) = create_test_repo();
3607 let repo = GitRepository::open(&repo_path).unwrap();
3608
3609 repo.create_branch("dev123", None).unwrap();
3611 repo.checkout_branch("dev123").unwrap();
3612 create_commit(&repo_path, "Base commit on dev123", "base.txt");
3613
3614 repo.create_branch("feature-branch", None).unwrap();
3616 repo.checkout_branch("feature-branch").unwrap();
3617 create_commit(&repo_path, "Feature commit", "feature.txt");
3618
3619 let detected_parent = repo.detect_parent_branch().unwrap();
3621
3622 assert!(detected_parent.is_some(), "Should detect a parent branch");
3625
3626 let parent = detected_parent.unwrap();
3629 assert!(
3630 parent == "dev123" || parent == "main" || parent == "master",
3631 "Parent should be dev123, main, or master, got: {parent}"
3632 );
3633 }
3634}