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, default_value_t = true, action = clap::ArgAction::Set)]
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();
890 let source_branch_info = if !entry.is_submitted {
891 if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash) {
892 if commit_meta.source_branch != commit_meta.branch
893 && !commit_meta.source_branch.is_empty()
894 {
895 format!(" (from {})", commit_meta.source_branch)
896 } else {
897 String::new()
898 }
899 } else {
900 String::new()
901 }
902 } else {
903 String::new()
904 };
905
906 let status_icon = if entry.is_submitted {
907 "[submitted]"
908 } else {
909 "[pending]"
910 };
911 Output::numbered_item(
912 entry_num,
913 format!("{short_hash} {status_icon} {short_msg}{source_branch_info}"),
914 );
915
916 if verbose {
917 Output::sub_item(format!("Branch: {}", entry.branch));
918 Output::sub_item(format!(
919 "Created: {}",
920 entry.created_at.format("%Y-%m-%d %H:%M")
921 ));
922 if let Some(pr_id) = &entry.pull_request_id {
923 Output::sub_item(format!("PR: #{pr_id}"));
924 }
925
926 Output::sub_item("Commit Message:");
928 let lines: Vec<&str> = entry.message.lines().collect();
929 for line in lines {
930 Output::sub_item(format!(" {line}"));
931 }
932 }
933 }
934
935 if show_mergeable {
937 Output::section("Mergability Status");
938
939 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
941 let config_path = config_dir.join("config.json");
942 let settings = crate::config::Settings::load_from_file(&config_path)?;
943
944 let cascade_config = crate::config::CascadeConfig {
945 bitbucket: Some(settings.bitbucket.clone()),
946 git: settings.git.clone(),
947 auth: crate::config::AuthConfig::default(),
948 cascade: settings.cascade.clone(),
949 };
950
951 let integration =
952 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
953
954 match integration.check_enhanced_stack_status(&stack_id).await {
955 Ok(status) => {
956 Output::bullet(format!("Total entries: {}", status.total_entries));
957 Output::bullet(format!("Submitted: {}", status.submitted_entries));
958 Output::bullet(format!("Open PRs: {}", status.open_prs));
959 Output::bullet(format!("Merged PRs: {}", status.merged_prs));
960 Output::bullet(format!("Declined PRs: {}", status.declined_prs));
961 Output::bullet(format!(
962 "Completion: {:.1}%",
963 status.completion_percentage()
964 ));
965
966 if !status.enhanced_statuses.is_empty() {
967 Output::section("Pull Request Status");
968 let mut ready_to_land = 0;
969
970 for enhanced in &status.enhanced_statuses {
971 let status_display = enhanced.get_display_status();
972 let ready_icon = if enhanced.is_ready_to_land() {
973 ready_to_land += 1;
974 "[READY]"
975 } else {
976 "[PENDING]"
977 };
978
979 Output::bullet(format!(
980 "{} PR #{}: {} ({})",
981 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
982 ));
983
984 if verbose {
985 println!(
986 " {} -> {}",
987 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
988 );
989
990 if !enhanced.is_ready_to_land() {
992 let blocking = enhanced.get_blocking_reasons();
993 if !blocking.is_empty() {
994 println!(" Blocking: {}", blocking.join(", "));
995 }
996 }
997
998 println!(
1000 " Reviews: {} approval{}",
1001 enhanced.review_status.current_approvals,
1002 if enhanced.review_status.current_approvals == 1 {
1003 ""
1004 } else {
1005 "s"
1006 }
1007 );
1008
1009 if enhanced.review_status.needs_work_count > 0 {
1010 println!(
1011 " {} reviewers requested changes",
1012 enhanced.review_status.needs_work_count
1013 );
1014 }
1015
1016 if let Some(build) = &enhanced.build_status {
1018 let build_icon = match build.state {
1019 crate::bitbucket::pull_request::BuildState::Successful => "✓",
1020 crate::bitbucket::pull_request::BuildState::Failed => "✗",
1021 crate::bitbucket::pull_request::BuildState::InProgress => "~",
1022 _ => "○",
1023 };
1024 println!(" Build: {} {:?}", build_icon, build.state);
1025 }
1026
1027 if let Some(url) = enhanced.pr.web_url() {
1028 println!(" URL: {url}");
1029 }
1030 println!();
1031 }
1032 }
1033
1034 if ready_to_land > 0 {
1035 println!(
1036 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
1037 ready_to_land,
1038 if ready_to_land == 1 { " is" } else { "s are" }
1039 );
1040 }
1041 }
1042 }
1043 Err(e) => {
1044 warn!("Failed to get enhanced stack status: {}", e);
1045 println!(" ⚠️ Could not fetch mergability status");
1046 println!(" Use 'ca stack show --verbose' for basic PR information");
1047 }
1048 }
1049 } else {
1050 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1052 let config_path = config_dir.join("config.json");
1053 let settings = crate::config::Settings::load_from_file(&config_path)?;
1054
1055 let cascade_config = crate::config::CascadeConfig {
1056 bitbucket: Some(settings.bitbucket.clone()),
1057 git: settings.git.clone(),
1058 auth: crate::config::AuthConfig::default(),
1059 cascade: settings.cascade.clone(),
1060 };
1061
1062 let integration =
1063 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1064
1065 match integration.check_stack_status(&stack_id).await {
1066 Ok(status) => {
1067 println!("\nPull Request Status:");
1068 println!(" Total entries: {}", status.total_entries);
1069 println!(" Submitted: {}", status.submitted_entries);
1070 println!(" Open PRs: {}", status.open_prs);
1071 println!(" Merged PRs: {}", status.merged_prs);
1072 println!(" Declined PRs: {}", status.declined_prs);
1073 println!(" Completion: {:.1}%", status.completion_percentage());
1074
1075 if !status.pull_requests.is_empty() {
1076 println!("\nPull Requests:");
1077 for pr in &status.pull_requests {
1078 let state_icon = match pr.state {
1079 crate::bitbucket::PullRequestState::Open => "→",
1080 crate::bitbucket::PullRequestState::Merged => "✓",
1081 crate::bitbucket::PullRequestState::Declined => "✗",
1082 };
1083 println!(
1084 " {} PR #{}: {} ({} -> {})",
1085 state_icon,
1086 pr.id,
1087 pr.title,
1088 pr.from_ref.display_id,
1089 pr.to_ref.display_id
1090 );
1091 if let Some(url) = pr.web_url() {
1092 println!(" URL: {url}");
1093 }
1094 }
1095 }
1096
1097 println!();
1098 Output::tip("Use 'ca stack --mergeable' to see detailed status including build and review information");
1099 }
1100 Err(e) => {
1101 warn!("Failed to check stack status: {}", e);
1102 }
1103 }
1104 }
1105
1106 Ok(())
1107}
1108
1109#[allow(clippy::too_many_arguments)]
1110async fn push_to_stack(
1111 branch: Option<String>,
1112 message: Option<String>,
1113 commit: Option<String>,
1114 since: Option<String>,
1115 commits: Option<String>,
1116 squash: Option<usize>,
1117 squash_since: Option<String>,
1118 auto_branch: bool,
1119 allow_base_branch: bool,
1120 dry_run: bool,
1121) -> Result<()> {
1122 let current_dir = env::current_dir()
1123 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1124
1125 let repo_root = find_repository_root(¤t_dir)
1126 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1127
1128 let mut manager = StackManager::new(&repo_root)?;
1129 let repo = GitRepository::open(&repo_root)?;
1130
1131 if !manager.check_for_branch_change()? {
1133 return Ok(()); }
1135
1136 let active_stack = manager.get_active_stack().ok_or_else(|| {
1138 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1139 })?;
1140
1141 let current_branch = repo.get_current_branch()?;
1143 let base_branch = &active_stack.base_branch;
1144
1145 if current_branch == *base_branch {
1146 Output::error(format!(
1147 "You're currently on the base branch '{base_branch}'"
1148 ));
1149 Output::sub_item("Making commits directly on the base branch is not recommended.");
1150 Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1151
1152 if allow_base_branch {
1154 Output::warning("Proceeding anyway due to --allow-base-branch flag");
1155 } else {
1156 let has_changes = repo.is_dirty()?;
1158
1159 if has_changes {
1160 if auto_branch {
1161 let feature_branch = format!("feature/{}-work", active_stack.name);
1163 Output::progress(format!(
1164 "Auto-creating feature branch '{feature_branch}'..."
1165 ));
1166
1167 repo.create_branch(&feature_branch, None)?;
1168 repo.checkout_branch(&feature_branch)?;
1169
1170 Output::success(format!("Created and switched to '{feature_branch}'"));
1171 println!(" You can now commit and push your changes safely");
1172
1173 } else {
1175 println!("\nYou have uncommitted changes. Here are your options:");
1176 println!(" 1. Create a feature branch first:");
1177 println!(" git checkout -b feature/my-work");
1178 println!(" git commit -am \"your work\"");
1179 println!(" ca push");
1180 println!("\n 2. Auto-create a branch (recommended):");
1181 println!(" ca push --auto-branch");
1182 println!("\n 3. Force push to base branch (dangerous):");
1183 println!(" ca push --allow-base-branch");
1184
1185 return Err(CascadeError::config(
1186 "Refusing to push uncommitted changes from base branch. Use one of the options above."
1187 ));
1188 }
1189 } else {
1190 let commits_to_check = if let Some(commits_str) = &commits {
1192 commits_str
1193 .split(',')
1194 .map(|s| s.trim().to_string())
1195 .collect::<Vec<String>>()
1196 } else if let Some(since_ref) = &since {
1197 let since_commit = repo.resolve_reference(since_ref)?;
1198 let head_commit = repo.get_head_commit()?;
1199 let commits = repo.get_commits_between(
1200 &since_commit.id().to_string(),
1201 &head_commit.id().to_string(),
1202 )?;
1203 commits.into_iter().map(|c| c.id().to_string()).collect()
1204 } else if commit.is_none() {
1205 let mut unpushed = Vec::new();
1206 let head_commit = repo.get_head_commit()?;
1207 let mut current_commit = head_commit;
1208
1209 loop {
1210 let commit_hash = current_commit.id().to_string();
1211 let already_in_stack = active_stack
1212 .entries
1213 .iter()
1214 .any(|entry| entry.commit_hash == commit_hash);
1215
1216 if already_in_stack {
1217 break;
1218 }
1219
1220 unpushed.push(commit_hash);
1221
1222 if let Some(parent) = current_commit.parents().next() {
1223 current_commit = parent;
1224 } else {
1225 break;
1226 }
1227 }
1228
1229 unpushed.reverse();
1230 unpushed
1231 } else {
1232 vec![repo.get_head_commit()?.id().to_string()]
1233 };
1234
1235 if !commits_to_check.is_empty() {
1236 if auto_branch {
1237 let feature_branch = format!("feature/{}-work", active_stack.name);
1239 Output::progress(format!(
1240 "Auto-creating feature branch '{feature_branch}'..."
1241 ));
1242
1243 repo.create_branch(&feature_branch, Some(base_branch))?;
1244 repo.checkout_branch(&feature_branch)?;
1245
1246 println!(
1248 "🍒 Cherry-picking {} commit(s) to new branch...",
1249 commits_to_check.len()
1250 );
1251 for commit_hash in &commits_to_check {
1252 match repo.cherry_pick(commit_hash) {
1253 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1254 Err(e) => {
1255 println!(
1256 " ❌ Failed to cherry-pick {}: {}",
1257 &commit_hash[..8],
1258 e
1259 );
1260 println!(" 💡 You may need to resolve conflicts manually");
1261 return Err(CascadeError::branch(format!(
1262 "Failed to cherry-pick commit {commit_hash}: {e}"
1263 )));
1264 }
1265 }
1266 }
1267
1268 println!(
1269 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1270 commits_to_check.len()
1271 );
1272 println!(
1273 " You're now on the feature branch and can continue with 'ca push'"
1274 );
1275
1276 } else {
1278 println!(
1279 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1280 commits_to_check.len()
1281 );
1282 println!(" These commits are currently ON the base branch, which may not be intended.");
1283 println!("\n Options:");
1284 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1285 println!(" ca push --auto-branch");
1286 println!("\n 2. Manually create branch and move commits:");
1287 println!(" git checkout -b feature/my-work");
1288 println!(" ca push");
1289 println!("\n 3. Force push from base branch (not recommended):");
1290 println!(" ca push --allow-base-branch");
1291
1292 return Err(CascadeError::config(
1293 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1294 ));
1295 }
1296 }
1297 }
1298 }
1299 }
1300
1301 if let Some(squash_count) = squash {
1303 if squash_count == 0 {
1304 let active_stack = manager.get_active_stack().ok_or_else(|| {
1306 CascadeError::config(
1307 "No active stack. Create a stack first with 'ca stacks create'",
1308 )
1309 })?;
1310
1311 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1312
1313 if unpushed_count == 0 {
1314 Output::info(" No unpushed commits to squash");
1315 } else if unpushed_count == 1 {
1316 Output::info(" Only 1 unpushed commit, no squashing needed");
1317 } else {
1318 println!(" Auto-detected {unpushed_count} unpushed commits, squashing...");
1319 squash_commits(&repo, unpushed_count, None).await?;
1320 Output::success(" Squashed {unpushed_count} unpushed commits into one");
1321 }
1322 } else {
1323 println!(" Squashing last {squash_count} commits...");
1324 squash_commits(&repo, squash_count, None).await?;
1325 Output::success(" Squashed {squash_count} commits into one");
1326 }
1327 } else if let Some(since_ref) = squash_since {
1328 println!(" Squashing commits since {since_ref}...");
1329 let since_commit = repo.resolve_reference(&since_ref)?;
1330 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1331 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1332 Output::success(" Squashed {commits_count} commits since {since_ref} into one");
1333 }
1334
1335 let commits_to_push = if let Some(commits_str) = commits {
1337 commits_str
1339 .split(',')
1340 .map(|s| s.trim().to_string())
1341 .collect::<Vec<String>>()
1342 } else if let Some(since_ref) = since {
1343 let since_commit = repo.resolve_reference(&since_ref)?;
1345 let head_commit = repo.get_head_commit()?;
1346
1347 let commits = repo.get_commits_between(
1349 &since_commit.id().to_string(),
1350 &head_commit.id().to_string(),
1351 )?;
1352 commits.into_iter().map(|c| c.id().to_string()).collect()
1353 } else if let Some(hash) = commit {
1354 vec![hash]
1356 } else {
1357 let active_stack = manager.get_active_stack().ok_or_else(|| {
1359 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1360 })?;
1361
1362 let base_branch = &active_stack.base_branch;
1364 let current_branch = repo.get_current_branch()?;
1365
1366 if current_branch == *base_branch {
1368 let mut unpushed = Vec::new();
1369 let head_commit = repo.get_head_commit()?;
1370 let mut current_commit = head_commit;
1371
1372 loop {
1374 let commit_hash = current_commit.id().to_string();
1375 let already_in_stack = active_stack
1376 .entries
1377 .iter()
1378 .any(|entry| entry.commit_hash == commit_hash);
1379
1380 if already_in_stack {
1381 break;
1382 }
1383
1384 unpushed.push(commit_hash);
1385
1386 if let Some(parent) = current_commit.parents().next() {
1388 current_commit = parent;
1389 } else {
1390 break;
1391 }
1392 }
1393
1394 unpushed.reverse(); unpushed
1396 } else {
1397 match repo.get_commits_between(base_branch, ¤t_branch) {
1399 Ok(commits) => {
1400 let mut unpushed: Vec<String> =
1401 commits.into_iter().map(|c| c.id().to_string()).collect();
1402
1403 unpushed.retain(|commit_hash| {
1405 !active_stack
1406 .entries
1407 .iter()
1408 .any(|entry| entry.commit_hash == *commit_hash)
1409 });
1410
1411 unpushed.reverse(); unpushed
1413 }
1414 Err(e) => {
1415 return Err(CascadeError::branch(format!(
1416 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1417 This usually means the branches have diverged or don't share common history."
1418 )));
1419 }
1420 }
1421 }
1422 };
1423
1424 if commits_to_push.is_empty() {
1425 Output::info(" No commits to push to stack");
1426 return Ok(());
1427 }
1428
1429 analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1431
1432 if dry_run {
1434 return Ok(());
1435 }
1436
1437 let mut pushed_count = 0;
1439 let mut source_branches = std::collections::HashSet::new();
1440
1441 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1442 let commit_obj = repo.get_commit(commit_hash)?;
1443 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1444
1445 let commit_source_branch = repo
1447 .find_branch_containing_commit(commit_hash)
1448 .unwrap_or_else(|_| current_branch.clone());
1449 source_branches.insert(commit_source_branch.clone());
1450
1451 let branch_name = if i == 0 && branch.is_some() {
1453 branch.clone().unwrap()
1454 } else {
1455 let temp_repo = GitRepository::open(&repo_root)?;
1457 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1458 branch_mgr.generate_branch_name(&commit_msg)
1459 };
1460
1461 let final_message = if i == 0 && message.is_some() {
1463 message.clone().unwrap()
1464 } else {
1465 commit_msg.clone()
1466 };
1467
1468 let entry_id = manager.push_to_stack(
1469 branch_name.clone(),
1470 commit_hash.clone(),
1471 final_message.clone(),
1472 commit_source_branch.clone(),
1473 )?;
1474 pushed_count += 1;
1475
1476 Output::success(format!(
1477 "Pushed commit {}/{} to stack",
1478 i + 1,
1479 commits_to_push.len()
1480 ));
1481 Output::sub_item(format!(
1482 "Commit: {} ({})",
1483 &commit_hash[..8],
1484 commit_msg.split('\n').next().unwrap_or("")
1485 ));
1486 Output::sub_item(format!("Branch: {branch_name}"));
1487 Output::sub_item(format!("Source: {commit_source_branch}"));
1488 Output::sub_item(format!("Entry ID: {entry_id}"));
1489 println!();
1490 }
1491
1492 if source_branches.len() > 1 {
1494 Output::warning("Scattered Commit Detection");
1495 Output::sub_item(format!(
1496 "You've pushed commits from {} different Git branches:",
1497 source_branches.len()
1498 ));
1499 for branch in &source_branches {
1500 Output::bullet(branch.to_string());
1501 }
1502
1503 Output::section("This can lead to confusion because:");
1504 Output::bullet("Stack appears sequential but commits are scattered across branches");
1505 Output::bullet("Team members won't know which branch contains which work");
1506 Output::bullet("Branch cleanup becomes unclear after merge");
1507 Output::bullet("Rebase operations become more complex");
1508
1509 Output::tip("Consider consolidating work to a single feature branch:");
1510 Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1511 Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1512 Output::bullet("Delete old scattered branches");
1513 Output::bullet("Push the consolidated branch to your stack");
1514 println!();
1515 }
1516
1517 Output::success(format!(
1518 "Successfully pushed {} commit{} to stack",
1519 pushed_count,
1520 if pushed_count == 1 { "" } else { "s" }
1521 ));
1522
1523 Ok(())
1524}
1525
1526async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1527 let current_dir = env::current_dir()
1528 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1529
1530 let repo_root = find_repository_root(¤t_dir)
1531 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1532
1533 let mut manager = StackManager::new(&repo_root)?;
1534 let repo = GitRepository::open(&repo_root)?;
1535
1536 let entry = manager.pop_from_stack()?;
1537
1538 Output::success("Popped commit from stack");
1539 Output::sub_item(format!(
1540 "Commit: {} ({})",
1541 entry.short_hash(),
1542 entry.short_message(50)
1543 ));
1544 Output::sub_item(format!("Branch: {}", entry.branch));
1545
1546 if !keep_branch && entry.branch != repo.get_current_branch()? {
1548 match repo.delete_branch(&entry.branch) {
1549 Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1550 Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1551 }
1552 }
1553
1554 Ok(())
1555}
1556
1557async fn submit_entry(
1558 entry: Option<usize>,
1559 title: Option<String>,
1560 description: Option<String>,
1561 range: Option<String>,
1562 draft: bool,
1563 open: bool,
1564) -> Result<()> {
1565 let current_dir = env::current_dir()
1566 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1567
1568 let repo_root = find_repository_root(¤t_dir)
1569 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1570
1571 let mut stack_manager = StackManager::new(&repo_root)?;
1572
1573 if !stack_manager.check_for_branch_change()? {
1575 return Ok(()); }
1577
1578 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1580 let config_path = config_dir.join("config.json");
1581 let settings = crate::config::Settings::load_from_file(&config_path)?;
1582
1583 let cascade_config = crate::config::CascadeConfig {
1585 bitbucket: Some(settings.bitbucket.clone()),
1586 git: settings.git.clone(),
1587 auth: crate::config::AuthConfig::default(),
1588 cascade: settings.cascade.clone(),
1589 };
1590
1591 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1593 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1594 })?;
1595 let stack_id = active_stack.id;
1596
1597 let entries_to_submit = if let Some(range_str) = range {
1599 let mut entries = Vec::new();
1601
1602 if range_str.contains('-') {
1603 let parts: Vec<&str> = range_str.split('-').collect();
1605 if parts.len() != 2 {
1606 return Err(CascadeError::config(
1607 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1608 ));
1609 }
1610
1611 let start: usize = parts[0]
1612 .parse()
1613 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1614 let end: usize = parts[1]
1615 .parse()
1616 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1617
1618 if start == 0
1619 || end == 0
1620 || start > active_stack.entries.len()
1621 || end > active_stack.entries.len()
1622 {
1623 return Err(CascadeError::config(format!(
1624 "Range out of bounds. Stack has {} entries",
1625 active_stack.entries.len()
1626 )));
1627 }
1628
1629 for i in start..=end {
1630 entries.push((i, active_stack.entries[i - 1].clone()));
1631 }
1632 } else {
1633 for entry_str in range_str.split(',') {
1635 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1636 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1637 })?;
1638
1639 if entry_num == 0 || entry_num > active_stack.entries.len() {
1640 return Err(CascadeError::config(format!(
1641 "Entry {} out of bounds. Stack has {} entries",
1642 entry_num,
1643 active_stack.entries.len()
1644 )));
1645 }
1646
1647 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1648 }
1649 }
1650
1651 entries
1652 } else if let Some(entry_num) = entry {
1653 if entry_num == 0 || entry_num > active_stack.entries.len() {
1655 return Err(CascadeError::config(format!(
1656 "Invalid entry number: {}. Stack has {} entries",
1657 entry_num,
1658 active_stack.entries.len()
1659 )));
1660 }
1661 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1662 } else {
1663 active_stack
1665 .entries
1666 .iter()
1667 .enumerate()
1668 .filter(|(_, entry)| !entry.is_submitted)
1669 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1671 };
1672
1673 if entries_to_submit.is_empty() {
1674 Output::info("No entries to submit");
1675 return Ok(());
1676 }
1677
1678 Output::section(format!(
1680 "Submitting {} {}",
1681 entries_to_submit.len(),
1682 if entries_to_submit.len() == 1 {
1683 "entry"
1684 } else {
1685 "entries"
1686 }
1687 ));
1688 println!();
1689
1690 let integration_stack_manager = StackManager::new(&repo_root)?;
1692 let mut integration =
1693 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1694
1695 let mut submitted_count = 0;
1697 let mut failed_entries = Vec::new();
1698 let mut pr_urls = Vec::new(); let total_entries = entries_to_submit.len();
1700
1701 for (entry_num, entry_to_submit) in &entries_to_submit {
1702 let tree_char = if entries_to_submit.len() == 1 {
1704 "→"
1705 } else if entry_num == &entries_to_submit.len() {
1706 "└─"
1707 } else {
1708 "├─"
1709 };
1710 print!(
1711 " {} Entry {}: {}... ",
1712 tree_char, entry_num, entry_to_submit.branch
1713 );
1714 std::io::Write::flush(&mut std::io::stdout()).ok();
1715
1716 let entry_title = if total_entries == 1 {
1718 title.clone()
1719 } else {
1720 None
1721 };
1722 let entry_description = if total_entries == 1 {
1723 description.clone()
1724 } else {
1725 None
1726 };
1727
1728 match integration
1729 .submit_entry(
1730 &stack_id,
1731 &entry_to_submit.id,
1732 entry_title,
1733 entry_description,
1734 draft,
1735 )
1736 .await
1737 {
1738 Ok(pr) => {
1739 submitted_count += 1;
1740 println!("✓ PR #{}", pr.id);
1741 if let Some(url) = pr.web_url() {
1742 Output::sub_item(format!(
1743 "{} → {}",
1744 pr.from_ref.display_id, pr.to_ref.display_id
1745 ));
1746 Output::sub_item(format!("URL: {url}"));
1747 pr_urls.push(url); }
1749 }
1750 Err(e) => {
1751 println!("✗ Failed");
1752 let clean_error = if e.to_string().contains("non-fast-forward") {
1754 "Branch has diverged (was rebased after initial submission). Update to v0.1.41+ to auto force-push.".to_string()
1755 } else if e.to_string().contains("authentication") {
1756 "Authentication failed. Check your Bitbucket credentials.".to_string()
1757 } else {
1758 e.to_string()
1760 .lines()
1761 .filter(|l| !l.trim().starts_with("hint:") && !l.trim().is_empty())
1762 .take(1)
1763 .collect::<Vec<_>>()
1764 .join(" ")
1765 .trim()
1766 .to_string()
1767 };
1768 Output::sub_item(format!("Error: {}", clean_error));
1769 failed_entries.push((*entry_num, clean_error));
1770 }
1771 }
1772 }
1773
1774 println!();
1775
1776 let has_any_prs = active_stack
1778 .entries
1779 .iter()
1780 .any(|e| e.pull_request_id.is_some());
1781 if has_any_prs && submitted_count > 0 {
1782 match integration.update_all_pr_descriptions(&stack_id).await {
1783 Ok(updated_prs) => {
1784 if !updated_prs.is_empty() {
1785 Output::sub_item(format!(
1786 "Updated {} PR description{} with stack hierarchy",
1787 updated_prs.len(),
1788 if updated_prs.len() == 1 { "" } else { "s" }
1789 ));
1790 }
1791 }
1792 Err(e) => {
1793 let error_msg = e.to_string();
1796 if !error_msg.contains("409") && !error_msg.contains("out-of-date") {
1797 let clean_error = error_msg.lines().next().unwrap_or("Unknown error").trim();
1799 Output::warning(format!(
1800 "Could not update some PR descriptions: {}",
1801 clean_error
1802 ));
1803 Output::sub_item(
1804 "PRs were created successfully - descriptions can be updated manually",
1805 );
1806 }
1807 }
1808 }
1809 }
1810
1811 if failed_entries.is_empty() {
1813 Output::success(format!(
1814 "All {} {} submitted successfully!",
1815 submitted_count,
1816 if submitted_count == 1 {
1817 "entry"
1818 } else {
1819 "entries"
1820 }
1821 ));
1822 } else {
1823 println!();
1824 Output::section("Submission Summary");
1825 println!(" ✓ Successful: {submitted_count}");
1826 println!(" ✗ Failed: {}", failed_entries.len());
1827
1828 if !failed_entries.is_empty() {
1829 println!();
1830 Output::tip("Retry failed entries:");
1831 for (entry_num, _) in &failed_entries {
1832 Output::bullet(format!("ca stack submit {entry_num}"));
1833 }
1834 }
1835 }
1836
1837 if open && !pr_urls.is_empty() {
1839 println!();
1840 for url in &pr_urls {
1841 if let Err(e) = open::that(url) {
1842 Output::warning(format!("Could not open browser: {}", e));
1843 Output::tip(format!("Open manually: {}", url));
1844 }
1845 }
1846 }
1847
1848 Ok(())
1849}
1850
1851async fn check_stack_status(name: Option<String>) -> Result<()> {
1852 let current_dir = env::current_dir()
1853 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1854
1855 let repo_root = find_repository_root(¤t_dir)
1856 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1857
1858 let stack_manager = StackManager::new(&repo_root)?;
1859
1860 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1862 let config_path = config_dir.join("config.json");
1863 let settings = crate::config::Settings::load_from_file(&config_path)?;
1864
1865 let cascade_config = crate::config::CascadeConfig {
1867 bitbucket: Some(settings.bitbucket.clone()),
1868 git: settings.git.clone(),
1869 auth: crate::config::AuthConfig::default(),
1870 cascade: settings.cascade.clone(),
1871 };
1872
1873 let stack = if let Some(name) = name {
1875 stack_manager
1876 .get_stack_by_name(&name)
1877 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1878 } else {
1879 stack_manager.get_active_stack().ok_or_else(|| {
1880 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1881 })?
1882 };
1883 let stack_id = stack.id;
1884
1885 Output::section(format!("Stack: {}", stack.name));
1886 Output::sub_item(format!("ID: {}", stack.id));
1887 Output::sub_item(format!("Base: {}", stack.base_branch));
1888
1889 if let Some(description) = &stack.description {
1890 Output::sub_item(format!("Description: {description}"));
1891 }
1892
1893 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1895
1896 match integration.check_stack_status(&stack_id).await {
1898 Ok(status) => {
1899 Output::section("Pull Request Status");
1900 Output::sub_item(format!("Total entries: {}", status.total_entries));
1901 Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1902 Output::sub_item(format!("Open PRs: {}", status.open_prs));
1903 Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1904 Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1905 Output::sub_item(format!(
1906 "Completion: {:.1}%",
1907 status.completion_percentage()
1908 ));
1909
1910 if !status.pull_requests.is_empty() {
1911 Output::section("Pull Requests");
1912 for pr in &status.pull_requests {
1913 let state_icon = match pr.state {
1914 crate::bitbucket::PullRequestState::Open => "🔄",
1915 crate::bitbucket::PullRequestState::Merged => "✅",
1916 crate::bitbucket::PullRequestState::Declined => "❌",
1917 };
1918 Output::bullet(format!(
1919 "{} PR #{}: {} ({} -> {})",
1920 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1921 ));
1922 if let Some(url) = pr.web_url() {
1923 Output::sub_item(format!("URL: {url}"));
1924 }
1925 }
1926 }
1927 }
1928 Err(e) => {
1929 warn!("Failed to check stack status: {}", e);
1930 return Err(e);
1931 }
1932 }
1933
1934 Ok(())
1935}
1936
1937async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
1938 let current_dir = env::current_dir()
1939 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1940
1941 let repo_root = find_repository_root(¤t_dir)
1942 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1943
1944 let stack_manager = StackManager::new(&repo_root)?;
1945
1946 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1948 let config_path = config_dir.join("config.json");
1949 let settings = crate::config::Settings::load_from_file(&config_path)?;
1950
1951 let cascade_config = crate::config::CascadeConfig {
1953 bitbucket: Some(settings.bitbucket.clone()),
1954 git: settings.git.clone(),
1955 auth: crate::config::AuthConfig::default(),
1956 cascade: settings.cascade.clone(),
1957 };
1958
1959 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1961
1962 let pr_state = if let Some(state_str) = state {
1964 match state_str.to_lowercase().as_str() {
1965 "open" => Some(crate::bitbucket::PullRequestState::Open),
1966 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
1967 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
1968 _ => {
1969 return Err(CascadeError::config(format!(
1970 "Invalid state '{state_str}'. Use: open, merged, declined"
1971 )))
1972 }
1973 }
1974 } else {
1975 None
1976 };
1977
1978 match integration.list_pull_requests(pr_state).await {
1980 Ok(pr_page) => {
1981 if pr_page.values.is_empty() {
1982 Output::info("No pull requests found.");
1983 return Ok(());
1984 }
1985
1986 println!("Pull Requests ({} total):", pr_page.values.len());
1987 for pr in &pr_page.values {
1988 let state_icon = match pr.state {
1989 crate::bitbucket::PullRequestState::Open => "○",
1990 crate::bitbucket::PullRequestState::Merged => "✓",
1991 crate::bitbucket::PullRequestState::Declined => "✗",
1992 };
1993 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
1994 if verbose {
1995 println!(
1996 " From: {} -> {}",
1997 pr.from_ref.display_id, pr.to_ref.display_id
1998 );
1999 println!(
2000 " Author: {}",
2001 pr.author
2002 .user
2003 .display_name
2004 .as_deref()
2005 .unwrap_or(&pr.author.user.name)
2006 );
2007 if let Some(url) = pr.web_url() {
2008 println!(" URL: {url}");
2009 }
2010 if let Some(desc) = &pr.description {
2011 if !desc.is_empty() {
2012 println!(" Description: {desc}");
2013 }
2014 }
2015 println!();
2016 }
2017 }
2018
2019 if !verbose {
2020 println!("\nUse --verbose for more details");
2021 }
2022 }
2023 Err(e) => {
2024 warn!("Failed to list pull requests: {}", e);
2025 return Err(e);
2026 }
2027 }
2028
2029 Ok(())
2030}
2031
2032async fn check_stack(_force: bool) -> Result<()> {
2033 let current_dir = env::current_dir()
2034 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2035
2036 let repo_root = find_repository_root(¤t_dir)
2037 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2038
2039 let mut manager = StackManager::new(&repo_root)?;
2040
2041 let active_stack = manager
2042 .get_active_stack()
2043 .ok_or_else(|| CascadeError::config("No active stack"))?;
2044 let stack_id = active_stack.id;
2045
2046 manager.sync_stack(&stack_id)?;
2047
2048 Output::success("Stack check completed successfully");
2049
2050 Ok(())
2051}
2052
2053async fn continue_sync() -> Result<()> {
2054 let current_dir = env::current_dir()
2055 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2056
2057 let repo_root = find_repository_root(¤t_dir)?;
2058
2059 Output::section("Continuing sync from where it left off");
2060 println!();
2061
2062 let cherry_pick_head = repo_root.join(".git").join("CHERRY_PICK_HEAD");
2064 if !cherry_pick_head.exists() {
2065 return Err(CascadeError::config(
2066 "No in-progress cherry-pick found. Nothing to continue.\n\n\
2067 Use 'ca sync' to start a new sync."
2068 .to_string(),
2069 ));
2070 }
2071
2072 Output::info("Staging all resolved files");
2073
2074 std::process::Command::new("git")
2076 .args(["add", "-A"])
2077 .current_dir(&repo_root)
2078 .output()
2079 .map_err(CascadeError::Io)?;
2080
2081 Output::info("Continuing cherry-pick");
2082
2083 let continue_output = std::process::Command::new("git")
2085 .args(["cherry-pick", "--continue"])
2086 .current_dir(&repo_root)
2087 .output()
2088 .map_err(CascadeError::Io)?;
2089
2090 if !continue_output.status.success() {
2091 let stderr = String::from_utf8_lossy(&continue_output.stderr);
2092 return Err(CascadeError::Branch(format!(
2093 "Failed to continue cherry-pick: {}\n\n\
2094 Make sure all conflicts are resolved.",
2095 stderr
2096 )));
2097 }
2098
2099 Output::success("Cherry-pick continued successfully");
2100 println!();
2101
2102 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2109 let current_branch = git_repo.get_current_branch()?;
2110
2111 let stack_branch = if let Some(idx) = current_branch.rfind("-temp-") {
2114 current_branch[..idx].to_string()
2115 } else {
2116 return Err(CascadeError::config(format!(
2117 "Current branch '{}' doesn't appear to be a temp branch created by cascade.\n\
2118 Expected format: <branch>-temp-<timestamp>",
2119 current_branch
2120 )));
2121 };
2122
2123 Output::info(format!("Updating stack branch: {}", stack_branch));
2124
2125 std::process::Command::new("git")
2127 .args(["branch", "-f", &stack_branch])
2128 .current_dir(&repo_root)
2129 .output()
2130 .map_err(CascadeError::Io)?;
2131
2132 let manager = crate::stack::StackManager::new(&repo_root)?;
2134 let active_stack = manager
2135 .get_active_stack()
2136 .ok_or_else(|| CascadeError::config("No active stack found"))?;
2137
2138 let working_branch = active_stack
2139 .working_branch
2140 .as_ref()
2141 .ok_or_else(|| CascadeError::config("Active stack has no working branch"))?
2142 .clone();
2143
2144 Output::info(format!(
2145 "Checking out to working branch: {}",
2146 working_branch
2147 ));
2148
2149 git_repo.checkout_branch_unsafe(&working_branch)?;
2151
2152 println!();
2153 Output::info("Resuming sync to complete the rebase...");
2154 println!();
2155
2156 sync_stack(false, false, false).await
2158}
2159
2160async fn sync_stack(force: bool, cleanup: bool, interactive: bool) -> Result<()> {
2161 let current_dir = env::current_dir()
2162 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2163
2164 let repo_root = find_repository_root(¤t_dir)
2165 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2166
2167 let mut stack_manager = StackManager::new(&repo_root)?;
2168
2169 if stack_manager.is_in_edit_mode() {
2172 debug!("Exiting edit mode before sync (commit SHAs will change)");
2173 stack_manager.exit_edit_mode()?;
2174 }
2175
2176 let git_repo = GitRepository::open(&repo_root)?;
2177
2178 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2180 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2181 })?;
2182
2183 let base_branch = active_stack.base_branch.clone();
2184 let _stack_name = active_stack.name.clone();
2185
2186 let original_branch = git_repo.get_current_branch().ok();
2188
2189 match git_repo.checkout_branch_silent(&base_branch) {
2193 Ok(_) => {
2194 match git_repo.pull(&base_branch) {
2195 Ok(_) => {
2196 }
2198 Err(e) => {
2199 if force {
2200 Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
2201 } else {
2202 Output::error(format!("Failed to pull latest changes: {e}"));
2203 Output::tip("Use --force to skip pull and continue with rebase");
2204 return Err(CascadeError::branch(format!(
2205 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
2206 )));
2207 }
2208 }
2209 }
2210 }
2211 Err(e) => {
2212 if force {
2213 Output::warning(format!(
2214 "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2215 ));
2216 } else {
2217 Output::error(format!(
2218 "Failed to checkout base branch '{base_branch}': {e}"
2219 ));
2220 Output::tip("Use --force to bypass checkout issues and continue anyway");
2221 return Err(CascadeError::branch(format!(
2222 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2223 )));
2224 }
2225 }
2226 }
2227
2228 let mut updated_stack_manager = StackManager::new(&repo_root)?;
2231 let stack_id = active_stack.id;
2232
2233 if let Some(stack) = updated_stack_manager.get_stack_mut(&stack_id) {
2236 for entry in &mut stack.entries {
2237 if let Ok(current_commit) = git_repo.get_branch_head(&entry.branch) {
2238 if entry.commit_hash != current_commit {
2239 debug!(
2240 "Reconciling entry '{}': updating hash from {} to {} (current branch HEAD)",
2241 entry.branch,
2242 &entry.commit_hash[..8],
2243 ¤t_commit[..8]
2244 );
2245 entry.commit_hash = current_commit;
2246 }
2247 }
2248 }
2249 updated_stack_manager.save_to_disk()?;
2251 }
2252
2253 match updated_stack_manager.sync_stack(&stack_id) {
2254 Ok(_) => {
2255 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2257 if updated_stack.entries.is_empty() {
2259 println!(); Output::info("Stack has no entries yet");
2261 Output::tip("Use 'ca push' to add commits to this stack");
2262 return Ok(());
2263 }
2264
2265 match &updated_stack.status {
2266 crate::stack::StackStatus::NeedsSync => {
2267 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2269 let config_path = config_dir.join("config.json");
2270 let settings = crate::config::Settings::load_from_file(&config_path)?;
2271
2272 let cascade_config = crate::config::CascadeConfig {
2273 bitbucket: Some(settings.bitbucket.clone()),
2274 git: settings.git.clone(),
2275 auth: crate::config::AuthConfig::default(),
2276 cascade: settings.cascade.clone(),
2277 };
2278
2279 let options = crate::stack::RebaseOptions {
2282 strategy: crate::stack::RebaseStrategy::ForcePush,
2283 interactive,
2284 target_base: Some(base_branch.clone()),
2285 preserve_merges: true,
2286 auto_resolve: !interactive, max_retries: 3,
2288 skip_pull: Some(true), original_working_branch: original_branch.clone(), };
2291
2292 let mut rebase_manager = crate::stack::RebaseManager::new(
2293 updated_stack_manager,
2294 git_repo,
2295 options,
2296 );
2297
2298 match rebase_manager.rebase_stack(&stack_id) {
2299 Ok(result) => {
2300 if !result.branch_mapping.is_empty() {
2301 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2303 let integration_stack_manager =
2304 StackManager::new(&repo_root)?;
2305 let mut integration =
2306 crate::bitbucket::BitbucketIntegration::new(
2307 integration_stack_manager,
2308 cascade_config,
2309 )?;
2310
2311 match integration
2312 .update_prs_after_rebase(
2313 &stack_id,
2314 &result.branch_mapping,
2315 )
2316 .await
2317 {
2318 Ok(updated_prs) => {
2319 if !updated_prs.is_empty() {
2320 println!(
2321 "Updated {} pull requests",
2322 updated_prs.len()
2323 );
2324 }
2325 }
2326 Err(e) => {
2327 Output::warning(format!(
2328 "Failed to update pull requests: {e}"
2329 ));
2330 }
2331 }
2332 }
2333 }
2334 }
2335 Err(e) => {
2336 return Err(e);
2338 }
2339 }
2340 }
2341 crate::stack::StackStatus::Clean => {
2342 }
2344 other => {
2345 Output::info(format!("Stack status: {other:?}"));
2347 }
2348 }
2349 }
2350 }
2351 Err(e) => {
2352 if force {
2353 Output::warning(format!(
2354 "Failed to check stack status: {e} (continuing due to --force)"
2355 ));
2356 } else {
2357 return Err(e);
2358 }
2359 }
2360 }
2361
2362 if cleanup {
2364 let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2365 match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2366 Ok(result) => {
2367 if result.total_candidates > 0 {
2368 Output::section("Cleanup Summary");
2369 if !result.cleaned_branches.is_empty() {
2370 Output::success(format!(
2371 "Cleaned up {} merged branches",
2372 result.cleaned_branches.len()
2373 ));
2374 for branch in &result.cleaned_branches {
2375 Output::sub_item(format!("🗑️ Deleted: {branch}"));
2376 }
2377 }
2378 if !result.skipped_branches.is_empty() {
2379 Output::sub_item(format!(
2380 "Skipped {} branches",
2381 result.skipped_branches.len()
2382 ));
2383 }
2384 if !result.failed_branches.is_empty() {
2385 for (branch, error) in &result.failed_branches {
2386 Output::warning(format!("Failed to clean up {branch}: {error}"));
2387 }
2388 }
2389 }
2390 }
2391 Err(e) => {
2392 Output::warning(format!("Branch cleanup failed: {e}"));
2393 }
2394 }
2395 }
2396
2397 if let Some(orig_branch) = original_branch {
2399 if orig_branch != base_branch {
2400 if let Ok(git_repo) = GitRepository::open(&repo_root) {
2402 if let Err(e) = git_repo.checkout_branch(&orig_branch) {
2403 Output::warning(format!(
2404 "Could not return to original branch '{}': {}",
2405 orig_branch, e
2406 ));
2407 }
2408 }
2409 }
2410 }
2411
2412 Output::success("Sync completed successfully!");
2413
2414 Ok(())
2415}
2416
2417async fn rebase_stack(
2418 interactive: bool,
2419 onto: Option<String>,
2420 strategy: Option<RebaseStrategyArg>,
2421) -> Result<()> {
2422 let current_dir = env::current_dir()
2423 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2424
2425 let repo_root = find_repository_root(¤t_dir)
2426 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2427
2428 let stack_manager = StackManager::new(&repo_root)?;
2429 let git_repo = GitRepository::open(&repo_root)?;
2430
2431 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2433 let config_path = config_dir.join("config.json");
2434 let settings = crate::config::Settings::load_from_file(&config_path)?;
2435
2436 let cascade_config = crate::config::CascadeConfig {
2438 bitbucket: Some(settings.bitbucket.clone()),
2439 git: settings.git.clone(),
2440 auth: crate::config::AuthConfig::default(),
2441 cascade: settings.cascade.clone(),
2442 };
2443
2444 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2446 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2447 })?;
2448 let stack_id = active_stack.id;
2449
2450 let active_stack = stack_manager
2451 .get_stack(&stack_id)
2452 .ok_or_else(|| CascadeError::config("Active stack not found"))?
2453 .clone();
2454
2455 if active_stack.entries.is_empty() {
2456 Output::info("Stack is empty. Nothing to rebase.");
2457 return Ok(());
2458 }
2459
2460 Output::progress(format!("Rebasing stack: {}", active_stack.name));
2461 Output::sub_item(format!("Base: {}", active_stack.base_branch));
2462
2463 let rebase_strategy = if let Some(cli_strategy) = strategy {
2465 match cli_strategy {
2466 RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2467 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2468 }
2469 } else {
2470 crate::stack::RebaseStrategy::ForcePush
2472 };
2473
2474 let original_branch = git_repo.get_current_branch().ok();
2476
2477 let options = crate::stack::RebaseOptions {
2479 strategy: rebase_strategy.clone(),
2480 interactive,
2481 target_base: onto,
2482 preserve_merges: true,
2483 auto_resolve: !interactive, max_retries: 3,
2485 skip_pull: None, original_working_branch: original_branch,
2487 };
2488
2489 debug!(" Strategy: {:?}", rebase_strategy);
2490 debug!(" Interactive: {}", interactive);
2491 debug!(" Target base: {:?}", options.target_base);
2492 debug!(" Entries: {}", active_stack.entries.len());
2493
2494 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2496
2497 if rebase_manager.is_rebase_in_progress() {
2498 Output::warning("Rebase already in progress!");
2499 Output::tip("Use 'git status' to check the current state");
2500 Output::next_steps(&[
2501 "Run 'ca stack continue-rebase' to continue",
2502 "Run 'ca stack abort-rebase' to abort",
2503 ]);
2504 return Ok(());
2505 }
2506
2507 match rebase_manager.rebase_stack(&stack_id) {
2509 Ok(result) => {
2510 Output::success("Rebase completed!");
2511 Output::sub_item(result.get_summary());
2512
2513 if result.has_conflicts() {
2514 Output::warning(format!(
2515 "{} conflicts were resolved",
2516 result.conflicts.len()
2517 ));
2518 for conflict in &result.conflicts {
2519 Output::bullet(&conflict[..8.min(conflict.len())]);
2520 }
2521 }
2522
2523 if !result.branch_mapping.is_empty() {
2524 Output::section("Branch mapping");
2525 for (old, new) in &result.branch_mapping {
2526 Output::bullet(format!("{old} -> {new}"));
2527 }
2528
2529 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2531 let integration_stack_manager = StackManager::new(&repo_root)?;
2533 let mut integration = BitbucketIntegration::new(
2534 integration_stack_manager,
2535 cascade_config.clone(),
2536 )?;
2537
2538 match integration
2539 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2540 .await
2541 {
2542 Ok(updated_prs) => {
2543 if !updated_prs.is_empty() {
2544 println!(" 🔄 Preserved pull request history:");
2545 for pr_update in updated_prs {
2546 println!(" ✅ {pr_update}");
2547 }
2548 }
2549 }
2550 Err(e) => {
2551 eprintln!(" ⚠️ Failed to update pull requests: {e}");
2552 eprintln!(" You may need to manually update PRs in Bitbucket");
2553 }
2554 }
2555 }
2556 }
2557
2558 println!(
2559 " ✅ {} commits successfully rebased",
2560 result.success_count()
2561 );
2562
2563 if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2565 println!("\n📝 Next steps:");
2566 if !result.branch_mapping.is_empty() {
2567 println!(" 1. ✅ Branches have been rebased and force-pushed");
2568 println!(" 2. ✅ Pull requests updated automatically (history preserved)");
2569 println!(" 3. 🔍 Review the updated PRs in Bitbucket");
2570 println!(" 4. 🧪 Test your changes");
2571 } else {
2572 println!(" 1. Review the rebased stack");
2573 println!(" 2. Test your changes");
2574 println!(" 3. Submit new pull requests with 'ca stack submit'");
2575 }
2576 }
2577 }
2578 Err(e) => {
2579 warn!("❌ Rebase failed: {}", e);
2580 Output::tip(" Tips for resolving rebase issues:");
2581 println!(" - Check for uncommitted changes with 'git status'");
2582 println!(" - Ensure base branch is up to date");
2583 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2584 return Err(e);
2585 }
2586 }
2587
2588 Ok(())
2589}
2590
2591async fn continue_rebase() -> Result<()> {
2592 let current_dir = env::current_dir()
2593 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2594
2595 let repo_root = find_repository_root(¤t_dir)
2596 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2597
2598 let stack_manager = StackManager::new(&repo_root)?;
2599 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2600 let options = crate::stack::RebaseOptions::default();
2601 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2602
2603 if !rebase_manager.is_rebase_in_progress() {
2604 Output::info(" No rebase in progress");
2605 return Ok(());
2606 }
2607
2608 println!(" Continuing rebase...");
2609 match rebase_manager.continue_rebase() {
2610 Ok(_) => {
2611 Output::success(" Rebase continued successfully");
2612 println!(" Check 'ca stack rebase-status' for current state");
2613 }
2614 Err(e) => {
2615 warn!("❌ Failed to continue rebase: {}", e);
2616 Output::tip(" You may need to resolve conflicts first:");
2617 println!(" 1. Edit conflicted files");
2618 println!(" 2. Stage resolved files with 'git add'");
2619 println!(" 3. Run 'ca stack continue-rebase' again");
2620 }
2621 }
2622
2623 Ok(())
2624}
2625
2626async fn abort_rebase() -> Result<()> {
2627 let current_dir = env::current_dir()
2628 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2629
2630 let repo_root = find_repository_root(¤t_dir)
2631 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2632
2633 let stack_manager = StackManager::new(&repo_root)?;
2634 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2635 let options = crate::stack::RebaseOptions::default();
2636 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2637
2638 if !rebase_manager.is_rebase_in_progress() {
2639 Output::info(" No rebase in progress");
2640 return Ok(());
2641 }
2642
2643 println!("⚠️ Aborting rebase...");
2644 match rebase_manager.abort_rebase() {
2645 Ok(_) => {
2646 Output::success(" Rebase aborted successfully");
2647 println!(" Repository restored to pre-rebase state");
2648 }
2649 Err(e) => {
2650 warn!("❌ Failed to abort rebase: {}", e);
2651 println!("⚠️ You may need to manually clean up the repository state");
2652 }
2653 }
2654
2655 Ok(())
2656}
2657
2658async fn rebase_status() -> Result<()> {
2659 let current_dir = env::current_dir()
2660 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2661
2662 let repo_root = find_repository_root(¤t_dir)
2663 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2664
2665 let stack_manager = StackManager::new(&repo_root)?;
2666 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2667
2668 println!("Rebase Status");
2669
2670 let git_dir = current_dir.join(".git");
2672 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2673 || git_dir.join("rebase-merge").exists()
2674 || git_dir.join("rebase-apply").exists();
2675
2676 if rebase_in_progress {
2677 println!(" Status: 🔄 Rebase in progress");
2678 println!(
2679 "
2680📝 Actions available:"
2681 );
2682 println!(" - 'ca stack continue-rebase' to continue");
2683 println!(" - 'ca stack abort-rebase' to abort");
2684 println!(" - 'git status' to see conflicted files");
2685
2686 match git_repo.get_status() {
2688 Ok(statuses) => {
2689 let mut conflicts = Vec::new();
2690 for status in statuses.iter() {
2691 if status.status().contains(git2::Status::CONFLICTED) {
2692 if let Some(path) = status.path() {
2693 conflicts.push(path.to_string());
2694 }
2695 }
2696 }
2697
2698 if !conflicts.is_empty() {
2699 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2700 for conflict in conflicts {
2701 println!(" - {conflict}");
2702 }
2703 println!(
2704 "
2705💡 To resolve conflicts:"
2706 );
2707 println!(" 1. Edit the conflicted files");
2708 println!(" 2. Stage resolved files: git add <file>");
2709 println!(" 3. Continue: ca stack continue-rebase");
2710 }
2711 }
2712 Err(e) => {
2713 warn!("Failed to get git status: {}", e);
2714 }
2715 }
2716 } else {
2717 println!(" Status: ✅ No rebase in progress");
2718
2719 if let Some(active_stack) = stack_manager.get_active_stack() {
2721 println!(" Active stack: {}", active_stack.name);
2722 println!(" Entries: {}", active_stack.entries.len());
2723 println!(" Base branch: {}", active_stack.base_branch);
2724 }
2725 }
2726
2727 Ok(())
2728}
2729
2730async fn delete_stack(name: String, force: bool) -> Result<()> {
2731 let current_dir = env::current_dir()
2732 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2733
2734 let repo_root = find_repository_root(¤t_dir)
2735 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2736
2737 let mut manager = StackManager::new(&repo_root)?;
2738
2739 let stack = manager
2740 .get_stack_by_name(&name)
2741 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2742 let stack_id = stack.id;
2743
2744 if !force && !stack.entries.is_empty() {
2745 return Err(CascadeError::config(format!(
2746 "Stack '{}' has {} entries. Use --force to delete anyway",
2747 name,
2748 stack.entries.len()
2749 )));
2750 }
2751
2752 let deleted = manager.delete_stack(&stack_id)?;
2753
2754 Output::success(format!("Deleted stack '{}'", deleted.name));
2755 if !deleted.entries.is_empty() {
2756 Output::warning(format!("{} entries were removed", deleted.entries.len()));
2757 }
2758
2759 Ok(())
2760}
2761
2762async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2763 let current_dir = env::current_dir()
2764 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2765
2766 let repo_root = find_repository_root(¤t_dir)
2767 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2768
2769 let mut manager = StackManager::new(&repo_root)?;
2770
2771 if let Some(name) = name {
2772 let stack = manager
2774 .get_stack_by_name(&name)
2775 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2776
2777 let stack_id = stack.id;
2778
2779 match stack.validate() {
2781 Ok(_message) => {
2782 Output::success(format!("Stack '{}' structure validation passed", name));
2783 }
2784 Err(e) => {
2785 Output::error(format!(
2786 "Stack '{}' structure validation failed: {}",
2787 name, e
2788 ));
2789 return Err(CascadeError::config(e));
2790 }
2791 }
2792
2793 manager.handle_branch_modifications(&stack_id, fix_mode)?;
2795
2796 println!();
2797 Output::success(format!("Stack '{name}' validation completed"));
2798 Ok(())
2799 } else {
2800 Output::section("Validating all stacks");
2802 println!();
2803
2804 let all_stacks = manager.get_all_stacks();
2806 let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2807
2808 if stack_ids.is_empty() {
2809 Output::info("No stacks found");
2810 return Ok(());
2811 }
2812
2813 let mut all_valid = true;
2814 for stack_id in stack_ids {
2815 let stack = manager.get_stack(&stack_id).unwrap();
2816 let stack_name = &stack.name;
2817
2818 println!("Checking stack '{stack_name}':");
2819
2820 match stack.validate() {
2822 Ok(message) => {
2823 Output::sub_item(format!("Structure: {message}"));
2824 }
2825 Err(e) => {
2826 Output::sub_item(format!("Structure: {e}"));
2827 all_valid = false;
2828 continue;
2829 }
2830 }
2831
2832 match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2834 Ok(_) => {
2835 Output::sub_item("Git integrity: OK");
2836 }
2837 Err(e) => {
2838 Output::sub_item(format!("Git integrity: {e}"));
2839 all_valid = false;
2840 }
2841 }
2842 println!();
2843 }
2844
2845 if all_valid {
2846 Output::success("All stacks passed validation");
2847 } else {
2848 Output::warning("Some stacks have validation issues");
2849 return Err(CascadeError::config("Stack validation failed".to_string()));
2850 }
2851
2852 Ok(())
2853 }
2854}
2855
2856#[allow(dead_code)]
2858fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2859 let mut unpushed = Vec::new();
2860 let head_commit = repo.get_head_commit()?;
2861 let mut current_commit = head_commit;
2862
2863 loop {
2865 let commit_hash = current_commit.id().to_string();
2866 let already_in_stack = stack
2867 .entries
2868 .iter()
2869 .any(|entry| entry.commit_hash == commit_hash);
2870
2871 if already_in_stack {
2872 break;
2873 }
2874
2875 unpushed.push(commit_hash);
2876
2877 if let Some(parent) = current_commit.parents().next() {
2879 current_commit = parent;
2880 } else {
2881 break;
2882 }
2883 }
2884
2885 unpushed.reverse(); Ok(unpushed)
2887}
2888
2889pub async fn squash_commits(
2891 repo: &GitRepository,
2892 count: usize,
2893 since_ref: Option<String>,
2894) -> Result<()> {
2895 if count <= 1 {
2896 return Ok(()); }
2898
2899 let _current_branch = repo.get_current_branch()?;
2901
2902 let rebase_range = if let Some(ref since) = since_ref {
2904 since.clone()
2905 } else {
2906 format!("HEAD~{count}")
2907 };
2908
2909 println!(" Analyzing {count} commits to create smart squash message...");
2910
2911 let head_commit = repo.get_head_commit()?;
2913 let mut commits_to_squash = Vec::new();
2914 let mut current = head_commit;
2915
2916 for _ in 0..count {
2918 commits_to_squash.push(current.clone());
2919 if current.parent_count() > 0 {
2920 current = current.parent(0).map_err(CascadeError::Git)?;
2921 } else {
2922 break;
2923 }
2924 }
2925
2926 let smart_message = generate_squash_message(&commits_to_squash)?;
2928 println!(
2929 " Smart message: {}",
2930 smart_message.lines().next().unwrap_or("")
2931 );
2932
2933 let reset_target = if since_ref.is_some() {
2935 format!("{rebase_range}~1")
2937 } else {
2938 format!("HEAD~{count}")
2940 };
2941
2942 repo.reset_soft(&reset_target)?;
2944
2945 repo.stage_all()?;
2947
2948 let new_commit_hash = repo.commit(&smart_message)?;
2950
2951 println!(
2952 " Created squashed commit: {} ({})",
2953 &new_commit_hash[..8],
2954 smart_message.lines().next().unwrap_or("")
2955 );
2956 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2957
2958 Ok(())
2959}
2960
2961pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2963 if commits.is_empty() {
2964 return Ok("Squashed commits".to_string());
2965 }
2966
2967 let messages: Vec<String> = commits
2969 .iter()
2970 .map(|c| c.message().unwrap_or("").trim().to_string())
2971 .filter(|m| !m.is_empty())
2972 .collect();
2973
2974 if messages.is_empty() {
2975 return Ok("Squashed commits".to_string());
2976 }
2977
2978 if let Some(last_msg) = messages.first() {
2980 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2982 return Ok(last_msg
2983 .trim_start_matches("Final:")
2984 .trim_start_matches("final:")
2985 .trim()
2986 .to_string());
2987 }
2988 }
2989
2990 let wip_count = messages
2992 .iter()
2993 .filter(|m| {
2994 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2995 })
2996 .count();
2997
2998 if wip_count > messages.len() / 2 {
2999 let non_wip: Vec<&String> = messages
3001 .iter()
3002 .filter(|m| {
3003 !m.to_lowercase().starts_with("wip")
3004 && !m.to_lowercase().contains("work in progress")
3005 })
3006 .collect();
3007
3008 if let Some(best_msg) = non_wip.first() {
3009 return Ok(best_msg.to_string());
3010 }
3011
3012 let feature = extract_feature_from_wip(&messages);
3014 return Ok(feature);
3015 }
3016
3017 Ok(messages.first().unwrap().clone())
3019}
3020
3021pub fn extract_feature_from_wip(messages: &[String]) -> String {
3023 for msg in messages {
3025 if msg.to_lowercase().starts_with("wip:") {
3027 if let Some(rest) = msg
3028 .strip_prefix("WIP:")
3029 .or_else(|| msg.strip_prefix("wip:"))
3030 {
3031 let feature = rest.trim();
3032 if !feature.is_empty() && feature.len() > 3 {
3033 let mut chars: Vec<char> = feature.chars().collect();
3035 if let Some(first) = chars.first_mut() {
3036 *first = first.to_uppercase().next().unwrap_or(*first);
3037 }
3038 return chars.into_iter().collect();
3039 }
3040 }
3041 }
3042 }
3043
3044 if let Some(first) = messages.first() {
3046 let cleaned = first
3047 .trim_start_matches("WIP:")
3048 .trim_start_matches("wip:")
3049 .trim_start_matches("WIP")
3050 .trim_start_matches("wip")
3051 .trim();
3052
3053 if !cleaned.is_empty() {
3054 return format!("Implement {cleaned}");
3055 }
3056 }
3057
3058 format!("Squashed {} commits", messages.len())
3059}
3060
3061pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
3063 let head_commit = repo.get_head_commit()?;
3064 let since_commit = repo.get_commit(since_commit_hash)?;
3065
3066 let mut count = 0;
3067 let mut current = head_commit;
3068
3069 loop {
3071 if current.id() == since_commit.id() {
3072 break;
3073 }
3074
3075 count += 1;
3076
3077 if current.parent_count() == 0 {
3079 break; }
3081
3082 current = current.parent(0).map_err(CascadeError::Git)?;
3083 }
3084
3085 Ok(count)
3086}
3087
3088async fn land_stack(
3090 entry: Option<usize>,
3091 force: bool,
3092 dry_run: bool,
3093 auto: bool,
3094 wait_for_builds: bool,
3095 strategy: Option<MergeStrategyArg>,
3096 build_timeout: u64,
3097) -> Result<()> {
3098 let current_dir = env::current_dir()
3099 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3100
3101 let repo_root = find_repository_root(¤t_dir)
3102 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3103
3104 let stack_manager = StackManager::new(&repo_root)?;
3105
3106 let stack_id = stack_manager
3108 .get_active_stack()
3109 .map(|s| s.id)
3110 .ok_or_else(|| {
3111 CascadeError::config(
3112 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
3113 .to_string(),
3114 )
3115 })?;
3116
3117 let active_stack = stack_manager
3118 .get_active_stack()
3119 .cloned()
3120 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
3121
3122 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
3124 let config_path = config_dir.join("config.json");
3125 let settings = crate::config::Settings::load_from_file(&config_path)?;
3126
3127 let cascade_config = crate::config::CascadeConfig {
3128 bitbucket: Some(settings.bitbucket.clone()),
3129 git: settings.git.clone(),
3130 auth: crate::config::AuthConfig::default(),
3131 cascade: settings.cascade.clone(),
3132 };
3133
3134 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
3135
3136 let status = integration.check_enhanced_stack_status(&stack_id).await?;
3138
3139 if status.enhanced_statuses.is_empty() {
3140 println!("❌ No pull requests found to land");
3141 return Ok(());
3142 }
3143
3144 let ready_prs: Vec<_> = status
3146 .enhanced_statuses
3147 .iter()
3148 .filter(|pr_status| {
3149 if let Some(entry_num) = entry {
3151 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
3153 if pr_status.pr.from_ref.display_id != stack_entry.branch {
3155 return false;
3156 }
3157 } else {
3158 return false; }
3160 }
3161
3162 if force {
3163 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
3165 } else {
3166 pr_status.is_ready_to_land()
3167 }
3168 })
3169 .collect();
3170
3171 if ready_prs.is_empty() {
3172 if let Some(entry_num) = entry {
3173 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
3174 } else {
3175 println!("❌ No pull requests are ready to land");
3176 }
3177
3178 println!("\n🚫 Blocking Issues:");
3180 for pr_status in &status.enhanced_statuses {
3181 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
3182 let blocking = pr_status.get_blocking_reasons();
3183 if !blocking.is_empty() {
3184 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
3185 }
3186 }
3187 }
3188
3189 if !force {
3190 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
3191 }
3192 return Ok(());
3193 }
3194
3195 if dry_run {
3196 if let Some(entry_num) = entry {
3197 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
3198 } else {
3199 println!("🏃 Dry Run - PRs that would be landed:");
3200 }
3201 for pr_status in &ready_prs {
3202 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
3203 if !pr_status.is_ready_to_land() && force {
3204 let blocking = pr_status.get_blocking_reasons();
3205 println!(
3206 " ⚠️ Would force land despite: {}",
3207 blocking.join(", ")
3208 );
3209 }
3210 }
3211 return Ok(());
3212 }
3213
3214 if entry.is_some() && ready_prs.len() > 1 {
3217 println!(
3218 "🎯 {} PRs are ready to land, but landing only entry #{}",
3219 ready_prs.len(),
3220 entry.unwrap()
3221 );
3222 }
3223
3224 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
3226 strategy.unwrap_or(MergeStrategyArg::Squash).into();
3227 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3228 merge_strategy: merge_strategy.clone(),
3229 wait_for_builds,
3230 build_timeout: std::time::Duration::from_secs(build_timeout),
3231 allowed_authors: None, };
3233
3234 println!(
3236 "🚀 Landing {} PR{}...",
3237 ready_prs.len(),
3238 if ready_prs.len() == 1 { "" } else { "s" }
3239 );
3240
3241 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
3242 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
3243 );
3244
3245 let mut landed_count = 0;
3247 let mut failed_count = 0;
3248 let total_ready_prs = ready_prs.len();
3249
3250 for pr_status in ready_prs {
3251 let pr_id = pr_status.pr.id;
3252
3253 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
3254
3255 let land_result = if auto {
3256 pr_manager
3258 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
3259 .await
3260 } else {
3261 pr_manager
3263 .merge_pull_request(pr_id, merge_strategy.clone())
3264 .await
3265 .map(
3266 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3267 pr: Box::new(pr),
3268 merge_strategy: merge_strategy.clone(),
3269 },
3270 )
3271 };
3272
3273 match land_result {
3274 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3275 println!(" ✅");
3276 landed_count += 1;
3277
3278 if landed_count < total_ready_prs {
3280 println!(" Retargeting remaining PRs to latest base...");
3281
3282 let base_branch = active_stack.base_branch.clone();
3284 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3285
3286 println!(" 📥 Updating base branch: {base_branch}");
3287 match git_repo.pull(&base_branch) {
3288 Ok(_) => println!(" ✅ Base branch updated successfully"),
3289 Err(e) => {
3290 println!(" ⚠️ Warning: Failed to update base branch: {e}");
3291 println!(
3292 " 💡 You may want to manually run: git pull origin {base_branch}"
3293 );
3294 }
3295 }
3296
3297 let mut rebase_manager = crate::stack::RebaseManager::new(
3299 StackManager::new(&repo_root)?,
3300 git_repo,
3301 crate::stack::RebaseOptions {
3302 strategy: crate::stack::RebaseStrategy::ForcePush,
3303 target_base: Some(base_branch.clone()),
3304 ..Default::default()
3305 },
3306 );
3307
3308 match rebase_manager.rebase_stack(&stack_id) {
3309 Ok(rebase_result) => {
3310 if !rebase_result.branch_mapping.is_empty() {
3311 let retarget_config = crate::config::CascadeConfig {
3313 bitbucket: Some(settings.bitbucket.clone()),
3314 git: settings.git.clone(),
3315 auth: crate::config::AuthConfig::default(),
3316 cascade: settings.cascade.clone(),
3317 };
3318 let mut retarget_integration = BitbucketIntegration::new(
3319 StackManager::new(&repo_root)?,
3320 retarget_config,
3321 )?;
3322
3323 match retarget_integration
3324 .update_prs_after_rebase(
3325 &stack_id,
3326 &rebase_result.branch_mapping,
3327 )
3328 .await
3329 {
3330 Ok(updated_prs) => {
3331 if !updated_prs.is_empty() {
3332 println!(
3333 " ✅ Updated {} PRs with new targets",
3334 updated_prs.len()
3335 );
3336 }
3337 }
3338 Err(e) => {
3339 println!(" ⚠️ Failed to update remaining PRs: {e}");
3340 println!(
3341 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
3342 );
3343 }
3344 }
3345 }
3346 }
3347 Err(e) => {
3348 println!(" ❌ Auto-retargeting conflicts detected!");
3350 println!(" 📝 To resolve conflicts and continue landing:");
3351 println!(" 1. Resolve conflicts in the affected files");
3352 println!(" 2. Stage resolved files: git add <files>");
3353 println!(" 3. Continue the process: ca stack continue-land");
3354 println!(" 4. Or abort the operation: ca stack abort-land");
3355 println!();
3356 println!(" 💡 Check current status: ca stack land-status");
3357 println!(" ⚠️ Error details: {e}");
3358
3359 break;
3361 }
3362 }
3363 }
3364 }
3365 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3366 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3367 failed_count += 1;
3368 if !force {
3369 break;
3370 }
3371 }
3372 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3373 println!(" ❌ Failed: {error}");
3374 failed_count += 1;
3375 if !force {
3376 break;
3377 }
3378 }
3379 Err(e) => {
3380 println!(" ❌");
3381 eprintln!("Failed to land PR #{pr_id}: {e}");
3382 failed_count += 1;
3383
3384 if !force {
3385 break;
3386 }
3387 }
3388 }
3389 }
3390
3391 println!("\n🎯 Landing Summary:");
3393 println!(" ✅ Successfully landed: {landed_count}");
3394 if failed_count > 0 {
3395 println!(" ❌ Failed to land: {failed_count}");
3396 }
3397
3398 if landed_count > 0 {
3399 Output::success(" Landing operation completed!");
3400 } else {
3401 println!("❌ No PRs were successfully landed");
3402 }
3403
3404 Ok(())
3405}
3406
3407async fn auto_land_stack(
3409 force: bool,
3410 dry_run: bool,
3411 wait_for_builds: bool,
3412 strategy: Option<MergeStrategyArg>,
3413 build_timeout: u64,
3414) -> Result<()> {
3415 land_stack(
3417 None,
3418 force,
3419 dry_run,
3420 true, wait_for_builds,
3422 strategy,
3423 build_timeout,
3424 )
3425 .await
3426}
3427
3428async fn continue_land() -> Result<()> {
3429 let current_dir = env::current_dir()
3430 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3431
3432 let repo_root = find_repository_root(¤t_dir)
3433 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3434
3435 let stack_manager = StackManager::new(&repo_root)?;
3436 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3437 let options = crate::stack::RebaseOptions::default();
3438 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3439
3440 if !rebase_manager.is_rebase_in_progress() {
3441 Output::info(" No rebase in progress");
3442 return Ok(());
3443 }
3444
3445 println!(" Continuing land operation...");
3446 match rebase_manager.continue_rebase() {
3447 Ok(_) => {
3448 Output::success(" Land operation continued successfully");
3449 println!(" Check 'ca stack land-status' for current state");
3450 }
3451 Err(e) => {
3452 warn!("❌ Failed to continue land operation: {}", e);
3453 Output::tip(" You may need to resolve conflicts first:");
3454 println!(" 1. Edit conflicted files");
3455 println!(" 2. Stage resolved files with 'git add'");
3456 println!(" 3. Run 'ca stack continue-land' again");
3457 }
3458 }
3459
3460 Ok(())
3461}
3462
3463async fn abort_land() -> 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 let options = crate::stack::RebaseOptions::default();
3473 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3474
3475 if !rebase_manager.is_rebase_in_progress() {
3476 Output::info(" No rebase in progress");
3477 return Ok(());
3478 }
3479
3480 println!("⚠️ Aborting land operation...");
3481 match rebase_manager.abort_rebase() {
3482 Ok(_) => {
3483 Output::success(" Land operation aborted successfully");
3484 println!(" Repository restored to pre-land state");
3485 }
3486 Err(e) => {
3487 warn!("❌ Failed to abort land operation: {}", e);
3488 println!("⚠️ You may need to manually clean up the repository state");
3489 }
3490 }
3491
3492 Ok(())
3493}
3494
3495async fn land_status() -> Result<()> {
3496 let current_dir = env::current_dir()
3497 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3498
3499 let repo_root = find_repository_root(¤t_dir)
3500 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3501
3502 let stack_manager = StackManager::new(&repo_root)?;
3503 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3504
3505 println!("Land Status");
3506
3507 let git_dir = repo_root.join(".git");
3509 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3510 || git_dir.join("rebase-merge").exists()
3511 || git_dir.join("rebase-apply").exists();
3512
3513 if land_in_progress {
3514 println!(" Status: 🔄 Land operation in progress");
3515 println!(
3516 "
3517📝 Actions available:"
3518 );
3519 println!(" - 'ca stack continue-land' to continue");
3520 println!(" - 'ca stack abort-land' to abort");
3521 println!(" - 'git status' to see conflicted files");
3522
3523 match git_repo.get_status() {
3525 Ok(statuses) => {
3526 let mut conflicts = Vec::new();
3527 for status in statuses.iter() {
3528 if status.status().contains(git2::Status::CONFLICTED) {
3529 if let Some(path) = status.path() {
3530 conflicts.push(path.to_string());
3531 }
3532 }
3533 }
3534
3535 if !conflicts.is_empty() {
3536 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3537 for conflict in conflicts {
3538 println!(" - {conflict}");
3539 }
3540 println!(
3541 "
3542💡 To resolve conflicts:"
3543 );
3544 println!(" 1. Edit the conflicted files");
3545 println!(" 2. Stage resolved files: git add <file>");
3546 println!(" 3. Continue: ca stack continue-land");
3547 }
3548 }
3549 Err(e) => {
3550 warn!("Failed to get git status: {}", e);
3551 }
3552 }
3553 } else {
3554 println!(" Status: ✅ No land operation in progress");
3555
3556 if let Some(active_stack) = stack_manager.get_active_stack() {
3558 println!(" Active stack: {}", active_stack.name);
3559 println!(" Entries: {}", active_stack.entries.len());
3560 println!(" Base branch: {}", active_stack.base_branch);
3561 }
3562 }
3563
3564 Ok(())
3565}
3566
3567async fn repair_stack_data() -> Result<()> {
3568 let current_dir = env::current_dir()
3569 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3570
3571 let repo_root = find_repository_root(¤t_dir)
3572 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3573
3574 let mut stack_manager = StackManager::new(&repo_root)?;
3575
3576 println!("🔧 Repairing stack data consistency...");
3577
3578 stack_manager.repair_all_stacks()?;
3579
3580 Output::success(" Stack data consistency repaired successfully!");
3581 Output::tip(" Run 'ca stack --mergeable' to see updated status");
3582
3583 Ok(())
3584}
3585
3586async fn cleanup_branches(
3588 dry_run: bool,
3589 force: bool,
3590 include_stale: bool,
3591 stale_days: u32,
3592 cleanup_remote: bool,
3593 include_non_stack: bool,
3594 verbose: bool,
3595) -> Result<()> {
3596 let current_dir = env::current_dir()
3597 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3598
3599 let repo_root = find_repository_root(¤t_dir)
3600 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3601
3602 let stack_manager = StackManager::new(&repo_root)?;
3603 let git_repo = GitRepository::open(&repo_root)?;
3604
3605 let result = perform_cleanup(
3606 &stack_manager,
3607 &git_repo,
3608 dry_run,
3609 force,
3610 include_stale,
3611 stale_days,
3612 cleanup_remote,
3613 include_non_stack,
3614 verbose,
3615 )
3616 .await?;
3617
3618 if result.total_candidates == 0 {
3620 Output::success("No branches found that need cleanup");
3621 return Ok(());
3622 }
3623
3624 Output::section("Cleanup Results");
3625
3626 if dry_run {
3627 Output::sub_item(format!(
3628 "Found {} branches that would be cleaned up",
3629 result.total_candidates
3630 ));
3631 } else {
3632 if !result.cleaned_branches.is_empty() {
3633 Output::success(format!(
3634 "Successfully cleaned up {} branches",
3635 result.cleaned_branches.len()
3636 ));
3637 for branch in &result.cleaned_branches {
3638 Output::sub_item(format!("🗑️ Deleted: {branch}"));
3639 }
3640 }
3641
3642 if !result.skipped_branches.is_empty() {
3643 Output::sub_item(format!(
3644 "Skipped {} branches",
3645 result.skipped_branches.len()
3646 ));
3647 if verbose {
3648 for (branch, reason) in &result.skipped_branches {
3649 Output::sub_item(format!("⏭️ {branch}: {reason}"));
3650 }
3651 }
3652 }
3653
3654 if !result.failed_branches.is_empty() {
3655 Output::warning(format!(
3656 "Failed to clean up {} branches",
3657 result.failed_branches.len()
3658 ));
3659 for (branch, error) in &result.failed_branches {
3660 Output::sub_item(format!("❌ {branch}: {error}"));
3661 }
3662 }
3663 }
3664
3665 Ok(())
3666}
3667
3668#[allow(clippy::too_many_arguments)]
3670async fn perform_cleanup(
3671 stack_manager: &StackManager,
3672 git_repo: &GitRepository,
3673 dry_run: bool,
3674 force: bool,
3675 include_stale: bool,
3676 stale_days: u32,
3677 cleanup_remote: bool,
3678 include_non_stack: bool,
3679 verbose: bool,
3680) -> Result<CleanupResult> {
3681 let options = CleanupOptions {
3682 dry_run,
3683 force,
3684 include_stale,
3685 cleanup_remote,
3686 stale_threshold_days: stale_days,
3687 cleanup_non_stack: include_non_stack,
3688 };
3689
3690 let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
3691 let git_repo_copy = GitRepository::open(git_repo.path())?;
3692 let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
3693
3694 let candidates = cleanup_manager.find_cleanup_candidates()?;
3696
3697 if candidates.is_empty() {
3698 return Ok(CleanupResult {
3699 cleaned_branches: Vec::new(),
3700 failed_branches: Vec::new(),
3701 skipped_branches: Vec::new(),
3702 total_candidates: 0,
3703 });
3704 }
3705
3706 if verbose || dry_run {
3708 Output::section("Cleanup Candidates");
3709 for candidate in &candidates {
3710 let reason_icon = match candidate.reason {
3711 crate::stack::CleanupReason::FullyMerged => "🔀",
3712 crate::stack::CleanupReason::StackEntryMerged => "✅",
3713 crate::stack::CleanupReason::Stale => "⏰",
3714 crate::stack::CleanupReason::Orphaned => "👻",
3715 };
3716
3717 Output::sub_item(format!(
3718 "{} {} - {} ({})",
3719 reason_icon,
3720 candidate.branch_name,
3721 candidate.reason_to_string(),
3722 candidate.safety_info
3723 ));
3724 }
3725 }
3726
3727 if !force && !dry_run && !candidates.is_empty() {
3729 Output::warning(format!("About to delete {} branches", candidates.len()));
3730
3731 let preview_count = 5.min(candidates.len());
3733 for candidate in candidates.iter().take(preview_count) {
3734 println!(" • {}", candidate.branch_name);
3735 }
3736 if candidates.len() > preview_count {
3737 println!(" ... and {} more", candidates.len() - preview_count);
3738 }
3739 println!(); let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3743 .with_prompt("Continue with branch cleanup?")
3744 .default(false)
3745 .interact()
3746 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3747
3748 if !should_continue {
3749 Output::sub_item("Cleanup cancelled");
3750 return Ok(CleanupResult {
3751 cleaned_branches: Vec::new(),
3752 failed_branches: Vec::new(),
3753 skipped_branches: Vec::new(),
3754 total_candidates: candidates.len(),
3755 });
3756 }
3757 }
3758
3759 cleanup_manager.perform_cleanup(&candidates)
3761}
3762
3763async fn perform_simple_cleanup(
3765 stack_manager: &StackManager,
3766 git_repo: &GitRepository,
3767 dry_run: bool,
3768) -> Result<CleanupResult> {
3769 perform_cleanup(
3770 stack_manager,
3771 git_repo,
3772 dry_run,
3773 false, false, 30, false, false, false, )
3780 .await
3781}
3782
3783async fn analyze_commits_for_safeguards(
3785 commits_to_push: &[String],
3786 repo: &GitRepository,
3787 dry_run: bool,
3788) -> Result<()> {
3789 const LARGE_COMMIT_THRESHOLD: usize = 10;
3790 const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3791
3792 if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3794 println!(
3795 "⚠️ Warning: About to push {} commits to stack",
3796 commits_to_push.len()
3797 );
3798 println!(" This may indicate a merge commit issue or unexpected commit range.");
3799 println!(" Large commit counts often result from merging instead of rebasing.");
3800
3801 if !dry_run && !confirm_large_push(commits_to_push.len())? {
3802 return Err(CascadeError::config("Push cancelled by user"));
3803 }
3804 }
3805
3806 let commit_objects: Result<Vec<_>> = commits_to_push
3808 .iter()
3809 .map(|hash| repo.get_commit(hash))
3810 .collect();
3811 let commit_objects = commit_objects?;
3812
3813 let merge_commits: Vec<_> = commit_objects
3815 .iter()
3816 .filter(|c| c.parent_count() > 1)
3817 .collect();
3818
3819 if !merge_commits.is_empty() {
3820 println!(
3821 "⚠️ Warning: {} merge commits detected in push",
3822 merge_commits.len()
3823 );
3824 println!(" This often indicates you merged instead of rebased.");
3825 println!(" Consider using 'ca sync' to rebase on the base branch.");
3826 println!(" Merge commits in stacks can cause confusion and duplicate work.");
3827 }
3828
3829 if commit_objects.len() > 1 {
3831 let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
3832 let newest_commit_time = commit_objects.last().unwrap().time().seconds();
3833 let time_span = newest_commit_time - oldest_commit_time;
3834
3835 if time_span > WEEK_IN_SECONDS {
3836 let days = time_span / (24 * 3600);
3837 println!("⚠️ Warning: Commits span {days} days");
3838 println!(" This may indicate merged history rather than new work.");
3839 println!(" Recent work should typically span hours or days, not weeks.");
3840 }
3841 }
3842
3843 if commits_to_push.len() > 5 {
3845 Output::tip(" Tip: If you only want recent commits, use:");
3846 println!(
3847 " ca push --since HEAD~{} # pushes last {} commits",
3848 std::cmp::min(commits_to_push.len(), 5),
3849 std::cmp::min(commits_to_push.len(), 5)
3850 );
3851 println!(" ca push --commits <hash1>,<hash2> # pushes specific commits");
3852 println!(" ca push --dry-run # preview what would be pushed");
3853 }
3854
3855 if dry_run {
3857 println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
3858 for (i, (commit_hash, commit_obj)) in commits_to_push
3859 .iter()
3860 .zip(commit_objects.iter())
3861 .enumerate()
3862 {
3863 let summary = commit_obj.summary().unwrap_or("(no message)");
3864 let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
3865 println!(" {}: {} ({})", i + 1, summary, short_hash);
3866 }
3867 Output::tip(" Run without --dry-run to actually push these commits.");
3868 }
3869
3870 Ok(())
3871}
3872
3873fn confirm_large_push(count: usize) -> Result<bool> {
3875 let should_continue = Confirm::with_theme(&ColorfulTheme::default())
3877 .with_prompt(format!("Continue pushing {count} commits?"))
3878 .default(false)
3879 .interact()
3880 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
3881
3882 Ok(should_continue)
3883}
3884
3885#[cfg(test)]
3886mod tests {
3887 use super::*;
3888 use std::process::Command;
3889 use tempfile::TempDir;
3890
3891 fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
3892 let temp_dir = TempDir::new()
3893 .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
3894 let repo_path = temp_dir.path().to_path_buf();
3895
3896 let output = Command::new("git")
3898 .args(["init"])
3899 .current_dir(&repo_path)
3900 .output()
3901 .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
3902 if !output.status.success() {
3903 return Err(CascadeError::config("Git init failed".to_string()));
3904 }
3905
3906 let output = Command::new("git")
3907 .args(["config", "user.name", "Test User"])
3908 .current_dir(&repo_path)
3909 .output()
3910 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3911 if !output.status.success() {
3912 return Err(CascadeError::config(
3913 "Git config user.name failed".to_string(),
3914 ));
3915 }
3916
3917 let output = Command::new("git")
3918 .args(["config", "user.email", "test@example.com"])
3919 .current_dir(&repo_path)
3920 .output()
3921 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3922 if !output.status.success() {
3923 return Err(CascadeError::config(
3924 "Git config user.email failed".to_string(),
3925 ));
3926 }
3927
3928 std::fs::write(repo_path.join("README.md"), "# Test")
3930 .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
3931 let output = Command::new("git")
3932 .args(["add", "."])
3933 .current_dir(&repo_path)
3934 .output()
3935 .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
3936 if !output.status.success() {
3937 return Err(CascadeError::config("Git add failed".to_string()));
3938 }
3939
3940 let output = Command::new("git")
3941 .args(["commit", "-m", "Initial commit"])
3942 .current_dir(&repo_path)
3943 .output()
3944 .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
3945 if !output.status.success() {
3946 return Err(CascadeError::config("Git commit failed".to_string()));
3947 }
3948
3949 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
3951
3952 Ok((temp_dir, repo_path))
3953 }
3954
3955 #[tokio::test]
3956 async fn test_create_stack() {
3957 let (temp_dir, repo_path) = match create_test_repo() {
3958 Ok(repo) => repo,
3959 Err(_) => {
3960 println!("Skipping test due to git environment setup failure");
3961 return;
3962 }
3963 };
3964 let _ = &temp_dir;
3966
3967 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3971 match env::set_current_dir(&repo_path) {
3972 Ok(_) => {
3973 let result = create_stack(
3974 "test-stack".to_string(),
3975 None, Some("Test description".to_string()),
3977 )
3978 .await;
3979
3980 if let Ok(orig) = original_dir {
3982 let _ = env::set_current_dir(orig);
3983 }
3984
3985 assert!(
3986 result.is_ok(),
3987 "Stack creation should succeed in initialized repository"
3988 );
3989 }
3990 Err(_) => {
3991 println!("Skipping test due to directory access restrictions");
3993 }
3994 }
3995 }
3996
3997 #[tokio::test]
3998 async fn test_list_empty_stacks() {
3999 let (temp_dir, repo_path) = match create_test_repo() {
4000 Ok(repo) => repo,
4001 Err(_) => {
4002 println!("Skipping test due to git environment setup failure");
4003 return;
4004 }
4005 };
4006 let _ = &temp_dir;
4008
4009 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4013 match env::set_current_dir(&repo_path) {
4014 Ok(_) => {
4015 let result = list_stacks(false, false, None).await;
4016
4017 if let Ok(orig) = original_dir {
4019 let _ = env::set_current_dir(orig);
4020 }
4021
4022 assert!(
4023 result.is_ok(),
4024 "Listing stacks should succeed in initialized repository"
4025 );
4026 }
4027 Err(_) => {
4028 println!("Skipping test due to directory access restrictions");
4030 }
4031 }
4032 }
4033
4034 #[test]
4037 fn test_extract_feature_from_wip_basic() {
4038 let messages = vec![
4039 "WIP: add authentication".to_string(),
4040 "WIP: implement login flow".to_string(),
4041 ];
4042
4043 let result = extract_feature_from_wip(&messages);
4044 assert_eq!(result, "Add authentication");
4045 }
4046
4047 #[test]
4048 fn test_extract_feature_from_wip_capitalize() {
4049 let messages = vec!["WIP: fix user validation bug".to_string()];
4050
4051 let result = extract_feature_from_wip(&messages);
4052 assert_eq!(result, "Fix user validation bug");
4053 }
4054
4055 #[test]
4056 fn test_extract_feature_from_wip_fallback() {
4057 let messages = vec![
4058 "WIP user interface changes".to_string(),
4059 "wip: css styling".to_string(),
4060 ];
4061
4062 let result = extract_feature_from_wip(&messages);
4063 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
4065 }
4066
4067 #[test]
4068 fn test_extract_feature_from_wip_empty() {
4069 let messages = vec![];
4070
4071 let result = extract_feature_from_wip(&messages);
4072 assert_eq!(result, "Squashed 0 commits");
4073 }
4074
4075 #[test]
4076 fn test_extract_feature_from_wip_short_message() {
4077 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
4080 assert!(result.starts_with("Implement") || result.contains("Squashed"));
4081 }
4082
4083 #[test]
4086 fn test_squash_message_final_strategy() {
4087 let messages = [
4091 "Final: implement user authentication system".to_string(),
4092 "WIP: add tests".to_string(),
4093 "WIP: fix validation".to_string(),
4094 ];
4095
4096 assert!(messages[0].starts_with("Final:"));
4098
4099 let extracted = messages[0].trim_start_matches("Final:").trim();
4101 assert_eq!(extracted, "implement user authentication system");
4102 }
4103
4104 #[test]
4105 fn test_squash_message_wip_detection() {
4106 let messages = [
4107 "WIP: start feature".to_string(),
4108 "WIP: continue work".to_string(),
4109 "WIP: almost done".to_string(),
4110 "Regular commit message".to_string(),
4111 ];
4112
4113 let wip_count = messages
4114 .iter()
4115 .filter(|m| {
4116 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
4117 })
4118 .count();
4119
4120 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
4125 .iter()
4126 .filter(|m| {
4127 !m.to_lowercase().starts_with("wip")
4128 && !m.to_lowercase().contains("work in progress")
4129 })
4130 .collect();
4131
4132 assert_eq!(non_wip.len(), 1);
4133 assert_eq!(non_wip[0], "Regular commit message");
4134 }
4135
4136 #[test]
4137 fn test_squash_message_all_wip() {
4138 let messages = vec![
4139 "WIP: add feature A".to_string(),
4140 "WIP: add feature B".to_string(),
4141 "WIP: finish implementation".to_string(),
4142 ];
4143
4144 let result = extract_feature_from_wip(&messages);
4145 assert_eq!(result, "Add feature A");
4147 }
4148
4149 #[test]
4150 fn test_squash_message_edge_cases() {
4151 let empty_messages: Vec<String> = vec![];
4153 let result = extract_feature_from_wip(&empty_messages);
4154 assert_eq!(result, "Squashed 0 commits");
4155
4156 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
4158 let result = extract_feature_from_wip(&whitespace_messages);
4159 assert!(result.contains("Squashed") || result.contains("Implement"));
4160
4161 let mixed_case = vec!["wip: Add Feature".to_string()];
4163 let result = extract_feature_from_wip(&mixed_case);
4164 assert_eq!(result, "Add Feature");
4165 }
4166
4167 #[tokio::test]
4170 async fn test_auto_land_wrapper() {
4171 let (temp_dir, repo_path) = match create_test_repo() {
4173 Ok(repo) => repo,
4174 Err(_) => {
4175 println!("Skipping test due to git environment setup failure");
4176 return;
4177 }
4178 };
4179 let _ = &temp_dir;
4181
4182 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
4184 .expect("Failed to initialize Cascade in test repo");
4185
4186 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4187 match env::set_current_dir(&repo_path) {
4188 Ok(_) => {
4189 let result = create_stack(
4191 "test-stack".to_string(),
4192 None,
4193 Some("Test stack for auto-land".to_string()),
4194 )
4195 .await;
4196
4197 if let Ok(orig) = original_dir {
4198 let _ = env::set_current_dir(orig);
4199 }
4200
4201 assert!(
4204 result.is_ok(),
4205 "Stack creation should succeed in initialized repository"
4206 );
4207 }
4208 Err(_) => {
4209 println!("Skipping test due to directory access restrictions");
4210 }
4211 }
4212 }
4213
4214 #[test]
4215 fn test_auto_land_action_enum() {
4216 use crate::cli::commands::stack::StackAction;
4218
4219 let _action = StackAction::AutoLand {
4221 force: false,
4222 dry_run: true,
4223 wait_for_builds: true,
4224 strategy: Some(MergeStrategyArg::Squash),
4225 build_timeout: 1800,
4226 };
4227
4228 }
4230
4231 #[test]
4232 fn test_merge_strategy_conversion() {
4233 let squash_strategy = MergeStrategyArg::Squash;
4235 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
4236
4237 match merge_strategy {
4238 crate::bitbucket::pull_request::MergeStrategy::Squash => {
4239 }
4241 _ => unreachable!("SquashStrategyArg only has Squash variant"),
4242 }
4243
4244 let merge_strategy = MergeStrategyArg::Merge;
4245 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
4246
4247 match converted {
4248 crate::bitbucket::pull_request::MergeStrategy::Merge => {
4249 }
4251 _ => unreachable!("MergeStrategyArg::Merge maps to MergeStrategy::Merge"),
4252 }
4253 }
4254
4255 #[test]
4256 fn test_auto_merge_conditions_structure() {
4257 use std::time::Duration;
4259
4260 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
4261 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
4262 wait_for_builds: true,
4263 build_timeout: Duration::from_secs(1800),
4264 allowed_authors: None,
4265 };
4266
4267 assert!(conditions.wait_for_builds);
4269 assert_eq!(conditions.build_timeout.as_secs(), 1800);
4270 assert!(conditions.allowed_authors.is_none());
4271 assert!(matches!(
4272 conditions.merge_strategy,
4273 crate::bitbucket::pull_request::MergeStrategy::Squash
4274 ));
4275 }
4276
4277 #[test]
4278 fn test_polling_constants() {
4279 use std::time::Duration;
4281
4282 let expected_polling_interval = Duration::from_secs(30);
4284
4285 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
4290
4291 #[test]
4292 fn test_build_timeout_defaults() {
4293 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
4296 let timeout_value = 1800u64;
4298 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
4301
4302 #[test]
4303 fn test_scattered_commit_detection() {
4304 use std::collections::HashSet;
4305
4306 let mut source_branches = HashSet::new();
4308 source_branches.insert("feature-branch-1".to_string());
4309 source_branches.insert("feature-branch-2".to_string());
4310 source_branches.insert("feature-branch-3".to_string());
4311
4312 let single_branch = HashSet::from(["main".to_string()]);
4314 assert_eq!(single_branch.len(), 1);
4315
4316 assert!(source_branches.len() > 1);
4318 assert_eq!(source_branches.len(), 3);
4319
4320 assert!(source_branches.contains("feature-branch-1"));
4322 assert!(source_branches.contains("feature-branch-2"));
4323 assert!(source_branches.contains("feature-branch-3"));
4324 }
4325
4326 #[test]
4327 fn test_source_branch_tracking() {
4328 let branch_a = "feature-work";
4332 let branch_b = "feature-work";
4333 assert_eq!(branch_a, branch_b);
4334
4335 let branch_1 = "feature-ui";
4337 let branch_2 = "feature-api";
4338 assert_ne!(branch_1, branch_2);
4339
4340 assert!(branch_1.starts_with("feature-"));
4342 assert!(branch_2.starts_with("feature-"));
4343 }
4344
4345 #[tokio::test]
4348 async fn test_push_default_behavior() {
4349 let (temp_dir, repo_path) = match create_test_repo() {
4351 Ok(repo) => repo,
4352 Err(_) => {
4353 println!("Skipping test due to git environment setup failure");
4354 return;
4355 }
4356 };
4357 let _ = &temp_dir;
4359
4360 if !repo_path.exists() {
4362 println!("Skipping test due to temporary directory creation issue");
4363 return;
4364 }
4365
4366 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4368
4369 match env::set_current_dir(&repo_path) {
4370 Ok(_) => {
4371 let result = push_to_stack(
4373 None, None, None, None, None, None, None, false, false, false, )
4384 .await;
4385
4386 if let Ok(orig) = original_dir {
4388 let _ = env::set_current_dir(orig);
4389 }
4390
4391 match &result {
4393 Err(e) => {
4394 let error_msg = e.to_string();
4395 assert!(
4397 error_msg.contains("No active stack")
4398 || error_msg.contains("config")
4399 || error_msg.contains("current directory")
4400 || error_msg.contains("Not a git repository")
4401 || error_msg.contains("could not find repository"),
4402 "Expected 'No active stack' or repository error, got: {error_msg}"
4403 );
4404 }
4405 Ok(_) => {
4406 println!(
4408 "Push succeeded unexpectedly - test environment may have active stack"
4409 );
4410 }
4411 }
4412 }
4413 Err(_) => {
4414 println!("Skipping test due to directory access restrictions");
4416 }
4417 }
4418
4419 let push_action = StackAction::Push {
4421 branch: None,
4422 message: None,
4423 commit: None,
4424 since: None,
4425 commits: None,
4426 squash: None,
4427 squash_since: None,
4428 auto_branch: false,
4429 allow_base_branch: false,
4430 dry_run: false,
4431 };
4432
4433 assert!(matches!(
4434 push_action,
4435 StackAction::Push {
4436 branch: None,
4437 message: None,
4438 commit: None,
4439 since: None,
4440 commits: None,
4441 squash: None,
4442 squash_since: None,
4443 auto_branch: false,
4444 allow_base_branch: false,
4445 dry_run: false
4446 }
4447 ));
4448 }
4449
4450 #[tokio::test]
4451 async fn test_submit_default_behavior() {
4452 let (temp_dir, repo_path) = match create_test_repo() {
4454 Ok(repo) => repo,
4455 Err(_) => {
4456 println!("Skipping test due to git environment setup failure");
4457 return;
4458 }
4459 };
4460 let _ = &temp_dir;
4462
4463 if !repo_path.exists() {
4465 println!("Skipping test due to temporary directory creation issue");
4466 return;
4467 }
4468
4469 let original_dir = match env::current_dir() {
4471 Ok(dir) => dir,
4472 Err(_) => {
4473 println!("Skipping test due to current directory access restrictions");
4474 return;
4475 }
4476 };
4477
4478 match env::set_current_dir(&repo_path) {
4479 Ok(_) => {
4480 let result = submit_entry(
4482 None, None, None, None, false, true, )
4489 .await;
4490
4491 let _ = env::set_current_dir(original_dir);
4493
4494 match &result {
4496 Err(e) => {
4497 let error_msg = e.to_string();
4498 assert!(
4500 error_msg.contains("No active stack")
4501 || error_msg.contains("config")
4502 || error_msg.contains("current directory")
4503 || error_msg.contains("Not a git repository")
4504 || error_msg.contains("could not find repository"),
4505 "Expected 'No active stack' or repository error, got: {error_msg}"
4506 );
4507 }
4508 Ok(_) => {
4509 println!("Submit succeeded unexpectedly - test environment may have active stack");
4511 }
4512 }
4513 }
4514 Err(_) => {
4515 println!("Skipping test due to directory access restrictions");
4517 }
4518 }
4519
4520 let submit_action = StackAction::Submit {
4522 entry: None,
4523 title: None,
4524 description: None,
4525 range: None,
4526 draft: true, open: true,
4528 };
4529
4530 assert!(matches!(
4531 submit_action,
4532 StackAction::Submit {
4533 entry: None,
4534 title: None,
4535 description: None,
4536 range: None,
4537 draft: true, open: true
4539 }
4540 ));
4541 }
4542
4543 #[test]
4544 fn test_targeting_options_still_work() {
4545 let commits = "abc123,def456,ghi789";
4549 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4550 assert_eq!(parsed.len(), 3);
4551 assert_eq!(parsed[0], "abc123");
4552 assert_eq!(parsed[1], "def456");
4553 assert_eq!(parsed[2], "ghi789");
4554
4555 let range = "1-3";
4557 assert!(range.contains('-'));
4558 let parts: Vec<&str> = range.split('-').collect();
4559 assert_eq!(parts.len(), 2);
4560
4561 let since_ref = "HEAD~3";
4563 assert!(since_ref.starts_with("HEAD"));
4564 assert!(since_ref.contains('~'));
4565 }
4566
4567 #[test]
4568 fn test_command_flow_logic() {
4569 assert!(matches!(
4571 StackAction::Push {
4572 branch: None,
4573 message: None,
4574 commit: None,
4575 since: None,
4576 commits: None,
4577 squash: None,
4578 squash_since: None,
4579 auto_branch: false,
4580 allow_base_branch: false,
4581 dry_run: false
4582 },
4583 StackAction::Push { .. }
4584 ));
4585
4586 assert!(matches!(
4587 StackAction::Submit {
4588 entry: None,
4589 title: None,
4590 description: None,
4591 range: None,
4592 draft: false,
4593 open: true
4594 },
4595 StackAction::Submit { .. }
4596 ));
4597 }
4598
4599 #[tokio::test]
4600 async fn test_deactivate_command_structure() {
4601 let deactivate_action = StackAction::Deactivate { force: false };
4603
4604 assert!(matches!(
4606 deactivate_action,
4607 StackAction::Deactivate { force: false }
4608 ));
4609
4610 let force_deactivate = StackAction::Deactivate { force: true };
4612 assert!(matches!(
4613 force_deactivate,
4614 StackAction::Deactivate { force: true }
4615 ));
4616 }
4617}