1use crate::bitbucket::BitbucketIntegration;
2use crate::cli::output::Output;
3use crate::errors::{CascadeError, Result};
4use crate::git::{find_repository_root, GitRepository};
5use crate::stack::{StackManager, StackStatus};
6use clap::{Subcommand, ValueEnum};
7use indicatif::{ProgressBar, ProgressStyle};
8use std::env;
9use std::io::{self, Write};
10use tracing::{info, warn};
11
12#[derive(ValueEnum, Clone, Debug)]
14pub enum RebaseStrategyArg {
15 BranchVersioning,
17 CherryPick,
19 ThreeWayMerge,
21 Interactive,
23}
24
25#[derive(ValueEnum, Clone, Debug)]
26pub enum MergeStrategyArg {
27 Merge,
29 Squash,
31 FastForward,
33}
34
35impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
36 fn from(arg: MergeStrategyArg) -> Self {
37 match arg {
38 MergeStrategyArg::Merge => Self::Merge,
39 MergeStrategyArg::Squash => Self::Squash,
40 MergeStrategyArg::FastForward => Self::FastForward,
41 }
42 }
43}
44
45#[derive(Debug, Subcommand)]
46pub enum StackAction {
47 Create {
49 name: String,
51 #[arg(long, short)]
53 base: Option<String>,
54 #[arg(long, short)]
56 description: Option<String>,
57 },
58
59 List {
61 #[arg(long, short)]
63 verbose: bool,
64 #[arg(long)]
66 active: bool,
67 #[arg(long)]
69 format: Option<String>,
70 },
71
72 Switch {
74 name: String,
76 },
77
78 Deactivate {
80 #[arg(long)]
82 force: bool,
83 },
84
85 Show {
87 #[arg(short, long)]
89 verbose: bool,
90 #[arg(short, long)]
92 mergeable: bool,
93 },
94
95 Push {
97 #[arg(long, short)]
99 branch: Option<String>,
100 #[arg(long, short)]
102 message: Option<String>,
103 #[arg(long)]
105 commit: Option<String>,
106 #[arg(long)]
108 since: Option<String>,
109 #[arg(long)]
111 commits: Option<String>,
112 #[arg(long, num_args = 0..=1, default_missing_value = "0")]
114 squash: Option<usize>,
115 #[arg(long)]
117 squash_since: Option<String>,
118 #[arg(long)]
120 auto_branch: bool,
121 #[arg(long)]
123 allow_base_branch: bool,
124 #[arg(long)]
126 dry_run: bool,
127 },
128
129 Pop {
131 #[arg(long)]
133 keep_branch: bool,
134 },
135
136 Submit {
138 entry: Option<usize>,
140 #[arg(long, short)]
142 title: Option<String>,
143 #[arg(long, short)]
145 description: Option<String>,
146 #[arg(long)]
148 range: Option<String>,
149 #[arg(long)]
151 draft: bool,
152 },
153
154 Status {
156 name: Option<String>,
158 },
159
160 Prs {
162 #[arg(long)]
164 state: Option<String>,
165 #[arg(long, short)]
167 verbose: bool,
168 },
169
170 Check {
172 #[arg(long)]
174 force: bool,
175 },
176
177 Sync {
179 #[arg(long)]
181 force: bool,
182 #[arg(long)]
184 skip_cleanup: bool,
185 #[arg(long, short)]
187 interactive: bool,
188 },
189
190 Rebase {
192 #[arg(long, short)]
194 interactive: bool,
195 #[arg(long)]
197 onto: Option<String>,
198 #[arg(long, value_enum)]
200 strategy: Option<RebaseStrategyArg>,
201 },
202
203 ContinueRebase,
205
206 AbortRebase,
208
209 RebaseStatus,
211
212 Delete {
214 name: String,
216 #[arg(long)]
218 force: bool,
219 },
220
221 Validate {
233 name: Option<String>,
235 #[arg(long)]
237 fix: Option<String>,
238 },
239
240 Land {
242 entry: Option<usize>,
244 #[arg(short, long)]
246 force: bool,
247 #[arg(short, long)]
249 dry_run: bool,
250 #[arg(long)]
252 auto: bool,
253 #[arg(long)]
255 wait_for_builds: bool,
256 #[arg(long, value_enum, default_value = "squash")]
258 strategy: Option<MergeStrategyArg>,
259 #[arg(long, default_value = "1800")]
261 build_timeout: u64,
262 },
263
264 AutoLand {
266 #[arg(short, long)]
268 force: bool,
269 #[arg(short, long)]
271 dry_run: bool,
272 #[arg(long)]
274 wait_for_builds: bool,
275 #[arg(long, value_enum, default_value = "squash")]
277 strategy: Option<MergeStrategyArg>,
278 #[arg(long, default_value = "1800")]
280 build_timeout: u64,
281 },
282
283 ListPrs {
285 #[arg(short, long)]
287 state: Option<String>,
288 #[arg(short, long)]
290 verbose: bool,
291 },
292
293 ContinueLand,
295
296 AbortLand,
298
299 LandStatus,
301
302 Repair,
304}
305
306pub async fn run(action: StackAction) -> Result<()> {
307 match action {
308 StackAction::Create {
309 name,
310 base,
311 description,
312 } => create_stack(name, base, description).await,
313 StackAction::List {
314 verbose,
315 active,
316 format,
317 } => list_stacks(verbose, active, format).await,
318 StackAction::Switch { name } => switch_stack(name).await,
319 StackAction::Deactivate { force } => deactivate_stack(force).await,
320 StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
321 StackAction::Push {
322 branch,
323 message,
324 commit,
325 since,
326 commits,
327 squash,
328 squash_since,
329 auto_branch,
330 allow_base_branch,
331 dry_run,
332 } => {
333 push_to_stack(
334 branch,
335 message,
336 commit,
337 since,
338 commits,
339 squash,
340 squash_since,
341 auto_branch,
342 allow_base_branch,
343 dry_run,
344 )
345 .await
346 }
347 StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
348 StackAction::Submit {
349 entry,
350 title,
351 description,
352 range,
353 draft,
354 } => submit_entry(entry, title, description, range, draft).await,
355 StackAction::Status { name } => check_stack_status(name).await,
356 StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
357 StackAction::Check { force } => check_stack(force).await,
358 StackAction::Sync {
359 force,
360 skip_cleanup,
361 interactive,
362 } => sync_stack(force, skip_cleanup, interactive).await,
363 StackAction::Rebase {
364 interactive,
365 onto,
366 strategy,
367 } => rebase_stack(interactive, onto, strategy).await,
368 StackAction::ContinueRebase => continue_rebase().await,
369 StackAction::AbortRebase => abort_rebase().await,
370 StackAction::RebaseStatus => rebase_status().await,
371 StackAction::Delete { name, force } => delete_stack(name, force).await,
372 StackAction::Validate { name, fix } => validate_stack(name, fix).await,
373 StackAction::Land {
374 entry,
375 force,
376 dry_run,
377 auto,
378 wait_for_builds,
379 strategy,
380 build_timeout,
381 } => {
382 land_stack(
383 entry,
384 force,
385 dry_run,
386 auto,
387 wait_for_builds,
388 strategy,
389 build_timeout,
390 )
391 .await
392 }
393 StackAction::AutoLand {
394 force,
395 dry_run,
396 wait_for_builds,
397 strategy,
398 build_timeout,
399 } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
400 StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
401 StackAction::ContinueLand => continue_land().await,
402 StackAction::AbortLand => abort_land().await,
403 StackAction::LandStatus => land_status().await,
404 StackAction::Repair => repair_stack_data().await,
405 }
406}
407
408pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
410 show_stack(verbose, mergeable).await
411}
412
413#[allow(clippy::too_many_arguments)]
414pub async fn push(
415 branch: Option<String>,
416 message: Option<String>,
417 commit: Option<String>,
418 since: Option<String>,
419 commits: Option<String>,
420 squash: Option<usize>,
421 squash_since: Option<String>,
422 auto_branch: bool,
423 allow_base_branch: bool,
424 dry_run: bool,
425) -> Result<()> {
426 push_to_stack(
427 branch,
428 message,
429 commit,
430 since,
431 commits,
432 squash,
433 squash_since,
434 auto_branch,
435 allow_base_branch,
436 dry_run,
437 )
438 .await
439}
440
441pub async fn pop(keep_branch: bool) -> Result<()> {
442 pop_from_stack(keep_branch).await
443}
444
445pub async fn land(
446 entry: Option<usize>,
447 force: bool,
448 dry_run: bool,
449 auto: bool,
450 wait_for_builds: bool,
451 strategy: Option<MergeStrategyArg>,
452 build_timeout: u64,
453) -> Result<()> {
454 land_stack(
455 entry,
456 force,
457 dry_run,
458 auto,
459 wait_for_builds,
460 strategy,
461 build_timeout,
462 )
463 .await
464}
465
466pub async fn autoland(
467 force: bool,
468 dry_run: bool,
469 wait_for_builds: bool,
470 strategy: Option<MergeStrategyArg>,
471 build_timeout: u64,
472) -> Result<()> {
473 auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
474}
475
476pub async fn sync(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
477 sync_stack(force, skip_cleanup, interactive).await
478}
479
480pub async fn rebase(
481 interactive: bool,
482 onto: Option<String>,
483 strategy: Option<RebaseStrategyArg>,
484) -> Result<()> {
485 rebase_stack(interactive, onto, strategy).await
486}
487
488pub async fn deactivate(force: bool) -> Result<()> {
489 deactivate_stack(force).await
490}
491
492pub async fn switch(name: String) -> Result<()> {
493 switch_stack(name).await
494}
495
496async fn create_stack(
497 name: String,
498 base: Option<String>,
499 description: Option<String>,
500) -> Result<()> {
501 let current_dir = env::current_dir()
502 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
503
504 let repo_root = find_repository_root(¤t_dir)
505 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
506
507 let mut manager = StackManager::new(&repo_root)?;
508 let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
509
510 let stack = manager
512 .get_stack(&stack_id)
513 .ok_or_else(|| CascadeError::config("Failed to get created stack"))?;
514
515 Output::stack_info(
517 &name,
518 &stack_id.to_string(),
519 &stack.base_branch,
520 stack.working_branch.as_deref(),
521 true, );
523
524 if let Some(desc) = description {
525 Output::sub_item(format!("Description: {desc}"));
526 }
527
528 if stack.working_branch.is_none() {
530 Output::warning(format!(
531 "You're currently on the base branch '{}'",
532 stack.base_branch
533 ));
534 Output::next_steps(&[
535 &format!("Create a feature branch: git checkout -b {name}"),
536 "Make changes and commit them",
537 "Run 'ca push' to add commits to this stack",
538 ]);
539 } else {
540 Output::next_steps(&[
541 "Make changes and commit them",
542 "Run 'ca push' to add commits to this stack",
543 "Use 'ca submit' when ready to create pull requests",
544 ]);
545 }
546
547 Ok(())
548}
549
550async fn list_stacks(verbose: bool, _active: bool, _format: Option<String>) -> Result<()> {
551 let current_dir = env::current_dir()
552 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
553
554 let repo_root = find_repository_root(¤t_dir)
555 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
556
557 let manager = StackManager::new(&repo_root)?;
558 let stacks = manager.list_stacks();
559
560 if stacks.is_empty() {
561 Output::info("No stacks found. Create one with: ca stack create <name>");
562 return Ok(());
563 }
564
565 println!("📚 Stacks:");
566 for (stack_id, name, status, entry_count, active_marker) in stacks {
567 let status_icon = match status {
568 StackStatus::Clean => "✅",
569 StackStatus::Dirty => "🔄",
570 StackStatus::OutOfSync => "⚠️",
571 StackStatus::Conflicted => "❌",
572 StackStatus::Rebasing => "🔀",
573 StackStatus::NeedsSync => "🔄",
574 StackStatus::Corrupted => "💥",
575 };
576
577 let active_indicator = if active_marker.is_some() {
578 " (active)"
579 } else {
580 ""
581 };
582
583 let stack = manager.get_stack(&stack_id);
585
586 if verbose {
587 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
588 println!(" ID: {stack_id}");
589 if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
590 println!(" Base: {}", stack_meta.base_branch);
591 if let Some(desc) = &stack_meta.description {
592 println!(" Description: {desc}");
593 }
594 println!(
595 " Commits: {} total, {} submitted",
596 stack_meta.total_commits, stack_meta.submitted_commits
597 );
598 if stack_meta.has_conflicts {
599 println!(" ⚠️ Has conflicts");
600 }
601 }
602
603 if let Some(stack_obj) = stack {
605 if !stack_obj.entries.is_empty() {
606 println!(" Branches:");
607 for (i, entry) in stack_obj.entries.iter().enumerate() {
608 let entry_num = i + 1;
609 let submitted_indicator = if entry.is_submitted { "📤" } else { "📝" };
610 let branch_name = &entry.branch;
611 let short_message = if entry.message.len() > 40 {
612 format!("{}...", &entry.message[..37])
613 } else {
614 entry.message.clone()
615 };
616 println!(" {entry_num}. {submitted_indicator} {branch_name} - {short_message}");
617 }
618 }
619 }
620 println!();
621 } else {
622 let branch_info = if let Some(stack_obj) = stack {
624 if stack_obj.entries.is_empty() {
625 String::new()
626 } else if stack_obj.entries.len() == 1 {
627 format!(" → {}", stack_obj.entries[0].branch)
628 } else {
629 let first_branch = &stack_obj.entries[0].branch;
630 let last_branch = &stack_obj.entries.last().unwrap().branch;
631 format!(" → {first_branch} … {last_branch}")
632 }
633 } else {
634 String::new()
635 };
636
637 println!(" {status_icon} {name} [{entry_count}]{branch_info}{active_indicator}");
638 }
639 }
640
641 if !verbose {
642 println!("\nUse --verbose for more details");
643 }
644
645 Ok(())
646}
647
648async fn switch_stack(name: String) -> Result<()> {
649 let current_dir = env::current_dir()
650 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
651
652 let repo_root = find_repository_root(¤t_dir)
653 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
654
655 let mut manager = StackManager::new(&repo_root)?;
656 let repo = GitRepository::open(&repo_root)?;
657
658 let stack = manager
660 .get_stack_by_name(&name)
661 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
662
663 if let Some(working_branch) = &stack.working_branch {
665 let current_branch = repo.get_current_branch().ok();
667
668 if current_branch.as_ref() != Some(working_branch) {
669 Output::progress(format!(
670 "Switching to stack working branch: {working_branch}"
671 ));
672
673 if repo.branch_exists(working_branch) {
675 match repo.checkout_branch(working_branch) {
676 Ok(_) => {
677 Output::success(format!("Checked out branch: {working_branch}"));
678 }
679 Err(e) => {
680 Output::warning(format!("Failed to checkout '{working_branch}': {e}"));
681 Output::sub_item("Stack activated but stayed on current branch");
682 Output::sub_item(format!(
683 "You can manually checkout with: git checkout {working_branch}"
684 ));
685 }
686 }
687 } else {
688 Output::warning(format!(
689 "Stack working branch '{working_branch}' doesn't exist locally"
690 ));
691 Output::sub_item("Stack activated but stayed on current branch");
692 Output::sub_item(format!(
693 "You may need to fetch from remote: git fetch origin {working_branch}"
694 ));
695 }
696 } else {
697 Output::success(format!("Already on stack working branch: {working_branch}"));
698 }
699 } else {
700 Output::warning(format!("Stack '{name}' has no working branch set"));
702 Output::sub_item(
703 "This typically happens when a stack was created while on the base branch",
704 );
705
706 Output::tip("To start working on this stack:");
707 Output::bullet(format!("Create a feature branch: git checkout -b {name}"));
708 Output::bullet("The stack will automatically track this as its working branch");
709 Output::bullet("Then use 'ca push' to add commits to the stack");
710
711 Output::sub_item(format!("Base branch: {}", stack.base_branch));
712 }
713
714 manager.set_active_stack_by_name(&name)?;
716 Output::success(format!("Switched to stack '{name}'"));
717
718 Ok(())
719}
720
721async fn deactivate_stack(force: bool) -> Result<()> {
722 let current_dir = env::current_dir()
723 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
724
725 let repo_root = find_repository_root(¤t_dir)
726 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
727
728 let mut manager = StackManager::new(&repo_root)?;
729
730 let active_stack = manager.get_active_stack();
731
732 if active_stack.is_none() {
733 Output::info("No active stack to deactivate");
734 return Ok(());
735 }
736
737 let stack_name = active_stack.unwrap().name.clone();
738
739 if !force {
740 Output::warning(format!(
741 "This will deactivate stack '{stack_name}' and return to normal Git workflow"
742 ));
743 Output::sub_item(format!(
744 "You can reactivate it later with 'ca stacks switch {stack_name}'"
745 ));
746 print!(" Continue? (y/N): ");
747
748 use std::io::{self, Write};
749 io::stdout().flush().unwrap();
750
751 let mut input = String::new();
752 io::stdin().read_line(&mut input).unwrap();
753
754 if !input.trim().to_lowercase().starts_with('y') {
755 Output::info("Cancelled deactivation");
756 return Ok(());
757 }
758 }
759
760 manager.set_active_stack(None)?;
762
763 Output::success(format!("Deactivated stack '{stack_name}'"));
764 Output::sub_item("Stack management is now OFF - you can use normal Git workflow");
765 Output::sub_item(format!("To reactivate: ca stacks switch {stack_name}"));
766
767 Ok(())
768}
769
770async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
771 let current_dir = env::current_dir()
772 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
773
774 let repo_root = find_repository_root(¤t_dir)
775 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
776
777 let stack_manager = StackManager::new(&repo_root)?;
778
779 let (stack_id, stack_name, stack_base, stack_working, stack_entries) = {
781 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
782 CascadeError::config(
783 "No active stack. Use 'ca stacks create' or 'ca stacks switch' to select a stack"
784 .to_string(),
785 )
786 })?;
787
788 (
789 active_stack.id,
790 active_stack.name.clone(),
791 active_stack.base_branch.clone(),
792 active_stack.working_branch.clone(),
793 active_stack.entries.clone(),
794 )
795 };
796
797 Output::stack_info(
799 &stack_name,
800 &stack_id.to_string(),
801 &stack_base,
802 stack_working.as_deref(),
803 true, );
805 Output::sub_item(format!("Total entries: {}", stack_entries.len()));
806
807 if stack_entries.is_empty() {
808 Output::info("No entries in this stack yet");
809 Output::tip("Use 'ca push' to add commits to this stack");
810 return Ok(());
811 }
812
813 Output::section("Stack Entries");
815 for (i, entry) in stack_entries.iter().enumerate() {
816 let entry_num = i + 1;
817 let short_hash = entry.short_hash();
818 let short_msg = entry.short_message(50);
819
820 let metadata = stack_manager.get_repository_metadata();
822 let source_branch_info = if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash)
823 {
824 if commit_meta.source_branch != commit_meta.branch
825 && !commit_meta.source_branch.is_empty()
826 {
827 format!(" (from {})", commit_meta.source_branch)
828 } else {
829 String::new()
830 }
831 } else {
832 String::new()
833 };
834
835 let status_icon = if entry.is_submitted {
836 "[submitted]"
837 } else {
838 "[pending]"
839 };
840 Output::numbered_item(
841 entry_num,
842 format!("{short_hash} {status_icon} {short_msg}{source_branch_info}"),
843 );
844
845 if verbose {
846 Output::sub_item(format!("Branch: {}", entry.branch));
847 Output::sub_item(format!(
848 "Created: {}",
849 entry.created_at.format("%Y-%m-%d %H:%M")
850 ));
851 if let Some(pr_id) = &entry.pull_request_id {
852 Output::sub_item(format!("PR: #{pr_id}"));
853 }
854 }
855 }
856
857 if show_mergeable {
859 Output::section("Mergability Status");
860
861 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
863 let config_path = config_dir.join("config.json");
864 let settings = crate::config::Settings::load_from_file(&config_path)?;
865
866 let cascade_config = crate::config::CascadeConfig {
867 bitbucket: Some(settings.bitbucket.clone()),
868 git: settings.git.clone(),
869 auth: crate::config::AuthConfig::default(),
870 cascade: settings.cascade.clone(),
871 };
872
873 let integration =
874 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
875
876 match integration.check_enhanced_stack_status(&stack_id).await {
877 Ok(status) => {
878 Output::bullet(format!("Total entries: {}", status.total_entries));
879 Output::bullet(format!("Submitted: {}", status.submitted_entries));
880 Output::bullet(format!("Open PRs: {}", status.open_prs));
881 Output::bullet(format!("Merged PRs: {}", status.merged_prs));
882 Output::bullet(format!("Declined PRs: {}", status.declined_prs));
883 Output::bullet(format!(
884 "Completion: {:.1}%",
885 status.completion_percentage()
886 ));
887
888 if !status.enhanced_statuses.is_empty() {
889 Output::section("Pull Request Status");
890 let mut ready_to_land = 0;
891
892 for enhanced in &status.enhanced_statuses {
893 let status_display = enhanced.get_display_status();
894 let ready_icon = if enhanced.is_ready_to_land() {
895 ready_to_land += 1;
896 "[READY]"
897 } else {
898 "[PENDING]"
899 };
900
901 Output::bullet(format!(
902 "{} PR #{}: {} ({})",
903 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
904 ));
905
906 if verbose {
907 println!(
908 " {} -> {}",
909 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
910 );
911
912 if !enhanced.is_ready_to_land() {
914 let blocking = enhanced.get_blocking_reasons();
915 if !blocking.is_empty() {
916 println!(" Blocking: {}", blocking.join(", "));
917 }
918 }
919
920 println!(
922 " Reviews: {}/{} approvals",
923 enhanced.review_status.current_approvals,
924 enhanced.review_status.required_approvals
925 );
926
927 if enhanced.review_status.needs_work_count > 0 {
928 println!(
929 " {} reviewers requested changes",
930 enhanced.review_status.needs_work_count
931 );
932 }
933
934 if let Some(build) = &enhanced.build_status {
936 let build_icon = match build.state {
937 crate::bitbucket::pull_request::BuildState::Successful => "✅",
938 crate::bitbucket::pull_request::BuildState::Failed => "❌",
939 crate::bitbucket::pull_request::BuildState::InProgress => "🔄",
940 _ => "⚪",
941 };
942 println!(" Build: {} {:?}", build_icon, build.state);
943 }
944
945 if let Some(url) = enhanced.pr.web_url() {
946 println!(" URL: {url}");
947 }
948 println!();
949 }
950 }
951
952 if ready_to_land > 0 {
953 println!(
954 "\n🎯 {} PR{} ready to land! Use 'ca land' to land them all.",
955 ready_to_land,
956 if ready_to_land == 1 { " is" } else { "s are" }
957 );
958 }
959 }
960 }
961 Err(e) => {
962 warn!("Failed to get enhanced stack status: {}", e);
963 println!(" ⚠️ Could not fetch mergability status");
964 println!(" Use 'ca stack show --verbose' for basic PR information");
965 }
966 }
967 } else {
968 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
970 let config_path = config_dir.join("config.json");
971 let settings = crate::config::Settings::load_from_file(&config_path)?;
972
973 let cascade_config = crate::config::CascadeConfig {
974 bitbucket: Some(settings.bitbucket.clone()),
975 git: settings.git.clone(),
976 auth: crate::config::AuthConfig::default(),
977 cascade: settings.cascade.clone(),
978 };
979
980 let integration =
981 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
982
983 match integration.check_stack_status(&stack_id).await {
984 Ok(status) => {
985 println!("\n📊 Pull Request Status:");
986 println!(" Total entries: {}", status.total_entries);
987 println!(" Submitted: {}", status.submitted_entries);
988 println!(" Open PRs: {}", status.open_prs);
989 println!(" Merged PRs: {}", status.merged_prs);
990 println!(" Declined PRs: {}", status.declined_prs);
991 println!(" Completion: {:.1}%", status.completion_percentage());
992
993 if !status.pull_requests.is_empty() {
994 println!("\n📋 Pull Requests:");
995 for pr in &status.pull_requests {
996 let state_icon = match pr.state {
997 crate::bitbucket::PullRequestState::Open => "🔄",
998 crate::bitbucket::PullRequestState::Merged => "✅",
999 crate::bitbucket::PullRequestState::Declined => "❌",
1000 };
1001 println!(
1002 " {} PR #{}: {} ({} -> {})",
1003 state_icon,
1004 pr.id,
1005 pr.title,
1006 pr.from_ref.display_id,
1007 pr.to_ref.display_id
1008 );
1009 if let Some(url) = pr.web_url() {
1010 println!(" URL: {url}");
1011 }
1012 }
1013 }
1014
1015 println!("\n💡 Use 'ca stack --mergeable' to see detailed status including build and review information");
1016 }
1017 Err(e) => {
1018 warn!("Failed to check stack status: {}", e);
1019 }
1020 }
1021 }
1022
1023 Ok(())
1024}
1025
1026#[allow(clippy::too_many_arguments)]
1027async fn push_to_stack(
1028 branch: Option<String>,
1029 message: Option<String>,
1030 commit: Option<String>,
1031 since: Option<String>,
1032 commits: Option<String>,
1033 squash: Option<usize>,
1034 squash_since: Option<String>,
1035 auto_branch: bool,
1036 allow_base_branch: bool,
1037 dry_run: bool,
1038) -> Result<()> {
1039 let current_dir = env::current_dir()
1040 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1041
1042 let repo_root = find_repository_root(¤t_dir)
1043 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1044
1045 let mut manager = StackManager::new(&repo_root)?;
1046 let repo = GitRepository::open(&repo_root)?;
1047
1048 if !manager.check_for_branch_change()? {
1050 return Ok(()); }
1052
1053 let active_stack = manager.get_active_stack().ok_or_else(|| {
1055 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1056 })?;
1057
1058 let current_branch = repo.get_current_branch()?;
1060 let base_branch = &active_stack.base_branch;
1061
1062 if current_branch == *base_branch {
1063 Output::error(format!(
1064 "You're currently on the base branch '{base_branch}'"
1065 ));
1066 Output::sub_item("Making commits directly on the base branch is not recommended.");
1067 Output::sub_item("This can pollute the base branch with work-in-progress commits.");
1068
1069 if allow_base_branch {
1071 Output::warning("Proceeding anyway due to --allow-base-branch flag");
1072 } else {
1073 let has_changes = repo.is_dirty()?;
1075
1076 if has_changes {
1077 if auto_branch {
1078 let feature_branch = format!("feature/{}-work", active_stack.name);
1080 Output::progress(format!(
1081 "Auto-creating feature branch '{feature_branch}'..."
1082 ));
1083
1084 repo.create_branch(&feature_branch, None)?;
1085 repo.checkout_branch(&feature_branch)?;
1086
1087 println!("✅ Created and switched to '{feature_branch}'");
1088 println!(" You can now commit and push your changes safely");
1089
1090 } else {
1092 println!("\n💡 You have uncommitted changes. Here are your options:");
1093 println!(" 1. Create a feature branch first:");
1094 println!(" git checkout -b feature/my-work");
1095 println!(" git commit -am \"your work\"");
1096 println!(" ca push");
1097 println!("\n 2. Auto-create a branch (recommended):");
1098 println!(" ca push --auto-branch");
1099 println!("\n 3. Force push to base branch (dangerous):");
1100 println!(" ca push --allow-base-branch");
1101
1102 return Err(CascadeError::config(
1103 "Refusing to push uncommitted changes from base branch. Use one of the options above."
1104 ));
1105 }
1106 } else {
1107 let commits_to_check = if let Some(commits_str) = &commits {
1109 commits_str
1110 .split(',')
1111 .map(|s| s.trim().to_string())
1112 .collect::<Vec<String>>()
1113 } else if let Some(since_ref) = &since {
1114 let since_commit = repo.resolve_reference(since_ref)?;
1115 let head_commit = repo.get_head_commit()?;
1116 let commits = repo.get_commits_between(
1117 &since_commit.id().to_string(),
1118 &head_commit.id().to_string(),
1119 )?;
1120 commits.into_iter().map(|c| c.id().to_string()).collect()
1121 } else if commit.is_none() {
1122 let mut unpushed = Vec::new();
1123 let head_commit = repo.get_head_commit()?;
1124 let mut current_commit = head_commit;
1125
1126 loop {
1127 let commit_hash = current_commit.id().to_string();
1128 let already_in_stack = active_stack
1129 .entries
1130 .iter()
1131 .any(|entry| entry.commit_hash == commit_hash);
1132
1133 if already_in_stack {
1134 break;
1135 }
1136
1137 unpushed.push(commit_hash);
1138
1139 if let Some(parent) = current_commit.parents().next() {
1140 current_commit = parent;
1141 } else {
1142 break;
1143 }
1144 }
1145
1146 unpushed.reverse();
1147 unpushed
1148 } else {
1149 vec![repo.get_head_commit()?.id().to_string()]
1150 };
1151
1152 if !commits_to_check.is_empty() {
1153 if auto_branch {
1154 let feature_branch = format!("feature/{}-work", active_stack.name);
1156 Output::progress(format!(
1157 "Auto-creating feature branch '{feature_branch}'..."
1158 ));
1159
1160 repo.create_branch(&feature_branch, Some(base_branch))?;
1161 repo.checkout_branch(&feature_branch)?;
1162
1163 println!(
1165 "🍒 Cherry-picking {} commit(s) to new branch...",
1166 commits_to_check.len()
1167 );
1168 for commit_hash in &commits_to_check {
1169 match repo.cherry_pick(commit_hash) {
1170 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
1171 Err(e) => {
1172 println!(
1173 " ❌ Failed to cherry-pick {}: {}",
1174 &commit_hash[..8],
1175 e
1176 );
1177 println!(" 💡 You may need to resolve conflicts manually");
1178 return Err(CascadeError::branch(format!(
1179 "Failed to cherry-pick commit {commit_hash}: {e}"
1180 )));
1181 }
1182 }
1183 }
1184
1185 println!(
1186 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1187 commits_to_check.len()
1188 );
1189 println!(
1190 " You're now on the feature branch and can continue with 'ca push'"
1191 );
1192
1193 } else {
1195 println!(
1196 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1197 commits_to_check.len()
1198 );
1199 println!(" These commits are currently ON the base branch, which may not be intended.");
1200 println!("\n Options:");
1201 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1202 println!(" ca push --auto-branch");
1203 println!("\n 2. Manually create branch and move commits:");
1204 println!(" git checkout -b feature/my-work");
1205 println!(" ca push");
1206 println!("\n 3. Force push from base branch (not recommended):");
1207 println!(" ca push --allow-base-branch");
1208
1209 return Err(CascadeError::config(
1210 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1211 ));
1212 }
1213 }
1214 }
1215 }
1216 }
1217
1218 if let Some(squash_count) = squash {
1220 if squash_count == 0 {
1221 let active_stack = manager.get_active_stack().ok_or_else(|| {
1223 CascadeError::config(
1224 "No active stack. Create a stack first with 'ca stacks create'",
1225 )
1226 })?;
1227
1228 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1229
1230 if unpushed_count == 0 {
1231 println!("ℹ️ No unpushed commits to squash");
1232 } else if unpushed_count == 1 {
1233 println!("ℹ️ Only 1 unpushed commit, no squashing needed");
1234 } else {
1235 println!("🔄 Auto-detected {unpushed_count} unpushed commits, squashing...");
1236 squash_commits(&repo, unpushed_count, None).await?;
1237 println!("✅ Squashed {unpushed_count} unpushed commits into one");
1238 }
1239 } else {
1240 println!("🔄 Squashing last {squash_count} commits...");
1241 squash_commits(&repo, squash_count, None).await?;
1242 println!("✅ Squashed {squash_count} commits into one");
1243 }
1244 } else if let Some(since_ref) = squash_since {
1245 println!("🔄 Squashing commits since {since_ref}...");
1246 let since_commit = repo.resolve_reference(&since_ref)?;
1247 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1248 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1249 println!("✅ Squashed {commits_count} commits since {since_ref} into one");
1250 }
1251
1252 let commits_to_push = if let Some(commits_str) = commits {
1254 commits_str
1256 .split(',')
1257 .map(|s| s.trim().to_string())
1258 .collect::<Vec<String>>()
1259 } else if let Some(since_ref) = since {
1260 let since_commit = repo.resolve_reference(&since_ref)?;
1262 let head_commit = repo.get_head_commit()?;
1263
1264 let commits = repo.get_commits_between(
1266 &since_commit.id().to_string(),
1267 &head_commit.id().to_string(),
1268 )?;
1269 commits.into_iter().map(|c| c.id().to_string()).collect()
1270 } else if let Some(hash) = commit {
1271 vec![hash]
1273 } else {
1274 let active_stack = manager.get_active_stack().ok_or_else(|| {
1276 CascadeError::config("No active stack. Create a stack first with 'ca stacks create'")
1277 })?;
1278
1279 let base_branch = &active_stack.base_branch;
1281 let current_branch = repo.get_current_branch()?;
1282
1283 if current_branch == *base_branch {
1285 let mut unpushed = Vec::new();
1286 let head_commit = repo.get_head_commit()?;
1287 let mut current_commit = head_commit;
1288
1289 loop {
1291 let commit_hash = current_commit.id().to_string();
1292 let already_in_stack = active_stack
1293 .entries
1294 .iter()
1295 .any(|entry| entry.commit_hash == commit_hash);
1296
1297 if already_in_stack {
1298 break;
1299 }
1300
1301 unpushed.push(commit_hash);
1302
1303 if let Some(parent) = current_commit.parents().next() {
1305 current_commit = parent;
1306 } else {
1307 break;
1308 }
1309 }
1310
1311 unpushed.reverse(); unpushed
1313 } else {
1314 match repo.get_commits_between(base_branch, ¤t_branch) {
1316 Ok(commits) => {
1317 let mut unpushed: Vec<String> =
1318 commits.into_iter().map(|c| c.id().to_string()).collect();
1319
1320 unpushed.retain(|commit_hash| {
1322 !active_stack
1323 .entries
1324 .iter()
1325 .any(|entry| entry.commit_hash == *commit_hash)
1326 });
1327
1328 unpushed.reverse(); unpushed
1330 }
1331 Err(e) => {
1332 return Err(CascadeError::branch(format!(
1333 "Failed to calculate commits between '{base_branch}' and '{current_branch}': {e}. \
1334 This usually means the branches have diverged or don't share common history."
1335 )));
1336 }
1337 }
1338 }
1339 };
1340
1341 if commits_to_push.is_empty() {
1342 println!("ℹ️ No commits to push to stack");
1343 return Ok(());
1344 }
1345
1346 analyze_commits_for_safeguards(&commits_to_push, &repo, dry_run).await?;
1348
1349 if dry_run {
1351 return Ok(());
1352 }
1353
1354 let mut pushed_count = 0;
1356 let mut source_branches = std::collections::HashSet::new();
1357
1358 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1359 let commit_obj = repo.get_commit(commit_hash)?;
1360 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1361
1362 let commit_source_branch = repo
1364 .find_branch_containing_commit(commit_hash)
1365 .unwrap_or_else(|_| current_branch.clone());
1366 source_branches.insert(commit_source_branch.clone());
1367
1368 let branch_name = if i == 0 && branch.is_some() {
1370 branch.clone().unwrap()
1371 } else {
1372 let temp_repo = GitRepository::open(&repo_root)?;
1374 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1375 branch_mgr.generate_branch_name(&commit_msg)
1376 };
1377
1378 let final_message = if i == 0 && message.is_some() {
1380 message.clone().unwrap()
1381 } else {
1382 commit_msg.clone()
1383 };
1384
1385 let entry_id = manager.push_to_stack(
1386 branch_name.clone(),
1387 commit_hash.clone(),
1388 final_message.clone(),
1389 commit_source_branch.clone(),
1390 )?;
1391 pushed_count += 1;
1392
1393 Output::success(format!(
1394 "Pushed commit {}/{} to stack",
1395 i + 1,
1396 commits_to_push.len()
1397 ));
1398 Output::sub_item(format!(
1399 "Commit: {} ({})",
1400 &commit_hash[..8],
1401 commit_msg.split('\n').next().unwrap_or("")
1402 ));
1403 Output::sub_item(format!("Branch: {branch_name}"));
1404 Output::sub_item(format!("Source: {commit_source_branch}"));
1405 Output::sub_item(format!("Entry ID: {entry_id}"));
1406 println!();
1407 }
1408
1409 if source_branches.len() > 1 {
1411 Output::warning("Scattered Commit Detection");
1412 Output::sub_item(format!(
1413 "You've pushed commits from {} different Git branches:",
1414 source_branches.len()
1415 ));
1416 for branch in &source_branches {
1417 Output::bullet(branch.to_string());
1418 }
1419
1420 Output::section("This can lead to confusion because:");
1421 Output::bullet("Stack appears sequential but commits are scattered across branches");
1422 Output::bullet("Team members won't know which branch contains which work");
1423 Output::bullet("Branch cleanup becomes unclear after merge");
1424 Output::bullet("Rebase operations become more complex");
1425
1426 Output::tip("Consider consolidating work to a single feature branch:");
1427 Output::bullet("Create a new feature branch: git checkout -b feature/consolidated-work");
1428 Output::bullet("Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1429 Output::bullet("Delete old scattered branches");
1430 Output::bullet("Push the consolidated branch to your stack");
1431 println!();
1432 }
1433
1434 Output::success(format!(
1435 "Successfully pushed {} commit{} to stack",
1436 pushed_count,
1437 if pushed_count == 1 { "" } else { "s" }
1438 ));
1439
1440 Ok(())
1441}
1442
1443async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1444 let current_dir = env::current_dir()
1445 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1446
1447 let repo_root = find_repository_root(¤t_dir)
1448 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1449
1450 let mut manager = StackManager::new(&repo_root)?;
1451 let repo = GitRepository::open(&repo_root)?;
1452
1453 let entry = manager.pop_from_stack()?;
1454
1455 Output::success("Popped commit from stack");
1456 Output::sub_item(format!(
1457 "Commit: {} ({})",
1458 entry.short_hash(),
1459 entry.short_message(50)
1460 ));
1461 Output::sub_item(format!("Branch: {}", entry.branch));
1462
1463 if !keep_branch && entry.branch != repo.get_current_branch()? {
1465 match repo.delete_branch(&entry.branch) {
1466 Ok(_) => Output::sub_item(format!("Deleted branch: {}", entry.branch)),
1467 Err(e) => Output::warning(format!("Could not delete branch {}: {}", entry.branch, e)),
1468 }
1469 }
1470
1471 Ok(())
1472}
1473
1474async fn submit_entry(
1475 entry: Option<usize>,
1476 title: Option<String>,
1477 description: Option<String>,
1478 range: Option<String>,
1479 draft: bool,
1480) -> Result<()> {
1481 let current_dir = env::current_dir()
1482 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1483
1484 let repo_root = find_repository_root(¤t_dir)
1485 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1486
1487 let mut stack_manager = StackManager::new(&repo_root)?;
1488
1489 if !stack_manager.check_for_branch_change()? {
1491 return Ok(()); }
1493
1494 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1496 let config_path = config_dir.join("config.json");
1497 let settings = crate::config::Settings::load_from_file(&config_path)?;
1498
1499 let cascade_config = crate::config::CascadeConfig {
1501 bitbucket: Some(settings.bitbucket.clone()),
1502 git: settings.git.clone(),
1503 auth: crate::config::AuthConfig::default(),
1504 cascade: settings.cascade.clone(),
1505 };
1506
1507 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1509 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1510 })?;
1511 let stack_id = active_stack.id;
1512
1513 let entries_to_submit = if let Some(range_str) = range {
1515 let mut entries = Vec::new();
1517
1518 if range_str.contains('-') {
1519 let parts: Vec<&str> = range_str.split('-').collect();
1521 if parts.len() != 2 {
1522 return Err(CascadeError::config(
1523 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1524 ));
1525 }
1526
1527 let start: usize = parts[0]
1528 .parse()
1529 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1530 let end: usize = parts[1]
1531 .parse()
1532 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1533
1534 if start == 0
1535 || end == 0
1536 || start > active_stack.entries.len()
1537 || end > active_stack.entries.len()
1538 {
1539 return Err(CascadeError::config(format!(
1540 "Range out of bounds. Stack has {} entries",
1541 active_stack.entries.len()
1542 )));
1543 }
1544
1545 for i in start..=end {
1546 entries.push((i, active_stack.entries[i - 1].clone()));
1547 }
1548 } else {
1549 for entry_str in range_str.split(',') {
1551 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1552 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1553 })?;
1554
1555 if entry_num == 0 || entry_num > active_stack.entries.len() {
1556 return Err(CascadeError::config(format!(
1557 "Entry {} out of bounds. Stack has {} entries",
1558 entry_num,
1559 active_stack.entries.len()
1560 )));
1561 }
1562
1563 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1564 }
1565 }
1566
1567 entries
1568 } else if let Some(entry_num) = entry {
1569 if entry_num == 0 || entry_num > active_stack.entries.len() {
1571 return Err(CascadeError::config(format!(
1572 "Invalid entry number: {}. Stack has {} entries",
1573 entry_num,
1574 active_stack.entries.len()
1575 )));
1576 }
1577 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1578 } else {
1579 active_stack
1581 .entries
1582 .iter()
1583 .enumerate()
1584 .filter(|(_, entry)| !entry.is_submitted)
1585 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1587 };
1588
1589 if entries_to_submit.is_empty() {
1590 Output::info("No entries to submit");
1591 return Ok(());
1592 }
1593
1594 let total_operations = entries_to_submit.len() + 2; let pb = ProgressBar::new(total_operations as u64);
1597 pb.set_style(
1598 ProgressStyle::default_bar()
1599 .template("📤 {msg} [{bar:40.cyan/blue}] {pos}/{len}")
1600 .map_err(|e| CascadeError::config(format!("Progress bar template error: {e}")))?,
1601 );
1602
1603 pb.set_message("Connecting to Bitbucket");
1604 pb.inc(1);
1605
1606 let integration_stack_manager = StackManager::new(&repo_root)?;
1608 let mut integration =
1609 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1610
1611 pb.set_message("Starting batch submission");
1612 pb.inc(1);
1613
1614 let mut submitted_count = 0;
1616 let mut failed_entries = Vec::new();
1617 let total_entries = entries_to_submit.len();
1618
1619 for (entry_num, entry_to_submit) in &entries_to_submit {
1620 pb.set_message(format!("Submitting entry {entry_num}..."));
1621
1622 let entry_title = if total_entries == 1 {
1624 title.clone()
1625 } else {
1626 None
1627 };
1628 let entry_description = if total_entries == 1 {
1629 description.clone()
1630 } else {
1631 None
1632 };
1633
1634 match integration
1635 .submit_entry(
1636 &stack_id,
1637 &entry_to_submit.id,
1638 entry_title,
1639 entry_description,
1640 draft,
1641 )
1642 .await
1643 {
1644 Ok(pr) => {
1645 submitted_count += 1;
1646 Output::success(format!("Entry {} - PR #{}: {}", entry_num, pr.id, pr.title));
1647 if let Some(url) = pr.web_url() {
1648 Output::sub_item(format!("URL: {url}"));
1649 }
1650 Output::sub_item(format!(
1651 "From: {} -> {}",
1652 pr.from_ref.display_id, pr.to_ref.display_id
1653 ));
1654 println!();
1655 }
1656 Err(e) => {
1657 failed_entries.push((*entry_num, e.to_string()));
1658 }
1660 }
1661
1662 pb.inc(1);
1663 }
1664
1665 let has_any_prs = active_stack
1667 .entries
1668 .iter()
1669 .any(|e| e.pull_request_id.is_some());
1670 if has_any_prs && submitted_count > 0 {
1671 pb.set_message("Updating PR descriptions...");
1672 match integration.update_all_pr_descriptions(&stack_id).await {
1673 Ok(updated_prs) => {
1674 if !updated_prs.is_empty() {
1675 Output::sub_item(format!(
1676 "Updated {} PR descriptions with current stack hierarchy",
1677 updated_prs.len()
1678 ));
1679 }
1680 }
1681 Err(e) => {
1682 Output::warning(format!("Failed to update some PR descriptions: {e}"));
1683 }
1684 }
1685 }
1686
1687 if failed_entries.is_empty() {
1688 pb.finish_with_message("✅ All pull requests created successfully");
1689 Output::success(format!(
1690 "Successfully submitted {} entr{}",
1691 submitted_count,
1692 if submitted_count == 1 { "y" } else { "ies" }
1693 ));
1694 } else {
1695 pb.abandon_with_message("⚠️ Some submissions failed");
1696 Output::section("Submission Summary");
1697 Output::bullet(format!("Successful: {submitted_count}"));
1698 Output::bullet(format!("Failed: {}", failed_entries.len()));
1699
1700 Output::section("Failed entries:");
1701 for (entry_num, error) in failed_entries {
1702 Output::bullet(format!("Entry {entry_num}: {error}"));
1703 }
1704
1705 Output::tip("You can retry failed entries individually:");
1706 Output::command_example("ca stack submit <ENTRY_NUMBER>");
1707 }
1708
1709 Ok(())
1710}
1711
1712async fn check_stack_status(name: Option<String>) -> Result<()> {
1713 let current_dir = env::current_dir()
1714 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1715
1716 let repo_root = find_repository_root(¤t_dir)
1717 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1718
1719 let stack_manager = StackManager::new(&repo_root)?;
1720
1721 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1723 let config_path = config_dir.join("config.json");
1724 let settings = crate::config::Settings::load_from_file(&config_path)?;
1725
1726 let cascade_config = crate::config::CascadeConfig {
1728 bitbucket: Some(settings.bitbucket.clone()),
1729 git: settings.git.clone(),
1730 auth: crate::config::AuthConfig::default(),
1731 cascade: settings.cascade.clone(),
1732 };
1733
1734 let stack = if let Some(name) = name {
1736 stack_manager
1737 .get_stack_by_name(&name)
1738 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1739 } else {
1740 stack_manager.get_active_stack().ok_or_else(|| {
1741 CascadeError::config("No active stack. Use 'ca stack list' to see available stacks")
1742 })?
1743 };
1744 let stack_id = stack.id;
1745
1746 Output::section(format!("Stack: {}", stack.name));
1747 Output::sub_item(format!("ID: {}", stack.id));
1748 Output::sub_item(format!("Base: {}", stack.base_branch));
1749
1750 if let Some(description) = &stack.description {
1751 Output::sub_item(format!("Description: {description}"));
1752 }
1753
1754 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1756
1757 match integration.check_stack_status(&stack_id).await {
1759 Ok(status) => {
1760 Output::section("Pull Request Status");
1761 Output::sub_item(format!("Total entries: {}", status.total_entries));
1762 Output::sub_item(format!("Submitted: {}", status.submitted_entries));
1763 Output::sub_item(format!("Open PRs: {}", status.open_prs));
1764 Output::sub_item(format!("Merged PRs: {}", status.merged_prs));
1765 Output::sub_item(format!("Declined PRs: {}", status.declined_prs));
1766 Output::sub_item(format!(
1767 "Completion: {:.1}%",
1768 status.completion_percentage()
1769 ));
1770
1771 if !status.pull_requests.is_empty() {
1772 Output::section("Pull Requests");
1773 for pr in &status.pull_requests {
1774 let state_icon = match pr.state {
1775 crate::bitbucket::PullRequestState::Open => "🔄",
1776 crate::bitbucket::PullRequestState::Merged => "✅",
1777 crate::bitbucket::PullRequestState::Declined => "❌",
1778 };
1779 Output::bullet(format!(
1780 "{} PR #{}: {} ({} -> {})",
1781 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1782 ));
1783 if let Some(url) = pr.web_url() {
1784 Output::sub_item(format!("URL: {url}"));
1785 }
1786 }
1787 }
1788 }
1789 Err(e) => {
1790 warn!("Failed to check stack status: {}", e);
1791 return Err(e);
1792 }
1793 }
1794
1795 Ok(())
1796}
1797
1798async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
1799 let current_dir = env::current_dir()
1800 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1801
1802 let repo_root = find_repository_root(¤t_dir)
1803 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1804
1805 let stack_manager = StackManager::new(&repo_root)?;
1806
1807 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
1809 let config_path = config_dir.join("config.json");
1810 let settings = crate::config::Settings::load_from_file(&config_path)?;
1811
1812 let cascade_config = crate::config::CascadeConfig {
1814 bitbucket: Some(settings.bitbucket.clone()),
1815 git: settings.git.clone(),
1816 auth: crate::config::AuthConfig::default(),
1817 cascade: settings.cascade.clone(),
1818 };
1819
1820 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1822
1823 let pr_state = if let Some(state_str) = state {
1825 match state_str.to_lowercase().as_str() {
1826 "open" => Some(crate::bitbucket::PullRequestState::Open),
1827 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
1828 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
1829 _ => {
1830 return Err(CascadeError::config(format!(
1831 "Invalid state '{state_str}'. Use: open, merged, declined"
1832 )))
1833 }
1834 }
1835 } else {
1836 None
1837 };
1838
1839 match integration.list_pull_requests(pr_state).await {
1841 Ok(pr_page) => {
1842 if pr_page.values.is_empty() {
1843 Output::info("No pull requests found.");
1844 return Ok(());
1845 }
1846
1847 println!("📋 Pull Requests ({} total):", pr_page.values.len());
1848 for pr in &pr_page.values {
1849 let state_icon = match pr.state {
1850 crate::bitbucket::PullRequestState::Open => "🔄",
1851 crate::bitbucket::PullRequestState::Merged => "✅",
1852 crate::bitbucket::PullRequestState::Declined => "❌",
1853 };
1854 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
1855 if verbose {
1856 println!(
1857 " From: {} -> {}",
1858 pr.from_ref.display_id, pr.to_ref.display_id
1859 );
1860 println!(
1861 " Author: {}",
1862 pr.author
1863 .user
1864 .display_name
1865 .as_deref()
1866 .unwrap_or(&pr.author.user.name)
1867 );
1868 if let Some(url) = pr.web_url() {
1869 println!(" URL: {url}");
1870 }
1871 if let Some(desc) = &pr.description {
1872 if !desc.is_empty() {
1873 println!(" Description: {desc}");
1874 }
1875 }
1876 println!();
1877 }
1878 }
1879
1880 if !verbose {
1881 println!("\nUse --verbose for more details");
1882 }
1883 }
1884 Err(e) => {
1885 warn!("Failed to list pull requests: {}", e);
1886 return Err(e);
1887 }
1888 }
1889
1890 Ok(())
1891}
1892
1893async fn check_stack(_force: bool) -> Result<()> {
1894 let current_dir = env::current_dir()
1895 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1896
1897 let repo_root = find_repository_root(¤t_dir)
1898 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1899
1900 let mut manager = StackManager::new(&repo_root)?;
1901
1902 let active_stack = manager
1903 .get_active_stack()
1904 .ok_or_else(|| CascadeError::config("No active stack"))?;
1905 let stack_id = active_stack.id;
1906
1907 manager.sync_stack(&stack_id)?;
1908
1909 Output::success("Stack check completed successfully");
1910
1911 Ok(())
1912}
1913
1914async fn sync_stack(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
1915 let current_dir = env::current_dir()
1916 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1917
1918 let repo_root = find_repository_root(¤t_dir)
1919 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
1920
1921 let stack_manager = StackManager::new(&repo_root)?;
1922 let git_repo = GitRepository::open(&repo_root)?;
1923
1924 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1926 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
1927 })?;
1928
1929 let base_branch = active_stack.base_branch.clone();
1930 let stack_name = active_stack.name.clone();
1931
1932 Output::progress(format!("Syncing stack '{stack_name}' with remote..."));
1933
1934 Output::section(format!("Pulling latest changes from '{base_branch}'"));
1936
1937 match git_repo.checkout_branch(&base_branch) {
1939 Ok(_) => {
1940 Output::sub_item(format!("Switched to '{base_branch}'"));
1941
1942 match git_repo.pull(&base_branch) {
1944 Ok(_) => {
1945 Output::success("Successfully pulled latest changes");
1946 }
1947 Err(e) => {
1948 if force {
1949 Output::warning(format!("Pull failed: {e} (continuing due to --force)"));
1950 } else {
1951 Output::error(format!("Failed to pull latest changes: {e}"));
1952
1953 Output::section("Sync Diagnostic Information");
1955
1956 let error_str = e.to_string();
1957 if error_str.contains("SSL") || error_str.contains("TLS") {
1958 Output::bullet("SSL/TLS authentication issue detected");
1959 Output::bullet("This is common with corporate Git servers");
1960 }
1961
1962 Output::tip("Solutions to try:");
1963 Output::bullet("Test basic git authentication: git fetch origin");
1964 Output::bullet("Use --force to skip pull and continue with rebase");
1965 Output::bullet(format!(
1966 "Try manual pull first: git pull origin {base_branch}"
1967 ));
1968
1969 Output::section("Quick Fix");
1970 Output::command_example(
1971 "ca sync --force # Skip failed pull, continue with rebase",
1972 );
1973
1974 return Err(CascadeError::branch(format!(
1975 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
1976 )));
1977 }
1978 }
1979 }
1980 }
1981 Err(e) => {
1982 if force {
1983 Output::warning(format!(
1984 "Failed to checkout '{base_branch}': {e} (continuing due to --force)"
1985 ));
1986 } else {
1987 Output::error(format!(
1988 "Failed to checkout base branch '{base_branch}': {e}"
1989 ));
1990 Output::tip("Use --force to bypass checkout issues and continue anyway");
1991 return Err(CascadeError::branch(format!(
1992 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
1993 )));
1994 }
1995 }
1996 }
1997
1998 Output::section("Checking if stack needs rebase");
2000
2001 let mut updated_stack_manager = StackManager::new(&repo_root)?;
2002 let stack_id = active_stack.id;
2003
2004 match updated_stack_manager.sync_stack(&stack_id) {
2005 Ok(_) => {
2006 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
2008 match &updated_stack.status {
2009 crate::stack::StackStatus::NeedsSync => {
2010 Output::info(format!(
2011 "Stack needs rebase due to new commits on '{base_branch}'"
2012 ));
2013
2014 Output::section(format!("Rebasing stack onto updated '{base_branch}'"));
2016
2017 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2019 let config_path = config_dir.join("config.json");
2020 let settings = crate::config::Settings::load_from_file(&config_path)?;
2021
2022 let cascade_config = crate::config::CascadeConfig {
2023 bitbucket: Some(settings.bitbucket.clone()),
2024 git: settings.git.clone(),
2025 auth: crate::config::AuthConfig::default(),
2026 cascade: settings.cascade.clone(),
2027 };
2028
2029 let options = crate::stack::RebaseOptions {
2031 strategy: crate::stack::RebaseStrategy::BranchVersioning,
2032 interactive,
2033 target_base: Some(base_branch.clone()),
2034 preserve_merges: true,
2035 auto_resolve: !interactive,
2036 max_retries: 3,
2037 skip_pull: Some(true), };
2039
2040 let mut rebase_manager = crate::stack::RebaseManager::new(
2041 updated_stack_manager,
2042 git_repo,
2043 options,
2044 );
2045
2046 match rebase_manager.rebase_stack(&stack_id) {
2047 Ok(result) => {
2048 Output::success("Rebase completed successfully!");
2049
2050 if !result.branch_mapping.is_empty() {
2051 Output::section("Updated branches:");
2052 for (old, new) in &result.branch_mapping {
2053 Output::bullet(format!("{old} → {new}"));
2054 }
2055
2056 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2058 Output::progress("Updating pull requests...");
2059
2060 let integration_stack_manager =
2061 StackManager::new(&repo_root)?;
2062 let mut integration =
2063 crate::bitbucket::BitbucketIntegration::new(
2064 integration_stack_manager,
2065 cascade_config,
2066 )?;
2067
2068 match integration
2069 .update_prs_after_rebase(
2070 &stack_id,
2071 &result.branch_mapping,
2072 )
2073 .await
2074 {
2075 Ok(updated_prs) => {
2076 if !updated_prs.is_empty() {
2077 Output::success(format!(
2078 "Updated {} pull requests",
2079 updated_prs.len()
2080 ));
2081 }
2082 }
2083 Err(e) => {
2084 Output::warning(format!(
2085 "Failed to update pull requests: {e}"
2086 ));
2087 }
2088 }
2089 }
2090 }
2091 }
2092 Err(e) => {
2093 Output::error(format!("Rebase failed: {e}"));
2094 Output::tip("To resolve conflicts:");
2095 Output::bullet("Fix conflicts in the affected files");
2096 Output::bullet("Stage resolved files: git add <files>");
2097 Output::bullet("Continue: ca stack continue-rebase");
2098 return Err(e);
2099 }
2100 }
2101 }
2102 crate::stack::StackStatus::Clean => {
2103 Output::success("Stack is already up to date");
2104 }
2105 other => {
2106 Output::info(format!("Stack status: {other:?}"));
2107 }
2108 }
2109 }
2110 }
2111 Err(e) => {
2112 if force {
2113 Output::warning(format!(
2114 "Failed to check stack status: {e} (continuing due to --force)"
2115 ));
2116 } else {
2117 return Err(e);
2118 }
2119 }
2120 }
2121
2122 if !skip_cleanup {
2124 Output::section("Checking for merged branches to clean up");
2125 Output::info("Branch cleanup not yet implemented");
2131 } else {
2132 Output::info("Skipping branch cleanup");
2133 }
2134
2135 Output::success("Sync completed successfully!");
2136 Output::sub_item(format!("Base branch: {base_branch}"));
2137 Output::next_steps(&[
2138 "Review your updated stack: ca stack show",
2139 "Check PR status: ca stack status",
2140 ]);
2141
2142 Ok(())
2143}
2144
2145async fn rebase_stack(
2146 interactive: bool,
2147 onto: Option<String>,
2148 strategy: Option<RebaseStrategyArg>,
2149) -> Result<()> {
2150 let current_dir = env::current_dir()
2151 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2152
2153 let repo_root = find_repository_root(¤t_dir)
2154 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2155
2156 let stack_manager = StackManager::new(&repo_root)?;
2157 let git_repo = GitRepository::open(&repo_root)?;
2158
2159 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2161 let config_path = config_dir.join("config.json");
2162 let settings = crate::config::Settings::load_from_file(&config_path)?;
2163
2164 let cascade_config = crate::config::CascadeConfig {
2166 bitbucket: Some(settings.bitbucket.clone()),
2167 git: settings.git.clone(),
2168 auth: crate::config::AuthConfig::default(),
2169 cascade: settings.cascade.clone(),
2170 };
2171
2172 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
2174 CascadeError::config("No active stack. Create a stack first with 'ca stack create'")
2175 })?;
2176 let stack_id = active_stack.id;
2177
2178 let active_stack = stack_manager
2179 .get_stack(&stack_id)
2180 .ok_or_else(|| CascadeError::config("Active stack not found"))?
2181 .clone();
2182
2183 if active_stack.entries.is_empty() {
2184 Output::info("Stack is empty. Nothing to rebase.");
2185 return Ok(());
2186 }
2187
2188 Output::progress(format!("Rebasing stack: {}", active_stack.name));
2189 Output::sub_item(format!("Base: {}", active_stack.base_branch));
2190
2191 let rebase_strategy = if let Some(cli_strategy) = strategy {
2193 match cli_strategy {
2194 RebaseStrategyArg::BranchVersioning => crate::stack::RebaseStrategy::BranchVersioning,
2195 RebaseStrategyArg::CherryPick => crate::stack::RebaseStrategy::CherryPick,
2196 RebaseStrategyArg::ThreeWayMerge => crate::stack::RebaseStrategy::ThreeWayMerge,
2197 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
2198 }
2199 } else {
2200 match settings.cascade.default_sync_strategy.as_str() {
2202 "branch-versioning" => crate::stack::RebaseStrategy::BranchVersioning,
2203 "cherry-pick" => crate::stack::RebaseStrategy::CherryPick,
2204 "three-way-merge" => crate::stack::RebaseStrategy::ThreeWayMerge,
2205 "rebase" => crate::stack::RebaseStrategy::Interactive,
2206 _ => crate::stack::RebaseStrategy::BranchVersioning, }
2208 };
2209
2210 let options = crate::stack::RebaseOptions {
2212 strategy: rebase_strategy.clone(),
2213 interactive,
2214 target_base: onto,
2215 preserve_merges: true,
2216 auto_resolve: !interactive, max_retries: 3,
2218 skip_pull: None, };
2220
2221 info!(" Strategy: {:?}", rebase_strategy);
2222 info!(" Interactive: {}", interactive);
2223 info!(" Target base: {:?}", options.target_base);
2224 info!(" Entries: {}", active_stack.entries.len());
2225
2226 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2228
2229 if rebase_manager.is_rebase_in_progress() {
2230 Output::warning("Rebase already in progress!");
2231 Output::tip("Use 'git status' to check the current state");
2232 Output::next_steps(&[
2233 "Run 'ca stack continue-rebase' to continue",
2234 "Run 'ca stack abort-rebase' to abort",
2235 ]);
2236 return Ok(());
2237 }
2238
2239 match rebase_manager.rebase_stack(&stack_id) {
2241 Ok(result) => {
2242 Output::success("Rebase completed!");
2243 Output::sub_item(result.get_summary());
2244
2245 if result.has_conflicts() {
2246 Output::warning(format!(
2247 "{} conflicts were resolved",
2248 result.conflicts.len()
2249 ));
2250 for conflict in &result.conflicts {
2251 Output::bullet(&conflict[..8.min(conflict.len())]);
2252 }
2253 }
2254
2255 if !result.branch_mapping.is_empty() {
2256 Output::section("Branch mapping");
2257 for (old, new) in &result.branch_mapping {
2258 Output::bullet(format!("{old} -> {new}"));
2259 }
2260
2261 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
2263 let integration_stack_manager = StackManager::new(&repo_root)?;
2265 let mut integration = BitbucketIntegration::new(
2266 integration_stack_manager,
2267 cascade_config.clone(),
2268 )?;
2269
2270 match integration
2271 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
2272 .await
2273 {
2274 Ok(updated_prs) => {
2275 if !updated_prs.is_empty() {
2276 println!(" 🔄 Preserved pull request history:");
2277 for pr_update in updated_prs {
2278 println!(" ✅ {pr_update}");
2279 }
2280 }
2281 }
2282 Err(e) => {
2283 eprintln!(" ⚠️ Failed to update pull requests: {e}");
2284 eprintln!(" You may need to manually update PRs in Bitbucket");
2285 }
2286 }
2287 }
2288 }
2289
2290 println!(
2291 " ✅ {} commits successfully rebased",
2292 result.success_count()
2293 );
2294
2295 if matches!(
2297 rebase_strategy,
2298 crate::stack::RebaseStrategy::BranchVersioning
2299 ) {
2300 println!("\n📝 Next steps:");
2301 if !result.branch_mapping.is_empty() {
2302 println!(" 1. ✅ New versioned branches have been created");
2303 println!(" 2. ✅ Pull requests have been updated automatically");
2304 println!(" 3. 🔍 Review the updated PRs in Bitbucket");
2305 println!(" 4. 🧪 Test your changes on the new branches");
2306 println!(
2307 " 5. 🗑️ Old branches are preserved for safety (can be deleted later)"
2308 );
2309 } else {
2310 println!(" 1. Review the rebased stack");
2311 println!(" 2. Test your changes");
2312 println!(" 3. Submit new pull requests with 'ca stack submit'");
2313 }
2314 }
2315 }
2316 Err(e) => {
2317 warn!("❌ Rebase failed: {}", e);
2318 println!("💡 Tips for resolving rebase issues:");
2319 println!(" - Check for uncommitted changes with 'git status'");
2320 println!(" - Ensure base branch is up to date");
2321 println!(" - Try interactive mode: 'ca stack rebase --interactive'");
2322 return Err(e);
2323 }
2324 }
2325
2326 Ok(())
2327}
2328
2329async fn continue_rebase() -> Result<()> {
2330 let current_dir = env::current_dir()
2331 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2332
2333 let repo_root = find_repository_root(¤t_dir)
2334 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2335
2336 let stack_manager = StackManager::new(&repo_root)?;
2337 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2338 let options = crate::stack::RebaseOptions::default();
2339 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2340
2341 if !rebase_manager.is_rebase_in_progress() {
2342 println!("ℹ️ No rebase in progress");
2343 return Ok(());
2344 }
2345
2346 println!("🔄 Continuing rebase...");
2347 match rebase_manager.continue_rebase() {
2348 Ok(_) => {
2349 println!("✅ Rebase continued successfully");
2350 println!(" Check 'ca stack rebase-status' for current state");
2351 }
2352 Err(e) => {
2353 warn!("❌ Failed to continue rebase: {}", e);
2354 println!("💡 You may need to resolve conflicts first:");
2355 println!(" 1. Edit conflicted files");
2356 println!(" 2. Stage resolved files with 'git add'");
2357 println!(" 3. Run 'ca stack continue-rebase' again");
2358 }
2359 }
2360
2361 Ok(())
2362}
2363
2364async fn abort_rebase() -> Result<()> {
2365 let current_dir = env::current_dir()
2366 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2367
2368 let repo_root = find_repository_root(¤t_dir)
2369 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2370
2371 let stack_manager = StackManager::new(&repo_root)?;
2372 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2373 let options = crate::stack::RebaseOptions::default();
2374 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2375
2376 if !rebase_manager.is_rebase_in_progress() {
2377 println!("ℹ️ No rebase in progress");
2378 return Ok(());
2379 }
2380
2381 println!("⚠️ Aborting rebase...");
2382 match rebase_manager.abort_rebase() {
2383 Ok(_) => {
2384 println!("✅ Rebase aborted successfully");
2385 println!(" Repository restored to pre-rebase state");
2386 }
2387 Err(e) => {
2388 warn!("❌ Failed to abort rebase: {}", e);
2389 println!("⚠️ You may need to manually clean up the repository state");
2390 }
2391 }
2392
2393 Ok(())
2394}
2395
2396async fn rebase_status() -> Result<()> {
2397 let current_dir = env::current_dir()
2398 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2399
2400 let repo_root = find_repository_root(¤t_dir)
2401 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2402
2403 let stack_manager = StackManager::new(&repo_root)?;
2404 let git_repo = crate::git::GitRepository::open(&repo_root)?;
2405
2406 println!("📊 Rebase Status");
2407
2408 let git_dir = current_dir.join(".git");
2410 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2411 || git_dir.join("rebase-merge").exists()
2412 || git_dir.join("rebase-apply").exists();
2413
2414 if rebase_in_progress {
2415 println!(" Status: 🔄 Rebase in progress");
2416 println!(
2417 "
2418📝 Actions available:"
2419 );
2420 println!(" - 'ca stack continue-rebase' to continue");
2421 println!(" - 'ca stack abort-rebase' to abort");
2422 println!(" - 'git status' to see conflicted files");
2423
2424 match git_repo.get_status() {
2426 Ok(statuses) => {
2427 let mut conflicts = Vec::new();
2428 for status in statuses.iter() {
2429 if status.status().contains(git2::Status::CONFLICTED) {
2430 if let Some(path) = status.path() {
2431 conflicts.push(path.to_string());
2432 }
2433 }
2434 }
2435
2436 if !conflicts.is_empty() {
2437 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2438 for conflict in conflicts {
2439 println!(" - {conflict}");
2440 }
2441 println!(
2442 "
2443💡 To resolve conflicts:"
2444 );
2445 println!(" 1. Edit the conflicted files");
2446 println!(" 2. Stage resolved files: git add <file>");
2447 println!(" 3. Continue: ca stack continue-rebase");
2448 }
2449 }
2450 Err(e) => {
2451 warn!("Failed to get git status: {}", e);
2452 }
2453 }
2454 } else {
2455 println!(" Status: ✅ No rebase in progress");
2456
2457 if let Some(active_stack) = stack_manager.get_active_stack() {
2459 println!(" Active stack: {}", active_stack.name);
2460 println!(" Entries: {}", active_stack.entries.len());
2461 println!(" Base branch: {}", active_stack.base_branch);
2462 }
2463 }
2464
2465 Ok(())
2466}
2467
2468async fn delete_stack(name: String, force: bool) -> Result<()> {
2469 let current_dir = env::current_dir()
2470 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2471
2472 let repo_root = find_repository_root(¤t_dir)
2473 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2474
2475 let mut manager = StackManager::new(&repo_root)?;
2476
2477 let stack = manager
2478 .get_stack_by_name(&name)
2479 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2480 let stack_id = stack.id;
2481
2482 if !force && !stack.entries.is_empty() {
2483 return Err(CascadeError::config(format!(
2484 "Stack '{}' has {} entries. Use --force to delete anyway",
2485 name,
2486 stack.entries.len()
2487 )));
2488 }
2489
2490 let deleted = manager.delete_stack(&stack_id)?;
2491
2492 Output::success(format!("Deleted stack '{}'", deleted.name));
2493 if !deleted.entries.is_empty() {
2494 Output::warning(format!("{} entries were removed", deleted.entries.len()));
2495 }
2496
2497 Ok(())
2498}
2499
2500async fn validate_stack(name: Option<String>, fix_mode: Option<String>) -> Result<()> {
2501 let current_dir = env::current_dir()
2502 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2503
2504 let repo_root = find_repository_root(¤t_dir)
2505 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2506
2507 let mut manager = StackManager::new(&repo_root)?;
2508
2509 if let Some(name) = name {
2510 let stack = manager
2512 .get_stack_by_name(&name)
2513 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2514
2515 let stack_id = stack.id;
2516
2517 match stack.validate() {
2519 Ok(message) => {
2520 println!("✅ Stack '{name}' structure validation: {message}");
2521 }
2522 Err(e) => {
2523 println!("❌ Stack '{name}' structure validation failed: {e}");
2524 return Err(CascadeError::config(e));
2525 }
2526 }
2527
2528 manager.handle_branch_modifications(&stack_id, fix_mode)?;
2530
2531 println!("🎉 Stack '{name}' validation completed");
2532 Ok(())
2533 } else {
2534 println!("🔍 Validating all stacks...");
2536
2537 let all_stacks = manager.get_all_stacks();
2539 let stack_ids: Vec<uuid::Uuid> = all_stacks.iter().map(|s| s.id).collect();
2540
2541 if stack_ids.is_empty() {
2542 println!("📭 No stacks found");
2543 return Ok(());
2544 }
2545
2546 let mut all_valid = true;
2547 for stack_id in stack_ids {
2548 let stack = manager.get_stack(&stack_id).unwrap();
2549 let stack_name = &stack.name;
2550
2551 println!("\n📋 Checking stack '{stack_name}':");
2552
2553 match stack.validate() {
2555 Ok(message) => {
2556 println!(" ✅ Structure: {message}");
2557 }
2558 Err(e) => {
2559 println!(" ❌ Structure: {e}");
2560 all_valid = false;
2561 continue;
2562 }
2563 }
2564
2565 match manager.handle_branch_modifications(&stack_id, fix_mode.clone()) {
2567 Ok(_) => {
2568 println!(" ✅ Git integrity: OK");
2569 }
2570 Err(e) => {
2571 println!(" ❌ Git integrity: {e}");
2572 all_valid = false;
2573 }
2574 }
2575 }
2576
2577 if all_valid {
2578 println!("\n🎉 All stacks passed validation");
2579 } else {
2580 println!("\n⚠️ Some stacks have validation issues");
2581 return Err(CascadeError::config("Stack validation failed".to_string()));
2582 }
2583
2584 Ok(())
2585 }
2586}
2587
2588#[allow(dead_code)]
2590fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2591 let mut unpushed = Vec::new();
2592 let head_commit = repo.get_head_commit()?;
2593 let mut current_commit = head_commit;
2594
2595 loop {
2597 let commit_hash = current_commit.id().to_string();
2598 let already_in_stack = stack
2599 .entries
2600 .iter()
2601 .any(|entry| entry.commit_hash == commit_hash);
2602
2603 if already_in_stack {
2604 break;
2605 }
2606
2607 unpushed.push(commit_hash);
2608
2609 if let Some(parent) = current_commit.parents().next() {
2611 current_commit = parent;
2612 } else {
2613 break;
2614 }
2615 }
2616
2617 unpushed.reverse(); Ok(unpushed)
2619}
2620
2621pub async fn squash_commits(
2623 repo: &GitRepository,
2624 count: usize,
2625 since_ref: Option<String>,
2626) -> Result<()> {
2627 if count <= 1 {
2628 return Ok(()); }
2630
2631 let _current_branch = repo.get_current_branch()?;
2633
2634 let rebase_range = if let Some(ref since) = since_ref {
2636 since.clone()
2637 } else {
2638 format!("HEAD~{count}")
2639 };
2640
2641 println!(" Analyzing {count} commits to create smart squash message...");
2642
2643 let head_commit = repo.get_head_commit()?;
2645 let mut commits_to_squash = Vec::new();
2646 let mut current = head_commit;
2647
2648 for _ in 0..count {
2650 commits_to_squash.push(current.clone());
2651 if current.parent_count() > 0 {
2652 current = current.parent(0).map_err(CascadeError::Git)?;
2653 } else {
2654 break;
2655 }
2656 }
2657
2658 let smart_message = generate_squash_message(&commits_to_squash)?;
2660 println!(
2661 " Smart message: {}",
2662 smart_message.lines().next().unwrap_or("")
2663 );
2664
2665 let reset_target = if since_ref.is_some() {
2667 format!("{rebase_range}~1")
2669 } else {
2670 format!("HEAD~{count}")
2672 };
2673
2674 repo.reset_soft(&reset_target)?;
2676
2677 repo.stage_all()?;
2679
2680 let new_commit_hash = repo.commit(&smart_message)?;
2682
2683 println!(
2684 " Created squashed commit: {} ({})",
2685 &new_commit_hash[..8],
2686 smart_message.lines().next().unwrap_or("")
2687 );
2688 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2689
2690 Ok(())
2691}
2692
2693pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2695 if commits.is_empty() {
2696 return Ok("Squashed commits".to_string());
2697 }
2698
2699 let messages: Vec<String> = commits
2701 .iter()
2702 .map(|c| c.message().unwrap_or("").trim().to_string())
2703 .filter(|m| !m.is_empty())
2704 .collect();
2705
2706 if messages.is_empty() {
2707 return Ok("Squashed commits".to_string());
2708 }
2709
2710 if let Some(last_msg) = messages.first() {
2712 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2714 return Ok(last_msg
2715 .trim_start_matches("Final:")
2716 .trim_start_matches("final:")
2717 .trim()
2718 .to_string());
2719 }
2720 }
2721
2722 let wip_count = messages
2724 .iter()
2725 .filter(|m| {
2726 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2727 })
2728 .count();
2729
2730 if wip_count > messages.len() / 2 {
2731 let non_wip: Vec<&String> = messages
2733 .iter()
2734 .filter(|m| {
2735 !m.to_lowercase().starts_with("wip")
2736 && !m.to_lowercase().contains("work in progress")
2737 })
2738 .collect();
2739
2740 if let Some(best_msg) = non_wip.first() {
2741 return Ok(best_msg.to_string());
2742 }
2743
2744 let feature = extract_feature_from_wip(&messages);
2746 return Ok(feature);
2747 }
2748
2749 Ok(messages.first().unwrap().clone())
2751}
2752
2753pub fn extract_feature_from_wip(messages: &[String]) -> String {
2755 for msg in messages {
2757 if msg.to_lowercase().starts_with("wip:") {
2759 if let Some(rest) = msg
2760 .strip_prefix("WIP:")
2761 .or_else(|| msg.strip_prefix("wip:"))
2762 {
2763 let feature = rest.trim();
2764 if !feature.is_empty() && feature.len() > 3 {
2765 let mut chars: Vec<char> = feature.chars().collect();
2767 if let Some(first) = chars.first_mut() {
2768 *first = first.to_uppercase().next().unwrap_or(*first);
2769 }
2770 return chars.into_iter().collect();
2771 }
2772 }
2773 }
2774 }
2775
2776 if let Some(first) = messages.first() {
2778 let cleaned = first
2779 .trim_start_matches("WIP:")
2780 .trim_start_matches("wip:")
2781 .trim_start_matches("WIP")
2782 .trim_start_matches("wip")
2783 .trim();
2784
2785 if !cleaned.is_empty() {
2786 return format!("Implement {cleaned}");
2787 }
2788 }
2789
2790 format!("Squashed {} commits", messages.len())
2791}
2792
2793pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
2795 let head_commit = repo.get_head_commit()?;
2796 let since_commit = repo.get_commit(since_commit_hash)?;
2797
2798 let mut count = 0;
2799 let mut current = head_commit;
2800
2801 loop {
2803 if current.id() == since_commit.id() {
2804 break;
2805 }
2806
2807 count += 1;
2808
2809 if current.parent_count() == 0 {
2811 break; }
2813
2814 current = current.parent(0).map_err(CascadeError::Git)?;
2815 }
2816
2817 Ok(count)
2818}
2819
2820async fn land_stack(
2822 entry: Option<usize>,
2823 force: bool,
2824 dry_run: bool,
2825 auto: bool,
2826 wait_for_builds: bool,
2827 strategy: Option<MergeStrategyArg>,
2828 build_timeout: u64,
2829) -> Result<()> {
2830 let current_dir = env::current_dir()
2831 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2832
2833 let repo_root = find_repository_root(¤t_dir)
2834 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
2835
2836 let stack_manager = StackManager::new(&repo_root)?;
2837
2838 let stack_id = stack_manager
2840 .get_active_stack()
2841 .map(|s| s.id)
2842 .ok_or_else(|| {
2843 CascadeError::config(
2844 "No active stack. Use 'ca stack create' or 'ca stack switch' to select a stack"
2845 .to_string(),
2846 )
2847 })?;
2848
2849 let active_stack = stack_manager
2850 .get_active_stack()
2851 .cloned()
2852 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
2853
2854 let config_dir = crate::config::get_repo_config_dir(&repo_root)?;
2856 let config_path = config_dir.join("config.json");
2857 let settings = crate::config::Settings::load_from_file(&config_path)?;
2858
2859 let cascade_config = crate::config::CascadeConfig {
2860 bitbucket: Some(settings.bitbucket.clone()),
2861 git: settings.git.clone(),
2862 auth: crate::config::AuthConfig::default(),
2863 cascade: settings.cascade.clone(),
2864 };
2865
2866 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2867
2868 let status = integration.check_enhanced_stack_status(&stack_id).await?;
2870
2871 if status.enhanced_statuses.is_empty() {
2872 println!("❌ No pull requests found to land");
2873 return Ok(());
2874 }
2875
2876 let ready_prs: Vec<_> = status
2878 .enhanced_statuses
2879 .iter()
2880 .filter(|pr_status| {
2881 if let Some(entry_num) = entry {
2883 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
2885 if pr_status.pr.from_ref.display_id != stack_entry.branch {
2887 return false;
2888 }
2889 } else {
2890 return false; }
2892 }
2893
2894 if force {
2895 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
2897 } else {
2898 pr_status.is_ready_to_land()
2899 }
2900 })
2901 .collect();
2902
2903 if ready_prs.is_empty() {
2904 if let Some(entry_num) = entry {
2905 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
2906 } else {
2907 println!("❌ No pull requests are ready to land");
2908 }
2909
2910 println!("\n🚫 Blocking Issues:");
2912 for pr_status in &status.enhanced_statuses {
2913 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
2914 let blocking = pr_status.get_blocking_reasons();
2915 if !blocking.is_empty() {
2916 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
2917 }
2918 }
2919 }
2920
2921 if !force {
2922 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
2923 }
2924 return Ok(());
2925 }
2926
2927 if dry_run {
2928 if let Some(entry_num) = entry {
2929 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
2930 } else {
2931 println!("🏃 Dry Run - PRs that would be landed:");
2932 }
2933 for pr_status in &ready_prs {
2934 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
2935 if !pr_status.is_ready_to_land() && force {
2936 let blocking = pr_status.get_blocking_reasons();
2937 println!(
2938 " ⚠️ Would force land despite: {}",
2939 blocking.join(", ")
2940 );
2941 }
2942 }
2943 return Ok(());
2944 }
2945
2946 if entry.is_some() && ready_prs.len() > 1 {
2949 println!(
2950 "🎯 {} PRs are ready to land, but landing only entry #{}",
2951 ready_prs.len(),
2952 entry.unwrap()
2953 );
2954 }
2955
2956 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
2958 strategy.unwrap_or(MergeStrategyArg::Squash).into();
2959 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
2960 merge_strategy: merge_strategy.clone(),
2961 wait_for_builds,
2962 build_timeout: std::time::Duration::from_secs(build_timeout),
2963 allowed_authors: None, };
2965
2966 println!(
2968 "🚀 Landing {} PR{}...",
2969 ready_prs.len(),
2970 if ready_prs.len() == 1 { "" } else { "s" }
2971 );
2972
2973 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
2974 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
2975 );
2976
2977 let mut landed_count = 0;
2979 let mut failed_count = 0;
2980 let total_ready_prs = ready_prs.len();
2981
2982 for pr_status in ready_prs {
2983 let pr_id = pr_status.pr.id;
2984
2985 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
2986
2987 let land_result = if auto {
2988 pr_manager
2990 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
2991 .await
2992 } else {
2993 pr_manager
2995 .merge_pull_request(pr_id, merge_strategy.clone())
2996 .await
2997 .map(
2998 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
2999 pr: Box::new(pr),
3000 merge_strategy: merge_strategy.clone(),
3001 },
3002 )
3003 };
3004
3005 match land_result {
3006 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
3007 println!(" ✅");
3008 landed_count += 1;
3009
3010 if landed_count < total_ready_prs {
3012 println!("🔄 Retargeting remaining PRs to latest base...");
3013
3014 let base_branch = active_stack.base_branch.clone();
3016 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3017
3018 println!(" 📥 Updating base branch: {base_branch}");
3019 match git_repo.pull(&base_branch) {
3020 Ok(_) => println!(" ✅ Base branch updated successfully"),
3021 Err(e) => {
3022 println!(" ⚠️ Warning: Failed to update base branch: {e}");
3023 println!(
3024 " 💡 You may want to manually run: git pull origin {base_branch}"
3025 );
3026 }
3027 }
3028
3029 let mut rebase_manager = crate::stack::RebaseManager::new(
3031 StackManager::new(&repo_root)?,
3032 git_repo,
3033 crate::stack::RebaseOptions {
3034 strategy: crate::stack::RebaseStrategy::BranchVersioning,
3035 target_base: Some(base_branch.clone()),
3036 ..Default::default()
3037 },
3038 );
3039
3040 match rebase_manager.rebase_stack(&stack_id) {
3041 Ok(rebase_result) => {
3042 if !rebase_result.branch_mapping.is_empty() {
3043 let retarget_config = crate::config::CascadeConfig {
3045 bitbucket: Some(settings.bitbucket.clone()),
3046 git: settings.git.clone(),
3047 auth: crate::config::AuthConfig::default(),
3048 cascade: settings.cascade.clone(),
3049 };
3050 let mut retarget_integration = BitbucketIntegration::new(
3051 StackManager::new(&repo_root)?,
3052 retarget_config,
3053 )?;
3054
3055 match retarget_integration
3056 .update_prs_after_rebase(
3057 &stack_id,
3058 &rebase_result.branch_mapping,
3059 )
3060 .await
3061 {
3062 Ok(updated_prs) => {
3063 if !updated_prs.is_empty() {
3064 println!(
3065 " ✅ Updated {} PRs with new targets",
3066 updated_prs.len()
3067 );
3068 }
3069 }
3070 Err(e) => {
3071 println!(" ⚠️ Failed to update remaining PRs: {e}");
3072 println!(
3073 " 💡 You may need to run: ca stack rebase --onto {base_branch}"
3074 );
3075 }
3076 }
3077 }
3078 }
3079 Err(e) => {
3080 println!(" ❌ Auto-retargeting conflicts detected!");
3082 println!(" 📝 To resolve conflicts and continue landing:");
3083 println!(" 1. Resolve conflicts in the affected files");
3084 println!(" 2. Stage resolved files: git add <files>");
3085 println!(" 3. Continue the process: ca stack continue-land");
3086 println!(" 4. Or abort the operation: ca stack abort-land");
3087 println!();
3088 println!(" 💡 Check current status: ca stack land-status");
3089 println!(" ⚠️ Error details: {e}");
3090
3091 break;
3093 }
3094 }
3095 }
3096 }
3097 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
3098 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
3099 failed_count += 1;
3100 if !force {
3101 break;
3102 }
3103 }
3104 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
3105 println!(" ❌ Failed: {error}");
3106 failed_count += 1;
3107 if !force {
3108 break;
3109 }
3110 }
3111 Err(e) => {
3112 println!(" ❌");
3113 eprintln!("Failed to land PR #{pr_id}: {e}");
3114 failed_count += 1;
3115
3116 if !force {
3117 break;
3118 }
3119 }
3120 }
3121 }
3122
3123 println!("\n🎯 Landing Summary:");
3125 println!(" ✅ Successfully landed: {landed_count}");
3126 if failed_count > 0 {
3127 println!(" ❌ Failed to land: {failed_count}");
3128 }
3129
3130 if landed_count > 0 {
3131 println!("✅ Landing operation completed!");
3132 } else {
3133 println!("❌ No PRs were successfully landed");
3134 }
3135
3136 Ok(())
3137}
3138
3139async fn auto_land_stack(
3141 force: bool,
3142 dry_run: bool,
3143 wait_for_builds: bool,
3144 strategy: Option<MergeStrategyArg>,
3145 build_timeout: u64,
3146) -> Result<()> {
3147 land_stack(
3149 None,
3150 force,
3151 dry_run,
3152 true, wait_for_builds,
3154 strategy,
3155 build_timeout,
3156 )
3157 .await
3158}
3159
3160async fn continue_land() -> Result<()> {
3161 let current_dir = env::current_dir()
3162 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3163
3164 let repo_root = find_repository_root(¤t_dir)
3165 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3166
3167 let stack_manager = StackManager::new(&repo_root)?;
3168 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3169 let options = crate::stack::RebaseOptions::default();
3170 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3171
3172 if !rebase_manager.is_rebase_in_progress() {
3173 println!("ℹ️ No rebase in progress");
3174 return Ok(());
3175 }
3176
3177 println!("🔄 Continuing land operation...");
3178 match rebase_manager.continue_rebase() {
3179 Ok(_) => {
3180 println!("✅ Land operation continued successfully");
3181 println!(" Check 'ca stack land-status' for current state");
3182 }
3183 Err(e) => {
3184 warn!("❌ Failed to continue land operation: {}", e);
3185 println!("💡 You may need to resolve conflicts first:");
3186 println!(" 1. Edit conflicted files");
3187 println!(" 2. Stage resolved files with 'git add'");
3188 println!(" 3. Run 'ca stack continue-land' again");
3189 }
3190 }
3191
3192 Ok(())
3193}
3194
3195async fn abort_land() -> Result<()> {
3196 let current_dir = env::current_dir()
3197 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3198
3199 let repo_root = find_repository_root(¤t_dir)
3200 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3201
3202 let stack_manager = StackManager::new(&repo_root)?;
3203 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3204 let options = crate::stack::RebaseOptions::default();
3205 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
3206
3207 if !rebase_manager.is_rebase_in_progress() {
3208 println!("ℹ️ No rebase in progress");
3209 return Ok(());
3210 }
3211
3212 println!("⚠️ Aborting land operation...");
3213 match rebase_manager.abort_rebase() {
3214 Ok(_) => {
3215 println!("✅ Land operation aborted successfully");
3216 println!(" Repository restored to pre-land state");
3217 }
3218 Err(e) => {
3219 warn!("❌ Failed to abort land operation: {}", e);
3220 println!("⚠️ You may need to manually clean up the repository state");
3221 }
3222 }
3223
3224 Ok(())
3225}
3226
3227async fn land_status() -> Result<()> {
3228 let current_dir = env::current_dir()
3229 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3230
3231 let repo_root = find_repository_root(¤t_dir)
3232 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3233
3234 let stack_manager = StackManager::new(&repo_root)?;
3235 let git_repo = crate::git::GitRepository::open(&repo_root)?;
3236
3237 println!("📊 Land Status");
3238
3239 let git_dir = repo_root.join(".git");
3241 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
3242 || git_dir.join("rebase-merge").exists()
3243 || git_dir.join("rebase-apply").exists();
3244
3245 if land_in_progress {
3246 println!(" Status: 🔄 Land operation in progress");
3247 println!(
3248 "
3249📝 Actions available:"
3250 );
3251 println!(" - 'ca stack continue-land' to continue");
3252 println!(" - 'ca stack abort-land' to abort");
3253 println!(" - 'git status' to see conflicted files");
3254
3255 match git_repo.get_status() {
3257 Ok(statuses) => {
3258 let mut conflicts = Vec::new();
3259 for status in statuses.iter() {
3260 if status.status().contains(git2::Status::CONFLICTED) {
3261 if let Some(path) = status.path() {
3262 conflicts.push(path.to_string());
3263 }
3264 }
3265 }
3266
3267 if !conflicts.is_empty() {
3268 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
3269 for conflict in conflicts {
3270 println!(" - {conflict}");
3271 }
3272 println!(
3273 "
3274💡 To resolve conflicts:"
3275 );
3276 println!(" 1. Edit the conflicted files");
3277 println!(" 2. Stage resolved files: git add <file>");
3278 println!(" 3. Continue: ca stack continue-land");
3279 }
3280 }
3281 Err(e) => {
3282 warn!("Failed to get git status: {}", e);
3283 }
3284 }
3285 } else {
3286 println!(" Status: ✅ No land operation in progress");
3287
3288 if let Some(active_stack) = stack_manager.get_active_stack() {
3290 println!(" Active stack: {}", active_stack.name);
3291 println!(" Entries: {}", active_stack.entries.len());
3292 println!(" Base branch: {}", active_stack.base_branch);
3293 }
3294 }
3295
3296 Ok(())
3297}
3298
3299async fn repair_stack_data() -> Result<()> {
3300 let current_dir = env::current_dir()
3301 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
3302
3303 let repo_root = find_repository_root(¤t_dir)
3304 .map_err(|e| CascadeError::config(format!("Could not find git repository: {e}")))?;
3305
3306 let mut stack_manager = StackManager::new(&repo_root)?;
3307
3308 println!("🔧 Repairing stack data consistency...");
3309
3310 stack_manager.repair_all_stacks()?;
3311
3312 println!("✅ Stack data consistency repaired successfully!");
3313 println!("💡 Run 'ca stack --mergeable' to see updated status");
3314
3315 Ok(())
3316}
3317
3318async fn analyze_commits_for_safeguards(
3320 commits_to_push: &[String],
3321 repo: &GitRepository,
3322 dry_run: bool,
3323) -> Result<()> {
3324 const LARGE_COMMIT_THRESHOLD: usize = 10;
3325 const WEEK_IN_SECONDS: i64 = 7 * 24 * 3600;
3326
3327 if commits_to_push.len() > LARGE_COMMIT_THRESHOLD {
3329 println!(
3330 "⚠️ Warning: About to push {} commits to stack",
3331 commits_to_push.len()
3332 );
3333 println!(" This may indicate a merge commit issue or unexpected commit range.");
3334 println!(" Large commit counts often result from merging instead of rebasing.");
3335
3336 if !dry_run && !confirm_large_push(commits_to_push.len())? {
3337 return Err(CascadeError::config("Push cancelled by user"));
3338 }
3339 }
3340
3341 let commit_objects: Result<Vec<_>> = commits_to_push
3343 .iter()
3344 .map(|hash| repo.get_commit(hash))
3345 .collect();
3346 let commit_objects = commit_objects?;
3347
3348 let merge_commits: Vec<_> = commit_objects
3350 .iter()
3351 .filter(|c| c.parent_count() > 1)
3352 .collect();
3353
3354 if !merge_commits.is_empty() {
3355 println!(
3356 "⚠️ Warning: {} merge commits detected in push",
3357 merge_commits.len()
3358 );
3359 println!(" This often indicates you merged instead of rebased.");
3360 println!(" Consider using 'ca sync' to rebase on the base branch.");
3361 println!(" Merge commits in stacks can cause confusion and duplicate work.");
3362 }
3363
3364 if commit_objects.len() > 1 {
3366 let oldest_commit_time = commit_objects.first().unwrap().time().seconds();
3367 let newest_commit_time = commit_objects.last().unwrap().time().seconds();
3368 let time_span = newest_commit_time - oldest_commit_time;
3369
3370 if time_span > WEEK_IN_SECONDS {
3371 let days = time_span / (24 * 3600);
3372 println!("⚠️ Warning: Commits span {days} days");
3373 println!(" This may indicate merged history rather than new work.");
3374 println!(" Recent work should typically span hours or days, not weeks.");
3375 }
3376 }
3377
3378 if commits_to_push.len() > 5 {
3380 println!("💡 Tip: If you only want recent commits, use:");
3381 println!(
3382 " ca push --since HEAD~{} # pushes last {} commits",
3383 std::cmp::min(commits_to_push.len(), 5),
3384 std::cmp::min(commits_to_push.len(), 5)
3385 );
3386 println!(" ca push --commits <hash1>,<hash2> # pushes specific commits");
3387 println!(" ca push --dry-run # preview what would be pushed");
3388 }
3389
3390 if dry_run {
3392 println!("🔍 DRY RUN: Would push {} commits:", commits_to_push.len());
3393 for (i, (commit_hash, commit_obj)) in commits_to_push
3394 .iter()
3395 .zip(commit_objects.iter())
3396 .enumerate()
3397 {
3398 let summary = commit_obj.summary().unwrap_or("(no message)");
3399 let short_hash = &commit_hash[..std::cmp::min(commit_hash.len(), 7)];
3400 println!(" {}: {} ({})", i + 1, summary, short_hash);
3401 }
3402 println!("💡 Run without --dry-run to actually push these commits.");
3403 }
3404
3405 Ok(())
3406}
3407
3408fn confirm_large_push(count: usize) -> Result<bool> {
3410 print!("Do you want to continue pushing {count} commits? [y/N]: ");
3411 io::stdout()
3412 .flush()
3413 .map_err(|e| CascadeError::config(format!("Failed to flush stdout: {e}")))?;
3414
3415 let mut input = String::new();
3416 io::stdin()
3417 .read_line(&mut input)
3418 .map_err(|e| CascadeError::config(format!("Failed to read user input: {e}")))?;
3419
3420 let input = input.trim().to_lowercase();
3421 Ok(input == "y" || input == "yes")
3422}
3423
3424#[cfg(test)]
3425mod tests {
3426 use super::*;
3427 use std::process::Command;
3428 use tempfile::TempDir;
3429
3430 fn create_test_repo() -> Result<(TempDir, std::path::PathBuf)> {
3431 let temp_dir = TempDir::new()
3432 .map_err(|e| CascadeError::config(format!("Failed to create temp directory: {e}")))?;
3433 let repo_path = temp_dir.path().to_path_buf();
3434
3435 let output = Command::new("git")
3437 .args(["init"])
3438 .current_dir(&repo_path)
3439 .output()
3440 .map_err(|e| CascadeError::config(format!("Failed to run git init: {e}")))?;
3441 if !output.status.success() {
3442 return Err(CascadeError::config("Git init failed".to_string()));
3443 }
3444
3445 let output = Command::new("git")
3446 .args(["config", "user.name", "Test User"])
3447 .current_dir(&repo_path)
3448 .output()
3449 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3450 if !output.status.success() {
3451 return Err(CascadeError::config(
3452 "Git config user.name failed".to_string(),
3453 ));
3454 }
3455
3456 let output = Command::new("git")
3457 .args(["config", "user.email", "test@example.com"])
3458 .current_dir(&repo_path)
3459 .output()
3460 .map_err(|e| CascadeError::config(format!("Failed to run git config: {e}")))?;
3461 if !output.status.success() {
3462 return Err(CascadeError::config(
3463 "Git config user.email failed".to_string(),
3464 ));
3465 }
3466
3467 std::fs::write(repo_path.join("README.md"), "# Test")
3469 .map_err(|e| CascadeError::config(format!("Failed to write file: {e}")))?;
3470 let output = Command::new("git")
3471 .args(["add", "."])
3472 .current_dir(&repo_path)
3473 .output()
3474 .map_err(|e| CascadeError::config(format!("Failed to run git add: {e}")))?;
3475 if !output.status.success() {
3476 return Err(CascadeError::config("Git add failed".to_string()));
3477 }
3478
3479 let output = Command::new("git")
3480 .args(["commit", "-m", "Initial commit"])
3481 .current_dir(&repo_path)
3482 .output()
3483 .map_err(|e| CascadeError::config(format!("Failed to run git commit: {e}")))?;
3484 if !output.status.success() {
3485 return Err(CascadeError::config("Git commit failed".to_string()));
3486 }
3487
3488 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))?;
3490
3491 Ok((temp_dir, repo_path))
3492 }
3493
3494 #[tokio::test]
3495 async fn test_create_stack() {
3496 let (temp_dir, repo_path) = match create_test_repo() {
3497 Ok(repo) => repo,
3498 Err(_) => {
3499 println!("Skipping test due to git environment setup failure");
3500 return;
3501 }
3502 };
3503 let _ = &temp_dir;
3505
3506 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3510 match env::set_current_dir(&repo_path) {
3511 Ok(_) => {
3512 let result = create_stack(
3513 "test-stack".to_string(),
3514 None, Some("Test description".to_string()),
3516 )
3517 .await;
3518
3519 if let Ok(orig) = original_dir {
3521 let _ = env::set_current_dir(orig);
3522 }
3523
3524 assert!(
3525 result.is_ok(),
3526 "Stack creation should succeed in initialized repository"
3527 );
3528 }
3529 Err(_) => {
3530 println!("Skipping test due to directory access restrictions");
3532 }
3533 }
3534 }
3535
3536 #[tokio::test]
3537 async fn test_list_empty_stacks() {
3538 let (temp_dir, repo_path) = match create_test_repo() {
3539 Ok(repo) => repo,
3540 Err(_) => {
3541 println!("Skipping test due to git environment setup failure");
3542 return;
3543 }
3544 };
3545 let _ = &temp_dir;
3547
3548 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3552 match env::set_current_dir(&repo_path) {
3553 Ok(_) => {
3554 let result = list_stacks(false, false, None).await;
3555
3556 if let Ok(orig) = original_dir {
3558 let _ = env::set_current_dir(orig);
3559 }
3560
3561 assert!(
3562 result.is_ok(),
3563 "Listing stacks should succeed in initialized repository"
3564 );
3565 }
3566 Err(_) => {
3567 println!("Skipping test due to directory access restrictions");
3569 }
3570 }
3571 }
3572
3573 #[test]
3576 fn test_extract_feature_from_wip_basic() {
3577 let messages = vec![
3578 "WIP: add authentication".to_string(),
3579 "WIP: implement login flow".to_string(),
3580 ];
3581
3582 let result = extract_feature_from_wip(&messages);
3583 assert_eq!(result, "Add authentication");
3584 }
3585
3586 #[test]
3587 fn test_extract_feature_from_wip_capitalize() {
3588 let messages = vec!["WIP: fix user validation bug".to_string()];
3589
3590 let result = extract_feature_from_wip(&messages);
3591 assert_eq!(result, "Fix user validation bug");
3592 }
3593
3594 #[test]
3595 fn test_extract_feature_from_wip_fallback() {
3596 let messages = vec![
3597 "WIP user interface changes".to_string(),
3598 "wip: css styling".to_string(),
3599 ];
3600
3601 let result = extract_feature_from_wip(&messages);
3602 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
3604 }
3605
3606 #[test]
3607 fn test_extract_feature_from_wip_empty() {
3608 let messages = vec![];
3609
3610 let result = extract_feature_from_wip(&messages);
3611 assert_eq!(result, "Squashed 0 commits");
3612 }
3613
3614 #[test]
3615 fn test_extract_feature_from_wip_short_message() {
3616 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
3619 assert!(result.starts_with("Implement") || result.contains("Squashed"));
3620 }
3621
3622 #[test]
3625 fn test_squash_message_final_strategy() {
3626 let messages = [
3630 "Final: implement user authentication system".to_string(),
3631 "WIP: add tests".to_string(),
3632 "WIP: fix validation".to_string(),
3633 ];
3634
3635 assert!(messages[0].starts_with("Final:"));
3637
3638 let extracted = messages[0].trim_start_matches("Final:").trim();
3640 assert_eq!(extracted, "implement user authentication system");
3641 }
3642
3643 #[test]
3644 fn test_squash_message_wip_detection() {
3645 let messages = [
3646 "WIP: start feature".to_string(),
3647 "WIP: continue work".to_string(),
3648 "WIP: almost done".to_string(),
3649 "Regular commit message".to_string(),
3650 ];
3651
3652 let wip_count = messages
3653 .iter()
3654 .filter(|m| {
3655 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3656 })
3657 .count();
3658
3659 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
3664 .iter()
3665 .filter(|m| {
3666 !m.to_lowercase().starts_with("wip")
3667 && !m.to_lowercase().contains("work in progress")
3668 })
3669 .collect();
3670
3671 assert_eq!(non_wip.len(), 1);
3672 assert_eq!(non_wip[0], "Regular commit message");
3673 }
3674
3675 #[test]
3676 fn test_squash_message_all_wip() {
3677 let messages = vec![
3678 "WIP: add feature A".to_string(),
3679 "WIP: add feature B".to_string(),
3680 "WIP: finish implementation".to_string(),
3681 ];
3682
3683 let result = extract_feature_from_wip(&messages);
3684 assert_eq!(result, "Add feature A");
3686 }
3687
3688 #[test]
3689 fn test_squash_message_edge_cases() {
3690 let empty_messages: Vec<String> = vec![];
3692 let result = extract_feature_from_wip(&empty_messages);
3693 assert_eq!(result, "Squashed 0 commits");
3694
3695 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
3697 let result = extract_feature_from_wip(&whitespace_messages);
3698 assert!(result.contains("Squashed") || result.contains("Implement"));
3699
3700 let mixed_case = vec!["wip: Add Feature".to_string()];
3702 let result = extract_feature_from_wip(&mixed_case);
3703 assert_eq!(result, "Add Feature");
3704 }
3705
3706 #[tokio::test]
3709 async fn test_auto_land_wrapper() {
3710 let (temp_dir, repo_path) = match create_test_repo() {
3712 Ok(repo) => repo,
3713 Err(_) => {
3714 println!("Skipping test due to git environment setup failure");
3715 return;
3716 }
3717 };
3718 let _ = &temp_dir;
3720
3721 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
3723 .expect("Failed to initialize Cascade in test repo");
3724
3725 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3726 match env::set_current_dir(&repo_path) {
3727 Ok(_) => {
3728 let result = create_stack(
3730 "test-stack".to_string(),
3731 None,
3732 Some("Test stack for auto-land".to_string()),
3733 )
3734 .await;
3735
3736 if let Ok(orig) = original_dir {
3737 let _ = env::set_current_dir(orig);
3738 }
3739
3740 assert!(
3743 result.is_ok(),
3744 "Stack creation should succeed in initialized repository"
3745 );
3746 }
3747 Err(_) => {
3748 println!("Skipping test due to directory access restrictions");
3749 }
3750 }
3751 }
3752
3753 #[test]
3754 fn test_auto_land_action_enum() {
3755 use crate::cli::commands::stack::StackAction;
3757
3758 let _action = StackAction::AutoLand {
3760 force: false,
3761 dry_run: true,
3762 wait_for_builds: true,
3763 strategy: Some(MergeStrategyArg::Squash),
3764 build_timeout: 1800,
3765 };
3766
3767 }
3769
3770 #[test]
3771 fn test_merge_strategy_conversion() {
3772 let squash_strategy = MergeStrategyArg::Squash;
3774 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
3775
3776 match merge_strategy {
3777 crate::bitbucket::pull_request::MergeStrategy::Squash => {
3778 }
3780 _ => panic!("Expected Squash strategy"),
3781 }
3782
3783 let merge_strategy = MergeStrategyArg::Merge;
3784 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
3785
3786 match converted {
3787 crate::bitbucket::pull_request::MergeStrategy::Merge => {
3788 }
3790 _ => panic!("Expected Merge strategy"),
3791 }
3792 }
3793
3794 #[test]
3795 fn test_auto_merge_conditions_structure() {
3796 use std::time::Duration;
3798
3799 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3800 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
3801 wait_for_builds: true,
3802 build_timeout: Duration::from_secs(1800),
3803 allowed_authors: None,
3804 };
3805
3806 assert!(conditions.wait_for_builds);
3808 assert_eq!(conditions.build_timeout.as_secs(), 1800);
3809 assert!(conditions.allowed_authors.is_none());
3810 assert!(matches!(
3811 conditions.merge_strategy,
3812 crate::bitbucket::pull_request::MergeStrategy::Squash
3813 ));
3814 }
3815
3816 #[test]
3817 fn test_polling_constants() {
3818 use std::time::Duration;
3820
3821 let expected_polling_interval = Duration::from_secs(30);
3823
3824 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
3829
3830 #[test]
3831 fn test_build_timeout_defaults() {
3832 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
3835 let timeout_value = 1800u64;
3837 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
3840
3841 #[test]
3842 fn test_scattered_commit_detection() {
3843 use std::collections::HashSet;
3844
3845 let mut source_branches = HashSet::new();
3847 source_branches.insert("feature-branch-1".to_string());
3848 source_branches.insert("feature-branch-2".to_string());
3849 source_branches.insert("feature-branch-3".to_string());
3850
3851 let single_branch = HashSet::from(["main".to_string()]);
3853 assert_eq!(single_branch.len(), 1);
3854
3855 assert!(source_branches.len() > 1);
3857 assert_eq!(source_branches.len(), 3);
3858
3859 assert!(source_branches.contains("feature-branch-1"));
3861 assert!(source_branches.contains("feature-branch-2"));
3862 assert!(source_branches.contains("feature-branch-3"));
3863 }
3864
3865 #[test]
3866 fn test_source_branch_tracking() {
3867 let branch_a = "feature-work";
3871 let branch_b = "feature-work";
3872 assert_eq!(branch_a, branch_b);
3873
3874 let branch_1 = "feature-ui";
3876 let branch_2 = "feature-api";
3877 assert_ne!(branch_1, branch_2);
3878
3879 assert!(branch_1.starts_with("feature-"));
3881 assert!(branch_2.starts_with("feature-"));
3882 }
3883
3884 #[tokio::test]
3887 async fn test_push_default_behavior() {
3888 let (temp_dir, repo_path) = match create_test_repo() {
3890 Ok(repo) => repo,
3891 Err(_) => {
3892 println!("Skipping test due to git environment setup failure");
3893 return;
3894 }
3895 };
3896 let _ = &temp_dir;
3898
3899 if !repo_path.exists() {
3901 println!("Skipping test due to temporary directory creation issue");
3902 return;
3903 }
3904
3905 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3907
3908 match env::set_current_dir(&repo_path) {
3909 Ok(_) => {
3910 let result = push_to_stack(
3912 None, None, None, None, None, None, None, false, false, false, )
3923 .await;
3924
3925 if let Ok(orig) = original_dir {
3927 let _ = env::set_current_dir(orig);
3928 }
3929
3930 match &result {
3932 Err(e) => {
3933 let error_msg = e.to_string();
3934 assert!(
3936 error_msg.contains("No active stack")
3937 || error_msg.contains("config")
3938 || error_msg.contains("current directory")
3939 || error_msg.contains("Not a git repository")
3940 || error_msg.contains("could not find repository"),
3941 "Expected 'No active stack' or repository error, got: {error_msg}"
3942 );
3943 }
3944 Ok(_) => {
3945 println!(
3947 "Push succeeded unexpectedly - test environment may have active stack"
3948 );
3949 }
3950 }
3951 }
3952 Err(_) => {
3953 println!("Skipping test due to directory access restrictions");
3955 }
3956 }
3957
3958 let push_action = StackAction::Push {
3960 branch: None,
3961 message: None,
3962 commit: None,
3963 since: None,
3964 commits: None,
3965 squash: None,
3966 squash_since: None,
3967 auto_branch: false,
3968 allow_base_branch: false,
3969 dry_run: false,
3970 };
3971
3972 assert!(matches!(
3973 push_action,
3974 StackAction::Push {
3975 branch: None,
3976 message: None,
3977 commit: None,
3978 since: None,
3979 commits: None,
3980 squash: None,
3981 squash_since: None,
3982 auto_branch: false,
3983 allow_base_branch: false,
3984 dry_run: false
3985 }
3986 ));
3987 }
3988
3989 #[tokio::test]
3990 async fn test_submit_default_behavior() {
3991 let (temp_dir, repo_path) = match create_test_repo() {
3993 Ok(repo) => repo,
3994 Err(_) => {
3995 println!("Skipping test due to git environment setup failure");
3996 return;
3997 }
3998 };
3999 let _ = &temp_dir;
4001
4002 if !repo_path.exists() {
4004 println!("Skipping test due to temporary directory creation issue");
4005 return;
4006 }
4007
4008 let original_dir = match env::current_dir() {
4010 Ok(dir) => dir,
4011 Err(_) => {
4012 println!("Skipping test due to current directory access restrictions");
4013 return;
4014 }
4015 };
4016
4017 match env::set_current_dir(&repo_path) {
4018 Ok(_) => {
4019 let result = submit_entry(
4021 None, None, None, None, false, )
4027 .await;
4028
4029 let _ = env::set_current_dir(original_dir);
4031
4032 match &result {
4034 Err(e) => {
4035 let error_msg = e.to_string();
4036 assert!(
4038 error_msg.contains("No active stack")
4039 || error_msg.contains("config")
4040 || error_msg.contains("current directory")
4041 || error_msg.contains("Not a git repository")
4042 || error_msg.contains("could not find repository"),
4043 "Expected 'No active stack' or repository error, got: {error_msg}"
4044 );
4045 }
4046 Ok(_) => {
4047 println!("Submit succeeded unexpectedly - test environment may have active stack");
4049 }
4050 }
4051 }
4052 Err(_) => {
4053 println!("Skipping test due to directory access restrictions");
4055 }
4056 }
4057
4058 let submit_action = StackAction::Submit {
4060 entry: None,
4061 title: None,
4062 description: None,
4063 range: None,
4064 draft: false,
4065 };
4066
4067 assert!(matches!(
4068 submit_action,
4069 StackAction::Submit {
4070 entry: None,
4071 title: None,
4072 description: None,
4073 range: None,
4074 draft: false
4075 }
4076 ));
4077 }
4078
4079 #[test]
4080 fn test_targeting_options_still_work() {
4081 let commits = "abc123,def456,ghi789";
4085 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
4086 assert_eq!(parsed.len(), 3);
4087 assert_eq!(parsed[0], "abc123");
4088 assert_eq!(parsed[1], "def456");
4089 assert_eq!(parsed[2], "ghi789");
4090
4091 let range = "1-3";
4093 assert!(range.contains('-'));
4094 let parts: Vec<&str> = range.split('-').collect();
4095 assert_eq!(parts.len(), 2);
4096
4097 let since_ref = "HEAD~3";
4099 assert!(since_ref.starts_with("HEAD"));
4100 assert!(since_ref.contains('~'));
4101 }
4102
4103 #[test]
4104 fn test_command_flow_logic() {
4105 assert!(matches!(
4107 StackAction::Push {
4108 branch: None,
4109 message: None,
4110 commit: None,
4111 since: None,
4112 commits: None,
4113 squash: None,
4114 squash_since: None,
4115 auto_branch: false,
4116 allow_base_branch: false,
4117 dry_run: false
4118 },
4119 StackAction::Push { .. }
4120 ));
4121
4122 assert!(matches!(
4123 StackAction::Submit {
4124 entry: None,
4125 title: None,
4126 description: None,
4127 range: None,
4128 draft: false
4129 },
4130 StackAction::Submit { .. }
4131 ));
4132 }
4133
4134 #[tokio::test]
4135 async fn test_deactivate_command_structure() {
4136 let deactivate_action = StackAction::Deactivate { force: false };
4138
4139 assert!(matches!(
4141 deactivate_action,
4142 StackAction::Deactivate { force: false }
4143 ));
4144
4145 let force_deactivate = StackAction::Deactivate { force: true };
4147 assert!(matches!(
4148 force_deactivate,
4149 StackAction::Deactivate { force: true }
4150 ));
4151 }
4152}