1use crate::bitbucket::BitbucketIntegration;
2use crate::cli::output::Output;
3use crate::errors::{CascadeError, Result};
4use crate::git::{find_repository_root, GitRepository};
5use crate::stack::{CleanupManager, CleanupOptions, CleanupResult, StackManager, StackStatus};
6use clap::{Subcommand, ValueEnum};
7use dialoguer::{theme::ColorfulTheme, Confirm};
8use std::env;
10use tracing::{debug, warn};
11
12#[derive(ValueEnum, Clone, Debug)]
14pub enum RebaseStrategyArg {
15 ForcePush,
17 Interactive,
19}
20
21#[derive(ValueEnum, Clone, Debug)]
22pub enum MergeStrategyArg {
23 Merge,
25 Squash,
27 FastForward,
29}
30
31impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
32 fn from(arg: MergeStrategyArg) -> Self {
33 match arg {
34 MergeStrategyArg::Merge => Self::Merge,
35 MergeStrategyArg::Squash => Self::Squash,
36 MergeStrategyArg::FastForward => Self::FastForward,
37 }
38 }
39}
40
41#[derive(Debug, Subcommand)]
42pub enum StackAction {
43 Create {
45 name: String,
47 #[arg(long, short)]
49 base: Option<String>,
50 #[arg(long, short)]
52 description: Option<String>,
53 },
54
55 List {
57 #[arg(long, short)]
59 verbose: bool,
60 #[arg(long)]
62 active: bool,
63 #[arg(long)]
65 format: Option<String>,
66 },
67
68 Switch {
70 name: String,
72 },
73
74 Deactivate {
76 #[arg(long)]
78 force: bool,
79 },
80
81 Show {
83 #[arg(short, long)]
85 verbose: bool,
86 #[arg(short, long)]
88 mergeable: bool,
89 },
90
91 Push {
93 #[arg(long, short)]
95 branch: Option<String>,
96 #[arg(long, short)]
98 message: Option<String>,
99 #[arg(long)]
101 commit: Option<String>,
102 #[arg(long)]
104 since: Option<String>,
105 #[arg(long)]
107 commits: Option<String>,
108 #[arg(long, num_args = 0..=1, default_missing_value = "0")]
110 squash: Option<usize>,
111 #[arg(long)]
113 squash_since: Option<String>,
114 #[arg(long)]
116 auto_branch: bool,
117 #[arg(long)]
119 allow_base_branch: bool,
120 #[arg(long)]
122 dry_run: bool,
123 },
124
125 Pop {
127 #[arg(long)]
129 keep_branch: bool,
130 },
131
132 Submit {
134 entry: Option<usize>,
136 #[arg(long, short)]
138 title: Option<String>,
139 #[arg(long, short)]
141 description: Option<String>,
142 #[arg(long)]
144 range: Option<String>,
145 #[arg(long)]
147 draft: bool,
148 #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
150 open: bool,
151 },
152
153 Status {
155 name: Option<String>,
157 },
158
159 Prs {
161 #[arg(long)]
163 state: Option<String>,
164 #[arg(long, short)]
166 verbose: bool,
167 },
168
169 Check {
171 #[arg(long)]
173 force: bool,
174 },
175
176 Sync {
178 #[arg(long)]
180 force: bool,
181 #[arg(long)]
183 cleanup: bool,
184 #[arg(long, short)]
186 interactive: bool,
187 #[arg(long)]
189 r#continue: bool,
190 },
191
192 Rebase {
194 #[arg(long, short)]
196 interactive: bool,
197 #[arg(long)]
199 onto: Option<String>,
200 #[arg(long, value_enum)]
202 strategy: Option<RebaseStrategyArg>,
203 },
204
205 ContinueRebase,
207
208 AbortRebase,
210
211 RebaseStatus,
213
214 Delete {
216 name: String,
218 #[arg(long)]
220 force: bool,
221 },
222
223 Validate {
235 name: Option<String>,
237 #[arg(long)]
239 fix: Option<String>,
240 },
241
242 Land {
244 entry: Option<usize>,
246 #[arg(short, long)]
248 force: bool,
249 #[arg(short, long)]
251 dry_run: bool,
252 #[arg(long)]
254 auto: bool,
255 #[arg(long)]
257 wait_for_builds: bool,
258 #[arg(long, value_enum, default_value = "squash")]
260 strategy: Option<MergeStrategyArg>,
261 #[arg(long, default_value = "1800")]
263 build_timeout: u64,
264 },
265
266 AutoLand {
268 #[arg(short, long)]
270 force: bool,
271 #[arg(short, long)]
273 dry_run: bool,
274 #[arg(long)]
276 wait_for_builds: bool,
277 #[arg(long, value_enum, default_value = "squash")]
279 strategy: Option<MergeStrategyArg>,
280 #[arg(long, default_value = "1800")]
282 build_timeout: u64,
283 },
284
285 ListPrs {
287 #[arg(short, long)]
289 state: Option<String>,
290 #[arg(short, long)]
292 verbose: bool,
293 },
294
295 ContinueLand,
297
298 AbortLand,
300
301 LandStatus,
303
304 Cleanup {
306 #[arg(long)]
308 dry_run: bool,
309 #[arg(long)]
311 force: bool,
312 #[arg(long)]
314 include_stale: bool,
315 #[arg(long, default_value = "30")]
317 stale_days: u32,
318 #[arg(long)]
320 cleanup_remote: bool,
321 #[arg(long)]
323 include_non_stack: bool,
324 #[arg(long)]
326 verbose: bool,
327 },
328
329 Repair,
331}
332
333pub async fn run(action: StackAction) -> Result<()> {
334 match action {
335 StackAction::Create {
336 name,
337 base,
338 description,
339 } => create_stack(name, base, description).await,
340 StackAction::List {
341 verbose,
342 active,
343 format,
344 } => list_stacks(verbose, active, format).await,
345 StackAction::Switch { name } => switch_stack(name).await,
346 StackAction::Deactivate { force } => deactivate_stack(force).await,
347 StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
348 StackAction::Push {
349 branch,
350 message,
351 commit,
352 since,
353 commits,
354 squash,
355 squash_since,
356 auto_branch,
357 allow_base_branch,
358 dry_run,
359 } => {
360 push_to_stack(
361 branch,
362 message,
363 commit,
364 since,
365 commits,
366 squash,
367 squash_since,
368 auto_branch,
369 allow_base_branch,
370 dry_run,
371 )
372 .await
373 }
374 StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
375 StackAction::Submit {
376 entry,
377 title,
378 description,
379 range,
380 draft,
381 open,
382 } => submit_entry(entry, title, description, range, draft, open).await,
383 StackAction::Status { name } => check_stack_status(name).await,
384 StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
385 StackAction::Check { force } => check_stack(force).await,
386 StackAction::Sync {
387 force,
388 cleanup,
389 interactive,
390 r#continue,
391 } => {
392 if r#continue {
393 continue_sync().await
394 } else {
395 sync_stack(force, cleanup, interactive).await
396 }
397 }
398 StackAction::Rebase {
399 interactive,
400 onto,
401 strategy,
402 } => rebase_stack(interactive, onto, strategy).await,
403 StackAction::ContinueRebase => continue_rebase().await,
404 StackAction::AbortRebase => abort_rebase().await,
405 StackAction::RebaseStatus => rebase_status().await,
406 StackAction::Delete { name, force } => delete_stack(name, force).await,
407 StackAction::Validate { name, fix } => validate_stack(name, fix).await,
408 StackAction::Land {
409 entry,
410 force,
411 dry_run,
412 auto,
413 wait_for_builds,
414 strategy,
415 build_timeout,
416 } => {
417 land_stack(
418 entry,
419 force,
420 dry_run,
421 auto,
422 wait_for_builds,
423 strategy,
424 build_timeout,
425 )
426 .await
427 }
428 StackAction::AutoLand {
429 force,
430 dry_run,
431 wait_for_builds,
432 strategy,
433 build_timeout,
434 } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
435 StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
436 StackAction::ContinueLand => continue_land().await,
437 StackAction::AbortLand => abort_land().await,
438 StackAction::LandStatus => land_status().await,
439 StackAction::Cleanup {
440 dry_run,
441 force,
442 include_stale,
443 stale_days,
444 cleanup_remote,
445 include_non_stack,
446 verbose,
447 } => {
448 cleanup_branches(
449 dry_run,
450 force,
451 include_stale,
452 stale_days,
453 cleanup_remote,
454 include_non_stack,
455 verbose,
456 )
457 .await
458 }
459 StackAction::Repair => repair_stack_data().await,
460 }
461}
462
463pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
465 show_stack(verbose, mergeable).await
466}
467
468#[allow(clippy::too_many_arguments)]
469pub async fn push(
470 branch: Option<String>,
471 message: Option<String>,
472 commit: Option<String>,
473 since: Option<String>,
474 commits: Option<String>,
475 squash: Option<usize>,
476 squash_since: Option<String>,
477 auto_branch: bool,
478 allow_base_branch: bool,
479 dry_run: bool,
480) -> Result<()> {
481 push_to_stack(
482 branch,
483 message,
484 commit,
485 since,
486 commits,
487 squash,
488 squash_since,
489 auto_branch,
490 allow_base_branch,
491 dry_run,
492 )
493 .await
494}
495
496pub async fn pop(keep_branch: bool) -> Result<()> {
497 pop_from_stack(keep_branch).await
498}
499
500pub async fn land(
501 entry: Option<usize>,
502 force: bool,
503 dry_run: bool,
504 auto: bool,
505 wait_for_builds: bool,
506 strategy: Option<MergeStrategyArg>,
507 build_timeout: u64,
508) -> Result<()> {
509 land_stack(
510 entry,
511 force,
512 dry_run,
513 auto,
514 wait_for_builds,
515 strategy,
516 build_timeout,
517 )
518 .await
519}
520
521pub async fn autoland(
522 force: bool,
523 dry_run: bool,
524 wait_for_builds: bool,
525 strategy: Option<MergeStrategyArg>,
526 build_timeout: u64,
527) -> Result<()> {
528 auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
529}
530
531pub async fn sync(
532 force: bool,
533 skip_cleanup: bool,
534 interactive: bool,
535 r#continue: bool,
536) -> Result<()> {
537 if r#continue {
538 continue_sync().await
539 } else {
540 sync_stack(force, skip_cleanup, interactive).await
541 }
542}
543
544pub async fn rebase(
545 interactive: bool,
546 onto: Option<String>,
547 strategy: Option<RebaseStrategyArg>,
548) -> Result<()> {
549 rebase_stack(interactive, onto, strategy).await
550}
551
552pub async fn deactivate(force: bool) -> Result<()> {
553 deactivate_stack(force).await
554}
555
556pub async fn switch(name: String) -> Result<()> {
557 switch_stack(name).await
558}
559
560async fn create_stack(
561 name: String,
562 base: Option<String>,
563 description: Option<String>,
564) -> Result<()> {
565 let current_dir = env::current_dir()
566 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
567
568 let repo_root = find_repository_root(¤t_dir)
569 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
570
571 let mut manager = StackManager::new(&repo_root)?;
572 let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
573
574 let stack = manager
576 .get_stack(&stack_id)
577 .ok_or_else(|| CascadeError::config("Failed to get created stack"))?;
578
579 Output::stack_info(
581 &name,
582 &stack_id.to_string(),
583 &stack.base_branch,
584 stack.working_branch.as_deref(),
585 true, );
587
588 if let Some(desc) = description {
589 Output::sub_item(format!("Description: {desc}"));
590 }
591
592 if stack.working_branch.is_none() {
594 Output::warning(format!(
595 "You're currently on the base branch '{}'",
596 stack.base_branch
597 ));
598 Output::next_steps(&[
599 &format!("Create a feature branch: git checkout -b {name}"),
600 "Make changes and commit them",
601 "Run 'ca push' to add commits to this stack",
602 ]);
603 } else {
604 Output::next_steps(&[
605 "Make changes and commit them",
606 "Run 'ca push' to add commits to this stack",
607 "Use 'ca submit' when ready to create pull requests",
608 ]);
609 }
610
611 Ok(())
612}
613
614async fn list_stacks(verbose: bool, _active: bool, _format: Option<String>) -> Result<()> {
615 let current_dir = env::current_dir()
616 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
617
618 let repo_root = find_repository_root(¤t_dir)
619 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
620
621 let manager = StackManager::new(&repo_root)?;
622 let stacks = manager.list_stacks();
623
624 if stacks.is_empty() {
625 Output::info("No stacks found. Create one with: ca stack create <name>");
626 return Ok(());
627 }
628
629 println!("Stacks:");
630 for (stack_id, name, status, entry_count, active_marker) in stacks {
631 let status_icon = match status {
632 StackStatus::Clean => "✓",
633 StackStatus::Dirty => "~",
634 StackStatus::OutOfSync => "!",
635 StackStatus::Conflicted => "✗",
636 StackStatus::Rebasing => "↔",
637 StackStatus::NeedsSync => "~",
638 StackStatus::Corrupted => "✗",
639 };
640
641 let active_indicator = if active_marker.is_some() {
642 " (active)"
643 } else {
644 ""
645 };
646
647 let stack = manager.get_stack(&stack_id);
649
650 if verbose {
651 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
652 println!(" ID: {stack_id}");
653 if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
654 println!(" Base: {}", stack_meta.base_branch);
655 if let Some(desc) = &stack_meta.description {
656 println!(" Description: {desc}");
657 }
658 println!(
659 " Commits: {} total, {} submitted",
660 stack_meta.total_commits, stack_meta.submitted_commits
661 );
662 if stack_meta.has_conflicts {
663 println!(" ⚠️ Has conflicts");
664 }
665 }
666
667 if let Some(stack_obj) = stack {
669 if !stack_obj.entries.is_empty() {
670 println!(" Branches:");
671 for (i, entry) in stack_obj.entries.iter().enumerate() {
672 let entry_num = i + 1;
673 let submitted_indicator = if entry.is_submitted {
674 "[submitted]"
675 } else {
676 ""
677 };
678 let branch_name = &entry.branch;
679 let short_message = if entry.message.len() > 40 {
680 format!("{}...", &entry.message[..37])
681 } else {
682 entry.message.clone()
683 };
684 println!(" {entry_num}. {submitted_indicator} {branch_name} - {short_message}");
685 }
686 }
687 }
688 println!();
689 } else {
690 let branch_info = if let Some(stack_obj) = stack {
692 if stack_obj.entries.is_empty() {
693 String::new()
694 } else if stack_obj.entries.len() == 1 {
695 format!(" → {}", stack_obj.entries[0].branch)
696 } else {
697 let first_branch = &stack_obj.entries[0].branch;
698 let last_branch = &stack_obj.entries.last().unwrap().branch;
699 format!(" → {first_branch} … {last_branch}")
700 }
701 } else {
702 String::new()
703 };
704
705 println!(" {status_icon} {name} [{entry_count}]{branch_info}{active_indicator}");
706 }
707 }
708
709 if !verbose {
710 println!("\nUse --verbose for more details");
711 }
712
713 Ok(())
714}
715
716async fn switch_stack(name: String) -> Result<()> {
717 let current_dir = env::current_dir()
718 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
719
720 let repo_root = find_repository_root(¤t_dir)
721 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
722
723 let mut manager = StackManager::new(&repo_root)?;
724 let repo = GitRepository::open(&repo_root)?;
725
726 let stack = manager
728 .get_stack_by_name(&name)
729 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
730
731 if let Some(working_branch) = &stack.working_branch {
733 let current_branch = repo.get_current_branch().ok();
735
736 if current_branch.as_ref() != Some(working_branch) {
737 Output::progress(format!(
738 "Switching to stack working branch: {working_branch}"
739 ));
740
741 if repo.branch_exists(working_branch) {
743 match repo.checkout_branch(working_branch) {
744 Ok(_) => {
745 Output::success(format!("Checked out branch: {working_branch}"));
746 }
747 Err(e) => {
748 Output::warning(format!("Failed to checkout '{working_branch}': {e}"));
749 Output::sub_item("Stack activated but stayed on current branch");
750 Output::sub_item(format!(
751 "You can manually checkout with: git checkout {working_branch}"
752 ));
753 }
754 }
755 } else {
756 Output::warning(format!(
757 "Stack working branch '{working_branch}' doesn't exist locally"
758 ));
759 Output::sub_item("Stack activated but stayed on current branch");
760 Output::sub_item(format!(
761 "You may need to fetch from remote: git fetch origin {working_branch}"
762 ));
763 }
764 } else {
765 Output::success(format!("Already on stack working branch: {working_branch}"));
766 }
767 } else {
768 Output::warning(format!("Stack '{name}' has no working branch set"));
770 Output::sub_item(
771 "This typically happens when a stack was created while on the base branch",
772 );
773
774 Output::tip("To start working on this stack:");
775 Output::bullet(format!("Create a feature branch: git checkout -b {name}"));
776 Output::bullet("The stack will automatically track this as its working branch");
777 Output::bullet("Then use 'ca push' to add commits to the stack");
778
779 Output::sub_item(format!("Base branch: {}", stack.base_branch));
780 }
781
782 manager.set_active_stack_by_name(&name)?;
784 Output::success(format!("Switched to stack '{name}'"));
785
786 Ok(())
787}
788
789async fn deactivate_stack(force: bool) -> Result<()> {
790 let current_dir = env::current_dir()
791 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
792
793 let repo_root = find_repository_root(¤t_dir)
794 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
795
796 let mut manager = StackManager::new(&repo_root)?;
797
798 let active_stack = manager.get_active_stack();
799
800 if active_stack.is_none() {
801 Output::info("No active stack to deactivate");
802 return Ok(());
803 }
804
805 let stack_name = active_stack.unwrap().name.clone();
806
807 if !force {
808 Output::warning(format!(
809 "This will deactivate stack '{stack_name}' and return to normal Git workflow"
810 ));
811 Output::sub_item(format!(
812 "You can reactivate it later with 'ca stacks switch {stack_name}'"
813 ));
814 let should_deactivate = Confirm::with_theme(&ColorfulTheme::default())
816 .with_prompt("Continue with deactivation?")
817 .default(false)
818 .interact()
819 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
820
821 if !should_deactivate {
822 Output::info("Cancelled deactivation");
823 return Ok(());
824 }
825 }
826
827 manager.set_active_stack(None)?;
829
830 Output::success(format!("Deactivated stack '{stack_name}'"));
831 Output::sub_item("Stack management is now OFF - you can use normal Git workflow");
832 Output::sub_item(format!("To reactivate: ca stacks switch {stack_name}"));
833
834 Ok(())
835}
836
837async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
838 let current_dir = env::current_dir()
839 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
840
841 let repo_root = find_repository_root(¤t_dir)
842 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
843
844 let stack_manager = StackManager::new(&repo_root)?;
845
846 let (stack_id, stack_name, stack_base, stack_working, stack_entries) = {
848 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
849 CascadeError::config(
850 "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
851 .to_string(),
852 )
853 })?;
854
855 (
856 active_stack.id,
857 active_stack.name.clone(),
858 active_stack.base_branch.clone(),
859 active_stack.working_branch.clone(),
860 active_stack.entries.clone(),
861 )
862 };
863
864 Output::stack_info(
866 &stack_name,
867 &stack_id.to_string(),
868 &stack_base,
869 stack_working.as_deref(),
870 true, );
872 Output::sub_item(format!("Total entries: {}", stack_entries.len()));
873
874 if stack_entries.is_empty() {
875 Output::info("No entries in this stack yet");
876 Output::tip("Use 'ca push' to add commits to this stack");
877 return Ok(());
878 }
879
880 Output::section("Stack Entries");
882 for (i, entry) in stack_entries.iter().enumerate() {
883 let entry_num = i + 1;
884 let short_hash = entry.short_hash();
885 let short_msg = entry.short_message(50);
886
887 let metadata = stack_manager.get_repository_metadata();
889 let source_branch_info = if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash)
890 {
891 if commit_meta.source_branch != commit_meta.branch
892 && !commit_meta.source_branch.is_empty()
893 {
894 format!(" (from {})", commit_meta.source_branch)
895 } else {
896 String::new()
897 }
898 } else {
899 String::new()
900 };
901
902 let status_icon = if entry.is_submitted {
903 "[submitted]"
904 } else {
905 "[pending]"
906 };
907 Output::numbered_item(
908 entry_num,
909 format!("{short_hash} {status_icon} {short_msg}{source_branch_info}"),
910 );
911
912 if verbose {
913 Output::sub_item(format!("Branch: {}", entry.branch));
914 Output::sub_item(format!(
915 "Created: {}",
916 entry.created_at.format("%Y-%m-%d %H:%M")
917 ));
918 if let Some(pr_id) = &entry.pull_request_id {
919 Output::sub_item(format!("PR: #{pr_id}"));
920 }
921
922 Output::sub_item("Commit Message:");
924 let lines: Vec<&str> = entry.message.lines().collect();
925 for line in lines {
926 Output::sub_item(format!(" {line}"));
927 }
928 }
929 }
930
931 if show_mergeable {
933 Output::section("Mergability Status");
934
935 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
937 let config_path = config_dir.join("config.json");
938 let settings = crate::config::Settings::load_from_file(&config_path)?;
939
940 let cascade_config = crate::config::CascadeConfig {
941 bitbucket: Some(settings.bitbucket.clone()),
942 git: settings.git.clone(),
943 auth: crate::config::AuthConfig::default(),
944 cascade: settings.cascade.clone(),
945 };
946
947 let integration =
948 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
949
950 match integration.check_enhanced_stack_status(&stack_id).await {
951 Ok(status) => {
952 Output::bullet(format!("Total entries: {}", status.total_entries));
953 Output::bullet(format!("Submitted: {}", status.submitted_entries));
954 Output::bullet(format!("Open PRs: {}", status.open_prs));
955 Output::bullet(format!("Merged PRs: {}", status.merged_prs));
956 Output::bullet(format!("Declined PRs: {}", status.declined_prs));
957 Output::bullet(format!(
958 "Completion: {:.1}%",
959 status.completion_percentage()
960 ));
961
962 if !status.enhanced_statuses.is_empty() {
963 Output::section("Pull Request Status");
964 let mut ready_to_land = 0;
965
966 for enhanced in &status.enhanced_statuses {
967 let status_display = enhanced.get_display_status();
968 let ready_icon = if enhanced.is_ready_to_land() {
969 ready_to_land += 1;
970 "[READY]"
971 } else {
972 "[PENDING]"
973 };
974
975 Output::bullet(format!(
976 "{} PR #{}: {} ({})",
977 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
978 ));
979
980 if verbose {
981 println!(
982 " {} -> {}",
983 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
984 );
985
986 if !enhanced.is_ready_to_land() {
988 let blocking = enhanced.get_blocking_reasons();
989 if !blocking.is_empty() {
990 println!(" Blocking: {}", blocking.join(", "));
991 }
992 }
993
994 println!(
996 " Reviews: {} approval{}",
997 enhanced.review_status.current_approvals,
998 if enhanced.review_status.current_approvals == 1 {
999 ""
1000 } else {
1001 "s"
1002 }
1003 );
1004
1005 if enhanced.review_status.needs_work_count > 0 {
1006 println!(
1007 " {} reviewers requested changes",
1008 enhanced.review_status.needs_work_count
1009 );
1010 }
1011
1012 if let Some(build) = &enhanced.build_status {
1014 let build_icon = match build.state {
1015 crate::bitbucket::pull_request::BuildState::Successful => "✓",
1016 crate::bitbucket::pull_request::BuildState::Failed => "✗",
1017 crate::bitbucket::pull_request::BuildState::InProgress => "~",
1018 _ => "○",
1019 };
1020 println!(" Build: {} {:?}", build_icon, build.state);
1021 }
1022
1023 if let Some(url) = enhanced.pr.web_url() {
1024 println!(" URL: {url}");
1025 }
1026 println!();
1027 }
1028 }
1029
1030 if ready_to_land > 0 {
1031 println!(
1032 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
1033 ready_to_land,
1034 if ready_to_land == 1 { " is" } else { "s are" }
1035 );
1036 }
1037 }
1038 }
1039 Err(e) => {
1040 warn!("Failed to get enhanced stack status: {}", e);
1041 println!(" ⚠️ Could not fetch mergability status");
1042 println!(" Use 'ca stack show --verbose' for basic PR information");
1043 }
1044 }
1045 } else {
1046 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1048 let config_path = config_dir.join("config.json");
1049 let settings = crate::config::Settings::load_from_file(&config_path)?;
1050
1051 let cascade_config = crate::config::CascadeConfig {
1052 bitbucket: Some(settings.bitbucket.clone()),
1053 git: settings.git.clone(),
1054 auth: crate::config::AuthConfig::default(),
1055 cascade: settings.cascade.clone(),
1056 };
1057
1058 let integration =
1059 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1060
1061 match integration.check_stack_status(&stack_id).await {
1062 Ok(status) => {
1063 println!("\nPull Request Status:");
1064 println!(" Total entries: {}", status.total_entries);
1065 println!(" Submitted: {}", status.submitted_entries);
1066 println!(" Open PRs: {}", status.open_prs);
1067 println!(" Merged PRs: {}", status.merged_prs);
1068 println!(" Declined PRs: {}", status.declined_prs);
1069 println!(" Completion: {:.1}%", status.completion_percentage());
1070
1071 if !status.pull_requests.is_empty() {
1072 println!("\nPull Requests:");
1073 for pr in &status.pull_requests {
1074 let state_icon = match pr.state {
1075 crate::bitbucket::PullRequestState::Open => "○",
1076 crate::bitbucket::PullRequestState::Merged => "✓",
1077 crate::bitbucket::PullRequestState::Declined => "✗",
1078 };
1079 println!(
1080 " {} PR #{}: {} ({} -> {})",
1081 state_icon,
1082 pr.id,
1083 pr.title,
1084 pr.from_ref.display_id,
1085 pr.to_ref.display_id
1086 );
1087 if let Some(url) = pr.web_url() {
1088 println!(" URL: {url}");
1089 }
1090 }
1091 }
1092
1093 println!("\n💡 Use 'ca stack --mergeable' to see detailed status including build and review information");
1094 }
1095 Err(e) => {
1096 warn!("Failed to check stack status: {}", e);
1097 }
1098 }
1099 }
1100
1101 Ok(())
1102}
1103
1104#[allow(clippy::too_many_arguments)]
1105async fn push_to_stack(
1106 branch: Option<String>,
1107 message: Option<String>,
1108 commit: Option<String>,
1109 since: Option<String>,
1110 commits: Option<String>,
1111 squash: Option<usize>,
1112 squash_since: Option<String>,
1113 auto_branch: bool,
1114 allow_base_branch: bool,
1115 dry_run: bool,
1116) -> Result<()> {
1117 let current_dir = env::current_dir()
1118 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1119
1120 let repo_root = find_repository_root(¤t_dir)
1121 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1122
1123 let mut manager = StackManager::new(&repo_root)?;
1124 let repo = GitRepository::open(&repo_root)?;
1125
1126 if !manager.check_for_branch_change()? {
1128 return Ok(()); }
1130
1131 let active_stack = manager.get_active_stack().ok_or_else(|| {
1133 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1134 })?;
1135
1136 let current_branch = repo.get_current_branch()?;
1138 let base_branch = &active_stack.base_branch;
1139
1140 if current_branch == *base_branch {
1141 Output::error(format!(
1142 "You're currently on the base branch '{base_branch}'"
1143 ));
1144 Output::sub_item("Making commits directly on the base branch is not recommended.");
1145 Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1146
1147 if allow_base_branch {
1149 Output::warning("Proceeding anyway due to --allow-base-branch flag");
1150 } else {
1151 let has_changes = repo.is_dirty()?;
1153
1154 if has_changes {
1155 if auto_branch {
1156 let feature_branch = format!("feature/{}-work", active_stack.name);
1158 Output::progress(format!(
1159 "Auto-creating feature branch '{feature_branch}'..."
1160 ));
1161
1162 repo.create_branch(&feature_branch, None)?;
1163 repo.checkout_branch(&feature_branch)?;
1164
1165 Output::success(format!("Created and switched to '{feature_branch}'"));
1166 println!(" You can now commit and push your changes safely");
1167
1168 } else {
1170 println!("\nYou have uncommitted changes. Here are your options:");
1171 println!(" 1. Create a feature branch first:");
1172 println!(" git checkout -b feature/my-work");
1173 println!(" git commit -am \"your work\"");
1174 println!(" ca push");
1175 println!("\n 2. Auto-create a branch (recommended):");
1176 println!(" ca push --auto-branch");
1177 println!("\n 3. Force push to base branch (dangerous):");
1178 println!(" ca push --allow-base-branch");
1179
1180 return Err(CascadeError::config(
1181 "Refusing to push uncommitted changes from base branch. Use one of the options above."
1182 ));
1183 }
1184 } else {
1185 let commits_to_check = if let Some(commits_str) = &commits {
1187 commits_str
1188 .split(',')
1189 .map(|s| s.trim().to_string())
1190 .collect::<Vec<String>>()
1191 } else if let Some(since_ref) = &since {
1192 let since_commit = repo.resolve_reference(since_ref)?;
1193 let head_commit = repo.get_head_commit()?;
1194 let commits = repo.get_commits_between(
1195 &since_commit.id().to_string(),
1196 &head_commit.id().to_string(),
1197 )?;
1198 commits.into_iter().map(|c| c.id().to_string()).collect()
1199 } else if commit.is_none() {
1200 let mut unpushed = Vec::new();
1201 let head_commit = repo.get_head_commit()?;
1202 let mut current_commit = head_commit;
1203
1204 loop {
1205 let commit_hash = current_commit.id().to_string();
1206 let already_in_stack = active_stack
1207 .entries
1208 .iter()
1209 .any(|entry| entry.commit_hash == commit_hash);
1210
1211 if already_in_stack {
1212 break;
1213 }
1214
1215 unpushed.push(commit_hash);
1216
1217 if let Some(parent) = current_commit.parents().next() {
1218 current_commit = parent;
1219 } else {
1220 break;
1221 }
1222 }
1223
1224 unpushed.reverse();
1225 unpushed
1226 } else {
1227 vec![repo.get_head_commit()?.id().to_string()]
1228 };
1229
1230 if !commits_to_check.is_empty() {
1231 if auto_branch {
1232 let feature_branch = format!("feature/{}-work", active_stack.name);
1234 Output::progress(format!(
1235 "Auto-creating feature branch '{feature_branch}'..."
1236 ));
1237
1238 repo.create_branch(&feature_branch, Some(base_branch))?;
1239 repo.checkout_branch(&feature_branch)?;
1240
1241 println!(
1243 "🍒 Cherry-picking {} commit(s) to new branch...",
1244 commits_to_check.len()
1245 );
1246 for commit_hash in &commits_to_check {
1247 match repo.cherry_pick(commit_hash) {
1248 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1249 Err(e) => {
1250 println!(
1251 " ❌ Failed to cherry-pick {}: {}",
1252 &commit_hash[..8],
1253 e
1254 );
1255 println!(" 💡 You may need to resolve conflicts manually");
1256 return Err(CascadeError::branch(format!(
1257 "Failed to cherry-pick commit {commit_hash}: {e}"
1258 )));
1259 }
1260 }
1261 }
1262
1263 println!(
1264 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1265 commits_to_check.len()
1266 );
1267 println!(
1268 " You're now on the feature branch and can continue with 'ca push'"
1269 );
1270
1271 } else {
1273 println!(
1274 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1275 commits_to_check.len()
1276 );
1277 println!(" These commits are currently ON the base branch, which may not be intended.");
1278 println!("\n Options:");
1279 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1280 println!(" ca push --auto-branch");
1281 println!("\n 2. Manually create branch and move commits:");
1282 println!(" git checkout -b feature/my-work");
1283 println!(" ca push");
1284 println!("\n 3. Force push from base branch (not recommended):");
1285 println!(" ca push --allow-base-branch");
1286
1287 return Err(CascadeError::config(
1288 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1289 ));
1290 }
1291 }
1292 }
1293 }
1294 }
1295
1296 if let Some(squash_count) = squash {
1298 if squash_count == 0 {
1299 let active_stack = manager.get_active_stack().ok_or_else(|| {
1301 CascadeError::config(
1302 "No active stack. Create a stack first with 'ca stacks create'",
1303 )
1304 })?;
1305
1306 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1307
1308 if unpushed_count == 0 {
1309 Output::info(" No unpushed commits to squash");
1310 } else if unpushed_count == 1 {
1311 Output::info(" Only 1 unpushed commit, no squashing needed");
1312 } else {
1313 println!(" Auto-detected {unpushed_count} unpushed commits, squashing...");
1314 squash_commits(&repo, unpushed_count, None).await?;
1315 Output::success(" Squashed {unpushed_count} unpushed commits into one");
1316 }
1317 } else {
1318 println!(" Squashing last {squash_count} commits...");
1319 squash_commits(&repo, squash_count, None).await?;
1320 Output::success(" Squashed {squash_count} commits into one");
1321 }
1322 } else if let Some(since_ref) = squash_since {
1323 println!(" Squashing commits since {since_ref}...");
1324 let since_commit = repo.resolve_reference(&since_ref)?;
1325 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1326 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1327 Output::success(" Squashed {commits_count} commits since {since_ref} into one");
1328 }
1329
1330 let commits_to_push = if let Some(commits_str) = commits {
1332 commits_str
1334 .split(',')
1335 .map(|s| s.trim().to_string())
1336 .collect::<Vec<String>>()
1337 } else if let Some(since_ref) = since {
1338 let since_commit = repo.resolve_reference(&since_ref)?;
1340 let head_commit = repo.get_head_commit()?;
1341
1342 let commits = repo.get_commits_between(
1344 &since_commit.id().to_string(),
1345 &head_commit.id().to_string(),
1346 )?;
1347 commits.into_iter().map(|c| c.id().to_string()).collect()
1348 } else if let Some(hash) = commit {
1349 vec![hash]
1351 } else {
1352 let active_stack = manager.get_active_stack().ok_or_else(|| {
1354 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1355 })?;
1356
1357 let base_branch = &active_stack.base_branch;
1359 let current_branch = repo.get_current_branch()?;
1360
1361 if current_branch == *base_branch {
1363 let mut unpushed = Vec::new();
1364 let head_commit = repo.get_head_commit()?;
1365 let mut current_commit = head_commit;
1366
1367 loop {
1369 let commit_hash = current_commit.id().to_string();
1370 let already_in_stack = active_stack
1371 .entries
1372 .iter()
1373 .any(|entry| entry.commit_hash == commit_hash);
1374
1375 if already_in_stack {
1376 break;
1377 }
1378
1379 unpushed.push(commit_hash);
1380
1381 if let Some(parent) = current_commit.parents().next() {
1383 current_commit = parent;
1384 } else {
1385 break;
1386 }
1387 }
1388
1389 unpushed.reverse(); unpushed
1391 } else {
1392 match repo.get_commits_between(base_branch, ¤t_branch) {
1394 Ok(commits) => {
1395 let mut unpushed: Vec<String> =
1396 commits.into_iter().map(|c| c.id().to_string()).collect();
1397
1398 unpushed.retain(|commit_hash| {
1400 !active_stack
1401 .entries
1402 .iter()
1403 .any(|entry| entry.commit_hash == *commit_hash)
1404 });
1405
1406 unpushed.reverse(); unpushed
1408 }
1409 Err(e) => {
1410 return Err(CascadeError::branch(format!(
1411 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1412 This usually means the branches have diverged or don't share common history."
1413 )));
1414 }
1415 }
1416 }
1417 };
1418
1419 if commits_to_push.is_empty() {
1420 Output::info(" No commits to push to stack");
1421 return Ok(());
1422 }
1423
1424 analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1426
1427 if dry_run {
1429 return Ok(());
1430 }
1431
1432 let mut pushed_count = 0;
1434 let mut source_branches = std::collections::HashSet::new();
1435
1436 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1437 let commit_obj = repo.get_commit(commit_hash)?;
1438 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1439
1440 let commit_source_branch = repo
1442 .find_branch_containing_commit(commit_hash)
1443 .unwrap_or_else(|_| current_branch.clone());
1444 source_branches.insert(commit_source_branch.clone());
1445
1446 let branch_name = if i == 0 && branch.is_some() {
1448 branch.clone().unwrap()
1449 } else {
1450 let temp_repo = GitRepository::open(&repo_root)?;
1452 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1453 branch_mgr.generate_branch_name(&commit_msg)
1454 };
1455
1456 let final_message = if i == 0 && message.is_some() {
1458 message.clone().unwrap()
1459 } else {
1460 commit_msg.clone()
1461 };
1462
1463 let entry_id = manager.push_to_stack(
1464 branch_name.clone(),
1465 commit_hash.clone(),
1466 final_message.clone(),
1467 commit_source_branch.clone(),
1468 )?;
1469 pushed_count += 1;
1470
1471 Output::success(format!(
1472 "Pushed commit {}/{} to stack",
1473 i + 1,
1474 commits_to_push.len()
1475 ));
1476 Output::sub_item(format!(
1477 "Commit: {} ({})",
1478 &commit_hash[..8],
1479 commit_msg.split('\n').next().unwrap_or("")
1480 ));
1481 Output::sub_item(format!("Branch: {branch_name}"));
1482 Output::sub_item(format!("Source: {commit_source_branch}"));
1483 Output::sub_item(format!("Entry ID: {entry_id}"));
1484 println!();
1485 }
1486
1487 if source_branches.len() > 1 {
1489 Output::warning("Scattered Commit Detection");
1490 Output::sub_item(format!(
1491 "You've pushed commits from {} different Git branches:",
1492 source_branches.len()
1493 ));
1494 for branch in &source_branches {
1495 Output::bullet(branch.to_string());
1496 }
1497
1498 Output::section("This can lead to confusion because:");
1499 Output::bullet("Stack appears sequential but commits are scattered across branches");
1500 Output::bullet("Team members won't know which branch contains which work");
1501 Output::bullet("Branch cleanup becomes unclear after merge");
1502 Output::bullet("Rebase operations become more complex");
1503
1504 Output::tip("Consider consolidating work to a single feature branch:");
1505 Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1506 Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1507 Output::bullet("Delete old scattered branches");
1508 Output::bullet("Push the consolidated branch to your stack");
1509 println!();
1510 }
1511
1512 Output::success(format!(
1513 "Successfully pushed {} commit{} to stack",
1514 pushed_count,
1515 if pushed_count == 1 { "" } else { "s" }
1516 ));
1517
1518 Ok(())
1519}
1520
1521async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1522 let current_dir = env::current_dir()
1523 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1524
1525 let repo_root = find_repository_root(¤t_dir)
1526 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1527
1528 let mut manager = StackManager::new(&repo_root)?;
1529 let repo = GitRepository::open(&repo_root)?;
1530
1531 let entry = manager.pop_from_stack()?;
1532
1533 Output::success("Popped commit from stack");
1534 Output::sub_item(format!(
1535 "Commit: {} ({})",
1536 entry.short_hash(),
1537 entry.short_message(50)
1538 ));
1539 Output::sub_item(format!("Branch: {}", entry.branch));
1540
1541 if !keep_branch && entry.branch != repo.get_current_branch()? {
1543 match repo.delete_branch(&entry.branch) {
1544 Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1545 Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1546 }
1547 }
1548
1549 Ok(())
1550}
1551
1552async fn submit_entry(
1553 entry: Option<usize>,
1554 title: Option<String>,
1555 description: Option<String>,
1556 range: Option<String>,
1557 draft: bool,
1558 open: bool,
1559) -> Result<()> {
1560 let current_dir = env::current_dir()
1561 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1562
1563 let repo_root = find_repository_root(¤t_dir)
1564 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1565
1566 let mut stack_manager = StackManager::new(&repo_root)?;
1567
1568 if !stack_manager.check_for_branch_change()? {
1570 return Ok(()); }
1572
1573 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1575 let config_path = config_dir.join("config.json");
1576 let settings = crate::config::Settings::load_from_file(&config_path)?;
1577
1578 let cascade_config = crate::config::CascadeConfig {
1580 bitbucket: Some(settings.bitbucket.clone()),
1581 git: settings.git.clone(),
1582 auth: crate::config::AuthConfig::default(),
1583 cascade: settings.cascade.clone(),
1584 };
1585
1586 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1588 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1589 })?;
1590 let stack_id = active_stack.id;
1591
1592 let entries_to_submit = if let Some(range_str) = range {
1594 let mut entries = Vec::new();
1596
1597 if range_str.contains('-') {
1598 let parts: Vec<&str> = range_str.split('-').collect();
1600 if parts.len() != 2 {
1601 return Err(CascadeError::config(
1602 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1603 ));
1604 }
1605
1606 let start: usize = parts[0]
1607 .parse()
1608 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1609 let end: usize = parts[1]
1610 .parse()
1611 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1612
1613 if start == 0
1614 || end == 0
1615 || start > active_stack.entries.len()
1616 || end > active_stack.entries.len()
1617 {
1618 return Err(CascadeError::config(format!(
1619 "Range out of bounds. Stack has {} entries",
1620 active_stack.entries.len()
1621 )));
1622 }
1623
1624 for i in start..=end {
1625 entries.push((i, active_stack.entries[i - 1].clone()));
1626 }
1627 } else {
1628 for entry_str in range_str.split(',') {
1630 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1631 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1632 })?;
1633
1634 if entry_num == 0 || entry_num > active_stack.entries.len() {
1635 return Err(CascadeError::config(format!(
1636 "Entry {} out of bounds. Stack has {} entries",
1637 entry_num,
1638 active_stack.entries.len()
1639 )));
1640 }
1641
1642 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1643 }
1644 }
1645
1646 entries
1647 } else if let Some(entry_num) = entry {
1648 if entry_num == 0 || entry_num > active_stack.entries.len() {
1650 return Err(CascadeError::config(format!(
1651 "Invalid entry number: {}. Stack has {} entries",
1652 entry_num,
1653 active_stack.entries.len()
1654 )));
1655 }
1656 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1657 } else {
1658 active_stack
1660 .entries
1661 .iter()
1662 .enumerate()
1663 .filter(|(_, entry)| !entry.is_submitted)
1664 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1666 };
1667
1668 if entries_to_submit.is_empty() {
1669 Output::info("No entries to submit");
1670 return Ok(());
1671 }
1672
1673 Output::section(format!(
1675 "Submitting {} {}",
1676 entries_to_submit.len(),
1677 if entries_to_submit.len() == 1 {
1678 "entry"
1679 } else {
1680 "entries"
1681 }
1682 ));
1683 println!();
1684
1685 let integration_stack_manager = StackManager::new(&repo_root)?;
1687 let mut integration =
1688 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1689
1690 let mut submitted_count = 0;
1692 let mut failed_entries = Vec::new();
1693 let mut pr_urls = Vec::new(); let total_entries = entries_to_submit.len();
1695
1696 for (entry_num, entry_to_submit) in &entries_to_submit {
1697 let tree_char = if entries_to_submit.len() == 1 {
1699 "→"
1700 } else if entry_num == &entries_to_submit.len() {
1701 "└─"
1702 } else {
1703 "├─"
1704 };
1705 print!(
1706 " {} Entry {}: {}... ",
1707 tree_char, entry_num, entry_to_submit.branch
1708 );
1709 std::io::Write::flush(&mut std::io::stdout()).ok();
1710
1711 let entry_title = if total_entries == 1 {
1713 title.clone()
1714 } else {
1715 None
1716 };
1717 let entry_description = if total_entries == 1 {
1718 description.clone()
1719 } else {
1720 None
1721 };
1722
1723 match integration
1724 .submit_entry(
1725 &stack_id,
1726 &entry_to_submit.id,
1727 entry_title,
1728 entry_description,
1729 draft,
1730 )
1731 .await
1732 {
1733 Ok(pr) => {
1734 submitted_count += 1;
1735 println!("✓ PR #{}", pr.id);
1736 if let Some(url) = pr.web_url() {
1737 Output::sub_item(format!(
1738 "{} → {}",
1739 pr.from_ref.display_id, pr.to_ref.display_id
1740 ));
1741 Output::sub_item(format!("URL: {url}"));
1742 pr_urls.push(url); }
1744 }
1745 Err(e) => {
1746 println!("✗ Failed");
1747 let clean_error = if e.to_string().contains("non-fast-forward") {
1749 "Branch has diverged (was rebased after initial submission). Update to v0.1.41+ to auto force-push.".to_string()
1750 } else if e.to_string().contains("authentication") {
1751 "Authentication failed. Check your Bitbucket credentials.".to_string()
1752 } else {
1753 e.to_string()
1755 .lines()
1756 .filter(|l| !l.trim().starts_with("hint:") && !l.trim().is_empty())
1757 .take(1)
1758 .collect::<Vec<_>>()
1759 .join(" ")
1760 .trim()
1761 .to_string()
1762 };
1763 Output::sub_item(format!("Error: {}", clean_error));
1764 failed_entries.push((*entry_num, clean_error));
1765 }
1766 }
1767 }
1768
1769 println!();
1770
1771 let has_any_prs = active_stack
1773 .entries
1774 .iter()
1775 .any(|e| e.pull_request_id.is_some());
1776 if has_any_prs && submitted_count > 0 {
1777 match integration.update_all_pr_descriptions(&stack_id).await {
1778 Ok(updated_prs) => {
1779 if !updated_prs.is_empty() {
1780 Output::sub_item(format!(
1781 "Updated {} PR description{} with stack hierarchy",
1782 updated_prs.len(),
1783 if updated_prs.len() == 1 { "" } else { "s" }
1784 ));
1785 }
1786 }
1787 Err(e) => {
1788 Output::warning(format!("Failed to update some PR descriptions: {e}"));
1789 }
1790 }
1791 }
1792
1793 if failed_entries.is_empty() {
1795 Output::success(format!(
1796 "All {} {} submitted successfully!",
1797 submitted_count,
1798 if submitted_count == 1 {
1799 "entry"
1800 } else {
1801 "entries"
1802 }
1803 ));
1804 } else {
1805 println!();
1806 Output::section("Submission Summary");
1807 println!(" ✓ Successful: {submitted_count}");
1808 println!(" ✗ Failed: {}", failed_entries.len());
1809
1810 if !failed_entries.is_empty() {
1811 println!();
1812 Output::tip("Retry failed entries:");
1813 for (entry_num, _) in &failed_entries {
1814 Output::bullet(format!("ca stack submit {entry_num}"));
1815 }
1816 }
1817 }
1818
1819 if open && !pr_urls.is_empty() {
1821 println!();
1822 for url in &pr_urls {
1823 if let Err(e) = open::that(url) {
1824 Output::warning(format!("Could not open browser: {}", e));
1825 Output::tip(format!("Open manually: {}", url));
1826 }
1827 }
1828 }
1829
1830 Ok(())
1831}
1832
1833async fn check_stack_status(name: Option<String>) -> Result<()> {
1834 let current_dir = env::current_dir()
1835 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1836
1837 let repo_root = find_repository_root(¤t_dir)
1838 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1839
1840 let stack_manager = StackManager::new(&repo_root)?;
1841
1842 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1844 let config_path = config_dir.join("config.json");
1845 let settings = crate::config::Settings::load_from_file(&config_path)?;
1846
1847 let cascade_config = crate::config::CascadeConfig {
1849 bitbucket: Some(settings.bitbucket.clone()),
1850 git: settings.git.clone(),
1851 auth: crate::config::AuthConfig::default(),
1852 cascade: settings.cascade.clone(),
1853 };
1854
1855 let stack = if let Some(name) = name {
1857 stack_manager
1858 .get_stack_by_name(&name)
1859 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1860 } else {
1861 stack_manager.get_active_stack().ok_or_else(|| {
1862 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1863 })?
1864 };
1865 let stack_id = stack.id;
1866
1867 Output::section(format!("Stack: {}", stack.name));
1868 Output::sub_item(format!("ID: {}", stack.id));
1869 Output::sub_item(format!("Base: {}", stack.base_branch));
1870
1871 if let Some(description) = &stack.description {
1872 Output::sub_item(format!("Description: {description}"));
1873 }
1874
1875 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1877
1878 match integration.check_stack_status(&stack_id).await {
1880 Ok(status) => {
1881 Output::section("Pull Request Status");
1882 Output::sub_item(format!("Total entries: {}", status.total_entries));
1883 Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1884 Output::sub_item(format!("Open PRs: {}", status.open_prs));
1885 Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1886 Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1887 Output::sub_item(format!(
1888 "Completion: {:.1}%",
1889 status.completion_percentage()
1890 ));
1891
1892 if !status.pull_requests.is_empty() {
1893 Output::section("Pull Requests");
1894 for pr in &status.pull_requests {
1895 let state_icon = match pr.state {
1896 crate::bitbucket::PullRequestState::Open => "🔄",
1897 crate::bitbucket::PullRequestState::Merged => "✅",
1898 crate::bitbucket::PullRequestState::Declined => "❌",
1899 };
1900 Output::bullet(format!(
1901 "{} PR #{}: {} ({} -> {})",
1902 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1903 ));
1904 if let Some(url) = pr.web_url() {
1905 Output::sub_item(format!("URL: {url}"));
1906 }
1907 }
1908 }
1909 }
1910 Err(e) => {
1911 warn!("Failed to check stack status: {}", e);
1912 return Err(e);
1913 }
1914 }
1915
1916 Ok(())
1917}
1918
1919async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
1920 let current_dir = env::current_dir()
1921 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1922
1923 let repo_root = find_repository_root(¤t_dir)
1924 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1925
1926 let stack_manager = StackManager::new(&repo_root)?;
1927
1928 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1930 let config_path = config_dir.join("config.json");
1931 let settings = crate::config::Settings::load_from_file(&config_path)?;
1932
1933 let cascade_config = crate::config::CascadeConfig {
1935 bitbucket: Some(settings.bitbucket.clone()),
1936 git: settings.git.clone(),
1937 auth: crate::config::AuthConfig::default(),
1938 cascade: settings.cascade.clone(),
1939 };
1940
1941 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1943
1944 let pr_state = if let Some(state_str) = state {
1946 match state_str.to_lowercase().as_str() {
1947 "open" => Some(crate::bitbucket::PullRequestState::Open),
1948 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
1949 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
1950 _ => {
1951 return Err(CascadeError::config(format!(
1952 "Invalid state '{state_str}'. Use: open, merged, declined"
1953 )))
1954 }
1955 }
1956 } else {
1957 None
1958 };
1959
1960 match integration.list_pull_requests(pr_state).await {
1962 Ok(pr_page) => {
1963 if pr_page.values.is_empty() {
1964 Output::info("No pull requests found.");
1965 return Ok(());
1966 }
1967
1968 println!("Pull Requests ({} total):", pr_page.values.len());
1969 for pr in &pr_page.values {
1970 let state_icon = match pr.state {
1971 crate::bitbucket::PullRequestState::Open => "○",
1972 crate::bitbucket::PullRequestState::Merged => "✓",
1973 crate::bitbucket::PullRequestState::Declined => "✗",
1974 };
1975 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
1976 if verbose {
1977 println!(
1978 " From: {} -> {}",
1979 pr.from_ref.display_id, pr.to_ref.display_id
1980 );
1981 println!(
1982 " Author: {}",
1983 pr.author
1984 .user
1985 .display_name
1986 .as_deref()
1987 .unwrap_or(&pr.author.user.name)
1988 );
1989 if let Some(url) = pr.web_url() {
1990 println!(" URL: {url}");
1991 }
1992 if let Some(desc) = &pr.description {
1993 if !desc.is_empty() {
1994 println!(" Description: {desc}");
1995 }
1996 }
1997 println!();
1998 }
1999 }
2000
2001 if !verbose {
2002 println!("\nUse --verbose for more details");
2003 }
2004 }
2005 Err(e) => {
2006 warn!("Failed to list pull requests: {}", e);
2007 return Err(e);
2008 }
2009 }
2010
2011 Ok(())
2012}
2013
2014async fn check_stack(_force: bool) -> Result<()> {
2015 let current_dir = env::current_dir()
2016 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2017
2018 let repo_root = find_repository_root(¤t_dir)
2019 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2020
2021 let mut manager = StackManager::new(&repo_root)?;
2022
2023 let active_stack = manager
2024 .get_active_stack()
2025 .ok_or_else(|| CascadeError::config("No active stack"))?;
2026 let stack_id = active_stack.id;
2027
2028 manager.sync_stack(&stack_id)?;
2029
2030 Output::success("Stack check completed successfully");
2031
2032 Ok(())
2033}
2034
2035async fn continue_sync() -> Result<()> {
2036 let current_dir = env::current_dir()
2037 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2038
2039 let repo_root = find_repository_root(¤t_dir)?;
2040
2041 Output::section("Continuing sync from where it left off");
2042 println!();
2043
2044 let cherry_pick_head = repo_root.join(".git").join("CHERRY_PICK_HEAD");
2046 if !cherry_pick_head.exists() {
2047 return Err(CascadeError::config(
2048 "No in-progress cherry-pick found. Nothing to continue.\n\n\
2049 Use 'ca sync' to start a new sync."
2050 .to_string(),
2051 ));
2052 }
2053
2054 Output::info("Staging all resolved files");
2055
2056 std::process::Command::new("git")
2058 .args(["add", "-A"])
2059 .current_dir(&repo_root)
2060 .output()
2061 .map_err(CascadeError::Io)?;
2062
2063 Output::info("Continuing cherry-pick");
2064
2065 let continue_output = std::process::Command::new("git")
2067 .args(["cherry-pick", "--continue"])
2068 .current_dir(&repo_root)
2069 .output()
2070 .map_err(CascadeError::Io)?;
2071
2072 if !continue_output.status.success() {
2073 let stderr = String::from_utf8_lossy(&continue_output.stderr);
2074 return Err(CascadeError::Branch(format!(
2075 "Failed to continue cherry-pick: {}\n\n\
2076 Make sure all conflicts are resolved.",
2077 stderr
2078 )));
2079 }
2080
2081 Output::success("Cherry-pick continued successfully");
2082 println!();
2083
2084 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2091 let current_branch = git_repo.get_current_branch()?;
2092
2093 let stack_branch = if let Some(idx) = current_branch.rfind("-temp-") {
2096 current_branch[..idx].to_string()
2097 } else {
2098 return Err(CascadeError::config(format!(
2099 "Current branch '{}' doesn't appear to be a temp branch created by cascade.\n\
2100 Expected format: <branch>-temp-<timestamp>",
2101 current_branch
2102 )));
2103 };
2104
2105 Output::info(format!("Updating stack branch: {}", stack_branch));
2106
2107 std::process::Command::new("git")
2109 .args(["branch", "-f", &stack_branch])
2110 .current_dir(&repo_root)
2111 .output()
2112 .map_err(CascadeError::Io)?;
2113
2114 let manager = crate::stack::StackManager::new(&repo_root)?;
2116 let active_stack = manager
2117 .get_active_stack()
2118 .ok_or_else(|| CascadeError::config("No active stack found"))?;
2119
2120 let working_branch = active_stack
2121 .working_branch
2122 .as_ref()
2123 .ok_or_else(|| CascadeError::config("Active stack has no working branch"))?
2124 .clone();
2125
2126 Output::info(format!(
2127 "Checking out to working branch: {}",
2128 working_branch
2129 ));
2130
2131 git_repo.checkout_branch_unsafe(&working_branch)?;
2133
2134 println!();
2135 Output::info("Resuming sync to complete the rebase...");
2136 println!();
2137
2138 sync_stack(false, false, false).await
2140}
2141
2142async fn sync_stack(force: bool, cleanup: bool, interactive: bool) -> Result<()> {
2143 let current_dir = env::current_dir()
2144 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2145
2146 let repo_root = find_repository_root(¤t_dir)
2147 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2148
2149 let mut stack_manager = StackManager::new(&repo_root)?;
2150
2151 if stack_manager.is_in_edit_mode() {
2154 debug!("Exiting edit mode before sync (commit SHAs will change)");
2155 stack_manager.exit_edit_mode()?;
2156 }
2157
2158 let git_repo = GitRepository::open(&repo_root)?;
2159
2160 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2162 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2163 })?;
2164
2165 let base_branch = active_stack.base_branch.clone();
2166 let _stack_name = active_stack.name.clone();
2167
2168 let original_branch = git_repo.get_current_branch().ok();
2170
2171 match git_repo.checkout_branch_silent(&base_branch) {
2175 Ok(_) => {
2176 match git_repo.pull(&base_branch) {
2177 Ok(_) => {
2178 }
2180 Err(e) => {
2181 if force {
2182 Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
2183 } else {
2184 Output::error(format!("Failed to pull latest changes: {e}"));
2185 Output::tip("Use --force to skip pull and continue with rebase");
2186 return Err(CascadeError::branch(format!(
2187 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
2188 )));
2189 }
2190 }
2191 }
2192 }
2193 Err(e) => {
2194 if force {
2195 Output::warning(format!(
2196 "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2197 ));
2198 } else {
2199 Output::error(format!(
2200 "Failed to checkout base branch '{base_branch}': {e}"
2201 ));
2202 Output::tip("Use --force to bypass checkout issues and continue anyway");
2203 return Err(CascadeError::branch(format!(
2204 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2205 )));
2206 }
2207 }
2208 }
2209
2210 let mut updated_stack_manager = StackManager::new(&repo_root)?;
2213 let stack_id = active_stack.id;
2214
2215 if let Some(stack) = updated_stack_manager.get_stack_mut(&stack_id) {
2218 for entry in &mut stack.entries {
2219 if let Ok(current_commit) = git_repo.get_branch_head(&entry.branch) {
2220 if entry.commit_hash != current_commit {
2221 debug!(
2222 "Reconciling entry '{}': updating hash from {} to {} (current branch HEAD)",
2223 entry.branch,
2224 &entry.commit_hash[..8],
2225 ¤t_commit[..8]
2226 );
2227 entry.commit_hash = current_commit;
2228 }
2229 }
2230 }
2231 updated_stack_manager.save_to_disk()?;
2233 }
2234
2235 match updated_stack_manager.sync_stack(&stack_id) {
2236 Ok(_) => {
2237 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2239 match &updated_stack.status {
2240 crate::stack::StackStatus::NeedsSync => {
2241 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2243 let config_path = config_dir.join("config.json");
2244 let settings = crate::config::Settings::load_from_file(&config_path)?;
2245
2246 let cascade_config = crate::config::CascadeConfig {
2247 bitbucket: Some(settings.bitbucket.clone()),
2248 git: settings.git.clone(),
2249 auth: crate::config::AuthConfig::default(),
2250 cascade: settings.cascade.clone(),
2251 };
2252
2253 let options = crate::stack::RebaseOptions {
2256 strategy: crate::stack::RebaseStrategy::ForcePush,
2257 interactive,
2258 target_base: Some(base_branch.clone()),
2259 preserve_merges: true,
2260 auto_resolve: !interactive, max_retries: 3,
2262 skip_pull: Some(true), original_working_branch: original_branch.clone(), };
2265
2266 let mut rebase_manager = crate::stack::RebaseManager::new(
2267 updated_stack_manager,
2268 git_repo,
2269 options,
2270 );
2271
2272 match rebase_manager.rebase_stack(&stack_id) {
2273 Ok(result) => {
2274 if !result.branch_mapping.is_empty() {
2275 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2277 let integration_stack_manager =
2278 StackManager::new(&repo_root)?;
2279 let mut integration =
2280 crate::bitbucket::BitbucketIntegration::new(
2281 integration_stack_manager,
2282 cascade_config,
2283 )?;
2284
2285 match integration
2286 .update_prs_after_rebase(
2287 &stack_id,
2288 &result.branch_mapping,
2289 )
2290 .await
2291 {
2292 Ok(updated_prs) => {
2293 if !updated_prs.is_empty() {
2294 println!(
2295 "Updated {} pull requests",
2296 updated_prs.len()
2297 );
2298 }
2299 }
2300 Err(e) => {
2301 Output::warning(format!(
2302 "Failed to update pull requests: {e}"
2303 ));
2304 }
2305 }
2306 }
2307 }
2308 }
2309 Err(e) => {
2310 return Err(e);
2312 }
2313 }
2314 }
2315 crate::stack::StackStatus::Clean => {
2316 }
2318 other => {
2319 Output::info(format!("Stack status: {other:?}"));
2321 }
2322 }
2323 }
2324 }
2325 Err(e) => {
2326 if force {
2327 Output::warning(format!(
2328 "Failed to check stack status: {e} (continuing due to --force)"
2329 ));
2330 } else {
2331 return Err(e);
2332 }
2333 }
2334 }
2335
2336 if cleanup {
2338 let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2339 match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2340 Ok(result) => {
2341 if result.total_candidates > 0 {
2342 Output::section("Cleanup Summary");
2343 if !result.cleaned_branches.is_empty() {
2344 Output::success(format!(
2345 "Cleaned up {} merged branches",
2346 result.cleaned_branches.len()
2347 ));
2348 for branch in &result.cleaned_branches {
2349 Output::sub_item(format!("🗑️ Deleted: {branch}"));
2350 }
2351 }
2352 if !result.skipped_branches.is_empty() {
2353 Output::sub_item(format!(
2354 "Skipped {} branches",
2355 result.skipped_branches.len()
2356 ));
2357 }
2358 if !result.failed_branches.is_empty() {
2359 for (branch, error) in &result.failed_branches {
2360 Output::warning(format!("Failed to clean up {branch}: {error}"));
2361 }
2362 }
2363 }
2364 }
2365 Err(e) => {
2366 Output::warning(format!("Branch cleanup failed: {e}"));
2367 }
2368 }
2369 }
2370
2371 if let Some(orig_branch) = original_branch {
2373 if orig_branch != base_branch {
2374 if let Ok(git_repo) = GitRepository::open(&repo_root) {
2376 if let Err(e) = git_repo.checkout_branch(&orig_branch) {
2377 Output::warning(format!(
2378 "Could not return to original branch '{}': {}",
2379 orig_branch, e
2380 ));
2381 }
2382 }
2383 }
2384 }
2385
2386 Output::success("Sync completed successfully!");
2387
2388 Ok(())
2389}
2390
2391async fn rebase_stack(
2392 interactive: bool,
2393 onto: Option<String>,
2394 strategy: Option<RebaseStrategyArg>,
2395) -> Result<()> {
2396 let current_dir = env::current_dir()
2397 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2398
2399 let repo_root = find_repository_root(¤t_dir)
2400 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2401
2402 let stack_manager = StackManager::new(&repo_root)?;
2403 let git_repo = GitRepository::open(&repo_root)?;
2404
2405 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2407 let config_path = config_dir.join("config.json");
2408 let settings = crate::config::Settings::load_from_file(&config_path)?;
2409
2410 let cascade_config = crate::config::CascadeConfig {
2412 bitbucket: Some(settings.bitbucket.clone()),
2413 git: settings.git.clone(),
2414 auth: crate::config::AuthConfig::default(),
2415 cascade: settings.cascade.clone(),
2416 };
2417
2418 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2420 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2421 })?;
2422 let stack_id = active_stack.id;
2423
2424 let active_stack = stack_manager
2425 .get_stack(&stack_id)
2426 .ok_or_else(|| CascadeError::config("Active stack not found"))?
2427 .clone();
2428
2429 if active_stack.entries.is_empty() {
2430 Output::info("Stack is empty. Nothing to rebase.");
2431 return Ok(());
2432 }
2433
2434 Output::progress(format!("Rebasing stack: {}", active_stack.name));
2435 Output::sub_item(format!("Base: {}", active_stack.base_branch));
2436
2437 let rebase_strategy = if let Some(cli_strategy) = strategy {
2439 match cli_strategy {
2440 RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2441 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2442 }
2443 } else {
2444 crate::stack::RebaseStrategy::ForcePush
2446 };
2447
2448 let original_branch = git_repo.get_current_branch().ok();
2450
2451 let options = crate::stack::RebaseOptions {
2453 strategy: rebase_strategy.clone(),
2454 interactive,
2455 target_base: onto,
2456 preserve_merges: true,
2457 auto_resolve: !interactive, max_retries: 3,
2459 skip_pull: None, original_working_branch: original_branch,
2461 };
2462
2463 debug!(" Strategy: {:?}", rebase_strategy);
2464 debug!(" Interactive: {}", interactive);
2465 debug!(" Target base: {:?}", options.target_base);
2466 debug!(" Entries: {}", active_stack.entries.len());
2467
2468 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2470
2471 if rebase_manager.is_rebase_in_progress() {
2472 Output::warning("Rebase already in progress!");
2473 Output::tip("Use 'git status' to check the current state");
2474 Output::next_steps(&[
2475 "Run 'ca stack continue-rebase' to continue",
2476 "Run 'ca stack abort-rebase' to abort",
2477 ]);
2478 return Ok(());
2479 }
2480
2481 match rebase_manager.rebase_stack(&stack_id) {
2483 Ok(result) => {
2484 Output::success("Rebase completed!");
2485 Output::sub_item(result.get_summary());
2486
2487 if result.has_conflicts() {
2488 Output::warning(format!(
2489 "{} conflicts were resolved",
2490 result.conflicts.len()
2491 ));
2492 for conflict in &result.conflicts {
2493 Output::bullet(&conflict[..8.min(conflict.len())]);
2494 }
2495 }
2496
2497 if !result.branch_mapping.is_empty() {
2498 Output::section("Branch mapping");
2499 for (old, new) in &result.branch_mapping {
2500 Output::bullet(format!("{old} -> {new}"));
2501 }
2502
2503 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2505 let integration_stack_manager = StackManager::new(&repo_root)?;
2507 let mut integration = BitbucketIntegration::new(
2508 integration_stack_manager,
2509 cascade_config.clone(),
2510 )?;
2511
2512 match integration
2513 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2514 .await
2515 {
2516 Ok(updated_prs) => {
2517 if !updated_prs.is_empty() {
2518 println!(" 🔄 Preserved pull request history:");
2519 for pr_update in updated_prs {
2520 println!(" ✅ {pr_update}");
2521 }
2522 }
2523 }
2524 Err(e) => {
2525 eprintln!(" ⚠️ Failed to update pull requests: {e}");
2526 eprintln!(" You may need to manually update PRs in Bitbucket");
2527 }
2528 }
2529 }
2530 }
2531
2532 println!(
2533 " ✅ {} commits successfully rebased",
2534 result.success_count()
2535 );
2536
2537 if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2539 println!("\n📝 Next steps:");
2540 if !result.branch_mapping.is_empty() {
2541 println!(" 1. ✅ Branches have been rebased and force-pushed");
2542 println!(" 2. ✅ Pull requests updated automatically (history preserved)");
2543 println!(" 3. 🔍 Review the updated PRs in Bitbucket");
2544 println!(" 4. 🧪 Test your changes");
2545 } else {
2546 println!(" 1. Review the rebased stack");
2547 println!(" 2. Test your changes");
2548 println!(" 3. Submit new pull requests with 'ca stack submit'");
2549 }
2550 }
2551 }
2552 Err(e) => {
2553 warn!("❌ Rebase failed: {}", e);
2554 Output::tip(" Tips for resolving rebase issues:");
2555 println!(" - Check for uncommitted changes with 'git status'");
2556 println!(" - Ensure base branch is up to date");
2557 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2558 return Err(e);
2559 }
2560 }
2561
2562 Ok(())
2563}
2564
2565async fn continue_rebase() -> Result<()> {
2566 let current_dir = env::current_dir()
2567 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2568
2569 let repo_root = find_repository_root(¤t_dir)
2570 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2571
2572 let stack_manager = StackManager::new(&repo_root)?;
2573 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2574 let options = crate::stack::RebaseOptions::default();
2575 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2576
2577 if !rebase_manager.is_rebase_in_progress() {
2578 Output::info(" No rebase in progress");
2579 return Ok(());
2580 }
2581
2582 println!(" Continuing rebase...");
2583 match rebase_manager.continue_rebase() {
2584 Ok(_) => {
2585 Output::success(" Rebase continued successfully");
2586 println!(" Check 'ca stack rebase-status' for current state");
2587 }
2588 Err(e) => {
2589 warn!("❌ Failed to continue rebase: {}", e);
2590 Output::tip(" You may need to resolve conflicts first:");
2591 println!(" 1. Edit conflicted files");
2592 println!(" 2. Stage resolved files with 'git add'");
2593 println!(" 3. Run 'ca stack continue-rebase' again");
2594 }
2595 }
2596
2597 Ok(())
2598}
2599
2600async fn abort_rebase() -> Result<()> {
2601 let current_dir = env::current_dir()
2602 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2603
2604 let repo_root = find_repository_root(¤t_dir)
2605 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2606
2607 let stack_manager = StackManager::new(&repo_root)?;
2608 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2609 let options = crate::stack::RebaseOptions::default();
2610 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2611
2612 if !rebase_manager.is_rebase_in_progress() {
2613 Output::info(" No rebase in progress");
2614 return Ok(());
2615 }
2616
2617 println!("⚠️ Aborting rebase...");
2618 match rebase_manager.abort_rebase() {
2619 Ok(_) => {
2620 Output::success(" Rebase aborted successfully");
2621 println!(" Repository restored to pre-rebase state");
2622 }
2623 Err(e) => {
2624 warn!("❌ Failed to abort rebase: {}", e);
2625 println!("⚠️ You may need to manually clean up the repository state");
2626 }
2627 }
2628
2629 Ok(())
2630}
2631
2632async fn rebase_status() -> Result<()> {
2633 let current_dir = env::current_dir()
2634 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2635
2636 let repo_root = find_repository_root(¤t_dir)
2637 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2638
2639 let stack_manager = StackManager::new(&repo_root)?;
2640 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2641
2642 println!("Rebase Status");
2643
2644 let git_dir = current_dir.join(".git");
2646 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2647 || git_dir.join("rebase-merge").exists()
2648 || git_dir.join("rebase-apply").exists();
2649
2650 if rebase_in_progress {
2651 println!(" Status: 🔄 Rebase in progress");
2652 println!(
2653 "
2654📝 Actions available:"
2655 );
2656 println!(" - 'ca stack continue-rebase' to continue");
2657 println!(" - 'ca stack abort-rebase' to abort");
2658 println!(" - 'git status' to see conflicted files");
2659
2660 match git_repo.get_status() {
2662 Ok(statuses) => {
2663 let mut conflicts = Vec::new();
2664 for status in statuses.iter() {
2665 if status.status().contains(git2::Status::CONFLICTED) {
2666 if let Some(path) = status.path() {
2667 conflicts.push(path.to_string());
2668 }
2669 }
2670 }
2671
2672 if !conflicts.is_empty() {
2673 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2674 for conflict in conflicts {
2675 println!(" - {conflict}");
2676 }
2677 println!(
2678 "
2679💡 To resolve conflicts:"
2680 );
2681 println!(" 1. Edit the conflicted files");
2682 println!(" 2. Stage resolved files: git add <file>");
2683 println!(" 3. Continue: ca stack continue-rebase");
2684 }
2685 }
2686 Err(e) => {
2687 warn!("Failed to get git status: {}", e);
2688 }
2689 }
2690 } else {
2691 println!(" Status: ✅ No rebase in progress");
2692
2693 if let Some(active_stack) = stack_manager.get_active_stack() {
2695 println!(" Active stack: {}", active_stack.name);
2696 println!(" Entries: {}", active_stack.entries.len());
2697 println!(" Base branch: {}", active_stack.base_branch);
2698 }
2699 }
2700
2701 Ok(())
2702}
2703
2704async fn delete_stack(name: String, force: bool) -> Result<()> {
2705 let current_dir = env::current_dir()
2706 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2707
2708 let repo_root = find_repository_root(¤t_dir)
2709 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2710
2711 let mut manager = StackManager::new(&repo_root)?;
2712
2713 let stack = manager
2714 .get_stack_by_name(&name)
2715 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2716 let stack_id = stack.id;
2717
2718 if !force && !stack.entries.is_empty() {
2719 return Err(CascadeError::config(format!(
2720 "Stack '{}' has {} entries. Use --force to delete anyway",
2721 name,
2722 stack.entries.len()
2723 )));
2724 }
2725
2726 let deleted = manager.delete_stack(&stack_id)?;
2727
2728 Output::success(format!("Deleted stack '{}'", deleted.name));
2729 if !deleted.entries.is_empty() {
2730 Output::warning(format!("{} entries were removed", deleted.entries.len()));
2731 }
2732
2733 Ok(())
2734}
2735
2736async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2737 let current_dir = env::current_dir()
2738 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2739
2740 let repo_root = find_repository_root(¤t_dir)
2741 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2742
2743 let mut manager = StackManager::new(&repo_root)?;
2744
2745 if let Some(name) = name {
2746 let stack = manager
2748 .get_stack_by_name(&name)
2749 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2750
2751 let stack_id = stack.id;
2752
2753 match stack.validate() {
2755 Ok(_message) => {
2756 Output::success(format!("Stack '{}' structure validation passed", name));
2757 }
2758 Err(e) => {
2759 println!("✗ Stack '{}' structure validation failed: {}", name, e);
2760 return Err(CascadeError::config(e));
2761 }
2762 }
2763
2764 manager.handle_branch_modifications(&stack_id, fix_mode)?;
2766
2767 println!("🎉 Stack '{name}' validation completed");
2768 Ok(())
2769 } else {
2770 println!("🔍 Validating all stacks...");
2772
2773 let all_stacks = manager.get_all_stacks();
2775 let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2776
2777 if stack_ids.is_empty() {
2778 println!("📭 No stacks found");
2779 return Ok(());
2780 }
2781
2782 let mut all_valid = true;
2783 for stack_id in stack_ids {
2784 let stack = manager.get_stack(&stack_id).unwrap();
2785 let stack_name = &stack.name;
2786
2787 println!("\nChecking stack '{stack_name}':");
2788
2789 match stack.validate() {
2791 Ok(message) => {
2792 println!(" ✅ Structure: {message}");
2793 }
2794 Err(e) => {
2795 println!(" ❌ Structure: {e}");
2796 all_valid = false;
2797 continue;
2798 }
2799 }
2800
2801 match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2803 Ok(_) => {
2804 println!(" ✅ Git integrity: OK");
2805 }
2806 Err(e) => {
2807 println!(" ❌ Git integrity: {e}");
2808 all_valid = false;
2809 }
2810 }
2811 }
2812
2813 if all_valid {
2814 println!("\n🎉 All stacks passed validation");
2815 } else {
2816 println!("\n⚠️ Some stacks have validation issues");
2817 return Err(CascadeError::config("Stack validation failed".to_string()));
2818 }
2819
2820 Ok(())
2821 }
2822}
2823
2824#[allow(dead_code)]
2826fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2827 let mut unpushed = Vec::new();
2828 let head_commit = repo.get_head_commit()?;
2829 let mut current_commit = head_commit;
2830
2831 loop {
2833 let commit_hash = current_commit.id().to_string();
2834 let already_in_stack = stack
2835 .entries
2836 .iter()
2837 .any(|entry| entry.commit_hash == commit_hash);
2838
2839 if already_in_stack {
2840 break;
2841 }
2842
2843 unpushed.push(commit_hash);
2844
2845 if let Some(parent) = current_commit.parents().next() {
2847 current_commit = parent;
2848 } else {
2849 break;
2850 }
2851 }
2852
2853 unpushed.reverse(); Ok(unpushed)
2855}
2856
2857pub async fn squash_commits(
2859 repo: &GitRepository,
2860 count: usize,
2861 since_ref: Option<String>,
2862) -> Result<()> {
2863 if count <= 1 {
2864 return Ok(()); }
2866
2867 let _current_branch = repo.get_current_branch()?;
2869
2870 let rebase_range = if let Some(ref since) = since_ref {
2872 since.clone()
2873 } else {
2874 format!("HEAD~{count}")
2875 };
2876
2877 println!(" Analyzing {count} commits to create smart squash message...");
2878
2879 let head_commit = repo.get_head_commit()?;
2881 let mut commits_to_squash = Vec::new();
2882 let mut current = head_commit;
2883
2884 for _ in 0..count {
2886 commits_to_squash.push(current.clone());
2887 if current.parent_count() > 0 {
2888 current = current.parent(0).map_err(CascadeError::Git)?;
2889 } else {
2890 break;
2891 }
2892 }
2893
2894 let smart_message = generate_squash_message(&commits_to_squash)?;
2896 println!(
2897 " Smart message: {}",
2898 smart_message.lines().next().unwrap_or("")
2899 );
2900
2901 let reset_target = if since_ref.is_some() {
2903 format!("{rebase_range}~1")
2905 } else {
2906 format!("HEAD~{count}")
2908 };
2909
2910 repo.reset_soft(&reset_target)?;
2912
2913 repo.stage_all()?;
2915
2916 let new_commit_hash = repo.commit(&smart_message)?;
2918
2919 println!(
2920 " Created squashed commit: {} ({})",
2921 &new_commit_hash[..8],
2922 smart_message.lines().next().unwrap_or("")
2923 );
2924 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2925
2926 Ok(())
2927}
2928
2929pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2931 if commits.is_empty() {
2932 return Ok("Squashed commits".to_string());
2933 }
2934
2935 let messages: Vec<String> = commits
2937 .iter()
2938 .map(|c| c.message().unwrap_or("").trim().to_string())
2939 .filter(|m| !m.is_empty())
2940 .collect();
2941
2942 if messages.is_empty() {
2943 return Ok("Squashed commits".to_string());
2944 }
2945
2946 if let Some(last_msg) = messages.first() {
2948 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2950 return Ok(last_msg
2951 .trim_start_matches("Final:")
2952 .trim_start_matches("final:")
2953 .trim()
2954 .to_string());
2955 }
2956 }
2957
2958 let wip_count = messages
2960 .iter()
2961 .filter(|m| {
2962 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2963 })
2964 .count();
2965
2966 if wip_count > messages.len() / 2 {
2967 let non_wip: Vec<&String> = messages
2969 .iter()
2970 .filter(|m| {
2971 !m.to_lowercase().starts_with("wip")
2972 && !m.to_lowercase().contains("work in progress")
2973 })
2974 .collect();
2975
2976 if let Some(best_msg) = non_wip.first() {
2977 return Ok(best_msg.to_string());
2978 }
2979
2980 let feature = extract_feature_from_wip(&messages);
2982 return Ok(feature);
2983 }
2984
2985 Ok(messages.first().unwrap().clone())
2987}
2988
2989pub fn extract_feature_from_wip(messages: &[String]) -> String {
2991 for msg in messages {
2993 if msg.to_lowercase().starts_with("wip:") {
2995 if let Some(rest) = msg
2996 .strip_prefix("WIP:")
2997 .or_else(|| msg.strip_prefix("wip:"))
2998 {
2999 let feature = rest.trim();
3000 if !feature.is_empty() && feature.len() > 3 {
3001 let mut chars: Vec<char> = feature.chars().collect();
3003 if let Some(first) = chars.first_mut() {
3004 *first = first.to_uppercase().next().unwrap_or(*first);
3005 }
3006 return chars.into_iter().collect();
3007 }
3008 }
3009 }
3010 }
3011
3012 if let Some(first) = messages.first() {
3014 let cleaned = first
3015 .trim_start_matches("WIP:")
3016 .trim_start_matches("wip:")
3017 .trim_start_matches("WIP")
3018 .trim_start_matches("wip")
3019 .trim();
3020
3021 if !cleaned.is_empty() {
3022 return format!("Implement {cleaned}");
3023 }
3024 }
3025
3026 format!("Squashed {} commits", messages.len())
3027}
3028
3029pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
3031 let head_commit = repo.get_head_commit()?;
3032 let since_commit = repo.get_commit(since_commit_hash)?;
3033
3034 let mut count = 0;
3035 let mut current = head_commit;
3036
3037 loop {
3039 if current.id() == since_commit.id() {
3040 break;
3041 }
3042
3043 count += 1;
3044
3045 if current.parent_count() == 0 {
3047 break; }
3049
3050 current = current.parent(0).map_err(CascadeError::Git)?;
3051 }
3052
3053 Ok(count)
3054}
3055
3056async fn land_stack(
3058 entry: Option<usize>,
3059 force: bool,
3060 dry_run: bool,
3061 auto: bool,
3062 wait_for_builds: bool,
3063 strategy: Option<MergeStrategyArg>,
3064 build_timeout: u64,
3065) -> Result<()> {
3066 let current_dir = env::current_dir()
3067 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3068
3069 let repo_root = find_repository_root(¤t_dir)
3070 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3071
3072 let stack_manager = StackManager::new(&repo_root)?;
3073
3074 let stack_id = stack_manager
3076 .get_active_stack()
3077 .map(|s| s.id)
3078 .ok_or_else(|| {
3079 CascadeError::config(
3080 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
3081 .to_string(),
3082 )
3083 })?;
3084
3085 let active_stack = stack_manager
3086 .get_active_stack()
3087 .cloned()
3088 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
3089
3090 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
3092 let config_path = config_dir.join("config.json");
3093 let settings = crate::config::Settings::load_from_file(&config_path)?;
3094
3095 let cascade_config = crate::config::CascadeConfig {
3096 bitbucket: Some(settings.bitbucket.clone()),
3097 git: settings.git.clone(),
3098 auth: crate::config::AuthConfig::default(),
3099 cascade: settings.cascade.clone(),
3100 };
3101
3102 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
3103
3104 let status = integration.check_enhanced_stack_status(&stack_id).await?;
3106
3107 if status.enhanced_statuses.is_empty() {
3108 println!("❌ No pull requests found to land");
3109 return Ok(());
3110 }
3111
3112 let ready_prs: Vec<_> = status
3114 .enhanced_statuses
3115 .iter()
3116 .filter(|pr_status| {
3117 if let Some(entry_num) = entry {
3119 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
3121 if pr_status.pr.from_ref.display_id != stack_entry.branch {
3123 return false;
3124 }
3125 } else {
3126 return false; }
3128 }
3129
3130 if force {
3131 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
3133 } else {
3134 pr_status.is_ready_to_land()
3135 }
3136 })
3137 .collect();
3138
3139 if ready_prs.is_empty() {
3140 if let Some(entry_num) = entry {
3141 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
3142 } else {
3143 println!("❌ No pull requests are ready to land");
3144 }
3145
3146 println!("\n🚫 Blocking Issues:");
3148 for pr_status in &status.enhanced_statuses {
3149 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
3150 let blocking = pr_status.get_blocking_reasons();
3151 if !blocking.is_empty() {
3152 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
3153 }
3154 }
3155 }
3156
3157 if !force {
3158 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
3159 }
3160 return Ok(());
3161 }
3162
3163 if dry_run {
3164 if let Some(entry_num) = entry {
3165 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
3166 } else {
3167 println!("🏃 Dry Run - PRs that would be landed:");
3168 }
3169 for pr_status in &ready_prs {
3170 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
3171 if !pr_status.is_ready_to_land() && force {
3172 let blocking = pr_status.get_blocking_reasons();
3173 println!(
3174 " ⚠️ Would force land despite: {}",
3175 blocking.join(", ")
3176 );
3177 }
3178 }
3179 return Ok(());
3180 }
3181
3182 if entry.is_some() && ready_prs.len() > 1 {
3185 println!(
3186 "🎯 {} PRs are ready to land, but landing only entry #{}",
3187 ready_prs.len(),
3188 entry.unwrap()
3189 );
3190 }
3191
3192 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
3194 strategy.unwrap_or(MergeStrategyArg::Squash).into();
3195 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3196 merge_strategy: merge_strategy.clone(),
3197 wait_for_builds,
3198 build_timeout: std::time::Duration::from_secs(build_timeout),
3199 allowed_authors: None, };
3201
3202 println!(
3204 "🚀 Landing {} PR{}...",
3205 ready_prs.len(),
3206 if ready_prs.len() == 1 { "" } else { "s" }
3207 );
3208
3209 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
3210 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
3211 );
3212
3213 let mut landed_count = 0;
3215 let mut failed_count = 0;
3216 let total_ready_prs = ready_prs.len();
3217
3218 for pr_status in ready_prs {
3219 let pr_id = pr_status.pr.id;
3220
3221 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
3222
3223 let land_result = if auto {
3224 pr_manager
3226 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
3227 .await
3228 } else {
3229 pr_manager
3231 .merge_pull_request(pr_id, merge_strategy.clone())
3232 .await
3233 .map(
3234 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3235 pr: Box::new(pr),
3236 merge_strategy: merge_strategy.clone(),
3237 },
3238 )
3239 };
3240
3241 match land_result {
3242 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3243 println!(" ✅");
3244 landed_count += 1;
3245
3246 if landed_count < total_ready_prs {
3248 println!(" Retargeting remaining PRs to latest base...");
3249
3250 let base_branch = active_stack.base_branch.clone();
3252 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3253
3254 println!(" 📥 Updating base branch: {base_branch}");
3255 match git_repo.pull(&base_branch) {
3256 Ok(_) => println!(" ✅ Base branch updated successfully"),
3257 Err(e) => {
3258 println!(" ⚠️ Warning: Failed to update base branch: {e}");
3259 println!(
3260 " 💡 You may want to manually run: git pull origin {base_branch}"
3261 );
3262 }
3263 }
3264
3265 let mut rebase_manager = crate::stack::RebaseManager::new(
3267 StackManager::new(&repo_root)?,
3268 git_repo,
3269 crate::stack::RebaseOptions {
3270 strategy: crate::stack::RebaseStrategy::ForcePush,
3271 target_base: Some(base_branch.clone()),
3272 ..Default::default()
3273 },
3274 );
3275
3276 match rebase_manager.rebase_stack(&stack_id) {
3277 Ok(rebase_result) => {
3278 if !rebase_result.branch_mapping.is_empty() {
3279 let retarget_config = crate::config::CascadeConfig {
3281 bitbucket: Some(settings.bitbucket.clone()),
3282 git: settings.git.clone(),
3283 auth: crate::config::AuthConfig::default(),
3284 cascade: settings.cascade.clone(),
3285 };
3286 let mut retarget_integration = BitbucketIntegration::new(
3287 StackManager::new(&repo_root)?,
3288 retarget_config,
3289 )?;
3290
3291 match retarget_integration
3292 .update_prs_after_rebase(
3293 &stack_id,
3294 &rebase_result.branch_mapping,
3295 )
3296 .await
3297 {
3298 Ok(updated_prs) => {
3299 if !updated_prs.is_empty() {
3300 println!(
3301 " ✅ Updated {} PRs with new targets",
3302 updated_prs.len()
3303 );
3304 }
3305 }
3306 Err(e) => {
3307 println!(" ⚠️ Failed to update remaining PRs: {e}");
3308 println!(
3309 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
3310 );
3311 }
3312 }
3313 }
3314 }
3315 Err(e) => {
3316 println!(" ❌ Auto-retargeting conflicts detected!");
3318 println!(" 📝 To resolve conflicts and continue landing:");
3319 println!(" 1. Resolve conflicts in the affected files");
3320 println!(" 2. Stage resolved files: git add <files>");
3321 println!(" 3. Continue the process: ca stack continue-land");
3322 println!(" 4. Or abort the operation: ca stack abort-land");
3323 println!();
3324 println!(" 💡 Check current status: ca stack land-status");
3325 println!(" ⚠️ Error details: {e}");
3326
3327 break;
3329 }
3330 }
3331 }
3332 }
3333 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3334 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3335 failed_count += 1;
3336 if !force {
3337 break;
3338 }
3339 }
3340 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3341 println!(" ❌ Failed: {error}");
3342 failed_count += 1;
3343 if !force {
3344 break;
3345 }
3346 }
3347 Err(e) => {
3348 println!(" ❌");
3349 eprintln!("Failed to land PR #{pr_id}: {e}");
3350 failed_count += 1;
3351
3352 if !force {
3353 break;
3354 }
3355 }
3356 }
3357 }
3358
3359 println!("\n🎯 Landing Summary:");
3361 println!(" ✅ Successfully landed: {landed_count}");
3362 if failed_count > 0 {
3363 println!(" ❌ Failed to land: {failed_count}");
3364 }
3365
3366 if landed_count > 0 {
3367 Output::success(" Landing operation completed!");
3368 } else {
3369 println!("❌ No PRs were successfully landed");
3370 }
3371
3372 Ok(())
3373}
3374
3375async fn auto_land_stack(
3377 force: bool,
3378 dry_run: bool,
3379 wait_for_builds: bool,
3380 strategy: Option<MergeStrategyArg>,
3381 build_timeout: u64,
3382) -> Result<()> {
3383 land_stack(
3385 None,
3386 force,
3387 dry_run,
3388 true, wait_for_builds,
3390 strategy,
3391 build_timeout,
3392 )
3393 .await
3394}
3395
3396async fn continue_land() -> Result<()> {
3397 let current_dir = env::current_dir()
3398 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3399
3400 let repo_root = find_repository_root(¤t_dir)
3401 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3402
3403 let stack_manager = StackManager::new(&repo_root)?;
3404 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3405 let options = crate::stack::RebaseOptions::default();
3406 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3407
3408 if !rebase_manager.is_rebase_in_progress() {
3409 Output::info(" No rebase in progress");
3410 return Ok(());
3411 }
3412
3413 println!(" Continuing land operation...");
3414 match rebase_manager.continue_rebase() {
3415 Ok(_) => {
3416 Output::success(" Land operation continued successfully");
3417 println!(" Check 'ca stack land-status' for current state");
3418 }
3419 Err(e) => {
3420 warn!("❌ Failed to continue land operation: {}", e);
3421 Output::tip(" You may need to resolve conflicts first:");
3422 println!(" 1. Edit conflicted files");
3423 println!(" 2. Stage resolved files with 'git add'");
3424 println!(" 3. Run 'ca stack continue-land' again");
3425 }
3426 }
3427
3428 Ok(())
3429}
3430
3431async fn abort_land() -> Result<()> {
3432 let current_dir = env::current_dir()
3433 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3434
3435 let repo_root = find_repository_root(¤t_dir)
3436 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3437
3438 let stack_manager = StackManager::new(&repo_root)?;
3439 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3440 let options = crate::stack::RebaseOptions::default();
3441 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3442
3443 if !rebase_manager.is_rebase_in_progress() {
3444 Output::info(" No rebase in progress");
3445 return Ok(());
3446 }
3447
3448 println!("⚠️ Aborting land operation...");
3449 match rebase_manager.abort_rebase() {
3450 Ok(_) => {
3451 Output::success(" Land operation aborted successfully");
3452 println!(" Repository restored to pre-land state");
3453 }
3454 Err(e) => {
3455 warn!("❌ Failed to abort land operation: {}", e);
3456 println!("⚠️ You may need to manually clean up the repository state");
3457 }
3458 }
3459
3460 Ok(())
3461}
3462
3463async fn land_status() -> Result<()> {
3464 let current_dir = env::current_dir()
3465 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3466
3467 let repo_root = find_repository_root(¤t_dir)
3468 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3469
3470 let stack_manager = StackManager::new(&repo_root)?;
3471 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3472
3473 println!("Land Status");
3474
3475 let git_dir = repo_root.join(".git");
3477 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3478 || git_dir.join("rebase-merge").exists()
3479 || git_dir.join("rebase-apply").exists();
3480
3481 if land_in_progress {
3482 println!(" Status: 🔄 Land operation in progress");
3483 println!(
3484 "
3485📝 Actions available:"
3486 );
3487 println!(" - 'ca stack continue-land' to continue");
3488 println!(" - 'ca stack abort-land' to abort");
3489 println!(" - 'git status' to see conflicted files");
3490
3491 match git_repo.get_status() {
3493 Ok(statuses) => {
3494 let mut conflicts = Vec::new();
3495 for status in statuses.iter() {
3496 if status.status().contains(git2::Status::CONFLICTED) {
3497 if let Some(path) = status.path() {
3498 conflicts.push(path.to_string());
3499 }
3500 }
3501 }
3502
3503 if !conflicts.is_empty() {
3504 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3505 for conflict in conflicts {
3506 println!(" - {conflict}");
3507 }
3508 println!(
3509 "
3510💡 To resolve conflicts:"
3511 );
3512 println!(" 1. Edit the conflicted files");
3513 println!(" 2. Stage resolved files: git add <file>");
3514 println!(" 3. Continue: ca stack continue-land");
3515 }
3516 }
3517 Err(e) => {
3518 warn!("Failed to get git status: {}", e);
3519 }
3520 }
3521 } else {
3522 println!(" Status: ✅ No land operation in progress");
3523
3524 if let Some(active_stack) = stack_manager.get_active_stack() {
3526 println!(" Active stack: {}", active_stack.name);
3527 println!(" Entries: {}", active_stack.entries.len());
3528 println!(" Base branch: {}", active_stack.base_branch);
3529 }
3530 }
3531
3532 Ok(())
3533}
3534
3535async fn repair_stack_data() -> Result<()> {
3536 let current_dir = env::current_dir()
3537 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3538
3539 let repo_root = find_repository_root(¤t_dir)
3540 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3541
3542 let mut stack_manager = StackManager::new(&repo_root)?;
3543
3544 println!("🔧 Repairing stack data consistency...");
3545
3546 stack_manager.repair_all_stacks()?;
3547
3548 Output::success(" Stack data consistency repaired successfully!");
3549 Output::tip(" Run 'ca stack --mergeable' to see updated status");
3550
3551 Ok(())
3552}
3553
3554async fn cleanup_branches(
3556 dry_run: bool,
3557 force: bool,
3558 include_stale: bool,
3559 stale_days: u32,
3560 cleanup_remote: bool,
3561 include_non_stack: bool,
3562 verbose: bool,
3563) -> Result<()> {
3564 let current_dir = env::current_dir()
3565 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3566
3567 let repo_root = find_repository_root(¤t_dir)
3568 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3569
3570 let stack_manager = StackManager::new(&repo_root)?;
3571 let git_repo = GitRepository::open(&repo_root)?;
3572
3573 let result = perform_cleanup(
3574 &stack_manager,
3575 &git_repo,
3576 dry_run,
3577 force,
3578 include_stale,
3579 stale_days,
3580 cleanup_remote,
3581 include_non_stack,
3582 verbose,
3583 )
3584 .await?;
3585
3586 if result.total_candidates == 0 {
3588 Output::success("No branches found that need cleanup");
3589 return Ok(());
3590 }
3591
3592 Output::section("Cleanup Results");
3593
3594 if dry_run {
3595 Output::sub_item(format!(
3596 "Found {} branches that would be cleaned up",
3597 result.total_candidates
3598 ));
3599 } else {
3600 if !result.cleaned_branches.is_empty() {
3601 Output::success(format!(
3602 "Successfully cleaned up {} branches",
3603 result.cleaned_branches.len()
3604 ));
3605 for branch in &result.cleaned_branches {
3606 Output::sub_item(format!("🗑️ Deleted: {branch}"));
3607 }
3608 }
3609
3610 if !result.skipped_branches.is_empty() {
3611 Output::sub_item(format!(
3612 "Skipped {} branches",
3613 result.skipped_branches.len()
3614 ));
3615 if verbose {
3616 for (branch, reason) in &result.skipped_branches {
3617 Output::sub_item(format!("⏭️ {branch}: {reason}"));
3618 }
3619 }
3620 }
3621
3622 if !result.failed_branches.is_empty() {
3623 Output::warning(format!(
3624 "Failed to clean up {} branches",
3625 result.failed_branches.len()
3626 ));
3627 for (branch, error) in &result.failed_branches {
3628 Output::sub_item(format!("❌ {branch}: {error}"));
3629 }
3630 }
3631 }
3632
3633 Ok(())
3634}
3635
3636#[allow(clippy::too_many_arguments)]
3638async fn perform_cleanup(
3639 stack_manager: &StackManager,
3640 git_repo: &GitRepository,
3641 dry_run: bool,
3642 force: bool,
3643 include_stale: bool,
3644 stale_days: u32,
3645 cleanup_remote: bool,
3646 include_non_stack: bool,
3647 verbose: bool,
3648) -> Result<CleanupResult> {
3649 let options = CleanupOptions {
3650 dry_run,
3651 force,
3652 include_stale,
3653 cleanup_remote,
3654 stale_threshold_days: stale_days,
3655 cleanup_non_stack: include_non_stack,
3656 };
3657
3658 let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
3659 let git_repo_copy = GitRepository::open(git_repo.path())?;
3660 let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
3661
3662 let candidates = cleanup_manager.find_cleanup_candidates()?;
3664
3665 if candidates.is_empty() {
3666 return Ok(CleanupResult {
3667 cleaned_branches: Vec::new(),
3668 failed_branches: Vec::new(),
3669 skipped_branches: Vec::new(),
3670 total_candidates: 0,
3671 });
3672 }
3673
3674 if verbose || dry_run {
3676 Output::section("Cleanup Candidates");
3677 for candidate in &candidates {
3678 let reason_icon = match candidate.reason {
3679 crate::stack::CleanupReason::FullyMerged => "🔀",
3680 crate::stack::CleanupReason::StackEntryMerged => "✅",
3681 crate::stack::CleanupReason::Stale => "⏰",
3682 crate::stack::CleanupReason::Orphaned => "👻",
3683 };
3684
3685 Output::sub_item(format!(
3686 "{} {} - {} ({})",
3687 reason_icon,
3688 candidate.branch_name,
3689 candidate.reason_to_string(),
3690 candidate.safety_info
3691 ));
3692 }
3693 }
3694
3695 if !force && !dry_run && !candidates.is_empty() {
3697 Output::warning(format!("About to delete {} branches", candidates.len()));
3698
3699 let preview_count = 5.min(candidates.len());
3701 for candidate in candidates.iter().take(preview_count) {
3702 println!(" • {}", candidate.branch_name);
3703 }
3704 if candidates.len() > preview_count {
3705 println!(" ... and {} more", candidates.len() - preview_count);
3706 }
3707 println!(); let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3711 .with_prompt("Continue with branch cleanup?")
3712 .default(false)
3713 .interact()
3714 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3715
3716 if !should_continue {
3717 Output::sub_item("Cleanup cancelled");
3718 return Ok(CleanupResult {
3719 cleaned_branches: Vec::new(),
3720 failed_branches: Vec::new(),
3721 skipped_branches: Vec::new(),
3722 total_candidates: candidates.len(),
3723 });
3724 }
3725 }
3726
3727 cleanup_manager.perform_cleanup(&candidates)
3729}
3730
3731async fn perform_simple_cleanup(
3733 stack_manager: &StackManager,
3734 git_repo: &GitRepository,
3735 dry_run: bool,
3736) -> Result<CleanupResult> {
3737 perform_cleanup(
3738 stack_manager,
3739 git_repo,
3740 dry_run,
3741 false, false, 30, false, false, false, )
3748 .await
3749}
3750
3751async fn analyze_commits_for_safeguards(
3753 commits_to_push: &[String],
3754 repo: &GitRepository,
3755 dry_run: bool,
3756) -> Result<()> {
3757 const LARGE_COMMIT_THRESHOLD: usize = 10;
3758 const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3759
3760 if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3762 println!(
3763 "⚠️ Warning: About to push {} commits to stack",
3764 commits_to_push.len()
3765 );
3766 println!(" This may indicate a merge commit issue or unexpected commit range.");
3767 println!(" Large commit counts often result from merging instead of rebasing.");
3768
3769 if !dry_run && !confirm_large_push(commits_to_push.len())? {
3770 return Err(CascadeError::config("Push cancelled by user"));
3771 }
3772 }
3773
3774 let commit_objects: Result<Vec<_>> = commits_to_push
3776 .iter()
3777 .map(|hash| repo.get_commit(hash))
3778 .collect();
3779 let commit_objects = commit_objects?;
3780
3781 let merge_commits: Vec<_> = commit_objects
3783 .iter()
3784 .filter(|c| c.parent_count() > 1)
3785 .collect();
3786
3787 if !merge_commits.is_empty() {
3788 println!(
3789 "⚠️ Warning: {} merge commits detected in push",
3790 merge_commits.len()
3791 );
3792 println!(" This often indicates you merged instead of rebased.");
3793 println!(" Consider using 'ca sync' to rebase on the base branch.");
3794 println!(" Merge commits in stacks can cause confusion and duplicate work.");
3795 }
3796
3797 if commit_objects.len() > 1 {
3799 let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
3800 let newest_commit_time = commit_objects.last().unwrap().time().seconds();
3801 let time_span = newest_commit_time - oldest_commit_time;
3802
3803 if time_span > WEEK_IN_SECONDS {
3804 let days = time_span / (24 * 3600);
3805 println!("⚠️ Warning: Commits span {days} days");
3806 println!(" This may indicate merged history rather than new work.");
3807 println!(" Recent work should typically span hours or days, not weeks.");
3808 }
3809 }
3810
3811 if commits_to_push.len() > 5 {
3813 Output::tip(" Tip: If you only want recent commits, use:");
3814 println!(
3815 " ca push --since HEAD~{} # pushes last {} commits",
3816 std::cmp::min(commits_to_push.len(), 5),
3817 std::cmp::min(commits_to_push.len(), 5)
3818 );
3819 println!(" ca push --commits <hash1>,<hash2> # pushes specific commits");
3820 println!(" ca push --dry-run # preview what would be pushed");
3821 }
3822
3823 if dry_run {
3825 println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
3826 for (i, (commit_hash, commit_obj)) in commits_to_push
3827 .iter()
3828 .zip(commit_objects.iter())
3829 .enumerate()
3830 {
3831 let summary = commit_obj.summary().unwrap_or("(no message)");
3832 let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
3833 println!(" {}: {} ({})", i + 1, summary, short_hash);
3834 }
3835 Output::tip(" Run without --dry-run to actually push these commits.");
3836 }
3837
3838 Ok(())
3839}
3840
3841fn confirm_large_push(count: usize) -> Result<bool> {
3843 let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3845 .with_prompt(format!("Continue pushing {count} commits?"))
3846 .default(false)
3847 .interact()
3848 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3849
3850 Ok(should_continue)
3851}
3852
3853#[cfg(test)]
3854mod tests {
3855 use super::*;
3856 use std::process::Command;
3857 use tempfile::TempDir;
3858
3859 fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
3860 let temp_dir = TempDir::new()
3861 .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
3862 let repo_path = temp_dir.path().to_path_buf();
3863
3864 let output = Command::new("git")
3866 .args(["init"])
3867 .current_dir(&repo_path)
3868 .output()
3869 .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
3870 if !output.status.success() {
3871 return Err(CascadeError::config("Git init failed".to_string()));
3872 }
3873
3874 let output = Command::new("git")
3875 .args(["config", "user.name", "Test User"])
3876 .current_dir(&repo_path)
3877 .output()
3878 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3879 if !output.status.success() {
3880 return Err(CascadeError::config(
3881 "Git config user.name failed".to_string(),
3882 ));
3883 }
3884
3885 let output = Command::new("git")
3886 .args(["config", "user.email", "test@example.com"])
3887 .current_dir(&repo_path)
3888 .output()
3889 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3890 if !output.status.success() {
3891 return Err(CascadeError::config(
3892 "Git config user.email failed".to_string(),
3893 ));
3894 }
3895
3896 std::fs::write(repo_path.join("README.md"), "# Test")
3898 .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
3899 let output = Command::new("git")
3900 .args(["add", "."])
3901 .current_dir(&repo_path)
3902 .output()
3903 .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
3904 if !output.status.success() {
3905 return Err(CascadeError::config("Git add failed".to_string()));
3906 }
3907
3908 let output = Command::new("git")
3909 .args(["commit", "-m", "Initial commit"])
3910 .current_dir(&repo_path)
3911 .output()
3912 .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
3913 if !output.status.success() {
3914 return Err(CascadeError::config("Git commit failed".to_string()));
3915 }
3916
3917 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
3919
3920 Ok((temp_dir, repo_path))
3921 }
3922
3923 #[tokio::test]
3924 async fn test_create_stack() {
3925 let (temp_dir, repo_path) = match create_test_repo() {
3926 Ok(repo) => repo,
3927 Err(_) => {
3928 println!("Skipping test due to git environment setup failure");
3929 return;
3930 }
3931 };
3932 let _ = &temp_dir;
3934
3935 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3939 match env::set_current_dir(&repo_path) {
3940 Ok(_) => {
3941 let result = create_stack(
3942 "test-stack".to_string(),
3943 None, Some("Test description".to_string()),
3945 )
3946 .await;
3947
3948 if let Ok(orig) = original_dir {
3950 let _ = env::set_current_dir(orig);
3951 }
3952
3953 assert!(
3954 result.is_ok(),
3955 "Stack creation should succeed in initialized repository"
3956 );
3957 }
3958 Err(_) => {
3959 println!("Skipping test due to directory access restrictions");
3961 }
3962 }
3963 }
3964
3965 #[tokio::test]
3966 async fn test_list_empty_stacks() {
3967 let (temp_dir, repo_path) = match create_test_repo() {
3968 Ok(repo) => repo,
3969 Err(_) => {
3970 println!("Skipping test due to git environment setup failure");
3971 return;
3972 }
3973 };
3974 let _ = &temp_dir;
3976
3977 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3981 match env::set_current_dir(&repo_path) {
3982 Ok(_) => {
3983 let result = list_stacks(false, false, None).await;
3984
3985 if let Ok(orig) = original_dir {
3987 let _ = env::set_current_dir(orig);
3988 }
3989
3990 assert!(
3991 result.is_ok(),
3992 "Listing stacks should succeed in initialized repository"
3993 );
3994 }
3995 Err(_) => {
3996 println!("Skipping test due to directory access restrictions");
3998 }
3999 }
4000 }
4001
4002 #[test]
4005 fn test_extract_feature_from_wip_basic() {
4006 let messages = vec![
4007 "WIP: add authentication".to_string(),
4008 "WIP: implement login flow".to_string(),
4009 ];
4010
4011 let result = extract_feature_from_wip(&messages);
4012 assert_eq!(result, "Add authentication");
4013 }
4014
4015 #[test]
4016 fn test_extract_feature_from_wip_capitalize() {
4017 let messages = vec!["WIP: fix user validation bug".to_string()];
4018
4019 let result = extract_feature_from_wip(&messages);
4020 assert_eq!(result, "Fix user validation bug");
4021 }
4022
4023 #[test]
4024 fn test_extract_feature_from_wip_fallback() {
4025 let messages = vec![
4026 "WIP user interface changes".to_string(),
4027 "wip: css styling".to_string(),
4028 ];
4029
4030 let result = extract_feature_from_wip(&messages);
4031 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
4033 }
4034
4035 #[test]
4036 fn test_extract_feature_from_wip_empty() {
4037 let messages = vec![];
4038
4039 let result = extract_feature_from_wip(&messages);
4040 assert_eq!(result, "Squashed 0 commits");
4041 }
4042
4043 #[test]
4044 fn test_extract_feature_from_wip_short_message() {
4045 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
4048 assert!(result.starts_with("Implement") || result.contains("Squashed"));
4049 }
4050
4051 #[test]
4054 fn test_squash_message_final_strategy() {
4055 let messages = [
4059 "Final: implement user authentication system".to_string(),
4060 "WIP: add tests".to_string(),
4061 "WIP: fix validation".to_string(),
4062 ];
4063
4064 assert!(messages[0].starts_with("Final:"));
4066
4067 let extracted = messages[0].trim_start_matches("Final:").trim();
4069 assert_eq!(extracted, "implement user authentication system");
4070 }
4071
4072 #[test]
4073 fn test_squash_message_wip_detection() {
4074 let messages = [
4075 "WIP: start feature".to_string(),
4076 "WIP: continue work".to_string(),
4077 "WIP: almost done".to_string(),
4078 "Regular commit message".to_string(),
4079 ];
4080
4081 let wip_count = messages
4082 .iter()
4083 .filter(|m| {
4084 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
4085 })
4086 .count();
4087
4088 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
4093 .iter()
4094 .filter(|m| {
4095 !m.to_lowercase().starts_with("wip")
4096 && !m.to_lowercase().contains("work in progress")
4097 })
4098 .collect();
4099
4100 assert_eq!(non_wip.len(), 1);
4101 assert_eq!(non_wip[0], "Regular commit message");
4102 }
4103
4104 #[test]
4105 fn test_squash_message_all_wip() {
4106 let messages = vec![
4107 "WIP: add feature A".to_string(),
4108 "WIP: add feature B".to_string(),
4109 "WIP: finish implementation".to_string(),
4110 ];
4111
4112 let result = extract_feature_from_wip(&messages);
4113 assert_eq!(result, "Add feature A");
4115 }
4116
4117 #[test]
4118 fn test_squash_message_edge_cases() {
4119 let empty_messages: Vec<String> = vec![];
4121 let result = extract_feature_from_wip(&empty_messages);
4122 assert_eq!(result, "Squashed 0 commits");
4123
4124 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
4126 let result = extract_feature_from_wip(&whitespace_messages);
4127 assert!(result.contains("Squashed") || result.contains("Implement"));
4128
4129 let mixed_case = vec!["wip: Add Feature".to_string()];
4131 let result = extract_feature_from_wip(&mixed_case);
4132 assert_eq!(result, "Add Feature");
4133 }
4134
4135 #[tokio::test]
4138 async fn test_auto_land_wrapper() {
4139 let (temp_dir, repo_path) = match create_test_repo() {
4141 Ok(repo) => repo,
4142 Err(_) => {
4143 println!("Skipping test due to git environment setup failure");
4144 return;
4145 }
4146 };
4147 let _ = &temp_dir;
4149
4150 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
4152 .expect("Failed to initialize Cascade in test repo");
4153
4154 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4155 match env::set_current_dir(&repo_path) {
4156 Ok(_) => {
4157 let result = create_stack(
4159 "test-stack".to_string(),
4160 None,
4161 Some("Test stack for auto-land".to_string()),
4162 )
4163 .await;
4164
4165 if let Ok(orig) = original_dir {
4166 let _ = env::set_current_dir(orig);
4167 }
4168
4169 assert!(
4172 result.is_ok(),
4173 "Stack creation should succeed in initialized repository"
4174 );
4175 }
4176 Err(_) => {
4177 println!("Skipping test due to directory access restrictions");
4178 }
4179 }
4180 }
4181
4182 #[test]
4183 fn test_auto_land_action_enum() {
4184 use crate::cli::commands::stack::StackAction;
4186
4187 let _action = StackAction::AutoLand {
4189 force: false,
4190 dry_run: true,
4191 wait_for_builds: true,
4192 strategy: Some(MergeStrategyArg::Squash),
4193 build_timeout: 1800,
4194 };
4195
4196 }
4198
4199 #[test]
4200 fn test_merge_strategy_conversion() {
4201 let squash_strategy = MergeStrategyArg::Squash;
4203 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
4204
4205 match merge_strategy {
4206 crate::bitbucket::pull_request::MergeStrategy::Squash => {
4207 }
4209 _ => unreachable!("SquashStrategyArg only has Squash variant"),
4210 }
4211
4212 let merge_strategy = MergeStrategyArg::Merge;
4213 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
4214
4215 match converted {
4216 crate::bitbucket::pull_request::MergeStrategy::Merge => {
4217 }
4219 _ => unreachable!("MergeStrategyArg::Merge maps to MergeStrategy::Merge"),
4220 }
4221 }
4222
4223 #[test]
4224 fn test_auto_merge_conditions_structure() {
4225 use std::time::Duration;
4227
4228 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
4229 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
4230 wait_for_builds: true,
4231 build_timeout: Duration::from_secs(1800),
4232 allowed_authors: None,
4233 };
4234
4235 assert!(conditions.wait_for_builds);
4237 assert_eq!(conditions.build_timeout.as_secs(), 1800);
4238 assert!(conditions.allowed_authors.is_none());
4239 assert!(matches!(
4240 conditions.merge_strategy,
4241 crate::bitbucket::pull_request::MergeStrategy::Squash
4242 ));
4243 }
4244
4245 #[test]
4246 fn test_polling_constants() {
4247 use std::time::Duration;
4249
4250 let expected_polling_interval = Duration::from_secs(30);
4252
4253 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
4258
4259 #[test]
4260 fn test_build_timeout_defaults() {
4261 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
4264 let timeout_value = 1800u64;
4266 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
4269
4270 #[test]
4271 fn test_scattered_commit_detection() {
4272 use std::collections::HashSet;
4273
4274 let mut source_branches = HashSet::new();
4276 source_branches.insert("feature-branch-1".to_string());
4277 source_branches.insert("feature-branch-2".to_string());
4278 source_branches.insert("feature-branch-3".to_string());
4279
4280 let single_branch = HashSet::from(["main".to_string()]);
4282 assert_eq!(single_branch.len(), 1);
4283
4284 assert!(source_branches.len() > 1);
4286 assert_eq!(source_branches.len(), 3);
4287
4288 assert!(source_branches.contains("feature-branch-1"));
4290 assert!(source_branches.contains("feature-branch-2"));
4291 assert!(source_branches.contains("feature-branch-3"));
4292 }
4293
4294 #[test]
4295 fn test_source_branch_tracking() {
4296 let branch_a = "feature-work";
4300 let branch_b = "feature-work";
4301 assert_eq!(branch_a, branch_b);
4302
4303 let branch_1 = "feature-ui";
4305 let branch_2 = "feature-api";
4306 assert_ne!(branch_1, branch_2);
4307
4308 assert!(branch_1.starts_with("feature-"));
4310 assert!(branch_2.starts_with("feature-"));
4311 }
4312
4313 #[tokio::test]
4316 async fn test_push_default_behavior() {
4317 let (temp_dir, repo_path) = match create_test_repo() {
4319 Ok(repo) => repo,
4320 Err(_) => {
4321 println!("Skipping test due to git environment setup failure");
4322 return;
4323 }
4324 };
4325 let _ = &temp_dir;
4327
4328 if !repo_path.exists() {
4330 println!("Skipping test due to temporary directory creation issue");
4331 return;
4332 }
4333
4334 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4336
4337 match env::set_current_dir(&repo_path) {
4338 Ok(_) => {
4339 let result = push_to_stack(
4341 None, None, None, None, None, None, None, false, false, false, )
4352 .await;
4353
4354 if let Ok(orig) = original_dir {
4356 let _ = env::set_current_dir(orig);
4357 }
4358
4359 match &result {
4361 Err(e) => {
4362 let error_msg = e.to_string();
4363 assert!(
4365 error_msg.contains("No active stack")
4366 || error_msg.contains("config")
4367 || error_msg.contains("current directory")
4368 || error_msg.contains("Not a git repository")
4369 || error_msg.contains("could not find repository"),
4370 "Expected 'No active stack' or repository error, got: {error_msg}"
4371 );
4372 }
4373 Ok(_) => {
4374 println!(
4376 "Push succeeded unexpectedly - test environment may have active stack"
4377 );
4378 }
4379 }
4380 }
4381 Err(_) => {
4382 println!("Skipping test due to directory access restrictions");
4384 }
4385 }
4386
4387 let push_action = StackAction::Push {
4389 branch: None,
4390 message: None,
4391 commit: None,
4392 since: None,
4393 commits: None,
4394 squash: None,
4395 squash_since: None,
4396 auto_branch: false,
4397 allow_base_branch: false,
4398 dry_run: false,
4399 };
4400
4401 assert!(matches!(
4402 push_action,
4403 StackAction::Push {
4404 branch: None,
4405 message: None,
4406 commit: None,
4407 since: None,
4408 commits: None,
4409 squash: None,
4410 squash_since: None,
4411 auto_branch: false,
4412 allow_base_branch: false,
4413 dry_run: false
4414 }
4415 ));
4416 }
4417
4418 #[tokio::test]
4419 async fn test_submit_default_behavior() {
4420 let (temp_dir, repo_path) = match create_test_repo() {
4422 Ok(repo) => repo,
4423 Err(_) => {
4424 println!("Skipping test due to git environment setup failure");
4425 return;
4426 }
4427 };
4428 let _ = &temp_dir;
4430
4431 if !repo_path.exists() {
4433 println!("Skipping test due to temporary directory creation issue");
4434 return;
4435 }
4436
4437 let original_dir = match env::current_dir() {
4439 Ok(dir) => dir,
4440 Err(_) => {
4441 println!("Skipping test due to current directory access restrictions");
4442 return;
4443 }
4444 };
4445
4446 match env::set_current_dir(&repo_path) {
4447 Ok(_) => {
4448 let result = submit_entry(
4450 None, None, None, None, false, true, )
4457 .await;
4458
4459 let _ = env::set_current_dir(original_dir);
4461
4462 match &result {
4464 Err(e) => {
4465 let error_msg = e.to_string();
4466 assert!(
4468 error_msg.contains("No active stack")
4469 || error_msg.contains("config")
4470 || error_msg.contains("current directory")
4471 || error_msg.contains("Not a git repository")
4472 || error_msg.contains("could not find repository"),
4473 "Expected 'No active stack' or repository error, got: {error_msg}"
4474 );
4475 }
4476 Ok(_) => {
4477 println!("Submit succeeded unexpectedly - test environment may have active stack");
4479 }
4480 }
4481 }
4482 Err(_) => {
4483 println!("Skipping test due to directory access restrictions");
4485 }
4486 }
4487
4488 let submit_action = StackAction::Submit {
4490 entry: None,
4491 title: None,
4492 description: None,
4493 range: None,
4494 draft: false,
4495 open: true,
4496 };
4497
4498 assert!(matches!(
4499 submit_action,
4500 StackAction::Submit {
4501 entry: None,
4502 title: None,
4503 description: None,
4504 range: None,
4505 draft: false,
4506 open: true
4507 }
4508 ));
4509 }
4510
4511 #[test]
4512 fn test_targeting_options_still_work() {
4513 let commits = "abc123,def456,ghi789";
4517 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4518 assert_eq!(parsed.len(), 3);
4519 assert_eq!(parsed[0], "abc123");
4520 assert_eq!(parsed[1], "def456");
4521 assert_eq!(parsed[2], "ghi789");
4522
4523 let range = "1-3";
4525 assert!(range.contains('-'));
4526 let parts: Vec<&str> = range.split('-').collect();
4527 assert_eq!(parts.len(), 2);
4528
4529 let since_ref = "HEAD~3";
4531 assert!(since_ref.starts_with("HEAD"));
4532 assert!(since_ref.contains('~'));
4533 }
4534
4535 #[test]
4536 fn test_command_flow_logic() {
4537 assert!(matches!(
4539 StackAction::Push {
4540 branch: None,
4541 message: None,
4542 commit: None,
4543 since: None,
4544 commits: None,
4545 squash: None,
4546 squash_since: None,
4547 auto_branch: false,
4548 allow_base_branch: false,
4549 dry_run: false
4550 },
4551 StackAction::Push { .. }
4552 ));
4553
4554 assert!(matches!(
4555 StackAction::Submit {
4556 entry: None,
4557 title: None,
4558 description: None,
4559 range: None,
4560 draft: false,
4561 open: true
4562 },
4563 StackAction::Submit { .. }
4564 ));
4565 }
4566
4567 #[tokio::test]
4568 async fn test_deactivate_command_structure() {
4569 let deactivate_action = StackAction::Deactivate { force: false };
4571
4572 assert!(matches!(
4574 deactivate_action,
4575 StackAction::Deactivate { force: false }
4576 ));
4577
4578 let force_deactivate = StackAction::Deactivate { force: true };
4580 assert!(matches!(
4581 force_deactivate,
4582 StackAction::Deactivate { force: true }
4583 ));
4584 }
4585}