1use crate::bitbucket::BitbucketIntegration;
2use crate::errors::{CascadeError, Result};
3use crate::git::GitRepository;
4use crate::stack::{StackManager, StackStatus};
5use clap::{Subcommand, ValueEnum};
6use indicatif::{ProgressBar, ProgressStyle};
7use std::env;
8use tracing::{info, warn};
9
10#[derive(ValueEnum, Clone, Debug)]
12pub enum RebaseStrategyArg {
13 BranchVersioning,
15 CherryPick,
17 ThreeWayMerge,
19 Interactive,
21}
22
23#[derive(ValueEnum, Clone, Debug)]
24pub enum MergeStrategyArg {
25 Merge,
27 Squash,
29 FastForward,
31}
32
33impl From<MergeStrategyArg> for crate::bitbucket::pull_request::MergeStrategy {
34 fn from(arg: MergeStrategyArg) -> Self {
35 match arg {
36 MergeStrategyArg::Merge => Self::Merge,
37 MergeStrategyArg::Squash => Self::Squash,
38 MergeStrategyArg::FastForward => Self::FastForward,
39 }
40 }
41}
42
43#[derive(Subcommand)]
44pub enum StackAction {
45 Create {
47 name: String,
49 #[arg(long, short)]
51 base: Option<String>,
52 #[arg(long, short)]
54 description: Option<String>,
55 },
56
57 List {
59 #[arg(long, short)]
61 verbose: bool,
62 #[arg(long)]
64 active: bool,
65 #[arg(long)]
67 format: Option<String>,
68 },
69
70 Switch {
72 name: String,
74 },
75
76 Deactivate {
78 #[arg(long)]
80 force: bool,
81 },
82
83 Show {
85 #[arg(short, long)]
87 verbose: bool,
88 #[arg(short, long)]
90 mergeable: bool,
91 },
92
93 Push {
95 #[arg(long, short)]
97 branch: Option<String>,
98 #[arg(long, short)]
100 message: Option<String>,
101 #[arg(long)]
103 commit: Option<String>,
104 #[arg(long)]
106 since: Option<String>,
107 #[arg(long)]
109 commits: Option<String>,
110 #[arg(long, num_args = 0..=1, default_missing_value = "0")]
112 squash: Option<usize>,
113 #[arg(long)]
115 squash_since: Option<String>,
116 #[arg(long)]
118 auto_branch: bool,
119 #[arg(long)]
121 allow_base_branch: bool,
122 },
123
124 Pop {
126 #[arg(long)]
128 keep_branch: bool,
129 },
130
131 Submit {
133 entry: Option<usize>,
135 #[arg(long, short)]
137 title: Option<String>,
138 #[arg(long, short)]
140 description: Option<String>,
141 #[arg(long)]
143 range: Option<String>,
144 #[arg(long)]
146 draft: bool,
147 },
148
149 Status {
151 name: Option<String>,
153 },
154
155 Prs {
157 #[arg(long)]
159 state: Option<String>,
160 #[arg(long, short)]
162 verbose: bool,
163 },
164
165 Check {
167 #[arg(long)]
169 force: bool,
170 },
171
172 Sync {
174 #[arg(long)]
176 force: bool,
177 #[arg(long)]
179 skip_cleanup: bool,
180 #[arg(long, short)]
182 interactive: bool,
183 },
184
185 Rebase {
187 #[arg(long, short)]
189 interactive: bool,
190 #[arg(long)]
192 onto: Option<String>,
193 #[arg(long, value_enum)]
195 strategy: Option<RebaseStrategyArg>,
196 },
197
198 ContinueRebase,
200
201 AbortRebase,
203
204 RebaseStatus,
206
207 Delete {
209 name: String,
211 #[arg(long)]
213 force: bool,
214 },
215
216 Validate {
218 name: Option<String>,
220 },
221
222 Land {
224 entry: Option<usize>,
226 #[arg(short, long)]
228 force: bool,
229 #[arg(short, long)]
231 dry_run: bool,
232 #[arg(long)]
234 auto: bool,
235 #[arg(long)]
237 wait_for_builds: bool,
238 #[arg(long, value_enum, default_value = "squash")]
240 strategy: Option<MergeStrategyArg>,
241 #[arg(long, default_value = "1800")]
243 build_timeout: u64,
244 },
245
246 AutoLand {
248 #[arg(short, long)]
250 force: bool,
251 #[arg(short, long)]
253 dry_run: bool,
254 #[arg(long)]
256 wait_for_builds: bool,
257 #[arg(long, value_enum, default_value = "squash")]
259 strategy: Option<MergeStrategyArg>,
260 #[arg(long, default_value = "1800")]
262 build_timeout: u64,
263 },
264
265 ListPrs {
267 #[arg(short, long)]
269 state: Option<String>,
270 #[arg(short, long)]
272 verbose: bool,
273 },
274
275 ContinueLand,
277
278 AbortLand,
280
281 LandStatus,
283}
284
285pub async fn run(action: StackAction) -> Result<()> {
286 match action {
287 StackAction::Create {
288 name,
289 base,
290 description,
291 } => create_stack(name, base, description).await,
292 StackAction::List {
293 verbose,
294 active,
295 format,
296 } => list_stacks(verbose, active, format).await,
297 StackAction::Switch { name } => switch_stack(name).await,
298 StackAction::Deactivate { force } => deactivate_stack(force).await,
299 StackAction::Show { verbose, mergeable } => show_stack(verbose, mergeable).await,
300 StackAction::Push {
301 branch,
302 message,
303 commit,
304 since,
305 commits,
306 squash,
307 squash_since,
308 auto_branch,
309 allow_base_branch,
310 } => {
311 push_to_stack(
312 branch,
313 message,
314 commit,
315 since,
316 commits,
317 squash,
318 squash_since,
319 auto_branch,
320 allow_base_branch,
321 )
322 .await
323 }
324 StackAction::Pop { keep_branch } => pop_from_stack(keep_branch).await,
325 StackAction::Submit {
326 entry,
327 title,
328 description,
329 range,
330 draft,
331 } => submit_entry(entry, title, description, range, draft).await,
332 StackAction::Status { name } => check_stack_status(name).await,
333 StackAction::Prs { state, verbose } => list_pull_requests(state, verbose).await,
334 StackAction::Check { force } => check_stack(force).await,
335 StackAction::Sync {
336 force,
337 skip_cleanup,
338 interactive,
339 } => sync_stack(force, skip_cleanup, interactive).await,
340 StackAction::Rebase {
341 interactive,
342 onto,
343 strategy,
344 } => rebase_stack(interactive, onto, strategy).await,
345 StackAction::ContinueRebase => continue_rebase().await,
346 StackAction::AbortRebase => abort_rebase().await,
347 StackAction::RebaseStatus => rebase_status().await,
348 StackAction::Delete { name, force } => delete_stack(name, force).await,
349 StackAction::Validate { name } => validate_stack(name).await,
350 StackAction::Land {
351 entry,
352 force,
353 dry_run,
354 auto,
355 wait_for_builds,
356 strategy,
357 build_timeout,
358 } => {
359 land_stack(
360 entry,
361 force,
362 dry_run,
363 auto,
364 wait_for_builds,
365 strategy,
366 build_timeout,
367 )
368 .await
369 }
370 StackAction::AutoLand {
371 force,
372 dry_run,
373 wait_for_builds,
374 strategy,
375 build_timeout,
376 } => auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await,
377 StackAction::ListPrs { state, verbose } => list_pull_requests(state, verbose).await,
378 StackAction::ContinueLand => continue_land().await,
379 StackAction::AbortLand => abort_land().await,
380 StackAction::LandStatus => land_status().await,
381 }
382}
383
384pub async fn show(verbose: bool, mergeable: bool) -> Result<()> {
386 show_stack(verbose, mergeable).await
387}
388
389#[allow(clippy::too_many_arguments)]
390pub async fn push(
391 branch: Option<String>,
392 message: Option<String>,
393 commit: Option<String>,
394 since: Option<String>,
395 commits: Option<String>,
396 squash: Option<usize>,
397 squash_since: Option<String>,
398 auto_branch: bool,
399 allow_base_branch: bool,
400) -> Result<()> {
401 push_to_stack(
402 branch,
403 message,
404 commit,
405 since,
406 commits,
407 squash,
408 squash_since,
409 auto_branch,
410 allow_base_branch,
411 )
412 .await
413}
414
415pub async fn pop(keep_branch: bool) -> Result<()> {
416 pop_from_stack(keep_branch).await
417}
418
419pub async fn land(
420 entry: Option<usize>,
421 force: bool,
422 dry_run: bool,
423 auto: bool,
424 wait_for_builds: bool,
425 strategy: Option<MergeStrategyArg>,
426 build_timeout: u64,
427) -> Result<()> {
428 land_stack(
429 entry,
430 force,
431 dry_run,
432 auto,
433 wait_for_builds,
434 strategy,
435 build_timeout,
436 )
437 .await
438}
439
440pub async fn autoland(
441 force: bool,
442 dry_run: bool,
443 wait_for_builds: bool,
444 strategy: Option<MergeStrategyArg>,
445 build_timeout: u64,
446) -> Result<()> {
447 auto_land_stack(force, dry_run, wait_for_builds, strategy, build_timeout).await
448}
449
450pub async fn sync(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
451 sync_stack(force, skip_cleanup, interactive).await
452}
453
454pub async fn rebase(
455 interactive: bool,
456 onto: Option<String>,
457 strategy: Option<RebaseStrategyArg>,
458) -> Result<()> {
459 rebase_stack(interactive, onto, strategy).await
460}
461
462pub async fn deactivate(force: bool) -> Result<()> {
463 deactivate_stack(force).await
464}
465
466pub async fn switch(name: String) -> Result<()> {
467 switch_stack(name).await
468}
469
470async fn create_stack(
471 name: String,
472 base: Option<String>,
473 description: Option<String>,
474) -> Result<()> {
475 let current_dir = env::current_dir()
476 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
477
478 let mut manager = StackManager::new(¤t_dir)?;
479 let stack_id = manager.create_stack(name.clone(), base.clone(), description.clone())?;
480
481 info!("✅ Created stack '{}'", name);
482 if let Some(base_branch) = base {
483 info!(" Base branch: {}", base_branch);
484 }
485 if let Some(desc) = description {
486 info!(" Description: {}", desc);
487 }
488 info!(" Stack ID: {}", stack_id);
489 info!(" Stack is now active");
490
491 Ok(())
492}
493
494async fn list_stacks(verbose: bool, _active: bool, _format: Option<String>) -> Result<()> {
495 let current_dir = env::current_dir()
496 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
497
498 let manager = StackManager::new(¤t_dir)?;
499 let stacks = manager.list_stacks();
500
501 if stacks.is_empty() {
502 info!("No stacks found. Create one with: cc stack create <name>");
503 return Ok(());
504 }
505
506 println!("📚 Stacks:");
507 for (stack_id, name, status, entry_count, active_marker) in stacks {
508 let status_icon = match status {
509 StackStatus::Clean => "✅",
510 StackStatus::Dirty => "🔄",
511 StackStatus::OutOfSync => "⚠️",
512 StackStatus::Conflicted => "❌",
513 StackStatus::Rebasing => "🔀",
514 StackStatus::NeedsSync => "🔄",
515 StackStatus::Corrupted => "💥",
516 };
517
518 let active_indicator = if active_marker.is_some() {
519 " (active)"
520 } else {
521 ""
522 };
523
524 if verbose {
525 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
526 println!(" ID: {stack_id}");
527 if let Some(stack_meta) = manager.get_stack_metadata(&stack_id) {
528 println!(" Base: {}", stack_meta.base_branch);
529 if let Some(desc) = &stack_meta.description {
530 println!(" Description: {desc}");
531 }
532 println!(
533 " Commits: {} total, {} submitted",
534 stack_meta.total_commits, stack_meta.submitted_commits
535 );
536 if stack_meta.has_conflicts {
537 println!(" ⚠️ Has conflicts");
538 }
539 }
540 println!();
541 } else {
542 println!(" {status_icon} {name} [{entry_count}]{active_indicator}");
543 }
544 }
545
546 if !verbose {
547 println!("\nUse --verbose for more details");
548 }
549
550 Ok(())
551}
552
553async fn switch_stack(name: String) -> Result<()> {
554 let current_dir = env::current_dir()
555 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
556
557 let mut manager = StackManager::new(¤t_dir)?;
558
559 if manager.get_stack_by_name(&name).is_none() {
561 return Err(CascadeError::config(format!("Stack '{name}' not found")));
562 }
563
564 manager.set_active_stack_by_name(&name)?;
565 info!("✅ Switched to stack '{}'", name);
566
567 Ok(())
568}
569
570async fn deactivate_stack(force: bool) -> Result<()> {
571 let current_dir = env::current_dir()
572 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
573
574 let mut manager = StackManager::new(¤t_dir)?;
575
576 let active_stack = manager.get_active_stack();
577
578 if active_stack.is_none() {
579 println!("ℹ️ No active stack to deactivate");
580 return Ok(());
581 }
582
583 let stack_name = active_stack.unwrap().name.clone();
584
585 if !force {
586 println!("⚠️ This will deactivate stack '{stack_name}' and return to normal Git workflow");
587 println!(" You can reactivate it later with 'cc stacks switch {stack_name}'");
588 print!(" Continue? (y/N): ");
589
590 use std::io::{self, Write};
591 io::stdout().flush().unwrap();
592
593 let mut input = String::new();
594 io::stdin().read_line(&mut input).unwrap();
595
596 if !input.trim().to_lowercase().starts_with('y') {
597 println!("Cancelled deactivation");
598 return Ok(());
599 }
600 }
601
602 manager.set_active_stack(None)?;
604
605 println!("✅ Deactivated stack '{stack_name}'");
606 println!(" Stack management is now OFF - you can use normal Git workflow");
607 println!(" To reactivate: cc stacks switch {stack_name}");
608
609 Ok(())
610}
611
612async fn show_stack(verbose: bool, show_mergeable: bool) -> Result<()> {
613 let current_dir = env::current_dir()
614 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
615
616 let stack_manager = StackManager::new(¤t_dir)?;
617
618 let (stack_id, stack_name, stack_base, stack_entries) = {
620 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
621 CascadeError::config(
622 "No active stack. Use 'cc stacks create' or 'cc stacks switch' to select a stack"
623 .to_string(),
624 )
625 })?;
626
627 (
628 active_stack.id,
629 active_stack.name.clone(),
630 active_stack.base_branch.clone(),
631 active_stack.entries.clone(),
632 )
633 };
634
635 println!("📊 Stack: {stack_name}");
636 println!(" Base branch: {stack_base}");
637 println!(" Total entries: {}", stack_entries.len());
638
639 if stack_entries.is_empty() {
640 println!(" No entries in this stack yet");
641 println!(" Use 'cc push' to add commits to this stack");
642 return Ok(());
643 }
644
645 println!("\n📚 Stack Entries:");
647 for (i, entry) in stack_entries.iter().enumerate() {
648 let entry_num = i + 1;
649 let short_hash = entry.short_hash();
650 let short_msg = entry.short_message(50);
651
652 let metadata = stack_manager.get_repository_metadata();
654 let source_branch_info = if let Some(commit_meta) = metadata.get_commit(&entry.commit_hash)
655 {
656 if commit_meta.source_branch != commit_meta.branch
657 && !commit_meta.source_branch.is_empty()
658 {
659 format!(" (from {})", commit_meta.source_branch)
660 } else {
661 String::new()
662 }
663 } else {
664 String::new()
665 };
666
667 println!(
668 " {entry_num}. {} {} {}{}",
669 short_hash,
670 if entry.is_submitted { "📤" } else { "📝" },
671 short_msg,
672 source_branch_info
673 );
674
675 if verbose {
676 println!(" Branch: {}", entry.branch);
677 println!(
678 " Created: {}",
679 entry.created_at.format("%Y-%m-%d %H:%M")
680 );
681 if let Some(pr_id) = &entry.pull_request_id {
682 println!(" PR: #{pr_id}");
683 }
684 }
685 }
686
687 if show_mergeable {
689 println!("\n🔍 Mergability Status:");
690
691 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
693 let config_path = config_dir.join("config.json");
694 let settings = crate::config::Settings::load_from_file(&config_path)?;
695
696 let cascade_config = crate::config::CascadeConfig {
697 bitbucket: Some(settings.bitbucket.clone()),
698 git: settings.git.clone(),
699 auth: crate::config::AuthConfig::default(),
700 };
701
702 let integration =
703 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
704
705 match integration.check_enhanced_stack_status(&stack_id).await {
706 Ok(status) => {
707 println!(" Total entries: {}", status.total_entries);
708 println!(" Submitted: {}", status.submitted_entries);
709 println!(" Open PRs: {}", status.open_prs);
710 println!(" Merged PRs: {}", status.merged_prs);
711 println!(" Declined PRs: {}", status.declined_prs);
712 println!(" Completion: {:.1}%", status.completion_percentage());
713
714 if !status.enhanced_statuses.is_empty() {
715 println!("\n📋 Pull Request Status:");
716 let mut ready_to_land = 0;
717
718 for enhanced in &status.enhanced_statuses {
719 let status_display = enhanced.get_display_status();
720 let ready_icon = if enhanced.is_ready_to_land() {
721 ready_to_land += 1;
722 "🚀"
723 } else {
724 "⏳"
725 };
726
727 println!(
728 " {} PR #{}: {} ({})",
729 ready_icon, enhanced.pr.id, enhanced.pr.title, status_display
730 );
731
732 if verbose {
733 println!(
734 " {} -> {}",
735 enhanced.pr.from_ref.display_id, enhanced.pr.to_ref.display_id
736 );
737
738 if !enhanced.is_ready_to_land() {
740 let blocking = enhanced.get_blocking_reasons();
741 if !blocking.is_empty() {
742 println!(" Blocking: {}", blocking.join(", "));
743 }
744 }
745
746 println!(
748 " Reviews: {}/{} approvals",
749 enhanced.review_status.current_approvals,
750 enhanced.review_status.required_approvals
751 );
752
753 if enhanced.review_status.needs_work_count > 0 {
754 println!(
755 " {} reviewers requested changes",
756 enhanced.review_status.needs_work_count
757 );
758 }
759
760 if let Some(build) = &enhanced.build_status {
762 let build_icon = match build.state {
763 crate::bitbucket::pull_request::BuildState::Successful => "✅",
764 crate::bitbucket::pull_request::BuildState::Failed => "❌",
765 crate::bitbucket::pull_request::BuildState::InProgress => "🔄",
766 _ => "⚪",
767 };
768 println!(" Build: {} {:?}", build_icon, build.state);
769 }
770
771 if let Some(url) = enhanced.pr.web_url() {
772 println!(" URL: {url}");
773 }
774 println!();
775 }
776 }
777
778 if ready_to_land > 0 {
779 println!(
780 "\n🎯 {} PR{} ready to land! Use 'cc land' to land them all.",
781 ready_to_land,
782 if ready_to_land == 1 { " is" } else { "s are" }
783 );
784 }
785 }
786 }
787 Err(e) => {
788 warn!("Failed to get enhanced stack status: {}", e);
789 println!(" ⚠️ Could not fetch mergability status");
790 println!(" Use 'cc stack show --verbose' for basic PR information");
791 }
792 }
793 } else {
794 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
796 let config_path = config_dir.join("config.json");
797 let settings = crate::config::Settings::load_from_file(&config_path)?;
798
799 let cascade_config = crate::config::CascadeConfig {
800 bitbucket: Some(settings.bitbucket.clone()),
801 git: settings.git.clone(),
802 auth: crate::config::AuthConfig::default(),
803 };
804
805 let integration =
806 crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
807
808 match integration.check_stack_status(&stack_id).await {
809 Ok(status) => {
810 println!("\n📊 Pull Request Status:");
811 println!(" Total entries: {}", status.total_entries);
812 println!(" Submitted: {}", status.submitted_entries);
813 println!(" Open PRs: {}", status.open_prs);
814 println!(" Merged PRs: {}", status.merged_prs);
815 println!(" Declined PRs: {}", status.declined_prs);
816 println!(" Completion: {:.1}%", status.completion_percentage());
817
818 if !status.pull_requests.is_empty() {
819 println!("\n📋 Pull Requests:");
820 for pr in &status.pull_requests {
821 let state_icon = match pr.state {
822 crate::bitbucket::PullRequestState::Open => "🔄",
823 crate::bitbucket::PullRequestState::Merged => "✅",
824 crate::bitbucket::PullRequestState::Declined => "❌",
825 };
826 println!(
827 " {} PR #{}: {} ({} -> {})",
828 state_icon,
829 pr.id,
830 pr.title,
831 pr.from_ref.display_id,
832 pr.to_ref.display_id
833 );
834 if let Some(url) = pr.web_url() {
835 println!(" URL: {url}");
836 }
837 }
838 }
839
840 println!("\n💡 Use 'cc stack show --mergeable' to see detailed status including build and review information");
841 }
842 Err(e) => {
843 warn!("Failed to check stack status: {}", e);
844 }
845 }
846 }
847
848 Ok(())
849}
850
851#[allow(clippy::too_many_arguments)]
852async fn push_to_stack(
853 branch: Option<String>,
854 message: Option<String>,
855 commit: Option<String>,
856 since: Option<String>,
857 commits: Option<String>,
858 squash: Option<usize>,
859 squash_since: Option<String>,
860 auto_branch: bool,
861 allow_base_branch: bool,
862) -> Result<()> {
863 let current_dir = env::current_dir()
864 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
865
866 let mut manager = StackManager::new(¤t_dir)?;
867 let repo = GitRepository::open(¤t_dir)?;
868
869 if !manager.check_for_branch_change()? {
871 return Ok(()); }
873
874 let active_stack = manager.get_active_stack().ok_or_else(|| {
876 CascadeError::config("No active stack. Create a stack first with 'cc stack create'")
877 })?;
878
879 let current_branch = repo.get_current_branch()?;
881 let base_branch = &active_stack.base_branch;
882
883 if current_branch == *base_branch {
884 println!("🚨 WARNING: You're currently on the base branch '{base_branch}'");
885 println!(" Making commits directly on the base branch is not recommended.");
886 println!(" This can pollute the base branch with work-in-progress commits.");
887
888 if allow_base_branch {
890 println!(" ⚠️ Proceeding anyway due to --allow-base-branch flag");
891 } else {
892 let has_changes = repo.is_dirty()?;
894
895 if has_changes {
896 if auto_branch {
897 let feature_branch = format!("feature/{}-work", active_stack.name);
899 println!("🚀 Auto-creating feature branch '{feature_branch}'...");
900
901 repo.create_branch(&feature_branch, None)?;
902 repo.checkout_branch(&feature_branch)?;
903
904 println!("✅ Created and switched to '{feature_branch}'");
905 println!(" You can now commit and push your changes safely");
906
907 } else {
909 println!("\n💡 You have uncommitted changes. Here are your options:");
910 println!(" 1. Create a feature branch first:");
911 println!(" git checkout -b feature/my-work");
912 println!(" git commit -am \"your work\"");
913 println!(" cc push");
914 println!("\n 2. Auto-create a branch (recommended):");
915 println!(" cc push --auto-branch");
916 println!("\n 3. Force push to base branch (dangerous):");
917 println!(" cc push --allow-base-branch");
918
919 return Err(CascadeError::config(
920 "Refusing to push uncommitted changes from base branch. Use one of the options above."
921 ));
922 }
923 } else {
924 let commits_to_check = if let Some(commits_str) = &commits {
926 commits_str
927 .split(',')
928 .map(|s| s.trim().to_string())
929 .collect::<Vec<String>>()
930 } else if let Some(since_ref) = &since {
931 let since_commit = repo.resolve_reference(since_ref)?;
932 let head_commit = repo.get_head_commit()?;
933 let commits = repo.get_commits_between(
934 &since_commit.id().to_string(),
935 &head_commit.id().to_string(),
936 )?;
937 commits.into_iter().map(|c| c.id().to_string()).collect()
938 } else if commit.is_none() {
939 let mut unpushed = Vec::new();
940 let head_commit = repo.get_head_commit()?;
941 let mut current_commit = head_commit;
942
943 loop {
944 let commit_hash = current_commit.id().to_string();
945 let already_in_stack = active_stack
946 .entries
947 .iter()
948 .any(|entry| entry.commit_hash == commit_hash);
949
950 if already_in_stack {
951 break;
952 }
953
954 unpushed.push(commit_hash);
955
956 if let Some(parent) = current_commit.parents().next() {
957 current_commit = parent;
958 } else {
959 break;
960 }
961 }
962
963 unpushed.reverse();
964 unpushed
965 } else {
966 vec![repo.get_head_commit()?.id().to_string()]
967 };
968
969 if !commits_to_check.is_empty() {
970 if auto_branch {
971 let feature_branch = format!("feature/{}-work", active_stack.name);
973 println!("🚀 Auto-creating feature branch '{feature_branch}'...");
974
975 repo.create_branch(&feature_branch, Some(base_branch))?;
976 repo.checkout_branch(&feature_branch)?;
977
978 println!(
980 "🍒 Cherry-picking {} commit(s) to new branch...",
981 commits_to_check.len()
982 );
983 for commit_hash in &commits_to_check {
984 match repo.cherry_pick(commit_hash) {
985 Ok(_) => println!(" ✅ Cherry-picked {}", &commit_hash[..8]),
986 Err(e) => {
987 println!(
988 " ❌ Failed to cherry-pick {}: {}",
989 &commit_hash[..8],
990 e
991 );
992 println!(" 💡 You may need to resolve conflicts manually");
993 return Err(CascadeError::branch(format!(
994 "Failed to cherry-pick commit {commit_hash}: {e}"
995 )));
996 }
997 }
998 }
999
1000 println!(
1001 "✅ Successfully moved {} commit(s) to '{feature_branch}'",
1002 commits_to_check.len()
1003 );
1004 println!(
1005 " You're now on the feature branch and can continue with 'cc push'"
1006 );
1007
1008 } else {
1010 println!(
1011 "\n💡 Found {} commit(s) to push from base branch '{base_branch}'",
1012 commits_to_check.len()
1013 );
1014 println!(" These commits are currently ON the base branch, which may not be intended.");
1015 println!("\n Options:");
1016 println!(" 1. Auto-create feature branch and cherry-pick commits:");
1017 println!(" cc push --auto-branch");
1018 println!("\n 2. Manually create branch and move commits:");
1019 println!(" git checkout -b feature/my-work");
1020 println!(" cc push");
1021 println!("\n 3. Force push from base branch (not recommended):");
1022 println!(" cc push --allow-base-branch");
1023
1024 return Err(CascadeError::config(
1025 "Refusing to push commits from base branch. Use --auto-branch or create a feature branch manually."
1026 ));
1027 }
1028 }
1029 }
1030 }
1031 }
1032
1033 if let Some(squash_count) = squash {
1035 if squash_count == 0 {
1036 let active_stack = manager.get_active_stack().ok_or_else(|| {
1038 CascadeError::config(
1039 "No active stack. Create a stack first with 'cc stacks create'",
1040 )
1041 })?;
1042
1043 let unpushed_count = get_unpushed_commits(&repo, active_stack)?.len();
1044
1045 if unpushed_count == 0 {
1046 println!("ℹ️ No unpushed commits to squash");
1047 } else if unpushed_count == 1 {
1048 println!("ℹ️ Only 1 unpushed commit, no squashing needed");
1049 } else {
1050 println!("🔄 Auto-detected {unpushed_count} unpushed commits, squashing...");
1051 squash_commits(&repo, unpushed_count, None).await?;
1052 println!("✅ Squashed {unpushed_count} unpushed commits into one");
1053 }
1054 } else {
1055 println!("🔄 Squashing last {squash_count} commits...");
1056 squash_commits(&repo, squash_count, None).await?;
1057 println!("✅ Squashed {squash_count} commits into one");
1058 }
1059 } else if let Some(since_ref) = squash_since {
1060 println!("🔄 Squashing commits since {since_ref}...");
1061 let since_commit = repo.resolve_reference(&since_ref)?;
1062 let commits_count = count_commits_since(&repo, &since_commit.id().to_string())?;
1063 squash_commits(&repo, commits_count, Some(since_ref.clone())).await?;
1064 println!("✅ Squashed {commits_count} commits since {since_ref} into one");
1065 }
1066
1067 let commits_to_push = if let Some(commits_str) = commits {
1069 commits_str
1071 .split(',')
1072 .map(|s| s.trim().to_string())
1073 .collect::<Vec<String>>()
1074 } else if let Some(since_ref) = since {
1075 let since_commit = repo.resolve_reference(&since_ref)?;
1077 let head_commit = repo.get_head_commit()?;
1078
1079 let commits = repo.get_commits_between(
1081 &since_commit.id().to_string(),
1082 &head_commit.id().to_string(),
1083 )?;
1084 commits.into_iter().map(|c| c.id().to_string()).collect()
1085 } else if let Some(hash) = commit {
1086 vec![hash]
1088 } else {
1089 let active_stack = manager.get_active_stack().ok_or_else(|| {
1091 CascadeError::config("No active stack. Create a stack first with 'cc stack create'")
1092 })?;
1093
1094 let mut unpushed = Vec::new();
1095 let head_commit = repo.get_head_commit()?;
1096 let mut current_commit = head_commit;
1097
1098 loop {
1100 let commit_hash = current_commit.id().to_string();
1101 let already_in_stack = active_stack
1102 .entries
1103 .iter()
1104 .any(|entry| entry.commit_hash == commit_hash);
1105
1106 if already_in_stack {
1107 break;
1108 }
1109
1110 unpushed.push(commit_hash);
1111
1112 if let Some(parent) = current_commit.parents().next() {
1114 current_commit = parent;
1115 } else {
1116 break;
1117 }
1118 }
1119
1120 unpushed.reverse(); unpushed
1122 };
1123
1124 if commits_to_push.is_empty() {
1125 println!("ℹ️ No commits to push to stack");
1126 return Ok(());
1127 }
1128
1129 let mut pushed_count = 0;
1131 let mut source_branches = std::collections::HashSet::new();
1132
1133 for (i, commit_hash) in commits_to_push.iter().enumerate() {
1134 let commit_obj = repo.get_commit(commit_hash)?;
1135 let commit_msg = commit_obj.message().unwrap_or("").to_string();
1136
1137 let commit_source_branch = repo
1139 .find_branch_containing_commit(commit_hash)
1140 .unwrap_or_else(|_| current_branch.clone());
1141 source_branches.insert(commit_source_branch.clone());
1142
1143 let branch_name = if i == 0 && branch.is_some() {
1145 branch.clone().unwrap()
1146 } else {
1147 let temp_repo = GitRepository::open(¤t_dir)?;
1149 let branch_mgr = crate::git::BranchManager::new(temp_repo);
1150 branch_mgr.generate_branch_name(&commit_msg)
1151 };
1152
1153 let final_message = if i == 0 && message.is_some() {
1155 message.clone().unwrap()
1156 } else {
1157 commit_msg.clone()
1158 };
1159
1160 let entry_id = manager.push_to_stack(
1161 branch_name.clone(),
1162 commit_hash.clone(),
1163 final_message.clone(),
1164 commit_source_branch.clone(),
1165 )?;
1166 pushed_count += 1;
1167
1168 println!(
1169 "✅ Pushed commit {}/{} to stack",
1170 i + 1,
1171 commits_to_push.len()
1172 );
1173 println!(
1174 " Commit: {} ({})",
1175 &commit_hash[..8],
1176 commit_msg.split('\n').next().unwrap_or("")
1177 );
1178 println!(" Branch: {branch_name}");
1179 println!(" Source: {commit_source_branch}");
1180 println!(" Entry ID: {entry_id}");
1181 println!();
1182 }
1183
1184 if source_branches.len() > 1 {
1186 println!("⚠️ WARNING: Scattered Commit Detection");
1187 println!(
1188 " You've pushed commits from {} different Git branches:",
1189 source_branches.len()
1190 );
1191 for branch in &source_branches {
1192 println!(" • {branch}");
1193 }
1194 println!();
1195 println!(" This can lead to confusion because:");
1196 println!(" • Stack appears sequential but commits are scattered across branches");
1197 println!(" • Team members won't know which branch contains which work");
1198 println!(" • Branch cleanup becomes unclear after merge");
1199 println!(" • Rebase operations become more complex");
1200 println!();
1201 println!(" 💡 Consider consolidating work to a single feature branch:");
1202 println!(" 1. Create a new feature branch: git checkout -b feature/consolidated-work");
1203 println!(" 2. Cherry-pick commits in order: git cherry-pick <commit1> <commit2> ...");
1204 println!(" 3. Delete old scattered branches");
1205 println!(" 4. Push the consolidated branch to your stack");
1206 println!();
1207 }
1208
1209 println!(
1210 "🎉 Successfully pushed {} commit{} to stack",
1211 pushed_count,
1212 if pushed_count == 1 { "" } else { "s" }
1213 );
1214
1215 Ok(())
1216}
1217
1218async fn pop_from_stack(keep_branch: bool) -> Result<()> {
1219 let current_dir = env::current_dir()
1220 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1221
1222 let mut manager = StackManager::new(¤t_dir)?;
1223 let repo = GitRepository::open(¤t_dir)?;
1224
1225 let entry = manager.pop_from_stack()?;
1226
1227 info!("✅ Popped commit from stack");
1228 info!(
1229 " Commit: {} ({})",
1230 entry.short_hash(),
1231 entry.short_message(50)
1232 );
1233 info!(" Branch: {}", entry.branch);
1234
1235 if !keep_branch && entry.branch != repo.get_current_branch()? {
1237 match repo.delete_branch(&entry.branch) {
1238 Ok(_) => info!(" Deleted branch: {}", entry.branch),
1239 Err(e) => warn!(" Could not delete branch {}: {}", entry.branch, e),
1240 }
1241 }
1242
1243 Ok(())
1244}
1245
1246async fn submit_entry(
1247 entry: Option<usize>,
1248 title: Option<String>,
1249 description: Option<String>,
1250 range: Option<String>,
1251 draft: bool,
1252) -> Result<()> {
1253 let current_dir = env::current_dir()
1254 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1255
1256 let mut stack_manager = StackManager::new(¤t_dir)?;
1257
1258 if !stack_manager.check_for_branch_change()? {
1260 return Ok(()); }
1262
1263 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
1265 let config_path = config_dir.join("config.json");
1266 let settings = crate::config::Settings::load_from_file(&config_path)?;
1267
1268 let cascade_config = crate::config::CascadeConfig {
1270 bitbucket: Some(settings.bitbucket.clone()),
1271 git: settings.git.clone(),
1272 auth: crate::config::AuthConfig::default(),
1273 };
1274
1275 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1277 CascadeError::config("No active stack. Create a stack first with 'cc stack create'")
1278 })?;
1279 let stack_id = active_stack.id;
1280
1281 let entries_to_submit = if let Some(range_str) = range {
1283 let mut entries = Vec::new();
1285
1286 if range_str.contains('-') {
1287 let parts: Vec<&str> = range_str.split('-').collect();
1289 if parts.len() != 2 {
1290 return Err(CascadeError::config(
1291 "Invalid range format. Use 'start-end' (e.g., '1-3')",
1292 ));
1293 }
1294
1295 let start: usize = parts[0]
1296 .parse()
1297 .map_err(|_| CascadeError::config("Invalid start number in range"))?;
1298 let end: usize = parts[1]
1299 .parse()
1300 .map_err(|_| CascadeError::config("Invalid end number in range"))?;
1301
1302 if start == 0
1303 || end == 0
1304 || start > active_stack.entries.len()
1305 || end > active_stack.entries.len()
1306 {
1307 return Err(CascadeError::config(format!(
1308 "Range out of bounds. Stack has {} entries",
1309 active_stack.entries.len()
1310 )));
1311 }
1312
1313 for i in start..=end {
1314 entries.push((i, active_stack.entries[i - 1].clone()));
1315 }
1316 } else {
1317 for entry_str in range_str.split(',') {
1319 let entry_num: usize = entry_str.trim().parse().map_err(|_| {
1320 CascadeError::config(format!("Invalid entry number: {entry_str}"))
1321 })?;
1322
1323 if entry_num == 0 || entry_num > active_stack.entries.len() {
1324 return Err(CascadeError::config(format!(
1325 "Entry {} out of bounds. Stack has {} entries",
1326 entry_num,
1327 active_stack.entries.len()
1328 )));
1329 }
1330
1331 entries.push((entry_num, active_stack.entries[entry_num - 1].clone()));
1332 }
1333 }
1334
1335 entries
1336 } else if let Some(entry_num) = entry {
1337 if entry_num == 0 || entry_num > active_stack.entries.len() {
1339 return Err(CascadeError::config(format!(
1340 "Invalid entry number: {}. Stack has {} entries",
1341 entry_num,
1342 active_stack.entries.len()
1343 )));
1344 }
1345 vec![(entry_num, active_stack.entries[entry_num - 1].clone())]
1346 } else {
1347 active_stack
1349 .entries
1350 .iter()
1351 .enumerate()
1352 .filter(|(_, entry)| !entry.is_submitted)
1353 .map(|(i, entry)| (i + 1, entry.clone())) .collect::<Vec<(usize, _)>>()
1355 };
1356
1357 if entries_to_submit.is_empty() {
1358 println!("ℹ️ No entries to submit");
1359 return Ok(());
1360 }
1361
1362 let total_operations = entries_to_submit.len() + 2; let pb = ProgressBar::new(total_operations as u64);
1365 pb.set_style(
1366 ProgressStyle::default_bar()
1367 .template("📤 {msg} [{bar:40.cyan/blue}] {pos}/{len}")
1368 .map_err(|e| CascadeError::config(format!("Progress bar template error: {e}")))?,
1369 );
1370
1371 pb.set_message("Connecting to Bitbucket");
1372 pb.inc(1);
1373
1374 let integration_stack_manager = StackManager::new(¤t_dir)?;
1376 let mut integration =
1377 BitbucketIntegration::new(integration_stack_manager, cascade_config.clone())?;
1378
1379 pb.set_message("Starting batch submission");
1380 pb.inc(1);
1381
1382 let mut submitted_count = 0;
1384 let mut failed_entries = Vec::new();
1385 let total_entries = entries_to_submit.len();
1386
1387 for (entry_num, entry_to_submit) in &entries_to_submit {
1388 pb.set_message("Submitting entries...");
1389
1390 let entry_title = if total_entries == 1 {
1392 title.clone()
1393 } else {
1394 None
1395 };
1396 let entry_description = if total_entries == 1 {
1397 description.clone()
1398 } else {
1399 None
1400 };
1401
1402 match integration
1403 .submit_entry(
1404 &stack_id,
1405 &entry_to_submit.id,
1406 entry_title,
1407 entry_description,
1408 draft,
1409 )
1410 .await
1411 {
1412 Ok(pr) => {
1413 submitted_count += 1;
1414 println!("✅ Entry {} - PR #{}: {}", entry_num, pr.id, pr.title);
1415 if let Some(url) = pr.web_url() {
1416 println!(" URL: {url}");
1417 }
1418 println!(
1419 " From: {} -> {}",
1420 pr.from_ref.display_id, pr.to_ref.display_id
1421 );
1422 println!();
1423 }
1424 Err(e) => {
1425 failed_entries.push((*entry_num, e.to_string()));
1426 println!("❌ Entry {entry_num} failed: {e}");
1427 }
1428 }
1429
1430 pb.inc(1);
1431 }
1432
1433 if failed_entries.is_empty() {
1434 pb.finish_with_message("✅ All pull requests created successfully");
1435 println!(
1436 "🎉 Successfully submitted {} entr{}",
1437 submitted_count,
1438 if submitted_count == 1 { "y" } else { "ies" }
1439 );
1440 } else {
1441 pb.abandon_with_message("⚠️ Some submissions failed");
1442 println!("📊 Submission Summary:");
1443 println!(" ✅ Successful: {submitted_count}");
1444 println!(" ❌ Failed: {}", failed_entries.len());
1445 println!();
1446 println!("💡 Failed entries:");
1447 for (entry_num, error) in failed_entries {
1448 println!(" - Entry {entry_num}: {error}");
1449 }
1450 println!();
1451 println!("💡 You can retry failed entries individually:");
1452 println!(" cc stack submit <ENTRY_NUMBER>");
1453 }
1454
1455 Ok(())
1456}
1457
1458async fn check_stack_status(name: Option<String>) -> Result<()> {
1459 let current_dir = env::current_dir()
1460 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1461
1462 let stack_manager = StackManager::new(¤t_dir)?;
1463
1464 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
1466 let config_path = config_dir.join("config.json");
1467 let settings = crate::config::Settings::load_from_file(&config_path)?;
1468
1469 let cascade_config = crate::config::CascadeConfig {
1471 bitbucket: Some(settings.bitbucket.clone()),
1472 git: settings.git.clone(),
1473 auth: crate::config::AuthConfig::default(),
1474 };
1475
1476 let stack = if let Some(name) = name {
1478 stack_manager
1479 .get_stack_by_name(&name)
1480 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?
1481 } else {
1482 stack_manager.get_active_stack().ok_or_else(|| {
1483 CascadeError::config("No active stack. Use 'cc stack list' to see available stacks")
1484 })?
1485 };
1486 let stack_id = stack.id;
1487
1488 println!("📋 Stack: {}", stack.name);
1489 println!(" ID: {}", stack.id);
1490 println!(" Base: {}", stack.base_branch);
1491
1492 if let Some(description) = &stack.description {
1493 println!(" Description: {description}");
1494 }
1495
1496 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1498
1499 match integration.check_stack_status(&stack_id).await {
1501 Ok(status) => {
1502 println!("\n📊 Pull Request Status:");
1503 println!(" Total entries: {}", status.total_entries);
1504 println!(" Submitted: {}", status.submitted_entries);
1505 println!(" Open PRs: {}", status.open_prs);
1506 println!(" Merged PRs: {}", status.merged_prs);
1507 println!(" Declined PRs: {}", status.declined_prs);
1508 println!(" Completion: {:.1}%", status.completion_percentage());
1509
1510 if !status.pull_requests.is_empty() {
1511 println!("\n📋 Pull Requests:");
1512 for pr in &status.pull_requests {
1513 let state_icon = match pr.state {
1514 crate::bitbucket::PullRequestState::Open => "🔄",
1515 crate::bitbucket::PullRequestState::Merged => "✅",
1516 crate::bitbucket::PullRequestState::Declined => "❌",
1517 };
1518 println!(
1519 " {} PR #{}: {} ({} -> {})",
1520 state_icon, pr.id, pr.title, pr.from_ref.display_id, pr.to_ref.display_id
1521 );
1522 if let Some(url) = pr.web_url() {
1523 println!(" URL: {url}");
1524 }
1525 }
1526 }
1527 }
1528 Err(e) => {
1529 warn!("Failed to check stack status: {}", e);
1530 return Err(e);
1531 }
1532 }
1533
1534 Ok(())
1535}
1536
1537async fn list_pull_requests(state: Option<String>, verbose: bool) -> Result<()> {
1538 let current_dir = env::current_dir()
1539 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1540
1541 let stack_manager = StackManager::new(¤t_dir)?;
1542
1543 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
1545 let config_path = config_dir.join("config.json");
1546 let settings = crate::config::Settings::load_from_file(&config_path)?;
1547
1548 let cascade_config = crate::config::CascadeConfig {
1550 bitbucket: Some(settings.bitbucket.clone()),
1551 git: settings.git.clone(),
1552 auth: crate::config::AuthConfig::default(),
1553 };
1554
1555 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
1557
1558 let pr_state = if let Some(state_str) = state {
1560 match state_str.to_lowercase().as_str() {
1561 "open" => Some(crate::bitbucket::PullRequestState::Open),
1562 "merged" => Some(crate::bitbucket::PullRequestState::Merged),
1563 "declined" => Some(crate::bitbucket::PullRequestState::Declined),
1564 _ => {
1565 return Err(CascadeError::config(format!(
1566 "Invalid state '{state_str}'. Use: open, merged, declined"
1567 )))
1568 }
1569 }
1570 } else {
1571 None
1572 };
1573
1574 match integration.list_pull_requests(pr_state).await {
1576 Ok(pr_page) => {
1577 if pr_page.values.is_empty() {
1578 info!("No pull requests found.");
1579 return Ok(());
1580 }
1581
1582 println!("📋 Pull Requests ({} total):", pr_page.values.len());
1583 for pr in &pr_page.values {
1584 let state_icon = match pr.state {
1585 crate::bitbucket::PullRequestState::Open => "🔄",
1586 crate::bitbucket::PullRequestState::Merged => "✅",
1587 crate::bitbucket::PullRequestState::Declined => "❌",
1588 };
1589 println!(" {} PR #{}: {}", state_icon, pr.id, pr.title);
1590 if verbose {
1591 println!(
1592 " From: {} -> {}",
1593 pr.from_ref.display_id, pr.to_ref.display_id
1594 );
1595 println!(" Author: {}", pr.author.user.display_name);
1596 if let Some(url) = pr.web_url() {
1597 println!(" URL: {url}");
1598 }
1599 if let Some(desc) = &pr.description {
1600 if !desc.is_empty() {
1601 println!(" Description: {desc}");
1602 }
1603 }
1604 println!();
1605 }
1606 }
1607
1608 if !verbose {
1609 println!("\nUse --verbose for more details");
1610 }
1611 }
1612 Err(e) => {
1613 warn!("Failed to list pull requests: {}", e);
1614 return Err(e);
1615 }
1616 }
1617
1618 Ok(())
1619}
1620
1621async fn check_stack(_force: bool) -> Result<()> {
1622 let current_dir = env::current_dir()
1623 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1624
1625 let mut manager = StackManager::new(¤t_dir)?;
1626
1627 let active_stack = manager
1628 .get_active_stack()
1629 .ok_or_else(|| CascadeError::config("No active stack"))?;
1630 let stack_id = active_stack.id;
1631
1632 manager.sync_stack(&stack_id)?;
1633
1634 info!("✅ Stack check completed successfully");
1635
1636 Ok(())
1637}
1638
1639async fn sync_stack(force: bool, skip_cleanup: bool, interactive: bool) -> Result<()> {
1640 let current_dir = env::current_dir()
1641 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1642
1643 let stack_manager = StackManager::new(¤t_dir)?;
1644 let git_repo = GitRepository::open(¤t_dir)?;
1645
1646 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1648 CascadeError::config("No active stack. Create a stack first with 'cc stack create'")
1649 })?;
1650
1651 let base_branch = active_stack.base_branch.clone();
1652 let stack_name = active_stack.name.clone();
1653
1654 println!("🔄 Syncing stack '{stack_name}' with remote...");
1655
1656 println!("📥 Pulling latest changes from '{base_branch}'...");
1658
1659 match git_repo.checkout_branch(&base_branch) {
1661 Ok(_) => {
1662 println!(" ✅ Switched to '{base_branch}'");
1663
1664 match git_repo.pull(&base_branch) {
1666 Ok(_) => {
1667 println!(" ✅ Successfully pulled latest changes");
1668 }
1669 Err(e) => {
1670 if force {
1671 println!(" ⚠️ Failed to pull: {e} (continuing due to --force)");
1672 } else {
1673 return Err(CascadeError::branch(format!(
1674 "Failed to pull latest changes from '{base_branch}': {e}. Use --force to continue anyway."
1675 )));
1676 }
1677 }
1678 }
1679 }
1680 Err(e) => {
1681 if force {
1682 println!(
1683 " ⚠️ Failed to checkout '{base_branch}': {e} (continuing due to --force)"
1684 );
1685 } else {
1686 return Err(CascadeError::branch(format!(
1687 "Failed to checkout base branch '{base_branch}': {e}. Use --force to continue anyway."
1688 )));
1689 }
1690 }
1691 }
1692
1693 println!("🔍 Checking if stack needs rebase...");
1695
1696 let mut updated_stack_manager = StackManager::new(¤t_dir)?;
1697 let stack_id = active_stack.id;
1698
1699 match updated_stack_manager.sync_stack(&stack_id) {
1700 Ok(_) => {
1701 if let Some(updated_stack) = updated_stack_manager.get_stack(&stack_id) {
1703 match &updated_stack.status {
1704 crate::stack::StackStatus::NeedsSync => {
1705 println!(" 🔄 Stack needs rebase due to new commits on '{base_branch}'");
1706
1707 println!("🔀 Rebasing stack onto updated '{base_branch}'...");
1709
1710 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
1712 let config_path = config_dir.join("config.json");
1713 let settings = crate::config::Settings::load_from_file(&config_path)?;
1714
1715 let cascade_config = crate::config::CascadeConfig {
1716 bitbucket: Some(settings.bitbucket.clone()),
1717 git: settings.git.clone(),
1718 auth: crate::config::AuthConfig::default(),
1719 };
1720
1721 let options = crate::stack::RebaseOptions {
1723 strategy: crate::stack::RebaseStrategy::BranchVersioning,
1724 interactive,
1725 target_base: Some(base_branch.clone()),
1726 preserve_merges: true,
1727 auto_resolve: !interactive,
1728 max_retries: 3,
1729 };
1730
1731 let mut rebase_manager = crate::stack::RebaseManager::new(
1732 updated_stack_manager,
1733 git_repo,
1734 options,
1735 );
1736
1737 match rebase_manager.rebase_stack(&stack_id) {
1738 Ok(result) => {
1739 println!(" ✅ Rebase completed successfully!");
1740
1741 if !result.branch_mapping.is_empty() {
1742 println!(" 📋 Updated branches:");
1743 for (old, new) in &result.branch_mapping {
1744 println!(" {old} → {new}");
1745 }
1746
1747 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
1749 println!(" 🔄 Updating pull requests...");
1750
1751 let integration_stack_manager =
1752 StackManager::new(¤t_dir)?;
1753 let mut integration =
1754 crate::bitbucket::BitbucketIntegration::new(
1755 integration_stack_manager,
1756 cascade_config,
1757 )?;
1758
1759 match integration
1760 .update_prs_after_rebase(
1761 &stack_id,
1762 &result.branch_mapping,
1763 )
1764 .await
1765 {
1766 Ok(updated_prs) => {
1767 if !updated_prs.is_empty() {
1768 println!(
1769 " ✅ Updated {} pull requests",
1770 updated_prs.len()
1771 );
1772 }
1773 }
1774 Err(e) => {
1775 println!(
1776 " ⚠️ Failed to update pull requests: {e}"
1777 );
1778 }
1779 }
1780 }
1781 }
1782 }
1783 Err(e) => {
1784 println!(" ❌ Rebase failed: {e}");
1785 println!(" 💡 To resolve conflicts:");
1786 println!(" 1. Fix conflicts in the affected files");
1787 println!(" 2. Stage resolved files: git add <files>");
1788 println!(" 3. Continue: cc stack continue-rebase");
1789 return Err(e);
1790 }
1791 }
1792 }
1793 crate::stack::StackStatus::Clean => {
1794 println!(" ✅ Stack is already up to date");
1795 }
1796 other => {
1797 println!(" ℹ️ Stack status: {other:?}");
1798 }
1799 }
1800 }
1801 }
1802 Err(e) => {
1803 if force {
1804 println!(" ⚠️ Failed to check stack status: {e} (continuing due to --force)");
1805 } else {
1806 return Err(e);
1807 }
1808 }
1809 }
1810
1811 if !skip_cleanup {
1813 println!("🧹 Checking for merged branches to clean up...");
1814 println!(" ℹ️ Branch cleanup not yet implemented");
1820 } else {
1821 println!("⏭️ Skipping branch cleanup");
1822 }
1823
1824 println!("🎉 Sync completed successfully!");
1825 println!(" Base branch: {base_branch}");
1826 println!(" 💡 Next steps:");
1827 println!(" • Review your updated stack: cc stack show");
1828 println!(" • Check PR status: cc stack status");
1829
1830 Ok(())
1831}
1832
1833async fn rebase_stack(
1834 interactive: bool,
1835 onto: Option<String>,
1836 strategy: Option<RebaseStrategyArg>,
1837) -> Result<()> {
1838 let current_dir = env::current_dir()
1839 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
1840
1841 let stack_manager = StackManager::new(¤t_dir)?;
1842 let git_repo = GitRepository::open(¤t_dir)?;
1843
1844 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
1846 let config_path = config_dir.join("config.json");
1847 let settings = crate::config::Settings::load_from_file(&config_path)?;
1848
1849 let cascade_config = crate::config::CascadeConfig {
1851 bitbucket: Some(settings.bitbucket.clone()),
1852 git: settings.git.clone(),
1853 auth: crate::config::AuthConfig::default(),
1854 };
1855
1856 let active_stack = stack_manager.get_active_stack().ok_or_else(|| {
1858 CascadeError::config("No active stack. Create a stack first with 'cc stack create'")
1859 })?;
1860 let stack_id = active_stack.id;
1861
1862 let active_stack = stack_manager
1863 .get_stack(&stack_id)
1864 .ok_or_else(|| CascadeError::config("Active stack not found"))?
1865 .clone();
1866
1867 if active_stack.entries.is_empty() {
1868 println!("ℹ️ Stack is empty. Nothing to rebase.");
1869 return Ok(());
1870 }
1871
1872 println!("🔄 Rebasing stack: {}", active_stack.name);
1873 println!(" Base: {}", active_stack.base_branch);
1874
1875 let rebase_strategy = if let Some(cli_strategy) = strategy {
1877 match cli_strategy {
1878 RebaseStrategyArg::BranchVersioning => crate::stack::RebaseStrategy::BranchVersioning,
1879 RebaseStrategyArg::CherryPick => crate::stack::RebaseStrategy::CherryPick,
1880 RebaseStrategyArg::ThreeWayMerge => crate::stack::RebaseStrategy::ThreeWayMerge,
1881 RebaseStrategyArg::Interactive => crate::stack::RebaseStrategy::Interactive,
1882 }
1883 } else {
1884 match settings.cascade.default_sync_strategy.as_str() {
1886 "branch-versioning" => crate::stack::RebaseStrategy::BranchVersioning,
1887 "cherry-pick" => crate::stack::RebaseStrategy::CherryPick,
1888 "three-way-merge" => crate::stack::RebaseStrategy::ThreeWayMerge,
1889 "rebase" => crate::stack::RebaseStrategy::Interactive,
1890 _ => crate::stack::RebaseStrategy::BranchVersioning, }
1892 };
1893
1894 let options = crate::stack::RebaseOptions {
1896 strategy: rebase_strategy.clone(),
1897 interactive,
1898 target_base: onto,
1899 preserve_merges: true,
1900 auto_resolve: !interactive, max_retries: 3,
1902 };
1903
1904 info!(" Strategy: {:?}", rebase_strategy);
1905 info!(" Interactive: {}", interactive);
1906 info!(" Target base: {:?}", options.target_base);
1907 info!(" Entries: {}", active_stack.entries.len());
1908
1909 let mut rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
1911
1912 if rebase_manager.is_rebase_in_progress() {
1913 println!("⚠️ Rebase already in progress!");
1914 println!(" Use 'git status' to check the current state");
1915 println!(" Use 'cc stack continue-rebase' to continue");
1916 println!(" Use 'cc stack abort-rebase' to abort");
1917 return Ok(());
1918 }
1919
1920 match rebase_manager.rebase_stack(&stack_id) {
1922 Ok(result) => {
1923 println!("🎉 Rebase completed!");
1924 println!(" {}", result.get_summary());
1925
1926 if result.has_conflicts() {
1927 println!(" ⚠️ {} conflicts were resolved", result.conflicts.len());
1928 for conflict in &result.conflicts {
1929 println!(" - {}", &conflict[..8.min(conflict.len())]);
1930 }
1931 }
1932
1933 if !result.branch_mapping.is_empty() {
1934 println!(" 📋 Branch mapping:");
1935 for (old, new) in &result.branch_mapping {
1936 println!(" {old} -> {new}");
1937 }
1938
1939 if let Some(ref _bitbucket_config) = cascade_config.bitbucket {
1941 let integration_stack_manager = StackManager::new(¤t_dir)?;
1943 let mut integration = BitbucketIntegration::new(
1944 integration_stack_manager,
1945 cascade_config.clone(),
1946 )?;
1947
1948 match integration
1949 .update_prs_after_rebase(&stack_id, &result.branch_mapping)
1950 .await
1951 {
1952 Ok(updated_prs) => {
1953 if !updated_prs.is_empty() {
1954 println!(" 🔄 Preserved pull request history:");
1955 for pr_update in updated_prs {
1956 println!(" ✅ {pr_update}");
1957 }
1958 }
1959 }
1960 Err(e) => {
1961 eprintln!(" ⚠️ Failed to update pull requests: {e}");
1962 eprintln!(" You may need to manually update PRs in Bitbucket");
1963 }
1964 }
1965 }
1966 }
1967
1968 println!(
1969 " ✅ {} commits successfully rebased",
1970 result.success_count()
1971 );
1972
1973 if matches!(
1975 rebase_strategy,
1976 crate::stack::RebaseStrategy::BranchVersioning
1977 ) {
1978 println!("\n📝 Next steps:");
1979 if !result.branch_mapping.is_empty() {
1980 println!(" 1. ✅ New versioned branches have been created");
1981 println!(" 2. ✅ Pull requests have been updated automatically");
1982 println!(" 3. 🔍 Review the updated PRs in Bitbucket");
1983 println!(" 4. 🧪 Test your changes on the new branches");
1984 println!(
1985 " 5. 🗑️ Old branches are preserved for safety (can be deleted later)"
1986 );
1987 } else {
1988 println!(" 1. Review the rebased stack");
1989 println!(" 2. Test your changes");
1990 println!(" 3. Submit new pull requests with 'cc stack submit'");
1991 }
1992 }
1993 }
1994 Err(e) => {
1995 warn!("❌ Rebase failed: {}", e);
1996 println!("💡 Tips for resolving rebase issues:");
1997 println!(" - Check for uncommitted changes with 'git status'");
1998 println!(" - Ensure base branch is up to date");
1999 println!(" - Try interactive mode: 'cc stack rebase --interactive'");
2000 return Err(e);
2001 }
2002 }
2003
2004 Ok(())
2005}
2006
2007async fn continue_rebase() -> Result<()> {
2008 let current_dir = env::current_dir()
2009 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2010
2011 let stack_manager = StackManager::new(¤t_dir)?;
2012 let git_repo = crate::git::GitRepository::open(¤t_dir)?;
2013 let options = crate::stack::RebaseOptions::default();
2014 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2015
2016 if !rebase_manager.is_rebase_in_progress() {
2017 println!("ℹ️ No rebase in progress");
2018 return Ok(());
2019 }
2020
2021 println!("🔄 Continuing rebase...");
2022 match rebase_manager.continue_rebase() {
2023 Ok(_) => {
2024 println!("✅ Rebase continued successfully");
2025 println!(" Check 'cc stack rebase-status' for current state");
2026 }
2027 Err(e) => {
2028 warn!("❌ Failed to continue rebase: {}", e);
2029 println!("💡 You may need to resolve conflicts first:");
2030 println!(" 1. Edit conflicted files");
2031 println!(" 2. Stage resolved files with 'git add'");
2032 println!(" 3. Run 'cc stack continue-rebase' again");
2033 }
2034 }
2035
2036 Ok(())
2037}
2038
2039async fn abort_rebase() -> Result<()> {
2040 let current_dir = env::current_dir()
2041 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2042
2043 let stack_manager = StackManager::new(¤t_dir)?;
2044 let git_repo = crate::git::GitRepository::open(¤t_dir)?;
2045 let options = crate::stack::RebaseOptions::default();
2046 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2047
2048 if !rebase_manager.is_rebase_in_progress() {
2049 println!("ℹ️ No rebase in progress");
2050 return Ok(());
2051 }
2052
2053 println!("⚠️ Aborting rebase...");
2054 match rebase_manager.abort_rebase() {
2055 Ok(_) => {
2056 println!("✅ Rebase aborted successfully");
2057 println!(" Repository restored to pre-rebase state");
2058 }
2059 Err(e) => {
2060 warn!("❌ Failed to abort rebase: {}", e);
2061 println!("⚠️ You may need to manually clean up the repository state");
2062 }
2063 }
2064
2065 Ok(())
2066}
2067
2068async fn rebase_status() -> Result<()> {
2069 let current_dir = env::current_dir()
2070 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2071
2072 let stack_manager = StackManager::new(¤t_dir)?;
2073 let git_repo = crate::git::GitRepository::open(¤t_dir)?;
2074
2075 println!("📊 Rebase Status");
2076
2077 let git_dir = current_dir.join(".git");
2079 let rebase_in_progress = git_dir.join("REBASE_HEAD").exists()
2080 || git_dir.join("rebase-merge").exists()
2081 || git_dir.join("rebase-apply").exists();
2082
2083 if rebase_in_progress {
2084 println!(" Status: 🔄 Rebase in progress");
2085 println!(
2086 "
2087📝 Actions available:"
2088 );
2089 println!(" - 'cc stack continue-rebase' to continue");
2090 println!(" - 'cc stack abort-rebase' to abort");
2091 println!(" - 'git status' to see conflicted files");
2092
2093 match git_repo.get_status() {
2095 Ok(statuses) => {
2096 let mut conflicts = Vec::new();
2097 for status in statuses.iter() {
2098 if status.status().contains(git2::Status::CONFLICTED) {
2099 if let Some(path) = status.path() {
2100 conflicts.push(path.to_string());
2101 }
2102 }
2103 }
2104
2105 if !conflicts.is_empty() {
2106 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2107 for conflict in conflicts {
2108 println!(" - {conflict}");
2109 }
2110 println!(
2111 "
2112💡 To resolve conflicts:"
2113 );
2114 println!(" 1. Edit the conflicted files");
2115 println!(" 2. Stage resolved files: git add <file>");
2116 println!(" 3. Continue: cc stack continue-rebase");
2117 }
2118 }
2119 Err(e) => {
2120 warn!("Failed to get git status: {}", e);
2121 }
2122 }
2123 } else {
2124 println!(" Status: ✅ No rebase in progress");
2125
2126 if let Some(active_stack) = stack_manager.get_active_stack() {
2128 println!(" Active stack: {}", active_stack.name);
2129 println!(" Entries: {}", active_stack.entries.len());
2130 println!(" Base branch: {}", active_stack.base_branch);
2131 }
2132 }
2133
2134 Ok(())
2135}
2136
2137async fn delete_stack(name: String, force: bool) -> Result<()> {
2138 let current_dir = env::current_dir()
2139 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2140
2141 let mut manager = StackManager::new(¤t_dir)?;
2142
2143 let stack = manager
2144 .get_stack_by_name(&name)
2145 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2146 let stack_id = stack.id;
2147
2148 if !force && !stack.entries.is_empty() {
2149 return Err(CascadeError::config(format!(
2150 "Stack '{}' has {} entries. Use --force to delete anyway",
2151 name,
2152 stack.entries.len()
2153 )));
2154 }
2155
2156 let deleted = manager.delete_stack(&stack_id)?;
2157
2158 info!("✅ Deleted stack '{}'", deleted.name);
2159 if !deleted.entries.is_empty() {
2160 warn!(" {} entries were removed", deleted.entries.len());
2161 }
2162
2163 Ok(())
2164}
2165
2166async fn validate_stack(name: Option<String>) -> Result<()> {
2167 let current_dir = env::current_dir()
2168 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2169
2170 let manager = StackManager::new(¤t_dir)?;
2171
2172 if let Some(name) = name {
2173 let stack = manager
2175 .get_stack_by_name(&name)
2176 .ok_or_else(|| CascadeError::config(format!("Stack '{name}' not found")))?;
2177
2178 match stack.validate() {
2179 Ok(_) => {
2180 println!("✅ Stack '{name}' validation passed");
2181 Ok(())
2182 }
2183 Err(e) => {
2184 println!("❌ Stack '{name}' validation failed: {e}");
2185 Err(CascadeError::config(e))
2186 }
2187 }
2188 } else {
2189 match manager.validate_all() {
2191 Ok(_) => {
2192 println!("✅ All stacks validation passed");
2193 Ok(())
2194 }
2195 Err(e) => {
2196 println!("❌ Stack validation failed: {e}");
2197 Err(e)
2198 }
2199 }
2200 }
2201}
2202
2203#[allow(dead_code)]
2205fn get_unpushed_commits(repo: &GitRepository, stack: &crate::stack::Stack) -> Result<Vec<String>> {
2206 let mut unpushed = Vec::new();
2207 let head_commit = repo.get_head_commit()?;
2208 let mut current_commit = head_commit;
2209
2210 loop {
2212 let commit_hash = current_commit.id().to_string();
2213 let already_in_stack = stack
2214 .entries
2215 .iter()
2216 .any(|entry| entry.commit_hash == commit_hash);
2217
2218 if already_in_stack {
2219 break;
2220 }
2221
2222 unpushed.push(commit_hash);
2223
2224 if let Some(parent) = current_commit.parents().next() {
2226 current_commit = parent;
2227 } else {
2228 break;
2229 }
2230 }
2231
2232 unpushed.reverse(); Ok(unpushed)
2234}
2235
2236pub async fn squash_commits(
2238 repo: &GitRepository,
2239 count: usize,
2240 since_ref: Option<String>,
2241) -> Result<()> {
2242 if count <= 1 {
2243 return Ok(()); }
2245
2246 let _current_branch = repo.get_current_branch()?;
2248
2249 let rebase_range = if let Some(ref since) = since_ref {
2251 since.clone()
2252 } else {
2253 format!("HEAD~{count}")
2254 };
2255
2256 println!(" Analyzing {count} commits to create smart squash message...");
2257
2258 let head_commit = repo.get_head_commit()?;
2260 let mut commits_to_squash = Vec::new();
2261 let mut current = head_commit;
2262
2263 for _ in 0..count {
2265 commits_to_squash.push(current.clone());
2266 if current.parent_count() > 0 {
2267 current = current.parent(0).map_err(CascadeError::Git)?;
2268 } else {
2269 break;
2270 }
2271 }
2272
2273 let smart_message = generate_squash_message(&commits_to_squash)?;
2275 println!(
2276 " Smart message: {}",
2277 smart_message.lines().next().unwrap_or("")
2278 );
2279
2280 let reset_target = if since_ref.is_some() {
2282 format!("{rebase_range}~1")
2284 } else {
2285 format!("HEAD~{count}")
2287 };
2288
2289 repo.reset_soft(&reset_target)?;
2291
2292 repo.stage_all()?;
2294
2295 let new_commit_hash = repo.commit(&smart_message)?;
2297
2298 println!(
2299 " Created squashed commit: {} ({})",
2300 &new_commit_hash[..8],
2301 smart_message.lines().next().unwrap_or("")
2302 );
2303 println!(" 💡 Tip: Use 'git commit --amend' to edit the commit message if needed");
2304
2305 Ok(())
2306}
2307
2308pub fn generate_squash_message(commits: &[git2::Commit]) -> Result<String> {
2310 if commits.is_empty() {
2311 return Ok("Squashed commits".to_string());
2312 }
2313
2314 let messages: Vec<String> = commits
2316 .iter()
2317 .map(|c| c.message().unwrap_or("").trim().to_string())
2318 .filter(|m| !m.is_empty())
2319 .collect();
2320
2321 if messages.is_empty() {
2322 return Ok("Squashed commits".to_string());
2323 }
2324
2325 if let Some(last_msg) = messages.first() {
2327 if last_msg.starts_with("Final:") || last_msg.starts_with("final:") {
2329 return Ok(last_msg
2330 .trim_start_matches("Final:")
2331 .trim_start_matches("final:")
2332 .trim()
2333 .to_string());
2334 }
2335 }
2336
2337 let wip_count = messages
2339 .iter()
2340 .filter(|m| {
2341 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
2342 })
2343 .count();
2344
2345 if wip_count > messages.len() / 2 {
2346 let non_wip: Vec<&String> = messages
2348 .iter()
2349 .filter(|m| {
2350 !m.to_lowercase().starts_with("wip")
2351 && !m.to_lowercase().contains("work in progress")
2352 })
2353 .collect();
2354
2355 if let Some(best_msg) = non_wip.first() {
2356 return Ok(best_msg.to_string());
2357 }
2358
2359 let feature = extract_feature_from_wip(&messages);
2361 return Ok(feature);
2362 }
2363
2364 Ok(messages.first().unwrap().clone())
2366}
2367
2368pub fn extract_feature_from_wip(messages: &[String]) -> String {
2370 for msg in messages {
2372 if msg.to_lowercase().starts_with("wip:") {
2374 if let Some(rest) = msg
2375 .strip_prefix("WIP:")
2376 .or_else(|| msg.strip_prefix("wip:"))
2377 {
2378 let feature = rest.trim();
2379 if !feature.is_empty() && feature.len() > 3 {
2380 let mut chars: Vec<char> = feature.chars().collect();
2382 if let Some(first) = chars.first_mut() {
2383 *first = first.to_uppercase().next().unwrap_or(*first);
2384 }
2385 return chars.into_iter().collect();
2386 }
2387 }
2388 }
2389 }
2390
2391 if let Some(first) = messages.first() {
2393 let cleaned = first
2394 .trim_start_matches("WIP:")
2395 .trim_start_matches("wip:")
2396 .trim_start_matches("WIP")
2397 .trim_start_matches("wip")
2398 .trim();
2399
2400 if !cleaned.is_empty() {
2401 return format!("Implement {cleaned}");
2402 }
2403 }
2404
2405 format!("Squashed {} commits", messages.len())
2406}
2407
2408pub fn count_commits_since(repo: &GitRepository, since_commit_hash: &str) -> Result<usize> {
2410 let head_commit = repo.get_head_commit()?;
2411 let since_commit = repo.get_commit(since_commit_hash)?;
2412
2413 let mut count = 0;
2414 let mut current = head_commit;
2415
2416 loop {
2418 if current.id() == since_commit.id() {
2419 break;
2420 }
2421
2422 count += 1;
2423
2424 if current.parent_count() == 0 {
2426 break; }
2428
2429 current = current.parent(0).map_err(CascadeError::Git)?;
2430 }
2431
2432 Ok(count)
2433}
2434
2435async fn land_stack(
2437 entry: Option<usize>,
2438 force: bool,
2439 dry_run: bool,
2440 auto: bool,
2441 wait_for_builds: bool,
2442 strategy: Option<MergeStrategyArg>,
2443 build_timeout: u64,
2444) -> Result<()> {
2445 let current_dir = env::current_dir()
2446 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2447
2448 let stack_manager = StackManager::new(¤t_dir)?;
2449
2450 let stack_id = stack_manager
2452 .get_active_stack()
2453 .map(|s| s.id)
2454 .ok_or_else(|| {
2455 CascadeError::config(
2456 "No active stack. Use 'cc stack create' or 'cc stack switch' to select a stack"
2457 .to_string(),
2458 )
2459 })?;
2460
2461 let active_stack = stack_manager
2462 .get_active_stack()
2463 .cloned()
2464 .ok_or_else(|| CascadeError::config("No active stack found".to_string()))?;
2465
2466 let config_dir = crate::config::get_repo_config_dir(¤t_dir)?;
2468 let config_path = config_dir.join("config.json");
2469 let settings = crate::config::Settings::load_from_file(&config_path)?;
2470
2471 let cascade_config = crate::config::CascadeConfig {
2472 bitbucket: Some(settings.bitbucket.clone()),
2473 git: settings.git.clone(),
2474 auth: crate::config::AuthConfig::default(),
2475 };
2476
2477 let integration = crate::bitbucket::BitbucketIntegration::new(stack_manager, cascade_config)?;
2478
2479 let status = integration.check_enhanced_stack_status(&stack_id).await?;
2481
2482 if status.enhanced_statuses.is_empty() {
2483 println!("❌ No pull requests found to land");
2484 return Ok(());
2485 }
2486
2487 let ready_prs: Vec<_> = status
2489 .enhanced_statuses
2490 .iter()
2491 .filter(|pr_status| {
2492 if let Some(entry_num) = entry {
2494 if let Some(stack_entry) = active_stack.entries.get(entry_num.saturating_sub(1)) {
2496 if pr_status.pr.from_ref.display_id != stack_entry.branch {
2498 return false;
2499 }
2500 } else {
2501 return false; }
2503 }
2504
2505 if force {
2506 pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open
2508 } else {
2509 pr_status.is_ready_to_land()
2510 }
2511 })
2512 .collect();
2513
2514 if ready_prs.is_empty() {
2515 if let Some(entry_num) = entry {
2516 println!("❌ Entry {entry_num} is not ready to land or doesn't exist");
2517 } else {
2518 println!("❌ No pull requests are ready to land");
2519 }
2520
2521 println!("\n🚫 Blocking Issues:");
2523 for pr_status in &status.enhanced_statuses {
2524 if pr_status.pr.state == crate::bitbucket::pull_request::PullRequestState::Open {
2525 let blocking = pr_status.get_blocking_reasons();
2526 if !blocking.is_empty() {
2527 println!(" PR #{}: {}", pr_status.pr.id, blocking.join(", "));
2528 }
2529 }
2530 }
2531
2532 if !force {
2533 println!("\n💡 Use --force to land PRs with blocking issues (dangerous!)");
2534 }
2535 return Ok(());
2536 }
2537
2538 if dry_run {
2539 if let Some(entry_num) = entry {
2540 println!("🏃 Dry Run - Entry {entry_num} that would be landed:");
2541 } else {
2542 println!("🏃 Dry Run - PRs that would be landed:");
2543 }
2544 for pr_status in &ready_prs {
2545 println!(" ✅ PR #{}: {}", pr_status.pr.id, pr_status.pr.title);
2546 if !pr_status.is_ready_to_land() && force {
2547 let blocking = pr_status.get_blocking_reasons();
2548 println!(
2549 " ⚠️ Would force land despite: {}",
2550 blocking.join(", ")
2551 );
2552 }
2553 }
2554 return Ok(());
2555 }
2556
2557 if entry.is_some() && ready_prs.len() > 1 {
2560 println!(
2561 "🎯 {} PRs are ready to land, but landing only entry #{}",
2562 ready_prs.len(),
2563 entry.unwrap()
2564 );
2565 }
2566
2567 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy =
2569 strategy.unwrap_or(MergeStrategyArg::Squash).into();
2570 let auto_merge_conditions = crate::bitbucket::pull_request::AutoMergeConditions {
2571 merge_strategy: merge_strategy.clone(),
2572 wait_for_builds,
2573 build_timeout: std::time::Duration::from_secs(build_timeout),
2574 allowed_authors: None, };
2576
2577 println!(
2579 "🚀 Landing {} PR{}...",
2580 ready_prs.len(),
2581 if ready_prs.len() == 1 { "" } else { "s" }
2582 );
2583
2584 let pr_manager = crate::bitbucket::pull_request::PullRequestManager::new(
2585 crate::bitbucket::BitbucketClient::new(&settings.bitbucket)?,
2586 );
2587
2588 let mut landed_count = 0;
2590 let mut failed_count = 0;
2591 let total_ready_prs = ready_prs.len();
2592
2593 for pr_status in ready_prs {
2594 let pr_id = pr_status.pr.id;
2595
2596 print!("🚀 Landing PR #{}: {}", pr_id, pr_status.pr.title);
2597
2598 let land_result = if auto {
2599 pr_manager
2601 .auto_merge_if_ready(pr_id, &auto_merge_conditions)
2602 .await
2603 } else {
2604 pr_manager
2606 .merge_pull_request(pr_id, merge_strategy.clone())
2607 .await
2608 .map(
2609 |pr| crate::bitbucket::pull_request::AutoMergeResult::Merged {
2610 pr: Box::new(pr),
2611 merge_strategy: merge_strategy.clone(),
2612 },
2613 )
2614 };
2615
2616 match land_result {
2617 Ok(crate::bitbucket::pull_request::AutoMergeResult::Merged { .. }) => {
2618 println!(" ✅");
2619 landed_count += 1;
2620
2621 if landed_count < total_ready_prs {
2623 println!("🔄 Retargeting remaining PRs to latest base...");
2624
2625 let base_branch = active_stack.base_branch.clone();
2627 let git_repo = crate::git::GitRepository::open(¤t_dir)?;
2628
2629 println!(" 📥 Updating base branch: {base_branch}");
2630 match git_repo.pull(&base_branch) {
2631 Ok(_) => println!(" ✅ Base branch updated successfully"),
2632 Err(e) => {
2633 println!(" ⚠️ Warning: Failed to update base branch: {e}");
2634 println!(
2635 " 💡 You may want to manually run: git pull origin {base_branch}"
2636 );
2637 }
2638 }
2639
2640 let mut rebase_manager = crate::stack::RebaseManager::new(
2642 StackManager::new(¤t_dir)?,
2643 git_repo,
2644 crate::stack::RebaseOptions {
2645 strategy: crate::stack::RebaseStrategy::BranchVersioning,
2646 target_base: Some(base_branch.clone()),
2647 ..Default::default()
2648 },
2649 );
2650
2651 match rebase_manager.rebase_stack(&stack_id) {
2652 Ok(rebase_result) => {
2653 if !rebase_result.branch_mapping.is_empty() {
2654 let retarget_config = crate::config::CascadeConfig {
2656 bitbucket: Some(settings.bitbucket.clone()),
2657 git: settings.git.clone(),
2658 auth: crate::config::AuthConfig::default(),
2659 };
2660 let mut retarget_integration = BitbucketIntegration::new(
2661 StackManager::new(¤t_dir)?,
2662 retarget_config,
2663 )?;
2664
2665 match retarget_integration
2666 .update_prs_after_rebase(
2667 &stack_id,
2668 &rebase_result.branch_mapping,
2669 )
2670 .await
2671 {
2672 Ok(updated_prs) => {
2673 if !updated_prs.is_empty() {
2674 println!(
2675 " ✅ Updated {} PRs with new targets",
2676 updated_prs.len()
2677 );
2678 }
2679 }
2680 Err(e) => {
2681 println!(" ⚠️ Failed to update remaining PRs: {e}");
2682 println!(
2683 " 💡 You may need to run: cc stack rebase --onto {base_branch}"
2684 );
2685 }
2686 }
2687 }
2688 }
2689 Err(e) => {
2690 println!(" ❌ Auto-retargeting conflicts detected!");
2692 println!(" 📝 To resolve conflicts and continue landing:");
2693 println!(" 1. Resolve conflicts in the affected files");
2694 println!(" 2. Stage resolved files: git add <files>");
2695 println!(" 3. Continue the process: cc stack continue-land");
2696 println!(" 4. Or abort the operation: cc stack abort-land");
2697 println!();
2698 println!(" 💡 Check current status: cc stack land-status");
2699 println!(" ⚠️ Error details: {e}");
2700
2701 break;
2703 }
2704 }
2705 }
2706 }
2707 Ok(crate::bitbucket::pull_request::AutoMergeResult::NotReady { blocking_reasons }) => {
2708 println!(" ❌ Not ready: {}", blocking_reasons.join(", "));
2709 failed_count += 1;
2710 if !force {
2711 break;
2712 }
2713 }
2714 Ok(crate::bitbucket::pull_request::AutoMergeResult::Failed { error }) => {
2715 println!(" ❌ Failed: {error}");
2716 failed_count += 1;
2717 if !force {
2718 break;
2719 }
2720 }
2721 Err(e) => {
2722 println!(" ❌");
2723 eprintln!("Failed to land PR #{pr_id}: {e}");
2724 failed_count += 1;
2725
2726 if !force {
2727 break;
2728 }
2729 }
2730 }
2731 }
2732
2733 println!("\n🎯 Landing Summary:");
2735 println!(" ✅ Successfully landed: {landed_count}");
2736 if failed_count > 0 {
2737 println!(" ❌ Failed to land: {failed_count}");
2738 }
2739
2740 if landed_count > 0 {
2741 println!("✅ Landing operation completed!");
2742 } else {
2743 println!("❌ No PRs were successfully landed");
2744 }
2745
2746 Ok(())
2747}
2748
2749async fn auto_land_stack(
2751 force: bool,
2752 dry_run: bool,
2753 wait_for_builds: bool,
2754 strategy: Option<MergeStrategyArg>,
2755 build_timeout: u64,
2756) -> Result<()> {
2757 land_stack(
2759 None,
2760 force,
2761 dry_run,
2762 true, wait_for_builds,
2764 strategy,
2765 build_timeout,
2766 )
2767 .await
2768}
2769
2770async fn continue_land() -> Result<()> {
2771 let current_dir = env::current_dir()
2772 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2773
2774 let stack_manager = StackManager::new(¤t_dir)?;
2775 let git_repo = crate::git::GitRepository::open(¤t_dir)?;
2776 let options = crate::stack::RebaseOptions::default();
2777 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2778
2779 if !rebase_manager.is_rebase_in_progress() {
2780 println!("ℹ️ No rebase in progress");
2781 return Ok(());
2782 }
2783
2784 println!("🔄 Continuing land operation...");
2785 match rebase_manager.continue_rebase() {
2786 Ok(_) => {
2787 println!("✅ Land operation continued successfully");
2788 println!(" Check 'cc stack land-status' for current state");
2789 }
2790 Err(e) => {
2791 warn!("❌ Failed to continue land operation: {}", e);
2792 println!("💡 You may need to resolve conflicts first:");
2793 println!(" 1. Edit conflicted files");
2794 println!(" 2. Stage resolved files with 'git add'");
2795 println!(" 3. Run 'cc stack continue-land' again");
2796 }
2797 }
2798
2799 Ok(())
2800}
2801
2802async fn abort_land() -> Result<()> {
2803 let current_dir = env::current_dir()
2804 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2805
2806 let stack_manager = StackManager::new(¤t_dir)?;
2807 let git_repo = crate::git::GitRepository::open(¤t_dir)?;
2808 let options = crate::stack::RebaseOptions::default();
2809 let rebase_manager = crate::stack::RebaseManager::new(stack_manager, git_repo, options);
2810
2811 if !rebase_manager.is_rebase_in_progress() {
2812 println!("ℹ️ No rebase in progress");
2813 return Ok(());
2814 }
2815
2816 println!("⚠️ Aborting land operation...");
2817 match rebase_manager.abort_rebase() {
2818 Ok(_) => {
2819 println!("✅ Land operation aborted successfully");
2820 println!(" Repository restored to pre-land state");
2821 }
2822 Err(e) => {
2823 warn!("❌ Failed to abort land operation: {}", e);
2824 println!("⚠️ You may need to manually clean up the repository state");
2825 }
2826 }
2827
2828 Ok(())
2829}
2830
2831async fn land_status() -> Result<()> {
2832 let current_dir = env::current_dir()
2833 .map_err(|e| CascadeError::config(format!("Could not get current directory: {e}")))?;
2834
2835 let stack_manager = StackManager::new(¤t_dir)?;
2836 let git_repo = crate::git::GitRepository::open(¤t_dir)?;
2837
2838 println!("📊 Land Status");
2839
2840 let git_dir = current_dir.join(".git");
2842 let land_in_progress = git_dir.join("REBASE_HEAD").exists()
2843 || git_dir.join("rebase-merge").exists()
2844 || git_dir.join("rebase-apply").exists();
2845
2846 if land_in_progress {
2847 println!(" Status: 🔄 Land operation in progress");
2848 println!(
2849 "
2850📝 Actions available:"
2851 );
2852 println!(" - 'cc stack continue-land' to continue");
2853 println!(" - 'cc stack abort-land' to abort");
2854 println!(" - 'git status' to see conflicted files");
2855
2856 match git_repo.get_status() {
2858 Ok(statuses) => {
2859 let mut conflicts = Vec::new();
2860 for status in statuses.iter() {
2861 if status.status().contains(git2::Status::CONFLICTED) {
2862 if let Some(path) = status.path() {
2863 conflicts.push(path.to_string());
2864 }
2865 }
2866 }
2867
2868 if !conflicts.is_empty() {
2869 println!(" ⚠️ Conflicts in {} files:", conflicts.len());
2870 for conflict in conflicts {
2871 println!(" - {conflict}");
2872 }
2873 println!(
2874 "
2875💡 To resolve conflicts:"
2876 );
2877 println!(" 1. Edit the conflicted files");
2878 println!(" 2. Stage resolved files: git add <file>");
2879 println!(" 3. Continue: cc stack continue-land");
2880 }
2881 }
2882 Err(e) => {
2883 warn!("Failed to get git status: {}", e);
2884 }
2885 }
2886 } else {
2887 println!(" Status: ✅ No land operation in progress");
2888
2889 if let Some(active_stack) = stack_manager.get_active_stack() {
2891 println!(" Active stack: {}", active_stack.name);
2892 println!(" Entries: {}", active_stack.entries.len());
2893 println!(" Base branch: {}", active_stack.base_branch);
2894 }
2895 }
2896
2897 Ok(())
2898}
2899
2900#[cfg(test)]
2901mod tests {
2902 use super::*;
2903 use std::process::Command;
2904 use tempfile::TempDir;
2905
2906 async fn create_test_repo() -> (TempDir, std::path::PathBuf) {
2907 let temp_dir = TempDir::new().unwrap();
2908 let repo_path = temp_dir.path().to_path_buf();
2909
2910 Command::new("git")
2912 .args(["init"])
2913 .current_dir(&repo_path)
2914 .output()
2915 .unwrap();
2916
2917 Command::new("git")
2918 .args(["config", "user.name", "Test User"])
2919 .current_dir(&repo_path)
2920 .output()
2921 .unwrap();
2922
2923 Command::new("git")
2924 .args(["config", "user.email", "test@example.com"])
2925 .current_dir(&repo_path)
2926 .output()
2927 .unwrap();
2928
2929 std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
2931 Command::new("git")
2932 .args(["add", "."])
2933 .current_dir(&repo_path)
2934 .output()
2935 .unwrap();
2936
2937 Command::new("git")
2938 .args(["commit", "-m", "Initial commit"])
2939 .current_dir(&repo_path)
2940 .output()
2941 .unwrap();
2942
2943 crate::config::initialize_repo(&repo_path, Some("https://test.bitbucket.com".to_string()))
2945 .unwrap();
2946
2947 (temp_dir, repo_path)
2948 }
2949
2950 #[tokio::test]
2951 async fn test_create_stack() {
2952 let (_temp_dir, repo_path) = create_test_repo().await;
2953
2954 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
2956 match env::set_current_dir(&repo_path) {
2957 Ok(_) => {
2958 let result = create_stack(
2959 "test-stack".to_string(),
2960 None, Some("Test description".to_string()),
2962 )
2963 .await;
2964
2965 if let Ok(orig) = original_dir {
2967 let _ = env::set_current_dir(orig);
2968 }
2969
2970 assert!(result.is_ok());
2971 }
2972 Err(_) => {
2973 println!("Skipping test due to directory access restrictions");
2975 }
2976 }
2977 }
2978
2979 #[tokio::test]
2980 async fn test_list_empty_stacks() {
2981 let (_temp_dir, repo_path) = create_test_repo().await;
2982
2983 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
2985 match env::set_current_dir(&repo_path) {
2986 Ok(_) => {
2987 let result = list_stacks(false, false, None).await;
2988
2989 if let Ok(orig) = original_dir {
2991 let _ = env::set_current_dir(orig);
2992 }
2993
2994 assert!(result.is_ok());
2995 }
2996 Err(_) => {
2997 println!("Skipping test due to directory access restrictions");
2999 }
3000 }
3001 }
3002
3003 #[test]
3006 fn test_extract_feature_from_wip_basic() {
3007 let messages = vec![
3008 "WIP: add authentication".to_string(),
3009 "WIP: implement login flow".to_string(),
3010 ];
3011
3012 let result = extract_feature_from_wip(&messages);
3013 assert_eq!(result, "Add authentication");
3014 }
3015
3016 #[test]
3017 fn test_extract_feature_from_wip_capitalize() {
3018 let messages = vec!["WIP: fix user validation bug".to_string()];
3019
3020 let result = extract_feature_from_wip(&messages);
3021 assert_eq!(result, "Fix user validation bug");
3022 }
3023
3024 #[test]
3025 fn test_extract_feature_from_wip_fallback() {
3026 let messages = vec![
3027 "WIP user interface changes".to_string(),
3028 "wip: css styling".to_string(),
3029 ];
3030
3031 let result = extract_feature_from_wip(&messages);
3032 assert!(result.contains("Implement") || result.contains("Squashed") || result.len() > 5);
3034 }
3035
3036 #[test]
3037 fn test_extract_feature_from_wip_empty() {
3038 let messages = vec![];
3039
3040 let result = extract_feature_from_wip(&messages);
3041 assert_eq!(result, "Squashed 0 commits");
3042 }
3043
3044 #[test]
3045 fn test_extract_feature_from_wip_short_message() {
3046 let messages = vec!["WIP: x".to_string()]; let result = extract_feature_from_wip(&messages);
3049 assert!(result.starts_with("Implement") || result.contains("Squashed"));
3050 }
3051
3052 #[test]
3055 fn test_squash_message_final_strategy() {
3056 let messages = [
3060 "Final: implement user authentication system".to_string(),
3061 "WIP: add tests".to_string(),
3062 "WIP: fix validation".to_string(),
3063 ];
3064
3065 assert!(messages[0].starts_with("Final:"));
3067
3068 let extracted = messages[0].trim_start_matches("Final:").trim();
3070 assert_eq!(extracted, "implement user authentication system");
3071 }
3072
3073 #[test]
3074 fn test_squash_message_wip_detection() {
3075 let messages = [
3076 "WIP: start feature".to_string(),
3077 "WIP: continue work".to_string(),
3078 "WIP: almost done".to_string(),
3079 "Regular commit message".to_string(),
3080 ];
3081
3082 let wip_count = messages
3083 .iter()
3084 .filter(|m| {
3085 m.to_lowercase().starts_with("wip") || m.to_lowercase().contains("work in progress")
3086 })
3087 .count();
3088
3089 assert_eq!(wip_count, 3); assert!(wip_count > messages.len() / 2); let non_wip: Vec<&String> = messages
3094 .iter()
3095 .filter(|m| {
3096 !m.to_lowercase().starts_with("wip")
3097 && !m.to_lowercase().contains("work in progress")
3098 })
3099 .collect();
3100
3101 assert_eq!(non_wip.len(), 1);
3102 assert_eq!(non_wip[0], "Regular commit message");
3103 }
3104
3105 #[test]
3106 fn test_squash_message_all_wip() {
3107 let messages = vec![
3108 "WIP: add feature A".to_string(),
3109 "WIP: add feature B".to_string(),
3110 "WIP: finish implementation".to_string(),
3111 ];
3112
3113 let result = extract_feature_from_wip(&messages);
3114 assert_eq!(result, "Add feature A");
3116 }
3117
3118 #[test]
3119 fn test_squash_message_edge_cases() {
3120 let empty_messages: Vec<String> = vec![];
3122 let result = extract_feature_from_wip(&empty_messages);
3123 assert_eq!(result, "Squashed 0 commits");
3124
3125 let whitespace_messages = vec![" ".to_string(), "\t\n".to_string()];
3127 let result = extract_feature_from_wip(&whitespace_messages);
3128 assert!(result.contains("Squashed") || result.contains("Implement"));
3129
3130 let mixed_case = vec!["wip: Add Feature".to_string()];
3132 let result = extract_feature_from_wip(&mixed_case);
3133 assert_eq!(result, "Add Feature");
3134 }
3135
3136 #[tokio::test]
3139 async fn test_auto_land_wrapper() {
3140 let (_temp_dir, repo_path) = create_test_repo().await;
3142
3143 let original_dir = env::current_dir().map_err(|_| "Failed to get current dir");
3144 match env::set_current_dir(&repo_path) {
3145 Ok(_) => {
3146 let result = create_stack(
3148 "test-stack".to_string(),
3149 None,
3150 Some("Test stack for auto-land".to_string()),
3151 )
3152 .await;
3153
3154 if let Ok(orig) = original_dir {
3155 let _ = env::set_current_dir(orig);
3156 }
3157
3158 assert!(result.is_ok());
3161 }
3162 Err(_) => {
3163 println!("Skipping test due to directory access restrictions");
3164 }
3165 }
3166 }
3167
3168 #[test]
3169 fn test_auto_land_action_enum() {
3170 use crate::cli::commands::stack::StackAction;
3172
3173 let _action = StackAction::AutoLand {
3175 force: false,
3176 dry_run: true,
3177 wait_for_builds: true,
3178 strategy: Some(MergeStrategyArg::Squash),
3179 build_timeout: 1800,
3180 };
3181
3182 }
3184
3185 #[test]
3186 fn test_merge_strategy_conversion() {
3187 let squash_strategy = MergeStrategyArg::Squash;
3189 let merge_strategy: crate::bitbucket::pull_request::MergeStrategy = squash_strategy.into();
3190
3191 match merge_strategy {
3192 crate::bitbucket::pull_request::MergeStrategy::Squash => {
3193 }
3195 _ => panic!("Expected Squash strategy"),
3196 }
3197
3198 let merge_strategy = MergeStrategyArg::Merge;
3199 let converted: crate::bitbucket::pull_request::MergeStrategy = merge_strategy.into();
3200
3201 match converted {
3202 crate::bitbucket::pull_request::MergeStrategy::Merge => {
3203 }
3205 _ => panic!("Expected Merge strategy"),
3206 }
3207 }
3208
3209 #[test]
3210 fn test_auto_merge_conditions_structure() {
3211 use std::time::Duration;
3213
3214 let conditions = crate::bitbucket::pull_request::AutoMergeConditions {
3215 merge_strategy: crate::bitbucket::pull_request::MergeStrategy::Squash,
3216 wait_for_builds: true,
3217 build_timeout: Duration::from_secs(1800),
3218 allowed_authors: None,
3219 };
3220
3221 assert!(conditions.wait_for_builds);
3223 assert_eq!(conditions.build_timeout.as_secs(), 1800);
3224 assert!(conditions.allowed_authors.is_none());
3225 assert!(matches!(
3226 conditions.merge_strategy,
3227 crate::bitbucket::pull_request::MergeStrategy::Squash
3228 ));
3229 }
3230
3231 #[test]
3232 fn test_polling_constants() {
3233 use std::time::Duration;
3235
3236 let expected_polling_interval = Duration::from_secs(30);
3238
3239 assert!(expected_polling_interval.as_secs() >= 10); assert!(expected_polling_interval.as_secs() <= 60); assert_eq!(expected_polling_interval.as_secs(), 30); }
3244
3245 #[test]
3246 fn test_build_timeout_defaults() {
3247 const DEFAULT_TIMEOUT: u64 = 1800; assert_eq!(DEFAULT_TIMEOUT, 1800);
3250 let timeout_value = 1800u64;
3252 assert!(timeout_value >= 300); assert!(timeout_value <= 3600); }
3255
3256 #[test]
3257 fn test_scattered_commit_detection() {
3258 use std::collections::HashSet;
3259
3260 let mut source_branches = HashSet::new();
3262 source_branches.insert("feature-branch-1".to_string());
3263 source_branches.insert("feature-branch-2".to_string());
3264 source_branches.insert("feature-branch-3".to_string());
3265
3266 let single_branch = HashSet::from(["main".to_string()]);
3268 assert_eq!(single_branch.len(), 1);
3269
3270 assert!(source_branches.len() > 1);
3272 assert_eq!(source_branches.len(), 3);
3273
3274 assert!(source_branches.contains("feature-branch-1"));
3276 assert!(source_branches.contains("feature-branch-2"));
3277 assert!(source_branches.contains("feature-branch-3"));
3278 }
3279
3280 #[test]
3281 fn test_source_branch_tracking() {
3282 let branch_a = "feature-work";
3286 let branch_b = "feature-work";
3287 assert_eq!(branch_a, branch_b);
3288
3289 let branch_1 = "feature-ui";
3291 let branch_2 = "feature-api";
3292 assert_ne!(branch_1, branch_2);
3293
3294 assert!(branch_1.starts_with("feature-"));
3296 assert!(branch_2.starts_with("feature-"));
3297 }
3298
3299 #[tokio::test]
3302 async fn test_push_default_behavior() {
3303 let (_temp_dir, repo_path) = create_test_repo().await;
3305
3306 let original_dir = env::current_dir();
3308 if let (Ok(orig), Ok(_)) = (original_dir, env::set_current_dir(&repo_path)) {
3309 if crate::config::initialize_repo(
3311 &repo_path,
3312 Some("https://test.bitbucket.com".to_string()),
3313 )
3314 .is_ok()
3315 {
3316 let result = create_stack("test-stack".to_string(), None, None).await;
3318 assert!(result.is_ok());
3319
3320 if std::fs::write(repo_path.join("test2.txt"), "test content 2").is_ok() {
3322 let _ = std::process::Command::new("git")
3323 .args(["add", "test2.txt"])
3324 .current_dir(&repo_path)
3325 .output();
3326 let _ = std::process::Command::new("git")
3327 .args(["commit", "-m", "Second commit"])
3328 .current_dir(&repo_path)
3329 .output();
3330 }
3331
3332 let result = push_to_stack(
3334 None, None, None, None, None, None, None, false, false, )
3344 .await;
3345
3346 match result {
3348 Ok(_) => {
3349 }
3351 Err(e) => {
3352 let error_msg = e.to_string();
3354 assert!(
3355 error_msg.contains("Bitbucket")
3356 || error_msg.contains("config")
3357 || error_msg.contains("remote")
3358 || error_msg.contains("auth")
3359 || error_msg.contains("Stack is empty")
3360 || error_msg.contains("base branch")
3361 || error_msg.contains("uncommitted changes")
3362 || error_msg.contains("current directory")
3363 || error_msg.contains("No such file"),
3364 "Unexpected error type: {error_msg}"
3365 );
3366 }
3367 }
3368 }
3369
3370 let _ = env::set_current_dir(orig);
3372 } else {
3373 println!("Skipping test due to directory access restrictions in test environment");
3375 }
3376 }
3377
3378 #[tokio::test]
3379 async fn test_submit_default_behavior() {
3380 let (_temp_dir, repo_path) = create_test_repo().await;
3382
3383 let original_dir = env::current_dir();
3384 if let (Ok(orig), Ok(_)) = (original_dir, env::set_current_dir(&repo_path)) {
3385 if crate::config::initialize_repo(
3387 &repo_path,
3388 Some("https://test.bitbucket.com".to_string()),
3389 )
3390 .is_ok()
3391 {
3392 let result = create_stack("test-stack".to_string(), None, None).await;
3394 assert!(result.is_ok());
3395
3396 let result = submit_entry(
3398 None, None, None, None, false, )
3404 .await;
3405
3406 match result {
3408 Ok(_) => {
3409 }
3411 Err(e) => {
3412 let error_msg = e.to_string();
3414 assert!(
3415 error_msg.contains("Stack is empty")
3416 || error_msg.contains("Bitbucket")
3417 || error_msg.contains("config")
3418 || error_msg.contains("auth")
3419 || error_msg.contains("current directory")
3420 || error_msg.contains("No such file"),
3421 "Unexpected error: {error_msg}"
3422 );
3423 }
3424 }
3425 }
3426
3427 let _ = env::set_current_dir(orig);
3428 } else {
3429 println!("Skipping test due to directory access restrictions in test environment");
3431 }
3432 }
3433
3434 #[test]
3435 fn test_targeting_options_still_work() {
3436 let commits = "abc123,def456,ghi789";
3440 let parsed: Vec<&str> = commits.split(',').map(|s| s.trim()).collect();
3441 assert_eq!(parsed.len(), 3);
3442 assert_eq!(parsed[0], "abc123");
3443 assert_eq!(parsed[1], "def456");
3444 assert_eq!(parsed[2], "ghi789");
3445
3446 let range = "1-3";
3448 assert!(range.contains('-'));
3449 let parts: Vec<&str> = range.split('-').collect();
3450 assert_eq!(parts.len(), 2);
3451
3452 let since_ref = "HEAD~3";
3454 assert!(since_ref.starts_with("HEAD"));
3455 assert!(since_ref.contains('~'));
3456 }
3457
3458 #[test]
3459 fn test_command_flow_logic() {
3460 assert!(matches!(
3462 StackAction::Push {
3463 branch: None,
3464 message: None,
3465 commit: None,
3466 since: None,
3467 commits: None,
3468 squash: None,
3469 squash_since: None,
3470 auto_branch: false,
3471 allow_base_branch: false
3472 },
3473 StackAction::Push { .. }
3474 ));
3475
3476 assert!(matches!(
3477 StackAction::Submit {
3478 entry: None,
3479 title: None,
3480 description: None,
3481 range: None,
3482 draft: false
3483 },
3484 StackAction::Submit { .. }
3485 ));
3486 }
3487
3488 #[tokio::test]
3489 async fn test_deactivate_command_structure() {
3490 let deactivate_action = StackAction::Deactivate { force: false };
3492
3493 assert!(matches!(
3495 deactivate_action,
3496 StackAction::Deactivate { force: false }
3497 ));
3498
3499 let force_deactivate = StackAction::Deactivate { force: true };
3501 assert!(matches!(
3502 force_deactivate,
3503 StackAction::Deactivate { force: true }
3504 ));
3505 }
3506}