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)]
147 draft: bool,
148 #[arg(long, default_value_t = true)]
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_only: 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 mut stacks = manager.list_stacks();
623
624 if active_only {
625 stacks.retain(|(_, _, _, _, active_marker)| active_marker.is_some());
626 }
627
628 if let Some(ref format) = format {
629 match format.as_str() {
630 "json" => {
631 let mut json_stacks = Vec::new();
632
633 for (stack_id, name, status, entry_count, active_marker) in &stacks {
634 let (entries_json, working_branch, base_branch) =
635 if let Some(stack_obj) = manager.get_stack(stack_id) {
636 let entries_json = stack_obj
637 .entries
638 .iter()
639 .enumerate()
640 .map(|(idx, entry)| {
641 serde_json::json!({
642 "position": idx + 1,
643 "entry_id": entry.id.to_string(),
644 "branch_name": entry.branch.clone(),
645 "commit_hash": entry.commit_hash.clone(),
646 "short_hash": entry.short_hash(),
647 "is_submitted": entry.is_submitted,
648 "is_merged": entry.is_merged,
649 "pull_request_id": entry.pull_request_id.clone(),
650 })
651 })
652 .collect::<Vec<_>>();
653
654 (
655 entries_json,
656 stack_obj.working_branch.clone(),
657 Some(stack_obj.base_branch.clone()),
658 )
659 } else {
660 (Vec::new(), None, None)
661 };
662
663 let status_label = format!("{status:?}");
664
665 json_stacks.push(serde_json::json!({
666 "id": stack_id.to_string(),
667 "name": name,
668 "status": status_label,
669 "entry_count": entry_count,
670 "is_active": active_marker.is_some(),
671 "base_branch": base_branch,
672 "working_branch": working_branch,
673 "entries": entries_json,
674 }));
675 }
676
677 let json_output = serde_json::json!({ "stacks": json_stacks });
678 let serialized = serde_json::to_string_pretty(&json_output)?;
679 println!("{serialized}");
680 return Ok(());
681 }
682 "name" => {
683 for (_, name, _, _, _) in &stacks {
684 println!("{name}");
685 }
686 return Ok(());
687 }
688 "id" => {
689 for (stack_id, _, _, _, _) in &stacks {
690 println!("{}", stack_id);
691 }
692 return Ok(());
693 }
694 "status" => {
695 for (_, name, status, _, active_marker) in &stacks {
696 let status_label = format!("{status:?}");
697 let marker = if active_marker.is_some() {
698 " (active)"
699 } else {
700 ""
701 };
702 println!("{name}: {status_label}{marker}");
703 }
704 return Ok(());
705 }
706 other => {
707 return Err(CascadeError::config(format!(
708 "Unsupported format '{}'. Supported formats: name, id, status, json",
709 other
710 )));
711 }
712 }
713 }
714
715 if stacks.is_empty() {
716 if active_only {
717 Output::info("No active stack. Activate one with 'ca stack switch <name>'");
718 } else {
719 Output::info("No stacks found. Create one with: ca stack create <name>");
720 }
721 return Ok(());
722 }
723
724 println!("Stacks:");
725 for (stack_id, name, status, entry_count, active_marker) in stacks {
726 let status_icon = match status {
727 StackStatus::Clean => "✓",
728 StackStatus::Dirty => "~",
729 StackStatus::OutOfSync => "!",
730 StackStatus::Conflicted => "✗",
731 StackStatus::Rebasing => "↔",
732 StackStatus::NeedsSync => "~",
733 StackStatus::Corrupted => "✗",
734 };
735
736 let active_indicator = if active_marker.is_some() {
737 " (active)"
738 } else {
739 ""
740 };
741
742 let stack = manager.get_stack(&stack_id);
744
745 if verbose {
746 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
747 println!(" ID: {stack_id}");
748 if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
749 println!(" Base: {}", stack_meta.base_branch);
750 if let Some(desc) = &stack_meta.description {
751 println!(" Description: {desc}");
752 }
753 println!(
754 " Commits: {} total, {} submitted",
755 stack_meta.total_commits, stack_meta.submitted_commits
756 );
757 if stack_meta.has_conflicts {
758 Output::warning(" Has conflicts");
759 }
760 }
761
762 if let Some(stack_obj) = stack {
764 if !stack_obj.entries.is_empty() {
765 println!(" Branches:");
766 for (i, entry) in stack_obj.entries.iter().enumerate() {
767 let entry_num = i + 1;
768 let submitted_indicator = if entry.is_submitted {
769 "[submitted]"
770 } else {
771 ""
772 };
773 let branch_name = &entry.branch;
774 let short_message = if entry.message.len() > 40 {
775 format!("{}...", &entry.message[..37])
776 } else {
777 entry.message.clone()
778 };
779 println!(" {entry_num}. {submitted_indicator} {branch_name} - {short_message}");
780 }
781 }
782 }
783 println!();
784 } else {
785 let branch_info = if let Some(stack_obj) = stack {
787 if stack_obj.entries.is_empty() {
788 String::new()
789 } else if stack_obj.entries.len() == 1 {
790 format!(" → {}", stack_obj.entries[0].branch)
791 } else {
792 let first_branch = &stack_obj.entries[0].branch;
793 let last_branch = &stack_obj.entries.last().unwrap().branch;
794 format!(" → {first_branch} … {last_branch}")
795 }
796 } else {
797 String::new()
798 };
799
800 println!(" {status_icon} {name} [{entry_count}]{branch_info}{active_indicator}");
801 }
802 }
803
804 if !verbose {
805 println!("\nUse --verbose for more details");
806 }
807
808 Ok(())
809}
810
811async fn switch_stack(name: String) -> Result<()> {
812 let current_dir = env::current_dir()
813 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
814
815 let repo_root = find_repository_root(¤t_dir)
816 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
817
818 let mut manager = StackManager::new(&repo_root)?;
819 let repo = GitRepository::open(&repo_root)?;
820
821 let stack = manager
823 .get_stack_by_name(&name)
824 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
825
826 if let Some(working_branch) = &stack.working_branch {
828 let current_branch = repo.get_current_branch().ok();
830
831 if current_branch.as_ref() != Some(working_branch) {
832 Output::progress(format!(
833 "Switching to stack working branch: {working_branch}"
834 ));
835
836 if repo.branch_exists(working_branch) {
838 match repo.checkout_branch(working_branch) {
839 Ok(_) => {
840 Output::success(format!("Checked out branch: {working_branch}"));
841 }
842 Err(e) => {
843 Output::warning(format!("Failed to checkout '{working_branch}': {e}"));
844 Output::sub_item("Stack activated but stayed on current branch");
845 Output::sub_item(format!(
846 "You can manually checkout with: git checkout {working_branch}"
847 ));
848 }
849 }
850 } else {
851 Output::warning(format!(
852 "Stack working branch '{working_branch}' doesn't exist locally"
853 ));
854 Output::sub_item("Stack activated but stayed on current branch");
855 Output::sub_item(format!(
856 "You may need to fetch from remote: git fetch origin {working_branch}"
857 ));
858 }
859 } else {
860 Output::success(format!("Already on stack working branch: {working_branch}"));
861 }
862 } else {
863 Output::warning(format!("Stack '{name}' has no working branch set"));
865 Output::sub_item(
866 "This typically happens when a stack was created while on the base branch",
867 );
868
869 Output::tip("To start working on this stack:");
870 Output::bullet(format!("Create a feature branch: git checkout -b {name}"));
871 Output::bullet("The stack will automatically track this as its working branch");
872 Output::bullet("Then use 'ca push' to add commits to the stack");
873
874 Output::sub_item(format!("Base branch: {}", stack.base_branch));
875 }
876
877 manager.set_active_stack_by_name(&name)?;
879 Output::success(format!("Switched to stack '{name}'"));
880
881 Ok(())
882}
883
884async fn deactivate_stack(force: bool) -> Result<()> {
885 let current_dir = env::current_dir()
886 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
887
888 let repo_root = find_repository_root(¤t_dir)
889 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
890
891 let mut manager = StackManager::new(&repo_root)?;
892
893 let active_stack = manager.get_active_stack();
894
895 if active_stack.is_none() {
896 Output::info("No active stack to deactivate");
897 return Ok(());
898 }
899
900 let stack_name = active_stack.unwrap().name.clone();
901
902 if !force {
903 Output::warning(format!(
904 "This will deactivate stack '{stack_name}' and return to normal Git workflow"
905 ));
906 Output::sub_item(format!(
907 "You can reactivate it later with 'ca stacks switch {stack_name}'"
908 ));
909 let should_deactivate = Confirm::with_theme(&ColorfulTheme::default())
911 .with_prompt("Continue with deactivation?")
912 .default(false)
913 .interact()
914 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
915
916 if !should_deactivate {
917 Output::info("Cancelled deactivation");
918 return Ok(());
919 }
920 }
921
922 manager.set_active_stack(None)?;
924
925 Output::success(format!("Deactivated stack '{stack_name}'"));
926 Output::sub_item("Stack management is now OFF - you can use normal Git workflow");
927 Output::sub_item(format!("To reactivate: ca stacks switch {stack_name}"));
928
929 Ok(())
930}
931
932async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
933 let current_dir = env::current_dir()
934 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
935
936 let repo_root = find_repository_root(¤t_dir)
937 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
938
939 let stack_manager = StackManager::new(&repo_root)?;
940
941 let (stack_id, stack_name, stack_base, stack_working, stack_entries) = {
943 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
944 CascadeError::config(
945 "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
946 .to_string(),
947 )
948 })?;
949
950 (
951 active_stack.id,
952 active_stack.name.clone(),
953 active_stack.base_branch.clone(),
954 active_stack.working_branch.clone(),
955 active_stack.entries.clone(),
956 )
957 };
958
959 Output::stack_info(
961 &stack_name,
962 &stack_id.to_string(),
963 &stack_base,
964 stack_working.as_deref(),
965 true, );
967 Output::sub_item(format!("Total entries: {}", stack_entries.len()));
968
969 if stack_entries.is_empty() {
970 Output::info("No entries in this stack yet");
971 Output::tip("Use 'ca push' to add commits to this stack");
972 return Ok(());
973 }
974
975 Output::section("Stack Entries");
977 for (i, entry) in stack_entries.iter().enumerate() {
978 let entry_num = i + 1;
979 let short_hash = entry.short_hash();
980 let short_msg = entry.short_message(50);
981
982 let metadata = stack_manager.get_repository_metadata();
985 let source_branch_info = if !entry.is_submitted {
986 if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash) {
987 if commit_meta.source_branch != commit_meta.branch
988 && !commit_meta.source_branch.is_empty()
989 {
990 format!(" (from {})", commit_meta.source_branch)
991 } else {
992 String::new()
993 }
994 } else {
995 String::new()
996 }
997 } else {
998 String::new()
999 };
1000
1001 let status_colored = Output::entry_status(entry.is_submitted, false);
1003
1004 Output::numbered_item(
1005 entry_num,
1006 format!("{short_hash} {status_colored} {short_msg}{source_branch_info}"),
1007 );
1008
1009 if verbose {
1010 Output::sub_item(format!("Branch: {}", entry.branch));
1011 Output::sub_item(format!(
1012 "Created: {}",
1013 entry.created_at.format("%Y-%m-%d %H:%M")
1014 ));
1015 if let Some(pr_id) = &entry.pull_request_id {
1016 Output::sub_item(format!("PR: #{pr_id}"));
1017 }
1018
1019 Output::sub_item("Commit Message:");
1021 let lines: Vec<&str> = entry.message.lines().collect();
1022 for line in lines {
1023 Output::sub_item(format!(" {line}"));
1024 }
1025 }
1026 }
1027
1028 if show_mergeable {
1030 Output::section("Mergability Status");
1031
1032 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1034 let config_path = config_dir.join("config.json");
1035 let settings = crate::config::Settings::load_from_file(&config_path)?;
1036
1037 let cascade_config = crate::config::CascadeConfig {
1038 bitbucket: Some(settings.bitbucket.clone()),
1039 git: settings.git.clone(),
1040 auth: crate::config::AuthConfig::default(),
1041 cascade: settings.cascade.clone(),
1042 };
1043
1044 let mut integration =
1045 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1046
1047 match integration.check_enhanced_stack_status(&stack_id).await {
1048 Ok(status) => {
1049 Output::bullet(format!("Total entries: {}", status.total_entries));
1050 Output::bullet(format!("Submitted: {}", status.submitted_entries));
1051 Output::bullet(format!("Open PRs: {}", status.open_prs));
1052 Output::bullet(format!("Merged PRs: {}", status.merged_prs));
1053 Output::bullet(format!("Declined PRs: {}", status.declined_prs));
1054 Output::bullet(format!(
1055 "Completion: {:.1}%",
1056 status.completion_percentage()
1057 ));
1058
1059 if !status.enhanced_statuses.is_empty() {
1060 Output::section("Pull Request Status");
1061 let mut ready_to_land = 0;
1062
1063 for enhanced in &status.enhanced_statuses {
1064 let status_display = enhanced.get_display_status();
1065 let ready_icon = if enhanced.is_ready_to_land() {
1066 ready_to_land += 1;
1067 "[READY]"
1068 } else {
1069 "[PENDING]"
1070 };
1071
1072 Output::bullet(format!(
1073 "{} PR #{}: {} ({})",
1074 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
1075 ));
1076
1077 if verbose {
1078 println!(
1079 " {} -> {}",
1080 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
1081 );
1082
1083 if !enhanced.is_ready_to_land() {
1085 let blocking = enhanced.get_blocking_reasons();
1086 if !blocking.is_empty() {
1087 println!(" Blocking: {}", blocking.join(", "));
1088 }
1089 }
1090
1091 println!(
1093 " Reviews: {} approval{}",
1094 enhanced.review_status.current_approvals,
1095 if enhanced.review_status.current_approvals == 1 {
1096 ""
1097 } else {
1098 "s"
1099 }
1100 );
1101
1102 if enhanced.review_status.needs_work_count > 0 {
1103 println!(
1104 " {} reviewers requested changes",
1105 enhanced.review_status.needs_work_count
1106 );
1107 }
1108
1109 if let Some(build) = &enhanced.build_status {
1111 let build_icon = match build.state {
1112 crate::bitbucket::pull_request::BuildState::Successful => "✓",
1113 crate::bitbucket::pull_request::BuildState::Failed => "✗",
1114 crate::bitbucket::pull_request::BuildState::InProgress => "~",
1115 _ => "○",
1116 };
1117 println!(" Build: {} {:?}", build_icon, build.state);
1118 }
1119
1120 if let Some(url) = enhanced.pr.web_url() {
1121 println!(" URL: {url}");
1122 }
1123 println!();
1124 }
1125 }
1126
1127 if ready_to_land > 0 {
1128 println!(
1129 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
1130 ready_to_land,
1131 if ready_to_land == 1 { " is" } else { "s are" }
1132 );
1133 }
1134 }
1135 }
1136 Err(e) => {
1137 tracing::debug!("Failed to get enhanced stack status: {}", e);
1138 Output::warning("Could not fetch mergability status");
1139 Output::sub_item("Use 'ca stack show --verbose' for basic PR information");
1140 }
1141 }
1142 } else {
1143 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1145 let config_path = config_dir.join("config.json");
1146 let settings = crate::config::Settings::load_from_file(&config_path)?;
1147
1148 let cascade_config = crate::config::CascadeConfig {
1149 bitbucket: Some(settings.bitbucket.clone()),
1150 git: settings.git.clone(),
1151 auth: crate::config::AuthConfig::default(),
1152 cascade: settings.cascade.clone(),
1153 };
1154
1155 let integration =
1156 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1157
1158 match integration.check_stack_status(&stack_id).await {
1159 Ok(status) => {
1160 println!("\nPull Request Status:");
1161 println!(" Total entries: {}", status.total_entries);
1162 println!(" Submitted: {}", status.submitted_entries);
1163 println!(" Open PRs: {}", status.open_prs);
1164 println!(" Merged PRs: {}", status.merged_prs);
1165 println!(" Declined PRs: {}", status.declined_prs);
1166 println!(" Completion: {:.1}%", status.completion_percentage());
1167
1168 if !status.pull_requests.is_empty() {
1169 println!("\nPull Requests:");
1170 for pr in &status.pull_requests {
1171 let state_icon = match pr.state {
1172 crate::bitbucket::PullRequestState::Open => "→",
1173 crate::bitbucket::PullRequestState::Merged => "✓",
1174 crate::bitbucket::PullRequestState::Declined => "✗",
1175 };
1176 println!(
1177 " {} PR #{}: {} ({} -> {})",
1178 state_icon,
1179 pr.id,
1180 pr.title,
1181 pr.from_ref.display_id,
1182 pr.to_ref.display_id
1183 );
1184 if let Some(url) = pr.web_url() {
1185 println!(" URL: {url}");
1186 }
1187 }
1188 }
1189
1190 println!();
1191 Output::tip("Use 'ca stack --mergeable' to see detailed status including build and review information");
1192 }
1193 Err(e) => {
1194 tracing::debug!("Failed to check stack status: {}", e);
1195 }
1196 }
1197 }
1198
1199 Ok(())
1200}
1201
1202#[allow(clippy::too_many_arguments)]
1203async fn push_to_stack(
1204 branch: Option<String>,
1205 message: Option<String>,
1206 commit: Option<String>,
1207 since: Option<String>,
1208 commits: Option<String>,
1209 squash: Option<usize>,
1210 squash_since: Option<String>,
1211 auto_branch: bool,
1212 allow_base_branch: bool,
1213 dry_run: bool,
1214) -> Result<()> {
1215 let current_dir = env::current_dir()
1216 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1217
1218 let repo_root = find_repository_root(¤t_dir)
1219 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1220
1221 let mut manager = StackManager::new(&repo_root)?;
1222 let repo = GitRepository::open(&repo_root)?;
1223
1224 if !manager.check_for_branch_change()? {
1226 return Ok(()); }
1228
1229 let active_stack = manager.get_active_stack().ok_or_else(|| {
1231 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1232 })?;
1233
1234 let current_branch = repo.get_current_branch()?;
1236 let base_branch = &active_stack.base_branch;
1237
1238 if current_branch == *base_branch {
1239 Output::error(format!(
1240 "You're currently on the base branch '{base_branch}'"
1241 ));
1242 Output::sub_item("Making commits directly on the base branch is not recommended.");
1243 Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1244
1245 if allow_base_branch {
1247 Output::warning("Proceeding anyway due to --allow-base-branch flag");
1248 } else {
1249 let has_changes = repo.is_dirty()?;
1251
1252 if has_changes {
1253 if auto_branch {
1254 let feature_branch = format!("feature/{}-work", active_stack.name);
1256 Output::progress(format!(
1257 "Auto-creating feature branch '{feature_branch}'..."
1258 ));
1259
1260 repo.create_branch(&feature_branch, None)?;
1261 repo.checkout_branch(&feature_branch)?;
1262
1263 Output::success(format!("Created and switched to '{feature_branch}'"));
1264 println!(" You can now commit and push your changes safely");
1265
1266 } else {
1268 println!("\nYou have uncommitted changes. Here are your options:");
1269 println!(" 1. Create a feature branch first:");
1270 println!(" git checkout -b feature/my-work");
1271 println!(" git commit -am \"your work\"");
1272 println!(" ca push");
1273 println!("\n 2. Auto-create a branch (recommended):");
1274 println!(" ca push --auto-branch");
1275 println!("\n 3. Force push to base branch (dangerous):");
1276 println!(" ca push --allow-base-branch");
1277
1278 return Err(CascadeError::config(
1279 "Refusing to push uncommitted changes from base branch. Use one of the options above."
1280 ));
1281 }
1282 } else {
1283 let commits_to_check = if let Some(commits_str) = &commits {
1285 commits_str
1286 .split(',')
1287 .map(|s| s.trim().to_string())
1288 .collect::<Vec<String>>()
1289 } else if let Some(since_ref) = &since {
1290 let since_commit = repo.resolve_reference(since_ref)?;
1291 let head_commit = repo.get_head_commit()?;
1292 let commits = repo.get_commits_between(
1293 &since_commit.id().to_string(),
1294 &head_commit.id().to_string(),
1295 )?;
1296 commits.into_iter().map(|c| c.id().to_string()).collect()
1297 } else if commit.is_none() {
1298 let mut unpushed = Vec::new();
1299 let head_commit = repo.get_head_commit()?;
1300 let mut current_commit = head_commit;
1301
1302 loop {
1303 let commit_hash = current_commit.id().to_string();
1304 let already_in_stack = active_stack
1305 .entries
1306 .iter()
1307 .any(|entry| entry.commit_hash == commit_hash);
1308
1309 if already_in_stack {
1310 break;
1311 }
1312
1313 unpushed.push(commit_hash);
1314
1315 if let Some(parent) = current_commit.parents().next() {
1316 current_commit = parent;
1317 } else {
1318 break;
1319 }
1320 }
1321
1322 unpushed.reverse();
1323 unpushed
1324 } else {
1325 vec![repo.get_head_commit()?.id().to_string()]
1326 };
1327
1328 if !commits_to_check.is_empty() {
1329 if auto_branch {
1330 let feature_branch = format!("feature/{}-work", active_stack.name);
1332 Output::progress(format!(
1333 "Auto-creating feature branch '{feature_branch}'..."
1334 ));
1335
1336 repo.create_branch(&feature_branch, Some(base_branch))?;
1337 repo.checkout_branch(&feature_branch)?;
1338
1339 println!(
1341 "🍒 Cherry-picking {} commit(s) to new branch...",
1342 commits_to_check.len()
1343 );
1344 for commit_hash in &commits_to_check {
1345 match repo.cherry_pick(commit_hash) {
1346 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1347 Err(e) => {
1348 Output::error(format!(
1349 "Failed to cherry-pick {}: {}",
1350 &commit_hash[..8],
1351 e
1352 ));
1353 Output::tip("You may need to resolve conflicts manually");
1354 return Err(CascadeError::branch(format!(
1355 "Failed to cherry-pick commit {commit_hash}: {e}"
1356 )));
1357 }
1358 }
1359 }
1360
1361 println!(
1362 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1363 commits_to_check.len()
1364 );
1365 println!(
1366 " You're now on the feature branch and can continue with 'ca push'"
1367 );
1368
1369 } else {
1371 println!(
1372 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1373 commits_to_check.len()
1374 );
1375 println!(" These commits are currently ON the base branch, which may not be intended.");
1376 println!("\n Options:");
1377 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1378 println!(" ca push --auto-branch");
1379 println!("\n 2. Manually create branch and move commits:");
1380 println!(" git checkout -b feature/my-work");
1381 println!(" ca push");
1382 println!("\n 3. Force push from base branch (not recommended):");
1383 println!(" ca push --allow-base-branch");
1384
1385 return Err(CascadeError::config(
1386 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1387 ));
1388 }
1389 }
1390 }
1391 }
1392 }
1393
1394 if let Some(squash_count) = squash {
1396 if squash_count == 0 {
1397 let active_stack = manager.get_active_stack().ok_or_else(|| {
1399 CascadeError::config(
1400 "No active stack. Create a stack first with 'ca stacks create'",
1401 )
1402 })?;
1403
1404 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1405
1406 if unpushed_count == 0 {
1407 Output::info(" No unpushed commits to squash");
1408 } else if unpushed_count == 1 {
1409 Output::info(" Only 1 unpushed commit, no squashing needed");
1410 } else {
1411 println!(" Auto-detected {unpushed_count} unpushed commits, squashing...");
1412 squash_commits(&repo, unpushed_count, None).await?;
1413 Output::success(" Squashed {unpushed_count} unpushed commits into one");
1414 }
1415 } else {
1416 println!(" Squashing last {squash_count} commits...");
1417 squash_commits(&repo, squash_count, None).await?;
1418 Output::success(" Squashed {squash_count} commits into one");
1419 }
1420 } else if let Some(since_ref) = squash_since {
1421 println!(" Squashing commits since {since_ref}...");
1422 let since_commit = repo.resolve_reference(&since_ref)?;
1423 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1424 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1425 Output::success(" Squashed {commits_count} commits since {since_ref} into one");
1426 }
1427
1428 let commits_to_push = if let Some(commits_str) = commits {
1430 commits_str
1432 .split(',')
1433 .map(|s| s.trim().to_string())
1434 .collect::<Vec<String>>()
1435 } else if let Some(since_ref) = since {
1436 let since_commit = repo.resolve_reference(&since_ref)?;
1438 let head_commit = repo.get_head_commit()?;
1439
1440 let commits = repo.get_commits_between(
1442 &since_commit.id().to_string(),
1443 &head_commit.id().to_string(),
1444 )?;
1445 commits.into_iter().map(|c| c.id().to_string()).collect()
1446 } else if let Some(hash) = commit {
1447 vec![hash]
1449 } else {
1450 let active_stack = manager.get_active_stack().ok_or_else(|| {
1452 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1453 })?;
1454
1455 let base_branch = &active_stack.base_branch;
1457 let current_branch = repo.get_current_branch()?;
1458
1459 if current_branch == *base_branch {
1461 let mut unpushed = Vec::new();
1462 let head_commit = repo.get_head_commit()?;
1463 let mut current_commit = head_commit;
1464
1465 loop {
1467 let commit_hash = current_commit.id().to_string();
1468 let already_in_stack = active_stack
1469 .entries
1470 .iter()
1471 .any(|entry| entry.commit_hash == commit_hash);
1472
1473 if already_in_stack {
1474 break;
1475 }
1476
1477 unpushed.push(commit_hash);
1478
1479 if let Some(parent) = current_commit.parents().next() {
1481 current_commit = parent;
1482 } else {
1483 break;
1484 }
1485 }
1486
1487 unpushed.reverse(); unpushed
1489 } else {
1490 match repo.get_commits_between(base_branch, ¤t_branch) {
1492 Ok(commits) => {
1493 let mut unpushed: Vec<String> =
1494 commits.into_iter().map(|c| c.id().to_string()).collect();
1495
1496 unpushed.retain(|commit_hash| {
1498 !active_stack
1499 .entries
1500 .iter()
1501 .any(|entry| entry.commit_hash == *commit_hash)
1502 });
1503
1504 unpushed.reverse(); unpushed
1506 }
1507 Err(e) => {
1508 return Err(CascadeError::branch(format!(
1509 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1510 This usually means the branches have diverged or don't share common history."
1511 )));
1512 }
1513 }
1514 }
1515 };
1516
1517 if commits_to_push.is_empty() {
1518 Output::info(" No commits to push to stack");
1519 return Ok(());
1520 }
1521
1522 analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1524
1525 if dry_run {
1527 return Ok(());
1528 }
1529
1530 let mut pushed_count = 0;
1532 let mut source_branches = std::collections::HashSet::new();
1533
1534 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1535 let commit_obj = repo.get_commit(commit_hash)?;
1536 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1537
1538 let commit_source_branch = repo
1540 .find_branch_containing_commit(commit_hash)
1541 .unwrap_or_else(|_| current_branch.clone());
1542 source_branches.insert(commit_source_branch.clone());
1543
1544 let branch_name = if i == 0 && branch.is_some() {
1546 branch.clone().unwrap()
1547 } else {
1548 let temp_repo = GitRepository::open(&repo_root)?;
1550 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1551 branch_mgr.generate_branch_name(&commit_msg)
1552 };
1553
1554 let final_message = if i == 0 && message.is_some() {
1556 message.clone().unwrap()
1557 } else {
1558 commit_msg.clone()
1559 };
1560
1561 let entry_id = manager.push_to_stack(
1562 branch_name.clone(),
1563 commit_hash.clone(),
1564 final_message.clone(),
1565 commit_source_branch.clone(),
1566 )?;
1567 pushed_count += 1;
1568
1569 Output::success(format!(
1570 "Pushed commit {}/{} to stack",
1571 i + 1,
1572 commits_to_push.len()
1573 ));
1574 Output::sub_item(format!(
1575 "Commit: {} ({})",
1576 &commit_hash[..8],
1577 commit_msg.split('\n').next().unwrap_or("")
1578 ));
1579 Output::sub_item(format!("Branch: {branch_name}"));
1580 Output::sub_item(format!("Source: {commit_source_branch}"));
1581 Output::sub_item(format!("Entry ID: {entry_id}"));
1582 println!();
1583 }
1584
1585 if source_branches.len() > 1 {
1587 Output::warning("Scattered Commit Detection");
1588 Output::sub_item(format!(
1589 "You've pushed commits from {} different Git branches:",
1590 source_branches.len()
1591 ));
1592 for branch in &source_branches {
1593 Output::bullet(branch.to_string());
1594 }
1595
1596 Output::section("This can lead to confusion because:");
1597 Output::bullet("Stack appears sequential but commits are scattered across branches");
1598 Output::bullet("Team members won't know which branch contains which work");
1599 Output::bullet("Branch cleanup becomes unclear after merge");
1600 Output::bullet("Rebase operations become more complex");
1601
1602 Output::tip("Consider consolidating work to a single feature branch:");
1603 Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1604 Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1605 Output::bullet("Delete old scattered branches");
1606 Output::bullet("Push the consolidated branch to your stack");
1607 println!();
1608 }
1609
1610 Output::success(format!(
1611 "Successfully pushed {} commit{} to stack",
1612 pushed_count,
1613 if pushed_count == 1 { "" } else { "s" }
1614 ));
1615
1616 Ok(())
1617}
1618
1619async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1620 let current_dir = env::current_dir()
1621 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1622
1623 let repo_root = find_repository_root(¤t_dir)
1624 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1625
1626 let mut manager = StackManager::new(&repo_root)?;
1627 let repo = GitRepository::open(&repo_root)?;
1628
1629 let entry = manager.pop_from_stack()?;
1630
1631 Output::success("Popped commit from stack");
1632 Output::sub_item(format!(
1633 "Commit: {} ({})",
1634 entry.short_hash(),
1635 entry.short_message(50)
1636 ));
1637 Output::sub_item(format!("Branch: {}", entry.branch));
1638
1639 if !keep_branch && entry.branch != repo.get_current_branch()? {
1641 match repo.delete_branch(&entry.branch) {
1642 Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1643 Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1644 }
1645 }
1646
1647 Ok(())
1648}
1649
1650async fn submit_entry(
1651 entry: Option<usize>,
1652 title: Option<String>,
1653 description: Option<String>,
1654 range: Option<String>,
1655 draft: bool,
1656 open: bool,
1657) -> Result<()> {
1658 let current_dir = env::current_dir()
1659 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1660
1661 let repo_root = find_repository_root(¤t_dir)
1662 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1663
1664 let mut stack_manager = StackManager::new(&repo_root)?;
1665
1666 if !stack_manager.check_for_branch_change()? {
1668 return Ok(()); }
1670
1671 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1673 let config_path = config_dir.join("config.json");
1674 let settings = crate::config::Settings::load_from_file(&config_path)?;
1675
1676 let cascade_config = crate::config::CascadeConfig {
1678 bitbucket: Some(settings.bitbucket.clone()),
1679 git: settings.git.clone(),
1680 auth: crate::config::AuthConfig::default(),
1681 cascade: settings.cascade.clone(),
1682 };
1683
1684 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1686 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1687 })?;
1688 let stack_id = active_stack.id;
1689
1690 let entries_to_submit = if let Some(range_str) = range {
1692 let mut entries = Vec::new();
1694
1695 if range_str.contains('-') {
1696 let parts: Vec<&str> = range_str.split('-').collect();
1698 if parts.len() != 2 {
1699 return Err(CascadeError::config(
1700 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1701 ));
1702 }
1703
1704 let start: usize = parts[0]
1705 .parse()
1706 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1707 let end: usize = parts[1]
1708 .parse()
1709 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1710
1711 if start == 0
1712 || end == 0
1713 || start > active_stack.entries.len()
1714 || end > active_stack.entries.len()
1715 {
1716 return Err(CascadeError::config(format!(
1717 "Range out of bounds. Stack has {} entries",
1718 active_stack.entries.len()
1719 )));
1720 }
1721
1722 for i in start..=end {
1723 entries.push((i, active_stack.entries[i - 1].clone()));
1724 }
1725 } else {
1726 for entry_str in range_str.split(',') {
1728 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1729 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1730 })?;
1731
1732 if entry_num == 0 || entry_num > active_stack.entries.len() {
1733 return Err(CascadeError::config(format!(
1734 "Entry {} out of bounds. Stack has {} entries",
1735 entry_num,
1736 active_stack.entries.len()
1737 )));
1738 }
1739
1740 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1741 }
1742 }
1743
1744 entries
1745 } else if let Some(entry_num) = entry {
1746 if entry_num == 0 || entry_num > active_stack.entries.len() {
1748 return Err(CascadeError::config(format!(
1749 "Invalid entry number: {}. Stack has {} entries",
1750 entry_num,
1751 active_stack.entries.len()
1752 )));
1753 }
1754 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1755 } else {
1756 active_stack
1758 .entries
1759 .iter()
1760 .enumerate()
1761 .filter(|(_, entry)| !entry.is_submitted)
1762 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1764 };
1765
1766 if entries_to_submit.is_empty() {
1767 Output::info("No entries to submit");
1768 return Ok(());
1769 }
1770
1771 Output::section(format!(
1773 "Submitting {} {}",
1774 entries_to_submit.len(),
1775 if entries_to_submit.len() == 1 {
1776 "entry"
1777 } else {
1778 "entries"
1779 }
1780 ));
1781 println!();
1782
1783 let integration_stack_manager = StackManager::new(&repo_root)?;
1785 let mut integration =
1786 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1787
1788 let mut submitted_count = 0;
1790 let mut failed_entries = Vec::new();
1791 let mut pr_urls = Vec::new(); let total_entries = entries_to_submit.len();
1793
1794 for (entry_num, entry_to_submit) in &entries_to_submit {
1795 let tree_char = if entries_to_submit.len() == 1 {
1797 "→"
1798 } else if entry_num == &entries_to_submit.len() {
1799 "└─"
1800 } else {
1801 "├─"
1802 };
1803 print!(
1804 " {} Entry {}: {}... ",
1805 tree_char, entry_num, entry_to_submit.branch
1806 );
1807 std::io::Write::flush(&mut std::io::stdout()).ok();
1808
1809 let entry_title = if total_entries == 1 {
1811 title.clone()
1812 } else {
1813 None
1814 };
1815 let entry_description = if total_entries == 1 {
1816 description.clone()
1817 } else {
1818 None
1819 };
1820
1821 match integration
1822 .submit_entry(
1823 &stack_id,
1824 &entry_to_submit.id,
1825 entry_title,
1826 entry_description,
1827 draft,
1828 )
1829 .await
1830 {
1831 Ok(pr) => {
1832 submitted_count += 1;
1833 Output::success(format!("PR #{}", pr.id));
1834 if let Some(url) = pr.web_url() {
1835 Output::sub_item(format!(
1836 "{} → {}",
1837 pr.from_ref.display_id, pr.to_ref.display_id
1838 ));
1839 Output::sub_item(format!("URL: {url}"));
1840 pr_urls.push(url); }
1842 }
1843 Err(e) => {
1844 Output::error("Failed");
1845 let clean_error = if e.to_string().contains("non-fast-forward") {
1847 "Branch has diverged (was rebased after initial submission). Update to v0.1.41+ to auto force-push.".to_string()
1848 } else if e.to_string().contains("authentication") {
1849 "Authentication failed. Check your Bitbucket credentials.".to_string()
1850 } else {
1851 e.to_string()
1853 .lines()
1854 .filter(|l| !l.trim().starts_with("hint:") && !l.trim().is_empty())
1855 .take(1)
1856 .collect::<Vec<_>>()
1857 .join(" ")
1858 .trim()
1859 .to_string()
1860 };
1861 Output::sub_item(format!("Error: {}", clean_error));
1862 failed_entries.push((*entry_num, clean_error));
1863 }
1864 }
1865 }
1866
1867 println!();
1868
1869 let has_any_prs = active_stack
1871 .entries
1872 .iter()
1873 .any(|e| e.pull_request_id.is_some());
1874 if has_any_prs && submitted_count > 0 {
1875 match integration.update_all_pr_descriptions(&stack_id).await {
1876 Ok(updated_prs) => {
1877 if !updated_prs.is_empty() {
1878 Output::sub_item(format!(
1879 "Updated {} PR description{} with stack hierarchy",
1880 updated_prs.len(),
1881 if updated_prs.len() == 1 { "" } else { "s" }
1882 ));
1883 }
1884 }
1885 Err(e) => {
1886 let error_msg = e.to_string();
1889 if !error_msg.contains("409") && !error_msg.contains("out-of-date") {
1890 let clean_error = error_msg.lines().next().unwrap_or("Unknown error").trim();
1892 Output::warning(format!(
1893 "Could not update some PR descriptions: {}",
1894 clean_error
1895 ));
1896 Output::sub_item(
1897 "PRs were created successfully - descriptions can be updated manually",
1898 );
1899 }
1900 }
1901 }
1902 }
1903
1904 if failed_entries.is_empty() {
1906 Output::success(format!(
1907 "{} {} submitted successfully!",
1908 submitted_count,
1909 if submitted_count == 1 {
1910 "entry"
1911 } else {
1912 "entries"
1913 }
1914 ));
1915 } else {
1916 println!();
1917 Output::section("Submission Summary");
1918 Output::success(format!("Successful: {submitted_count}"));
1919 Output::error(format!("Failed: {}", failed_entries.len()));
1920
1921 if !failed_entries.is_empty() {
1922 println!();
1923 Output::tip("Retry failed entries:");
1924 for (entry_num, _) in &failed_entries {
1925 Output::bullet(format!("ca stack submit {entry_num}"));
1926 }
1927 }
1928 }
1929
1930 if open && !pr_urls.is_empty() {
1932 println!();
1933 for url in &pr_urls {
1934 if let Err(e) = open::that(url) {
1935 Output::warning(format!("Could not open browser: {}", e));
1936 Output::tip(format!("Open manually: {}", url));
1937 }
1938 }
1939 }
1940
1941 Ok(())
1942}
1943
1944async fn check_stack_status(name: Option<String>) -> Result<()> {
1945 let current_dir = env::current_dir()
1946 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1947
1948 let repo_root = find_repository_root(¤t_dir)
1949 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1950
1951 let stack_manager = StackManager::new(&repo_root)?;
1952
1953 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1955 let config_path = config_dir.join("config.json");
1956 let settings = crate::config::Settings::load_from_file(&config_path)?;
1957
1958 let cascade_config = crate::config::CascadeConfig {
1960 bitbucket: Some(settings.bitbucket.clone()),
1961 git: settings.git.clone(),
1962 auth: crate::config::AuthConfig::default(),
1963 cascade: settings.cascade.clone(),
1964 };
1965
1966 let stack = if let Some(name) = name {
1968 stack_manager
1969 .get_stack_by_name(&name)
1970 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1971 } else {
1972 stack_manager.get_active_stack().ok_or_else(|| {
1973 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1974 })?
1975 };
1976 let stack_id = stack.id;
1977
1978 Output::section(format!("Stack: {}", stack.name));
1979 Output::sub_item(format!("ID: {}", stack.id));
1980 Output::sub_item(format!("Base: {}", stack.base_branch));
1981
1982 if let Some(description) = &stack.description {
1983 Output::sub_item(format!("Description: {description}"));
1984 }
1985
1986 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1988
1989 match integration.check_stack_status(&stack_id).await {
1991 Ok(status) => {
1992 Output::section("Pull Request Status");
1993 Output::sub_item(format!("Total entries: {}", status.total_entries));
1994 Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1995 Output::sub_item(format!("Open PRs: {}", status.open_prs));
1996 Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1997 Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1998 Output::sub_item(format!(
1999 "Completion: {:.1}%",
2000 status.completion_percentage()
2001 ));
2002
2003 if !status.pull_requests.is_empty() {
2004 Output::section("Pull Requests");
2005 for pr in &status.pull_requests {
2006 let state_icon = match pr.state {
2007 crate::bitbucket::PullRequestState::Open => "🔄",
2008 crate::bitbucket::PullRequestState::Merged => "✅",
2009 crate::bitbucket::PullRequestState::Declined => "❌",
2010 };
2011 Output::bullet(format!(
2012 "{} PR #{}: {} ({} -> {})",
2013 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
2014 ));
2015 if let Some(url) = pr.web_url() {
2016 Output::sub_item(format!("URL: {url}"));
2017 }
2018 }
2019 }
2020 }
2021 Err(e) => {
2022 tracing::debug!("Failed to check stack status: {}", e);
2023 return Err(e);
2024 }
2025 }
2026
2027 Ok(())
2028}
2029
2030async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
2031 let current_dir = env::current_dir()
2032 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2033
2034 let repo_root = find_repository_root(¤t_dir)
2035 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2036
2037 let stack_manager = StackManager::new(&repo_root)?;
2038
2039 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2041 let config_path = config_dir.join("config.json");
2042 let settings = crate::config::Settings::load_from_file(&config_path)?;
2043
2044 let cascade_config = crate::config::CascadeConfig {
2046 bitbucket: Some(settings.bitbucket.clone()),
2047 git: settings.git.clone(),
2048 auth: crate::config::AuthConfig::default(),
2049 cascade: settings.cascade.clone(),
2050 };
2051
2052 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2054
2055 let pr_state = if let Some(state_str) = state {
2057 match state_str.to_lowercase().as_str() {
2058 "open" => Some(crate::bitbucket::PullRequestState::Open),
2059 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
2060 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
2061 _ => {
2062 return Err(CascadeError::config(format!(
2063 "Invalid state '{state_str}'. Use: open, merged, declined"
2064 )))
2065 }
2066 }
2067 } else {
2068 None
2069 };
2070
2071 match integration.list_pull_requests(pr_state).await {
2073 Ok(pr_page) => {
2074 if pr_page.values.is_empty() {
2075 Output::info("No pull requests found.");
2076 return Ok(());
2077 }
2078
2079 println!("Pull Requests ({} total):", pr_page.values.len());
2080 for pr in &pr_page.values {
2081 let state_icon = match pr.state {
2082 crate::bitbucket::PullRequestState::Open => "○",
2083 crate::bitbucket::PullRequestState::Merged => "✓",
2084 crate::bitbucket::PullRequestState::Declined => "✗",
2085 };
2086 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
2087 if verbose {
2088 println!(
2089 " From: {} -> {}",
2090 pr.from_ref.display_id, pr.to_ref.display_id
2091 );
2092 println!(
2093 " Author: {}",
2094 pr.author
2095 .user
2096 .display_name
2097 .as_deref()
2098 .unwrap_or(&pr.author.user.name)
2099 );
2100 if let Some(url) = pr.web_url() {
2101 println!(" URL: {url}");
2102 }
2103 if let Some(desc) = &pr.description {
2104 if !desc.is_empty() {
2105 println!(" Description: {desc}");
2106 }
2107 }
2108 println!();
2109 }
2110 }
2111
2112 if !verbose {
2113 println!("\nUse --verbose for more details");
2114 }
2115 }
2116 Err(e) => {
2117 warn!("Failed to list pull requests: {}", e);
2118 return Err(e);
2119 }
2120 }
2121
2122 Ok(())
2123}
2124
2125async fn check_stack(_force: bool) -> Result<()> {
2126 let current_dir = env::current_dir()
2127 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2128
2129 let repo_root = find_repository_root(¤t_dir)
2130 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2131
2132 let mut manager = StackManager::new(&repo_root)?;
2133
2134 let active_stack = manager
2135 .get_active_stack()
2136 .ok_or_else(|| CascadeError::config("No active stack"))?;
2137 let stack_id = active_stack.id;
2138
2139 manager.sync_stack(&stack_id)?;
2140
2141 Output::success("Stack check completed successfully");
2142
2143 Ok(())
2144}
2145
2146async fn continue_sync() -> Result<()> {
2147 let current_dir = env::current_dir()
2148 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2149
2150 let repo_root = find_repository_root(¤t_dir)?;
2151
2152 Output::section("Continuing sync from where it left off");
2153 println!();
2154
2155 let cherry_pick_head = repo_root.join(".git").join("CHERRY_PICK_HEAD");
2157 if !cherry_pick_head.exists() {
2158 return Err(CascadeError::config(
2159 "No in-progress cherry-pick found. Nothing to continue.\n\n\
2160 Use 'ca sync' to start a new sync."
2161 .to_string(),
2162 ));
2163 }
2164
2165 Output::info("Staging all resolved files");
2166
2167 std::process::Command::new("git")
2169 .args(["add", "-A"])
2170 .current_dir(&repo_root)
2171 .output()
2172 .map_err(CascadeError::Io)?;
2173
2174 Output::info("Continuing cherry-pick");
2175
2176 let continue_output = std::process::Command::new("git")
2178 .args(["cherry-pick", "--continue"])
2179 .current_dir(&repo_root)
2180 .output()
2181 .map_err(CascadeError::Io)?;
2182
2183 if !continue_output.status.success() {
2184 let stderr = String::from_utf8_lossy(&continue_output.stderr);
2185 return Err(CascadeError::Branch(format!(
2186 "Failed to continue cherry-pick: {}\n\n\
2187 Make sure all conflicts are resolved.",
2188 stderr
2189 )));
2190 }
2191
2192 Output::success("Cherry-pick continued successfully");
2193 println!();
2194
2195 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2202 let current_branch = git_repo.get_current_branch()?;
2203
2204 let stack_branch = if let Some(idx) = current_branch.rfind("-temp-") {
2207 current_branch[..idx].to_string()
2208 } else {
2209 return Err(CascadeError::config(format!(
2210 "Current branch '{}' doesn't appear to be a temp branch created by cascade.\n\
2211 Expected format: <branch>-temp-<timestamp>",
2212 current_branch
2213 )));
2214 };
2215
2216 Output::info(format!("Updating stack branch: {}", stack_branch));
2217
2218 std::process::Command::new("git")
2220 .args(["branch", "-f", &stack_branch])
2221 .current_dir(&repo_root)
2222 .output()
2223 .map_err(CascadeError::Io)?;
2224
2225 let mut manager = crate::stack::StackManager::new(&repo_root)?;
2227
2228 let new_commit_hash = git_repo.get_branch_head(&stack_branch)?;
2231
2232 let (stack_id, entry_id_opt, working_branch) = {
2234 let active_stack = manager
2235 .get_active_stack()
2236 .ok_or_else(|| CascadeError::config("No active stack found"))?;
2237
2238 let entry_id_opt = active_stack
2239 .entries
2240 .iter()
2241 .find(|e| e.branch == stack_branch)
2242 .map(|e| e.id);
2243
2244 let working_branch = active_stack
2245 .working_branch
2246 .as_ref()
2247 .ok_or_else(|| CascadeError::config("Active stack has no working branch"))?
2248 .clone();
2249
2250 (active_stack.id, entry_id_opt, working_branch)
2251 };
2252
2253 if let Some(entry_id) = entry_id_opt {
2255 let stack = manager
2256 .get_stack_mut(&stack_id)
2257 .ok_or_else(|| CascadeError::config("Could not get mutable stack reference"))?;
2258
2259 stack
2260 .update_entry_commit_hash(&entry_id, new_commit_hash.clone())
2261 .map_err(CascadeError::config)?;
2262
2263 manager.save_to_disk()?;
2264 }
2265
2266 let top_commit = {
2268 let active_stack = manager
2269 .get_active_stack()
2270 .ok_or_else(|| CascadeError::config("No active stack found"))?;
2271
2272 if let Some(last_entry) = active_stack.entries.last() {
2273 git_repo.get_branch_head(&last_entry.branch)?
2274 } else {
2275 new_commit_hash.clone()
2276 }
2277 };
2278
2279 Output::info(format!(
2280 "Checking out to working branch: {}",
2281 working_branch
2282 ));
2283
2284 git_repo.checkout_branch_unsafe(&working_branch)?;
2286
2287 if let Ok(working_head) = git_repo.get_branch_head(&working_branch) {
2296 if working_head != top_commit {
2297 git_repo.update_branch_to_commit(&working_branch, &top_commit)?;
2298 }
2299 }
2300
2301 println!();
2302 Output::info("Resuming sync to complete the rebase...");
2303 println!();
2304
2305 sync_stack(false, false, false).await
2307}
2308
2309async fn sync_stack(force: bool, cleanup: bool, interactive: bool) -> Result<()> {
2310 let current_dir = env::current_dir()
2311 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2312
2313 let repo_root = find_repository_root(¤t_dir)
2314 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2315
2316 let mut stack_manager = StackManager::new(&repo_root)?;
2317
2318 if stack_manager.is_in_edit_mode() {
2321 debug!("Exiting edit mode before sync (commit SHAs will change)");
2322 stack_manager.exit_edit_mode()?;
2323 }
2324
2325 let git_repo = GitRepository::open(&repo_root)?;
2326
2327 if git_repo.is_dirty()? {
2328 return Err(CascadeError::branch(
2329 "Working tree has uncommitted changes. Commit or stash them before running 'ca sync'."
2330 .to_string(),
2331 ));
2332 }
2333
2334 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2336 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2337 })?;
2338
2339 let base_branch = active_stack.base_branch.clone();
2340 let _stack_name = active_stack.name.clone();
2341
2342 let original_branch = git_repo.get_current_branch().ok();
2344
2345 match git_repo.checkout_branch_silent(&base_branch) {
2349 Ok(_) => {
2350 match git_repo.pull(&base_branch) {
2351 Ok(_) => {
2352 }
2354 Err(e) => {
2355 if force {
2356 Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
2357 } else {
2358 Output::error(format!("Failed to pull latest changes: {e}"));
2359 Output::tip("Use --force to skip pull and continue with rebase");
2360 return Err(CascadeError::branch(format!(
2361 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
2362 )));
2363 }
2364 }
2365 }
2366 }
2367 Err(e) => {
2368 if force {
2369 Output::warning(format!(
2370 "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
2371 ));
2372 } else {
2373 Output::error(format!(
2374 "Failed to checkout base branch '{base_branch}': {e}"
2375 ));
2376 Output::tip("Use --force to bypass checkout issues and continue anyway");
2377 return Err(CascadeError::branch(format!(
2378 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
2379 )));
2380 }
2381 }
2382 }
2383
2384 let mut updated_stack_manager = StackManager::new(&repo_root)?;
2387 let stack_id = active_stack.id;
2388
2389 if let Some(stack) = updated_stack_manager.get_stack_mut(&stack_id) {
2392 let mut updates = Vec::new();
2393 for entry in &stack.entries {
2394 if let Ok(current_commit) = git_repo.get_branch_head(&entry.branch) {
2395 if entry.commit_hash != current_commit {
2396 let is_safe_descendant = match git_repo.commit_exists(&entry.commit_hash) {
2397 Ok(true) => {
2398 match git_repo.is_descendant_of(¤t_commit, &entry.commit_hash) {
2399 Ok(result) => result,
2400 Err(e) => {
2401 warn!(
2402 "Cannot verify ancestry for '{}': {} - treating as unsafe to prevent potential data loss",
2403 entry.branch, e
2404 );
2405 false
2406 }
2407 }
2408 }
2409 Ok(false) => {
2410 debug!(
2411 "Recorded commit {} for '{}' no longer exists in repository",
2412 &entry.commit_hash[..8],
2413 entry.branch
2414 );
2415 false
2416 }
2417 Err(e) => {
2418 warn!(
2419 "Cannot verify commit existence for '{}': {} - treating as unsafe to prevent potential data loss",
2420 entry.branch, e
2421 );
2422 false
2423 }
2424 };
2425
2426 if is_safe_descendant {
2427 debug!(
2428 "Reconciling entry '{}': updating hash from {} to {} (current branch HEAD)",
2429 entry.branch,
2430 &entry.commit_hash[..8],
2431 ¤t_commit[..8]
2432 );
2433 updates.push((entry.id, current_commit));
2434 } else {
2435 warn!(
2436 "Skipped automatic reconciliation for entry '{}' because local HEAD ({}) does not descend from recorded commit ({})",
2437 entry.branch,
2438 ¤t_commit[..8],
2439 &entry.commit_hash[..8]
2440 );
2441 }
2442 }
2443 }
2444 }
2445
2446 for (entry_id, new_hash) in updates {
2448 stack
2449 .update_entry_commit_hash(&entry_id, new_hash)
2450 .map_err(CascadeError::config)?;
2451 }
2452
2453 updated_stack_manager.save_to_disk()?;
2455 }
2456
2457 match updated_stack_manager.sync_stack(&stack_id) {
2458 Ok(_) => {
2459 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2461 if updated_stack.entries.is_empty() {
2463 println!(); Output::info("Stack has no entries yet");
2465 Output::tip("Use 'ca push' to add commits to this stack");
2466 return Ok(());
2467 }
2468
2469 match &updated_stack.status {
2470 crate::stack::StackStatus::NeedsSync => {
2471 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2473 let config_path = config_dir.join("config.json");
2474 let settings = crate::config::Settings::load_from_file(&config_path)?;
2475
2476 let cascade_config = crate::config::CascadeConfig {
2477 bitbucket: Some(settings.bitbucket.clone()),
2478 git: settings.git.clone(),
2479 auth: crate::config::AuthConfig::default(),
2480 cascade: settings.cascade.clone(),
2481 };
2482
2483 println!(); let rebase_spinner = crate::utils::spinner::Spinner::new_with_output_below(
2487 format!("Rebasing stack: {}", active_stack.name),
2488 );
2489
2490 let options = crate::stack::RebaseOptions {
2493 strategy: crate::stack::RebaseStrategy::ForcePush,
2494 interactive,
2495 target_base: Some(base_branch.clone()),
2496 preserve_merges: true,
2497 auto_resolve: !interactive, max_retries: 3,
2499 skip_pull: Some(true), original_working_branch: original_branch.clone(), progress_printer: Some(rebase_spinner.printer()),
2502 };
2503
2504 let mut rebase_manager = crate::stack::RebaseManager::new(
2505 updated_stack_manager,
2506 git_repo,
2507 options,
2508 );
2509
2510 let rebase_result = rebase_manager.rebase_stack(&stack_id);
2512
2513 rebase_spinner.stop();
2515 println!(); match rebase_result {
2518 Ok(result) => {
2519 if !result.branch_mapping.is_empty() {
2520 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2522 let integration_stack_manager =
2523 StackManager::new(&repo_root)?;
2524 let mut integration =
2525 crate::bitbucket::BitbucketIntegration::new(
2526 integration_stack_manager,
2527 cascade_config,
2528 )?;
2529
2530 let pr_word = if result.branch_mapping.len() == 1 {
2532 "PR"
2533 } else {
2534 "PRs"
2535 };
2536 let pr_spinner =
2537 crate::utils::spinner::Spinner::new_with_output_below(
2538 format!(
2539 "Updating {} {}",
2540 result.branch_mapping.len(),
2541 pr_word
2542 ),
2543 );
2544
2545 let pr_result = integration
2546 .update_prs_after_rebase(
2547 &stack_id,
2548 &result.branch_mapping,
2549 )
2550 .await;
2551
2552 pr_spinner.stop();
2553
2554 match pr_result {
2555 Ok(updated_prs) => {
2556 if !updated_prs.is_empty() {
2557 Output::success(format!(
2558 "Updated {} pull request{}",
2559 updated_prs.len(),
2560 if updated_prs.len() == 1 {
2561 ""
2562 } else {
2563 "s"
2564 }
2565 ));
2566 }
2567 }
2568 Err(e) => {
2569 Output::warning(format!(
2570 "Failed to update pull requests: {e}"
2571 ));
2572 }
2573 }
2574 }
2575 }
2576 }
2577 Err(e) => {
2578 return Err(e);
2580 }
2581 }
2582 }
2583 crate::stack::StackStatus::Clean => {
2584 }
2586 other => {
2587 Output::info(format!("Stack status: {other:?}"));
2589 }
2590 }
2591 }
2592 }
2593 Err(e) => {
2594 if force {
2595 Output::warning(format!(
2596 "Failed to check stack status: {e} (continuing due to --force)"
2597 ));
2598 } else {
2599 return Err(e);
2600 }
2601 }
2602 }
2603
2604 if cleanup {
2606 let git_repo_for_cleanup = GitRepository::open(&repo_root)?;
2607 match perform_simple_cleanup(&stack_manager, &git_repo_for_cleanup, false).await {
2608 Ok(result) => {
2609 if result.total_candidates > 0 {
2610 Output::section("Cleanup Summary");
2611 if !result.cleaned_branches.is_empty() {
2612 Output::success(format!(
2613 "Cleaned up {} merged branches",
2614 result.cleaned_branches.len()
2615 ));
2616 for branch in &result.cleaned_branches {
2617 Output::sub_item(format!("🗑️ Deleted: {branch}"));
2618 }
2619 }
2620 if !result.skipped_branches.is_empty() {
2621 Output::sub_item(format!(
2622 "Skipped {} branches",
2623 result.skipped_branches.len()
2624 ));
2625 }
2626 if !result.failed_branches.is_empty() {
2627 for (branch, error) in &result.failed_branches {
2628 Output::warning(format!("Failed to clean up {branch}: {error}"));
2629 }
2630 }
2631 }
2632 }
2633 Err(e) => {
2634 Output::warning(format!("Branch cleanup failed: {e}"));
2635 }
2636 }
2637 }
2638
2639 Output::success("Sync completed successfully!");
2647
2648 Ok(())
2649}
2650
2651async fn rebase_stack(
2652 interactive: bool,
2653 onto: Option<String>,
2654 strategy: Option<RebaseStrategyArg>,
2655) -> Result<()> {
2656 let current_dir = env::current_dir()
2657 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2658
2659 let repo_root = find_repository_root(¤t_dir)
2660 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2661
2662 let stack_manager = StackManager::new(&repo_root)?;
2663 let git_repo = GitRepository::open(&repo_root)?;
2664
2665 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2667 let config_path = config_dir.join("config.json");
2668 let settings = crate::config::Settings::load_from_file(&config_path)?;
2669
2670 let cascade_config = crate::config::CascadeConfig {
2672 bitbucket: Some(settings.bitbucket.clone()),
2673 git: settings.git.clone(),
2674 auth: crate::config::AuthConfig::default(),
2675 cascade: settings.cascade.clone(),
2676 };
2677
2678 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2680 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2681 })?;
2682 let stack_id = active_stack.id;
2683
2684 let active_stack = stack_manager
2685 .get_stack(&stack_id)
2686 .ok_or_else(|| CascadeError::config("Active stack not found"))?
2687 .clone();
2688
2689 if active_stack.entries.is_empty() {
2690 Output::info("Stack is empty. Nothing to rebase.");
2691 return Ok(());
2692 }
2693
2694 let rebase_strategy = if let Some(cli_strategy) = strategy {
2696 match cli_strategy {
2697 RebaseStrategyArg::ForcePush => crate::stack::RebaseStrategy::ForcePush,
2698 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2699 }
2700 } else {
2701 crate::stack::RebaseStrategy::ForcePush
2703 };
2704
2705 let original_branch = git_repo.get_current_branch().ok();
2707
2708 debug!(" Strategy: {:?}", rebase_strategy);
2709 debug!(" Interactive: {}", interactive);
2710 debug!(" Target base: {:?}", onto);
2711 debug!(" Entries: {}", active_stack.entries.len());
2712
2713 println!(); let rebase_spinner = crate::utils::spinner::Spinner::new_with_output_below(format!(
2717 "Rebasing stack: {}",
2718 active_stack.name
2719 ));
2720
2721 let options = crate::stack::RebaseOptions {
2723 strategy: rebase_strategy.clone(),
2724 interactive,
2725 target_base: onto,
2726 preserve_merges: true,
2727 auto_resolve: !interactive, max_retries: 3,
2729 skip_pull: None, original_working_branch: original_branch,
2731 progress_printer: Some(rebase_spinner.printer()),
2732 };
2733
2734 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2736
2737 if rebase_manager.is_rebase_in_progress() {
2738 Output::warning("Rebase already in progress!");
2739 Output::tip("Use 'git status' to check the current state");
2740 Output::next_steps(&[
2741 "Run 'ca stack continue-rebase' to continue",
2742 "Run 'ca stack abort-rebase' to abort",
2743 ]);
2744 rebase_spinner.stop();
2745 return Ok(());
2746 }
2747
2748 let rebase_result = rebase_manager.rebase_stack(&stack_id);
2750
2751 rebase_spinner.stop();
2753 println!(); match rebase_result {
2756 Ok(result) => {
2757 Output::success("Rebase completed!");
2758 Output::sub_item(result.get_summary());
2759
2760 if result.has_conflicts() {
2761 Output::warning(format!(
2762 "{} conflicts were resolved",
2763 result.conflicts.len()
2764 ));
2765 for conflict in &result.conflicts {
2766 Output::bullet(&conflict[..8.min(conflict.len())]);
2767 }
2768 }
2769
2770 if !result.branch_mapping.is_empty() {
2771 Output::section("Branch mapping");
2772 for (old, new) in &result.branch_mapping {
2773 Output::bullet(format!("{old} -> {new}"));
2774 }
2775
2776 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2778 let integration_stack_manager = StackManager::new(&repo_root)?;
2780 let mut integration = BitbucketIntegration::new(
2781 integration_stack_manager,
2782 cascade_config.clone(),
2783 )?;
2784
2785 match integration
2786 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2787 .await
2788 {
2789 Ok(updated_prs) => {
2790 if !updated_prs.is_empty() {
2791 println!(" 🔄 Preserved pull request history:");
2792 for pr_update in updated_prs {
2793 println!(" ✅ {pr_update}");
2794 }
2795 }
2796 }
2797 Err(e) => {
2798 Output::warning(format!("Failed to update pull requests: {e}"));
2799 Output::sub_item("You may need to manually update PRs in Bitbucket");
2800 }
2801 }
2802 }
2803 }
2804
2805 Output::success(format!(
2806 "{} commits successfully rebased",
2807 result.success_count()
2808 ));
2809
2810 if matches!(rebase_strategy, crate::stack::RebaseStrategy::ForcePush) {
2812 println!();
2813 Output::section("Next steps");
2814 if !result.branch_mapping.is_empty() {
2815 Output::numbered_item(1, "Branches have been rebased and force-pushed");
2816 Output::numbered_item(
2817 2,
2818 "Pull requests updated automatically (history preserved)",
2819 );
2820 Output::numbered_item(3, "Review the updated PRs in Bitbucket");
2821 Output::numbered_item(4, "Test your changes");
2822 } else {
2823 println!(" 1. Review the rebased stack");
2824 println!(" 2. Test your changes");
2825 println!(" 3. Submit new pull requests with 'ca stack submit'");
2826 }
2827 }
2828 }
2829 Err(e) => {
2830 warn!("❌ Rebase failed: {}", e);
2831 Output::tip(" Tips for resolving rebase issues:");
2832 println!(" - Check for uncommitted changes with 'git status'");
2833 println!(" - Ensure base branch is up to date");
2834 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2835 return Err(e);
2836 }
2837 }
2838
2839 Ok(())
2840}
2841
2842async fn continue_rebase() -> Result<()> {
2843 let current_dir = env::current_dir()
2844 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2845
2846 let repo_root = find_repository_root(¤t_dir)
2847 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2848
2849 let stack_manager = StackManager::new(&repo_root)?;
2850 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2851 let options = crate::stack::RebaseOptions::default();
2852 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2853
2854 if !rebase_manager.is_rebase_in_progress() {
2855 Output::info(" No rebase in progress");
2856 return Ok(());
2857 }
2858
2859 println!(" Continuing rebase...");
2860 match rebase_manager.continue_rebase() {
2861 Ok(_) => {
2862 Output::success(" Rebase continued successfully");
2863 println!(" Check 'ca stack rebase-status' for current state");
2864 }
2865 Err(e) => {
2866 warn!("❌ Failed to continue rebase: {}", e);
2867 Output::tip(" You may need to resolve conflicts first:");
2868 println!(" 1. Edit conflicted files");
2869 println!(" 2. Stage resolved files with 'git add'");
2870 println!(" 3. Run 'ca stack continue-rebase' again");
2871 }
2872 }
2873
2874 Ok(())
2875}
2876
2877async fn abort_rebase() -> Result<()> {
2878 let current_dir = env::current_dir()
2879 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2880
2881 let repo_root = find_repository_root(¤t_dir)
2882 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2883
2884 let stack_manager = StackManager::new(&repo_root)?;
2885 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2886 let options = crate::stack::RebaseOptions::default();
2887 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2888
2889 if !rebase_manager.is_rebase_in_progress() {
2890 Output::info(" No rebase in progress");
2891 return Ok(());
2892 }
2893
2894 Output::warning("Aborting rebase...");
2895 match rebase_manager.abort_rebase() {
2896 Ok(_) => {
2897 Output::success(" Rebase aborted successfully");
2898 println!(" Repository restored to pre-rebase state");
2899 }
2900 Err(e) => {
2901 warn!("❌ Failed to abort rebase: {}", e);
2902 println!("⚠️ You may need to manually clean up the repository state");
2903 }
2904 }
2905
2906 Ok(())
2907}
2908
2909async fn rebase_status() -> Result<()> {
2910 let current_dir = env::current_dir()
2911 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2912
2913 let repo_root = find_repository_root(¤t_dir)
2914 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2915
2916 let stack_manager = StackManager::new(&repo_root)?;
2917 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2918
2919 println!("Rebase Status");
2920
2921 let git_dir = current_dir.join(".git");
2923 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2924 || git_dir.join("rebase-merge").exists()
2925 || git_dir.join("rebase-apply").exists();
2926
2927 if rebase_in_progress {
2928 println!(" Status: 🔄 Rebase in progress");
2929 println!(
2930 "
2931📝 Actions available:"
2932 );
2933 println!(" - 'ca stack continue-rebase' to continue");
2934 println!(" - 'ca stack abort-rebase' to abort");
2935 println!(" - 'git status' to see conflicted files");
2936
2937 match git_repo.get_status() {
2939 Ok(statuses) => {
2940 let mut conflicts = Vec::new();
2941 for status in statuses.iter() {
2942 if status.status().contains(git2::Status::CONFLICTED) {
2943 if let Some(path) = status.path() {
2944 conflicts.push(path.to_string());
2945 }
2946 }
2947 }
2948
2949 if !conflicts.is_empty() {
2950 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2951 for conflict in conflicts {
2952 println!(" - {conflict}");
2953 }
2954 println!(
2955 "
2956💡 To resolve conflicts:"
2957 );
2958 println!(" 1. Edit the conflicted files");
2959 println!(" 2. Stage resolved files: git add <file>");
2960 println!(" 3. Continue: ca stack continue-rebase");
2961 }
2962 }
2963 Err(e) => {
2964 warn!("Failed to get git status: {}", e);
2965 }
2966 }
2967 } else {
2968 println!(" Status: ✅ No rebase in progress");
2969
2970 if let Some(active_stack) = stack_manager.get_active_stack() {
2972 println!(" Active stack: {}", active_stack.name);
2973 println!(" Entries: {}", active_stack.entries.len());
2974 println!(" Base branch: {}", active_stack.base_branch);
2975 }
2976 }
2977
2978 Ok(())
2979}
2980
2981async fn delete_stack(name: String, force: bool) -> Result<()> {
2982 let current_dir = env::current_dir()
2983 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2984
2985 let repo_root = find_repository_root(¤t_dir)
2986 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2987
2988 let mut manager = StackManager::new(&repo_root)?;
2989
2990 let stack = manager
2991 .get_stack_by_name(&name)
2992 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2993 let stack_id = stack.id;
2994
2995 if !force && !stack.entries.is_empty() {
2996 return Err(CascadeError::config(format!(
2997 "Stack '{}' has {} entries. Use --force to delete anyway",
2998 name,
2999 stack.entries.len()
3000 )));
3001 }
3002
3003 let deleted = manager.delete_stack(&stack_id)?;
3004
3005 Output::success(format!("Deleted stack '{}'", deleted.name));
3006 if !deleted.entries.is_empty() {
3007 Output::warning(format!("{} entries were removed", deleted.entries.len()));
3008 }
3009
3010 Ok(())
3011}
3012
3013async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
3014 let current_dir = env::current_dir()
3015 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3016
3017 let repo_root = find_repository_root(¤t_dir)
3018 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3019
3020 let mut manager = StackManager::new(&repo_root)?;
3021
3022 if let Some(name) = name {
3023 let stack = manager
3025 .get_stack_by_name(&name)
3026 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
3027
3028 let stack_id = stack.id;
3029
3030 match stack.validate() {
3032 Ok(_message) => {
3033 Output::success(format!("Stack '{}' structure validation passed", name));
3034 }
3035 Err(e) => {
3036 Output::error(format!(
3037 "Stack '{}' structure validation failed: {}",
3038 name, e
3039 ));
3040 return Err(CascadeError::config(e));
3041 }
3042 }
3043
3044 manager.handle_branch_modifications(&stack_id, fix_mode)?;
3046
3047 println!();
3048 Output::success(format!("Stack '{name}' validation completed"));
3049 Ok(())
3050 } else {
3051 Output::section("Validating all stacks");
3053 println!();
3054
3055 let all_stacks = manager.get_all_stacks();
3057 let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
3058
3059 if stack_ids.is_empty() {
3060 Output::info("No stacks found");
3061 return Ok(());
3062 }
3063
3064 let mut all_valid = true;
3065 for stack_id in stack_ids {
3066 let stack = manager.get_stack(&stack_id).unwrap();
3067 let stack_name = &stack.name;
3068
3069 println!("Checking stack '{stack_name}':");
3070
3071 match stack.validate() {
3073 Ok(message) => {
3074 Output::sub_item(format!("Structure: {message}"));
3075 }
3076 Err(e) => {
3077 Output::sub_item(format!("Structure: {e}"));
3078 all_valid = false;
3079 continue;
3080 }
3081 }
3082
3083 match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
3085 Ok(_) => {
3086 Output::sub_item("Git integrity: OK");
3087 }
3088 Err(e) => {
3089 Output::sub_item(format!("Git integrity: {e}"));
3090 all_valid = false;
3091 }
3092 }
3093 println!();
3094 }
3095
3096 if all_valid {
3097 Output::success("All stacks passed validation");
3098 } else {
3099 Output::warning("Some stacks have validation issues");
3100 return Err(CascadeError::config("Stack validation failed".to_string()));
3101 }
3102
3103 Ok(())
3104 }
3105}
3106
3107#[allow(dead_code)]
3109fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
3110 let mut unpushed = Vec::new();
3111 let head_commit = repo.get_head_commit()?;
3112 let mut current_commit = head_commit;
3113
3114 loop {
3116 let commit_hash = current_commit.id().to_string();
3117 let already_in_stack = stack
3118 .entries
3119 .iter()
3120 .any(|entry| entry.commit_hash == commit_hash);
3121
3122 if already_in_stack {
3123 break;
3124 }
3125
3126 unpushed.push(commit_hash);
3127
3128 if let Some(parent) = current_commit.parents().next() {
3130 current_commit = parent;
3131 } else {
3132 break;
3133 }
3134 }
3135
3136 unpushed.reverse(); Ok(unpushed)
3138}
3139
3140pub async fn squash_commits(
3142 repo: &GitRepository,
3143 count: usize,
3144 since_ref: Option<String>,
3145) -> Result<()> {
3146 if count <= 1 {
3147 return Ok(()); }
3149
3150 let _current_branch = repo.get_current_branch()?;
3152
3153 let rebase_range = if let Some(ref since) = since_ref {
3155 since.clone()
3156 } else {
3157 format!("HEAD~{count}")
3158 };
3159
3160 println!(" Analyzing {count} commits to create smart squash message...");
3161
3162 let head_commit = repo.get_head_commit()?;
3164 let mut commits_to_squash = Vec::new();
3165 let mut current = head_commit;
3166
3167 for _ in 0..count {
3169 commits_to_squash.push(current.clone());
3170 if current.parent_count() > 0 {
3171 current = current.parent(0).map_err(CascadeError::Git)?;
3172 } else {
3173 break;
3174 }
3175 }
3176
3177 let smart_message = generate_squash_message(&commits_to_squash)?;
3179 println!(
3180 " Smart message: {}",
3181 smart_message.lines().next().unwrap_or("")
3182 );
3183
3184 let reset_target = if since_ref.is_some() {
3186 format!("{rebase_range}~1")
3188 } else {
3189 format!("HEAD~{count}")
3191 };
3192
3193 repo.reset_soft(&reset_target)?;
3195
3196 repo.stage_all()?;
3198
3199 let new_commit_hash = repo.commit(&smart_message)?;
3201
3202 println!(
3203 " Created squashed commit: {} ({})",
3204 &new_commit_hash[..8],
3205 smart_message.lines().next().unwrap_or("")
3206 );
3207 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
3208
3209 Ok(())
3210}
3211
3212pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
3214 if commits.is_empty() {
3215 return Ok("Squashed commits".to_string());
3216 }
3217
3218 let messages: Vec<String> = commits
3220 .iter()
3221 .map(|c| c.message().unwrap_or("").trim().to_string())
3222 .filter(|m| !m.is_empty())
3223 .collect();
3224
3225 if messages.is_empty() {
3226 return Ok("Squashed commits".to_string());
3227 }
3228
3229 if let Some(last_msg) = messages.first() {
3231 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
3233 return Ok(last_msg
3234 .trim_start_matches("Final:")
3235 .trim_start_matches("final:")
3236 .trim()
3237 .to_string());
3238 }
3239 }
3240
3241 let wip_count = messages
3243 .iter()
3244 .filter(|m| {
3245 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3246 })
3247 .count();
3248
3249 if wip_count > messages.len() / 2 {
3250 let non_wip: Vec<&String> = messages
3252 .iter()
3253 .filter(|m| {
3254 !m.to_lowercase().starts_with("wip")
3255 && !m.to_lowercase().contains("work in progress")
3256 })
3257 .collect();
3258
3259 if let Some(best_msg) = non_wip.first() {
3260 return Ok(best_msg.to_string());
3261 }
3262
3263 let feature = extract_feature_from_wip(&messages);
3265 return Ok(feature);
3266 }
3267
3268 Ok(messages.first().unwrap().clone())
3270}
3271
3272pub fn extract_feature_from_wip(messages: &[String]) -> String {
3274 for msg in messages {
3276 if msg.to_lowercase().starts_with("wip:") {
3278 if let Some(rest) = msg
3279 .strip_prefix("WIP:")
3280 .or_else(|| msg.strip_prefix("wip:"))
3281 {
3282 let feature = rest.trim();
3283 if !feature.is_empty() && feature.len() > 3 {
3284 let mut chars: Vec<char> = feature.chars().collect();
3286 if let Some(first) = chars.first_mut() {
3287 *first = first.to_uppercase().next().unwrap_or(*first);
3288 }
3289 return chars.into_iter().collect();
3290 }
3291 }
3292 }
3293 }
3294
3295 if let Some(first) = messages.first() {
3297 let cleaned = first
3298 .trim_start_matches("WIP:")
3299 .trim_start_matches("wip:")
3300 .trim_start_matches("WIP")
3301 .trim_start_matches("wip")
3302 .trim();
3303
3304 if !cleaned.is_empty() {
3305 return format!("Implement {cleaned}");
3306 }
3307 }
3308
3309 format!("Squashed {} commits", messages.len())
3310}
3311
3312pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
3314 let head_commit = repo.get_head_commit()?;
3315 let since_commit = repo.get_commit(since_commit_hash)?;
3316
3317 let mut count = 0;
3318 let mut current = head_commit;
3319
3320 loop {
3322 if current.id() == since_commit.id() {
3323 break;
3324 }
3325
3326 count += 1;
3327
3328 if current.parent_count() == 0 {
3330 break; }
3332
3333 current = current.parent(0).map_err(CascadeError::Git)?;
3334 }
3335
3336 Ok(count)
3337}
3338
3339async fn land_stack(
3341 entry: Option<usize>,
3342 force: bool,
3343 dry_run: bool,
3344 auto: bool,
3345 wait_for_builds: bool,
3346 strategy: Option<MergeStrategyArg>,
3347 build_timeout: u64,
3348) -> Result<()> {
3349 let current_dir = env::current_dir()
3350 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3351
3352 let repo_root = find_repository_root(¤t_dir)
3353 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3354
3355 let stack_manager = StackManager::new(&repo_root)?;
3356
3357 let stack_id = stack_manager
3359 .get_active_stack()
3360 .map(|s| s.id)
3361 .ok_or_else(|| {
3362 CascadeError::config(
3363 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
3364 .to_string(),
3365 )
3366 })?;
3367
3368 let active_stack = stack_manager
3369 .get_active_stack()
3370 .cloned()
3371 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
3372
3373 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
3375 let config_path = config_dir.join("config.json");
3376 let settings = crate::config::Settings::load_from_file(&config_path)?;
3377
3378 let cascade_config = crate::config::CascadeConfig {
3379 bitbucket: Some(settings.bitbucket.clone()),
3380 git: settings.git.clone(),
3381 auth: crate::config::AuthConfig::default(),
3382 cascade: settings.cascade.clone(),
3383 };
3384
3385 let mut integration =
3386 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
3387
3388 let status = integration.check_enhanced_stack_status(&stack_id).await?;
3390
3391 if status.enhanced_statuses.is_empty() {
3392 println!("❌ No pull requests found to land");
3393 return Ok(());
3394 }
3395
3396 let ready_prs: Vec<_> = status
3398 .enhanced_statuses
3399 .iter()
3400 .filter(|pr_status| {
3401 if let Some(entry_num) = entry {
3403 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
3405 if pr_status.pr.from_ref.display_id != stack_entry.branch {
3407 return false;
3408 }
3409 } else {
3410 return false; }
3412 }
3413
3414 if force {
3415 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
3417 } else {
3418 pr_status.is_ready_to_land()
3419 }
3420 })
3421 .collect();
3422
3423 if ready_prs.is_empty() {
3424 if let Some(entry_num) = entry {
3425 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
3426 } else {
3427 println!("❌ No pull requests are ready to land");
3428 }
3429
3430 println!("\n🚫 Blocking Issues:");
3432 for pr_status in &status.enhanced_statuses {
3433 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
3434 let blocking = pr_status.get_blocking_reasons();
3435 if !blocking.is_empty() {
3436 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
3437 }
3438 }
3439 }
3440
3441 if !force {
3442 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
3443 }
3444 return Ok(());
3445 }
3446
3447 if dry_run {
3448 if let Some(entry_num) = entry {
3449 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
3450 } else {
3451 println!("🏃 Dry Run - PRs that would be landed:");
3452 }
3453 for pr_status in &ready_prs {
3454 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
3455 if !pr_status.is_ready_to_land() && force {
3456 let blocking = pr_status.get_blocking_reasons();
3457 println!(
3458 " ⚠️ Would force land despite: {}",
3459 blocking.join(", ")
3460 );
3461 }
3462 }
3463 return Ok(());
3464 }
3465
3466 if entry.is_some() && ready_prs.len() > 1 {
3469 println!(
3470 "🎯 {} PRs are ready to land, but landing only entry #{}",
3471 ready_prs.len(),
3472 entry.unwrap()
3473 );
3474 }
3475
3476 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
3478 strategy.unwrap_or(MergeStrategyArg::Squash).into();
3479 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3480 merge_strategy: merge_strategy.clone(),
3481 wait_for_builds,
3482 build_timeout: std::time::Duration::from_secs(build_timeout),
3483 allowed_authors: None, };
3485
3486 println!(
3488 "🚀 Landing {} PR{}...",
3489 ready_prs.len(),
3490 if ready_prs.len() == 1 { "" } else { "s" }
3491 );
3492
3493 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
3494 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
3495 );
3496
3497 let mut landed_count = 0;
3499 let mut failed_count = 0;
3500 let total_ready_prs = ready_prs.len();
3501
3502 for pr_status in ready_prs {
3503 let pr_id = pr_status.pr.id;
3504
3505 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
3506
3507 let land_result = if auto {
3508 pr_manager
3510 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
3511 .await
3512 } else {
3513 pr_manager
3515 .merge_pull_request(pr_id, merge_strategy.clone())
3516 .await
3517 .map(
3518 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
3519 pr: Box::new(pr),
3520 merge_strategy: merge_strategy.clone(),
3521 },
3522 )
3523 };
3524
3525 match land_result {
3526 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3527 println!(" ✅");
3528 landed_count += 1;
3529
3530 if landed_count < total_ready_prs {
3532 println!(" Retargeting remaining PRs to latest base...");
3533
3534 let base_branch = active_stack.base_branch.clone();
3536 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3537
3538 println!(" 📥 Updating base branch: {base_branch}");
3539 match git_repo.pull(&base_branch) {
3540 Ok(_) => println!(" ✅ Base branch updated successfully"),
3541 Err(e) => {
3542 println!(" ⚠️ Warning: Failed to update base branch: {e}");
3543 println!(
3544 " 💡 You may want to manually run: git pull origin {base_branch}"
3545 );
3546 }
3547 }
3548
3549 let temp_manager = StackManager::new(&repo_root)?;
3551 let stack_for_count = temp_manager
3552 .get_stack(&stack_id)
3553 .ok_or_else(|| CascadeError::config("Stack not found"))?;
3554 let entry_count = stack_for_count.entries.len();
3555 let plural = if entry_count == 1 { "entry" } else { "entries" };
3556
3557 println!(); let rebase_spinner = crate::utils::spinner::Spinner::new_with_output_below(
3559 format!("Retargeting {} {}", entry_count, plural),
3560 );
3561
3562 let mut rebase_manager = crate::stack::RebaseManager::new(
3563 StackManager::new(&repo_root)?,
3564 git_repo,
3565 crate::stack::RebaseOptions {
3566 strategy: crate::stack::RebaseStrategy::ForcePush,
3567 target_base: Some(base_branch.clone()),
3568 progress_printer: Some(rebase_spinner.printer()),
3569 ..Default::default()
3570 },
3571 );
3572
3573 let rebase_result = rebase_manager.rebase_stack(&stack_id);
3574
3575 rebase_spinner.stop();
3576 println!(); match rebase_result {
3579 Ok(rebase_result) => {
3580 if !rebase_result.branch_mapping.is_empty() {
3581 let retarget_config = crate::config::CascadeConfig {
3583 bitbucket: Some(settings.bitbucket.clone()),
3584 git: settings.git.clone(),
3585 auth: crate::config::AuthConfig::default(),
3586 cascade: settings.cascade.clone(),
3587 };
3588 let mut retarget_integration = BitbucketIntegration::new(
3589 StackManager::new(&repo_root)?,
3590 retarget_config,
3591 )?;
3592
3593 match retarget_integration
3594 .update_prs_after_rebase(
3595 &stack_id,
3596 &rebase_result.branch_mapping,
3597 )
3598 .await
3599 {
3600 Ok(updated_prs) => {
3601 if !updated_prs.is_empty() {
3602 println!(
3603 " ✅ Updated {} PRs with new targets",
3604 updated_prs.len()
3605 );
3606 }
3607 }
3608 Err(e) => {
3609 println!(" ⚠️ Failed to update remaining PRs: {e}");
3610 println!(
3611 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
3612 );
3613 }
3614 }
3615 }
3616 }
3617 Err(e) => {
3618 println!(" ❌ Auto-retargeting conflicts detected!");
3620 println!(" 📝 To resolve conflicts and continue landing:");
3621 println!(" 1. Resolve conflicts in the affected files");
3622 println!(" 2. Stage resolved files: git add <files>");
3623 println!(" 3. Continue the process: ca stack continue-land");
3624 println!(" 4. Or abort the operation: ca stack abort-land");
3625 println!();
3626 println!(" 💡 Check current status: ca stack land-status");
3627 println!(" ⚠️ Error details: {e}");
3628
3629 break;
3631 }
3632 }
3633 }
3634 }
3635 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3636 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3637 failed_count += 1;
3638 if !force {
3639 break;
3640 }
3641 }
3642 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3643 println!(" ❌ Failed: {error}");
3644 failed_count += 1;
3645 if !force {
3646 break;
3647 }
3648 }
3649 Err(e) => {
3650 println!(" ❌");
3651 eprintln!("Failed to land PR #{pr_id}: {e}");
3652 failed_count += 1;
3653
3654 if !force {
3655 break;
3656 }
3657 }
3658 }
3659 }
3660
3661 println!("\n🎯 Landing Summary:");
3663 println!(" ✅ Successfully landed: {landed_count}");
3664 if failed_count > 0 {
3665 println!(" ❌ Failed to land: {failed_count}");
3666 }
3667
3668 if landed_count > 0 {
3669 Output::success(" Landing operation completed!");
3670 } else {
3671 println!("❌ No PRs were successfully landed");
3672 }
3673
3674 Ok(())
3675}
3676
3677async fn auto_land_stack(
3679 force: bool,
3680 dry_run: bool,
3681 wait_for_builds: bool,
3682 strategy: Option<MergeStrategyArg>,
3683 build_timeout: u64,
3684) -> Result<()> {
3685 land_stack(
3687 None,
3688 force,
3689 dry_run,
3690 true, wait_for_builds,
3692 strategy,
3693 build_timeout,
3694 )
3695 .await
3696}
3697
3698async fn continue_land() -> Result<()> {
3699 let current_dir = env::current_dir()
3700 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3701
3702 let repo_root = find_repository_root(¤t_dir)
3703 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3704
3705 let stack_manager = StackManager::new(&repo_root)?;
3706 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3707 let options = crate::stack::RebaseOptions::default();
3708 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3709
3710 if !rebase_manager.is_rebase_in_progress() {
3711 Output::info(" No rebase in progress");
3712 return Ok(());
3713 }
3714
3715 println!(" Continuing land operation...");
3716 match rebase_manager.continue_rebase() {
3717 Ok(_) => {
3718 Output::success(" Land operation continued successfully");
3719 println!(" Check 'ca stack land-status' for current state");
3720 }
3721 Err(e) => {
3722 warn!("❌ Failed to continue land operation: {}", e);
3723 Output::tip(" You may need to resolve conflicts first:");
3724 println!(" 1. Edit conflicted files");
3725 println!(" 2. Stage resolved files with 'git add'");
3726 println!(" 3. Run 'ca stack continue-land' again");
3727 }
3728 }
3729
3730 Ok(())
3731}
3732
3733async fn abort_land() -> Result<()> {
3734 let current_dir = env::current_dir()
3735 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3736
3737 let repo_root = find_repository_root(¤t_dir)
3738 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3739
3740 let stack_manager = StackManager::new(&repo_root)?;
3741 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3742 let options = crate::stack::RebaseOptions::default();
3743 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3744
3745 if !rebase_manager.is_rebase_in_progress() {
3746 Output::info(" No rebase in progress");
3747 return Ok(());
3748 }
3749
3750 println!("⚠️ Aborting land operation...");
3751 match rebase_manager.abort_rebase() {
3752 Ok(_) => {
3753 Output::success(" Land operation aborted successfully");
3754 println!(" Repository restored to pre-land state");
3755 }
3756 Err(e) => {
3757 warn!("❌ Failed to abort land operation: {}", e);
3758 println!("⚠️ You may need to manually clean up the repository state");
3759 }
3760 }
3761
3762 Ok(())
3763}
3764
3765async fn land_status() -> Result<()> {
3766 let current_dir = env::current_dir()
3767 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3768
3769 let repo_root = find_repository_root(¤t_dir)
3770 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3771
3772 let stack_manager = StackManager::new(&repo_root)?;
3773 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3774
3775 println!("Land Status");
3776
3777 let git_dir = repo_root.join(".git");
3779 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3780 || git_dir.join("rebase-merge").exists()
3781 || git_dir.join("rebase-apply").exists();
3782
3783 if land_in_progress {
3784 println!(" Status: 🔄 Land operation in progress");
3785 println!(
3786 "
3787📝 Actions available:"
3788 );
3789 println!(" - 'ca stack continue-land' to continue");
3790 println!(" - 'ca stack abort-land' to abort");
3791 println!(" - 'git status' to see conflicted files");
3792
3793 match git_repo.get_status() {
3795 Ok(statuses) => {
3796 let mut conflicts = Vec::new();
3797 for status in statuses.iter() {
3798 if status.status().contains(git2::Status::CONFLICTED) {
3799 if let Some(path) = status.path() {
3800 conflicts.push(path.to_string());
3801 }
3802 }
3803 }
3804
3805 if !conflicts.is_empty() {
3806 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3807 for conflict in conflicts {
3808 println!(" - {conflict}");
3809 }
3810 println!(
3811 "
3812💡 To resolve conflicts:"
3813 );
3814 println!(" 1. Edit the conflicted files");
3815 println!(" 2. Stage resolved files: git add <file>");
3816 println!(" 3. Continue: ca stack continue-land");
3817 }
3818 }
3819 Err(e) => {
3820 warn!("Failed to get git status: {}", e);
3821 }
3822 }
3823 } else {
3824 println!(" Status: ✅ No land operation in progress");
3825
3826 if let Some(active_stack) = stack_manager.get_active_stack() {
3828 println!(" Active stack: {}", active_stack.name);
3829 println!(" Entries: {}", active_stack.entries.len());
3830 println!(" Base branch: {}", active_stack.base_branch);
3831 }
3832 }
3833
3834 Ok(())
3835}
3836
3837async fn repair_stack_data() -> Result<()> {
3838 let current_dir = env::current_dir()
3839 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3840
3841 let repo_root = find_repository_root(¤t_dir)
3842 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3843
3844 let mut stack_manager = StackManager::new(&repo_root)?;
3845
3846 println!("🔧 Repairing stack data consistency...");
3847
3848 stack_manager.repair_all_stacks()?;
3849
3850 Output::success(" Stack data consistency repaired successfully!");
3851 Output::tip(" Run 'ca stack --mergeable' to see updated status");
3852
3853 Ok(())
3854}
3855
3856async fn cleanup_branches(
3858 dry_run: bool,
3859 force: bool,
3860 include_stale: bool,
3861 stale_days: u32,
3862 cleanup_remote: bool,
3863 include_non_stack: bool,
3864 verbose: bool,
3865) -> Result<()> {
3866 let current_dir = env::current_dir()
3867 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3868
3869 let repo_root = find_repository_root(¤t_dir)
3870 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3871
3872 let stack_manager = StackManager::new(&repo_root)?;
3873 let git_repo = GitRepository::open(&repo_root)?;
3874
3875 let result = perform_cleanup(
3876 &stack_manager,
3877 &git_repo,
3878 dry_run,
3879 force,
3880 include_stale,
3881 stale_days,
3882 cleanup_remote,
3883 include_non_stack,
3884 verbose,
3885 )
3886 .await?;
3887
3888 if result.total_candidates == 0 {
3890 Output::success("No branches found that need cleanup");
3891 return Ok(());
3892 }
3893
3894 Output::section("Cleanup Results");
3895
3896 if dry_run {
3897 Output::sub_item(format!(
3898 "Found {} branches that would be cleaned up",
3899 result.total_candidates
3900 ));
3901 } else {
3902 if !result.cleaned_branches.is_empty() {
3903 Output::success(format!(
3904 "Successfully cleaned up {} branches",
3905 result.cleaned_branches.len()
3906 ));
3907 for branch in &result.cleaned_branches {
3908 Output::sub_item(format!("🗑️ Deleted: {branch}"));
3909 }
3910 }
3911
3912 if !result.skipped_branches.is_empty() {
3913 Output::sub_item(format!(
3914 "Skipped {} branches",
3915 result.skipped_branches.len()
3916 ));
3917 if verbose {
3918 for (branch, reason) in &result.skipped_branches {
3919 Output::sub_item(format!("⏭️ {branch}: {reason}"));
3920 }
3921 }
3922 }
3923
3924 if !result.failed_branches.is_empty() {
3925 Output::warning(format!(
3926 "Failed to clean up {} branches",
3927 result.failed_branches.len()
3928 ));
3929 for (branch, error) in &result.failed_branches {
3930 Output::sub_item(format!("❌ {branch}: {error}"));
3931 }
3932 }
3933 }
3934
3935 Ok(())
3936}
3937
3938#[allow(clippy::too_many_arguments)]
3940async fn perform_cleanup(
3941 stack_manager: &StackManager,
3942 git_repo: &GitRepository,
3943 dry_run: bool,
3944 force: bool,
3945 include_stale: bool,
3946 stale_days: u32,
3947 cleanup_remote: bool,
3948 include_non_stack: bool,
3949 verbose: bool,
3950) -> Result<CleanupResult> {
3951 let options = CleanupOptions {
3952 dry_run,
3953 force,
3954 include_stale,
3955 cleanup_remote,
3956 stale_threshold_days: stale_days,
3957 cleanup_non_stack: include_non_stack,
3958 };
3959
3960 let stack_manager_copy = StackManager::new(stack_manager.repo_path())?;
3961 let git_repo_copy = GitRepository::open(git_repo.path())?;
3962 let mut cleanup_manager = CleanupManager::new(stack_manager_copy, git_repo_copy, options);
3963
3964 let candidates = cleanup_manager.find_cleanup_candidates()?;
3966
3967 if candidates.is_empty() {
3968 return Ok(CleanupResult {
3969 cleaned_branches: Vec::new(),
3970 failed_branches: Vec::new(),
3971 skipped_branches: Vec::new(),
3972 total_candidates: 0,
3973 });
3974 }
3975
3976 if verbose || dry_run {
3978 Output::section("Cleanup Candidates");
3979 for candidate in &candidates {
3980 let reason_icon = match candidate.reason {
3981 crate::stack::CleanupReason::FullyMerged => "🔀",
3982 crate::stack::CleanupReason::StackEntryMerged => "✅",
3983 crate::stack::CleanupReason::Stale => "⏰",
3984 crate::stack::CleanupReason::Orphaned => "👻",
3985 };
3986
3987 Output::sub_item(format!(
3988 "{} {} - {} ({})",
3989 reason_icon,
3990 candidate.branch_name,
3991 candidate.reason_to_string(),
3992 candidate.safety_info
3993 ));
3994 }
3995 }
3996
3997 if !force && !dry_run && !candidates.is_empty() {
3999 Output::warning(format!("About to delete {} branches", candidates.len()));
4000
4001 let preview_count = 5.min(candidates.len());
4003 for candidate in candidates.iter().take(preview_count) {
4004 println!(" • {}", candidate.branch_name);
4005 }
4006 if candidates.len() > preview_count {
4007 println!(" ... and {} more", candidates.len() - preview_count);
4008 }
4009 println!(); let should_continue = Confirm::with_theme(&ColorfulTheme::default())
4013 .with_prompt("Continue with branch cleanup?")
4014 .default(false)
4015 .interact()
4016 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
4017
4018 if !should_continue {
4019 Output::sub_item("Cleanup cancelled");
4020 return Ok(CleanupResult {
4021 cleaned_branches: Vec::new(),
4022 failed_branches: Vec::new(),
4023 skipped_branches: Vec::new(),
4024 total_candidates: candidates.len(),
4025 });
4026 }
4027 }
4028
4029 cleanup_manager.perform_cleanup(&candidates)
4031}
4032
4033async fn perform_simple_cleanup(
4035 stack_manager: &StackManager,
4036 git_repo: &GitRepository,
4037 dry_run: bool,
4038) -> Result<CleanupResult> {
4039 perform_cleanup(
4040 stack_manager,
4041 git_repo,
4042 dry_run,
4043 false, false, 30, false, false, false, )
4050 .await
4051}
4052
4053async fn analyze_commits_for_safeguards(
4055 commits_to_push: &[String],
4056 repo: &GitRepository,
4057 dry_run: bool,
4058) -> Result<()> {
4059 const LARGE_COMMIT_THRESHOLD: usize = 10;
4060 const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
4061
4062 if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
4064 println!(
4065 "⚠️ Warning: About to push {} commits to stack",
4066 commits_to_push.len()
4067 );
4068 println!(" This may indicate a merge commit issue or unexpected commit range.");
4069 println!(" Large commit counts often result from merging instead of rebasing.");
4070
4071 if !dry_run && !confirm_large_push(commits_to_push.len())? {
4072 return Err(CascadeError::config("Push cancelled by user"));
4073 }
4074 }
4075
4076 let commit_objects: Result<Vec<_>> = commits_to_push
4078 .iter()
4079 .map(|hash| repo.get_commit(hash))
4080 .collect();
4081 let commit_objects = commit_objects?;
4082
4083 let merge_commits: Vec<_> = commit_objects
4085 .iter()
4086 .filter(|c| c.parent_count() > 1)
4087 .collect();
4088
4089 if !merge_commits.is_empty() {
4090 println!(
4091 "⚠️ Warning: {} merge commits detected in push",
4092 merge_commits.len()
4093 );
4094 println!(" This often indicates you merged instead of rebased.");
4095 println!(" Consider using 'ca sync' to rebase on the base branch.");
4096 println!(" Merge commits in stacks can cause confusion and duplicate work.");
4097 }
4098
4099 if commit_objects.len() > 1 {
4101 let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
4102 let newest_commit_time = commit_objects.last().unwrap().time().seconds();
4103 let time_span = newest_commit_time - oldest_commit_time;
4104
4105 if time_span > WEEK_IN_SECONDS {
4106 let days = time_span / (24 * 3600);
4107 println!("⚠️ Warning: Commits span {days} days");
4108 println!(" This may indicate merged history rather than new work.");
4109 println!(" Recent work should typically span hours or days, not weeks.");
4110 }
4111 }
4112
4113 if commits_to_push.len() > 5 {
4115 Output::tip(" Tip: If you only want recent commits, use:");
4116 println!(
4117 " ca push --since HEAD~{} # pushes last {} commits",
4118 std::cmp::min(commits_to_push.len(), 5),
4119 std::cmp::min(commits_to_push.len(), 5)
4120 );
4121 println!(" ca push --commits <hash1>,<hash2> # pushes specific commits");
4122 println!(" ca push --dry-run # preview what would be pushed");
4123 }
4124
4125 if dry_run {
4127 println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
4128 for (i, (commit_hash, commit_obj)) in commits_to_push
4129 .iter()
4130 .zip(commit_objects.iter())
4131 .enumerate()
4132 {
4133 let summary = commit_obj.summary().unwrap_or("(no message)");
4134 let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
4135 println!(" {}: {} ({})", i + 1, summary, short_hash);
4136 }
4137 Output::tip(" Run without --dry-run to actually push these commits.");
4138 }
4139
4140 Ok(())
4141}
4142
4143fn confirm_large_push(count: usize) -> Result<bool> {
4145 let should_continue = Confirm::with_theme(&ColorfulTheme::default())
4147 .with_prompt(format!("Continue pushing {count} commits?"))
4148 .default(false)
4149 .interact()
4150 .map_err(|e| CascadeError::config(format!("Failed to get user confirmation: {e}")))?;
4151
4152 Ok(should_continue)
4153}
4154
4155#[cfg(test)]
4156mod tests {
4157 use super::*;
4158 use std::process::Command;
4159 use tempfile::TempDir;
4160
4161 fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
4162 let temp_dir = TempDir::new()
4163 .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
4164 let repo_path = temp_dir.path().to_path_buf();
4165
4166 let output = Command::new("git")
4168 .args(["init"])
4169 .current_dir(&repo_path)
4170 .output()
4171 .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
4172 if !output.status.success() {
4173 return Err(CascadeError::config("Git init failed".to_string()));
4174 }
4175
4176 let output = Command::new("git")
4177 .args(["config", "user.name", "Test User"])
4178 .current_dir(&repo_path)
4179 .output()
4180 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4181 if !output.status.success() {
4182 return Err(CascadeError::config(
4183 "Git config user.name failed".to_string(),
4184 ));
4185 }
4186
4187 let output = Command::new("git")
4188 .args(["config", "user.email", "test@example.com"])
4189 .current_dir(&repo_path)
4190 .output()
4191 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
4192 if !output.status.success() {
4193 return Err(CascadeError::config(
4194 "Git config user.email failed".to_string(),
4195 ));
4196 }
4197
4198 std::fs::write(repo_path.join("README.md"), "# Test")
4200 .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
4201 let output = Command::new("git")
4202 .args(["add", "."])
4203 .current_dir(&repo_path)
4204 .output()
4205 .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
4206 if !output.status.success() {
4207 return Err(CascadeError::config("Git add failed".to_string()));
4208 }
4209
4210 let output = Command::new("git")
4211 .args(["commit", "-m", "Initial commit"])
4212 .current_dir(&repo_path)
4213 .output()
4214 .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
4215 if !output.status.success() {
4216 return Err(CascadeError::config("Git commit failed".to_string()));
4217 }
4218
4219 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
4221
4222 Ok((temp_dir, repo_path))
4223 }
4224
4225 #[tokio::test]
4226 async fn test_create_stack() {
4227 let (temp_dir, repo_path) = match create_test_repo() {
4228 Ok(repo) => repo,
4229 Err(_) => {
4230 println!("Skipping test due to git environment setup failure");
4231 return;
4232 }
4233 };
4234 let _ = &temp_dir;
4236
4237 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4241 match env::set_current_dir(&repo_path) {
4242 Ok(_) => {
4243 let result = create_stack(
4244 "test-stack".to_string(),
4245 None, Some("Test description".to_string()),
4247 )
4248 .await;
4249
4250 if let Ok(orig) = original_dir {
4252 let _ = env::set_current_dir(orig);
4253 }
4254
4255 assert!(
4256 result.is_ok(),
4257 "Stack creation should succeed in initialized repository"
4258 );
4259 }
4260 Err(_) => {
4261 println!("Skipping test due to directory access restrictions");
4263 }
4264 }
4265 }
4266
4267 #[tokio::test]
4268 async fn test_list_empty_stacks() {
4269 let (temp_dir, repo_path) = match create_test_repo() {
4270 Ok(repo) => repo,
4271 Err(_) => {
4272 println!("Skipping test due to git environment setup failure");
4273 return;
4274 }
4275 };
4276 let _ = &temp_dir;
4278
4279 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4283 match env::set_current_dir(&repo_path) {
4284 Ok(_) => {
4285 let result = list_stacks(false, false, None).await;
4286
4287 if let Ok(orig) = original_dir {
4289 let _ = env::set_current_dir(orig);
4290 }
4291
4292 assert!(
4293 result.is_ok(),
4294 "Listing stacks should succeed in initialized repository"
4295 );
4296 }
4297 Err(_) => {
4298 println!("Skipping test due to directory access restrictions");
4300 }
4301 }
4302 }
4303
4304 #[test]
4307 fn test_extract_feature_from_wip_basic() {
4308 let messages = vec![
4309 "WIP: add authentication".to_string(),
4310 "WIP: implement login flow".to_string(),
4311 ];
4312
4313 let result = extract_feature_from_wip(&messages);
4314 assert_eq!(result, "Add authentication");
4315 }
4316
4317 #[test]
4318 fn test_extract_feature_from_wip_capitalize() {
4319 let messages = vec!["WIP: fix user validation bug".to_string()];
4320
4321 let result = extract_feature_from_wip(&messages);
4322 assert_eq!(result, "Fix user validation bug");
4323 }
4324
4325 #[test]
4326 fn test_extract_feature_from_wip_fallback() {
4327 let messages = vec![
4328 "WIP user interface changes".to_string(),
4329 "wip: css styling".to_string(),
4330 ];
4331
4332 let result = extract_feature_from_wip(&messages);
4333 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
4335 }
4336
4337 #[test]
4338 fn test_extract_feature_from_wip_empty() {
4339 let messages = vec![];
4340
4341 let result = extract_feature_from_wip(&messages);
4342 assert_eq!(result, "Squashed 0 commits");
4343 }
4344
4345 #[test]
4346 fn test_extract_feature_from_wip_short_message() {
4347 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
4350 assert!(result.starts_with("Implement") || result.contains("Squashed"));
4351 }
4352
4353 #[test]
4356 fn test_squash_message_final_strategy() {
4357 let messages = [
4361 "Final: implement user authentication system".to_string(),
4362 "WIP: add tests".to_string(),
4363 "WIP: fix validation".to_string(),
4364 ];
4365
4366 assert!(messages[0].starts_with("Final:"));
4368
4369 let extracted = messages[0].trim_start_matches("Final:").trim();
4371 assert_eq!(extracted, "implement user authentication system");
4372 }
4373
4374 #[test]
4375 fn test_squash_message_wip_detection() {
4376 let messages = [
4377 "WIP: start feature".to_string(),
4378 "WIP: continue work".to_string(),
4379 "WIP: almost done".to_string(),
4380 "Regular commit message".to_string(),
4381 ];
4382
4383 let wip_count = messages
4384 .iter()
4385 .filter(|m| {
4386 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
4387 })
4388 .count();
4389
4390 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
4395 .iter()
4396 .filter(|m| {
4397 !m.to_lowercase().starts_with("wip")
4398 && !m.to_lowercase().contains("work in progress")
4399 })
4400 .collect();
4401
4402 assert_eq!(non_wip.len(), 1);
4403 assert_eq!(non_wip[0], "Regular commit message");
4404 }
4405
4406 #[test]
4407 fn test_squash_message_all_wip() {
4408 let messages = vec![
4409 "WIP: add feature A".to_string(),
4410 "WIP: add feature B".to_string(),
4411 "WIP: finish implementation".to_string(),
4412 ];
4413
4414 let result = extract_feature_from_wip(&messages);
4415 assert_eq!(result, "Add feature A");
4417 }
4418
4419 #[test]
4420 fn test_squash_message_edge_cases() {
4421 let empty_messages: Vec<String> = vec![];
4423 let result = extract_feature_from_wip(&empty_messages);
4424 assert_eq!(result, "Squashed 0 commits");
4425
4426 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
4428 let result = extract_feature_from_wip(&whitespace_messages);
4429 assert!(result.contains("Squashed") || result.contains("Implement"));
4430
4431 let mixed_case = vec!["wip: Add Feature".to_string()];
4433 let result = extract_feature_from_wip(&mixed_case);
4434 assert_eq!(result, "Add Feature");
4435 }
4436
4437 #[tokio::test]
4440 async fn test_auto_land_wrapper() {
4441 let (temp_dir, repo_path) = match create_test_repo() {
4443 Ok(repo) => repo,
4444 Err(_) => {
4445 println!("Skipping test due to git environment setup failure");
4446 return;
4447 }
4448 };
4449 let _ = &temp_dir;
4451
4452 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
4454 .expect("Failed to initialize Cascade in test repo");
4455
4456 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4457 match env::set_current_dir(&repo_path) {
4458 Ok(_) => {
4459 let result = create_stack(
4461 "test-stack".to_string(),
4462 None,
4463 Some("Test stack for auto-land".to_string()),
4464 )
4465 .await;
4466
4467 if let Ok(orig) = original_dir {
4468 let _ = env::set_current_dir(orig);
4469 }
4470
4471 assert!(
4474 result.is_ok(),
4475 "Stack creation should succeed in initialized repository"
4476 );
4477 }
4478 Err(_) => {
4479 println!("Skipping test due to directory access restrictions");
4480 }
4481 }
4482 }
4483
4484 #[test]
4485 fn test_auto_land_action_enum() {
4486 use crate::cli::commands::stack::StackAction;
4488
4489 let _action = StackAction::AutoLand {
4491 force: false,
4492 dry_run: true,
4493 wait_for_builds: true,
4494 strategy: Some(MergeStrategyArg::Squash),
4495 build_timeout: 1800,
4496 };
4497
4498 }
4500
4501 #[test]
4502 fn test_merge_strategy_conversion() {
4503 let squash_strategy = MergeStrategyArg::Squash;
4505 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
4506
4507 match merge_strategy {
4508 crate::bitbucket::pull_request::MergeStrategy::Squash => {
4509 }
4511 _ => unreachable!("SquashStrategyArg only has Squash variant"),
4512 }
4513
4514 let merge_strategy = MergeStrategyArg::Merge;
4515 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
4516
4517 match converted {
4518 crate::bitbucket::pull_request::MergeStrategy::Merge => {
4519 }
4521 _ => unreachable!("MergeStrategyArg::Merge maps to MergeStrategy::Merge"),
4522 }
4523 }
4524
4525 #[test]
4526 fn test_auto_merge_conditions_structure() {
4527 use std::time::Duration;
4529
4530 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
4531 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
4532 wait_for_builds: true,
4533 build_timeout: Duration::from_secs(1800),
4534 allowed_authors: None,
4535 };
4536
4537 assert!(conditions.wait_for_builds);
4539 assert_eq!(conditions.build_timeout.as_secs(), 1800);
4540 assert!(conditions.allowed_authors.is_none());
4541 assert!(matches!(
4542 conditions.merge_strategy,
4543 crate::bitbucket::pull_request::MergeStrategy::Squash
4544 ));
4545 }
4546
4547 #[test]
4548 fn test_polling_constants() {
4549 use std::time::Duration;
4551
4552 let expected_polling_interval = Duration::from_secs(30);
4554
4555 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
4560
4561 #[test]
4562 fn test_build_timeout_defaults() {
4563 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
4566 let timeout_value = 1800u64;
4568 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
4571
4572 #[test]
4573 fn test_scattered_commit_detection() {
4574 use std::collections::HashSet;
4575
4576 let mut source_branches = HashSet::new();
4578 source_branches.insert("feature-branch-1".to_string());
4579 source_branches.insert("feature-branch-2".to_string());
4580 source_branches.insert("feature-branch-3".to_string());
4581
4582 let single_branch = HashSet::from(["main".to_string()]);
4584 assert_eq!(single_branch.len(), 1);
4585
4586 assert!(source_branches.len() > 1);
4588 assert_eq!(source_branches.len(), 3);
4589
4590 assert!(source_branches.contains("feature-branch-1"));
4592 assert!(source_branches.contains("feature-branch-2"));
4593 assert!(source_branches.contains("feature-branch-3"));
4594 }
4595
4596 #[test]
4597 fn test_source_branch_tracking() {
4598 let branch_a = "feature-work";
4602 let branch_b = "feature-work";
4603 assert_eq!(branch_a, branch_b);
4604
4605 let branch_1 = "feature-ui";
4607 let branch_2 = "feature-api";
4608 assert_ne!(branch_1, branch_2);
4609
4610 assert!(branch_1.starts_with("feature-"));
4612 assert!(branch_2.starts_with("feature-"));
4613 }
4614
4615 #[tokio::test]
4618 async fn test_push_default_behavior() {
4619 let (temp_dir, repo_path) = match create_test_repo() {
4621 Ok(repo) => repo,
4622 Err(_) => {
4623 println!("Skipping test due to git environment setup failure");
4624 return;
4625 }
4626 };
4627 let _ = &temp_dir;
4629
4630 if !repo_path.exists() {
4632 println!("Skipping test due to temporary directory creation issue");
4633 return;
4634 }
4635
4636 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
4638
4639 match env::set_current_dir(&repo_path) {
4640 Ok(_) => {
4641 let result = push_to_stack(
4643 None, None, None, None, None, None, None, false, false, false, )
4654 .await;
4655
4656 if let Ok(orig) = original_dir {
4658 let _ = env::set_current_dir(orig);
4659 }
4660
4661 match &result {
4663 Err(e) => {
4664 let error_msg = e.to_string();
4665 assert!(
4667 error_msg.contains("No active stack")
4668 || error_msg.contains("config")
4669 || error_msg.contains("current directory")
4670 || error_msg.contains("Not a git repository")
4671 || error_msg.contains("could not find repository"),
4672 "Expected 'No active stack' or repository error, got: {error_msg}"
4673 );
4674 }
4675 Ok(_) => {
4676 println!(
4678 "Push succeeded unexpectedly - test environment may have active stack"
4679 );
4680 }
4681 }
4682 }
4683 Err(_) => {
4684 println!("Skipping test due to directory access restrictions");
4686 }
4687 }
4688
4689 let push_action = StackAction::Push {
4691 branch: None,
4692 message: None,
4693 commit: None,
4694 since: None,
4695 commits: None,
4696 squash: None,
4697 squash_since: None,
4698 auto_branch: false,
4699 allow_base_branch: false,
4700 dry_run: false,
4701 };
4702
4703 assert!(matches!(
4704 push_action,
4705 StackAction::Push {
4706 branch: None,
4707 message: None,
4708 commit: None,
4709 since: None,
4710 commits: None,
4711 squash: None,
4712 squash_since: None,
4713 auto_branch: false,
4714 allow_base_branch: false,
4715 dry_run: false
4716 }
4717 ));
4718 }
4719
4720 #[tokio::test]
4721 async fn test_submit_default_behavior() {
4722 let (temp_dir, repo_path) = match create_test_repo() {
4724 Ok(repo) => repo,
4725 Err(_) => {
4726 println!("Skipping test due to git environment setup failure");
4727 return;
4728 }
4729 };
4730 let _ = &temp_dir;
4732
4733 if !repo_path.exists() {
4735 println!("Skipping test due to temporary directory creation issue");
4736 return;
4737 }
4738
4739 let original_dir = match env::current_dir() {
4741 Ok(dir) => dir,
4742 Err(_) => {
4743 println!("Skipping test due to current directory access restrictions");
4744 return;
4745 }
4746 };
4747
4748 match env::set_current_dir(&repo_path) {
4749 Ok(_) => {
4750 let result = submit_entry(
4752 None, None, None, None, false, true, )
4759 .await;
4760
4761 let _ = env::set_current_dir(original_dir);
4763
4764 match &result {
4766 Err(e) => {
4767 let error_msg = e.to_string();
4768 assert!(
4770 error_msg.contains("No active stack")
4771 || error_msg.contains("config")
4772 || error_msg.contains("current directory")
4773 || error_msg.contains("Not a git repository")
4774 || error_msg.contains("could not find repository"),
4775 "Expected 'No active stack' or repository error, got: {error_msg}"
4776 );
4777 }
4778 Ok(_) => {
4779 println!("Submit succeeded unexpectedly - test environment may have active stack");
4781 }
4782 }
4783 }
4784 Err(_) => {
4785 println!("Skipping test due to directory access restrictions");
4787 }
4788 }
4789
4790 let submit_action = StackAction::Submit {
4792 entry: None,
4793 title: None,
4794 description: None,
4795 range: None,
4796 draft: true, open: true,
4798 };
4799
4800 assert!(matches!(
4801 submit_action,
4802 StackAction::Submit {
4803 entry: None,
4804 title: None,
4805 description: None,
4806 range: None,
4807 draft: true, open: true
4809 }
4810 ));
4811 }
4812
4813 #[test]
4814 fn test_targeting_options_still_work() {
4815 let commits = "abc123,def456,ghi789";
4819 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4820 assert_eq!(parsed.len(), 3);
4821 assert_eq!(parsed[0], "abc123");
4822 assert_eq!(parsed[1], "def456");
4823 assert_eq!(parsed[2], "ghi789");
4824
4825 let range = "1-3";
4827 assert!(range.contains('-'));
4828 let parts: Vec<&str> = range.split('-').collect();
4829 assert_eq!(parts.len(), 2);
4830
4831 let since_ref = "HEAD~3";
4833 assert!(since_ref.starts_with("HEAD"));
4834 assert!(since_ref.contains('~'));
4835 }
4836
4837 #[test]
4838 fn test_command_flow_logic() {
4839 assert!(matches!(
4841 StackAction::Push {
4842 branch: None,
4843 message: None,
4844 commit: None,
4845 since: None,
4846 commits: None,
4847 squash: None,
4848 squash_since: None,
4849 auto_branch: false,
4850 allow_base_branch: false,
4851 dry_run: false
4852 },
4853 StackAction::Push { .. }
4854 ));
4855
4856 assert!(matches!(
4857 StackAction::Submit {
4858 entry: None,
4859 title: None,
4860 description: None,
4861 range: None,
4862 draft: false,
4863 open: true
4864 },
4865 StackAction::Submit { .. }
4866 ));
4867 }
4868
4869 #[tokio::test]
4870 async fn test_deactivate_command_structure() {
4871 let deactivate_action = StackAction::Deactivate { force: false };
4873
4874 assert!(matches!(
4876 deactivate_action,
4877 StackAction::Deactivate { force: false }
4878 ));
4879
4880 let force_deactivate = StackAction::Deactivate { force: true };
4882 assert!(matches!(
4883 force_deactivate,
4884 StackAction::Deactivate { force: true }
4885 ));
4886 }
4887}