From 0ef73a5955af9caf372d3dd2cbcbaa6044c38e86 Mon Sep 17 00:00:00 2001 From: Jon Deibel Date: Mon, 9 Mar 2026 09:37:55 -0400 Subject: [PATCH] feat: add gw split command for branch decomposition into stacks Split a fat branch with many commits into a clean stack of focused branches. Supports interactive TUI with bucket assignment and non-interactive --plan file mode. Cherry-picks commits one-at-a-time with full conflict handling (--continue/--abort), crash-safe state persistence, and automatic descendant rebasing for mid-stack splits. Co-Authored-By: Claude Opus 4.6 --- CLAUDE.md | 14 +- README.md | 31 ++ plugins/gw/skills/gw/SKILL.md | 8 + src/cli.rs | 26 ++ src/commands/mod.rs | 2 + src/commands/split.rs | 841 ++++++++++++++++++++++++++++++++++ src/commands/split_tui.rs | 393 ++++++++++++++++ src/context.rs | 18 +- src/git.rs | 110 +++++ src/main.rs | 76 ++- src/state.rs | 101 ++++ src/validate.rs | 29 ++ tests/split_test.rs | 489 ++++++++++++++++++++ 13 files changed, 2113 insertions(+), 25 deletions(-) create mode 100644 src/commands/split.rs create mode 100644 src/commands/split_tui.rs create mode 100644 tests/split_test.rs diff --git a/CLAUDE.md b/CLAUDE.md index f113786..f1e68c3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -46,6 +46,14 @@ gw switch # interactive picker gw switch # direct checkout ``` +### Splitting a fat branch into a stack +```bash +gw split # interactive TUI to assign commits to buckets +gw split --plan plan.txt # non-interactive, reads from plan file +gw split --continue # resume after resolving cherry-pick conflicts +gw split --abort # roll back, delete created branches +``` + ### Adopting existing branches ```bash gw adopt branch-a branch-b branch-c --base main @@ -53,7 +61,7 @@ gw adopt branch-a branch-b branch-c --base main ## Conflict Resolution -If `gw rebase` or `gw sync` hits a conflict: +If `gw rebase`, `gw sync`, or `gw split` hits a conflict: ```bash # resolve conflicts in your editor git add @@ -62,7 +70,7 @@ gw rebase --continue # resumes the cascade gw rebase --abort # rolls back ALL branches to pre-rebase state ``` -Most commands are blocked during a propagation. Only `gw tree` and `gw switch` work. +Most commands are blocked during a propagation or split. Only `gw tree`, `gw switch`, `gw status`, and `gw diff` work. ## Important Notes @@ -82,7 +90,7 @@ cargo install --path . # install to ~/.cargo/bin/gw ## Architecture - `src/cli.rs` - clap derive CLI definitions -- `src/commands/` - one file per command (stack, branch, adopt, rebase, sync, push, switch, tree, config, completions) +- `src/commands/` - one file per command (stack, branch, adopt, rebase, sync, push, switch, split, tree, config, completions) - `src/git.rs` - git CLI wrapper (all git operations go through here) - `src/propagation.rs` - shared rebase cascade engine - `src/state.rs` - TOML serialization for stack configs and propagation state diff --git a/README.md b/README.md index fc7de3e..56a05a7 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ Everything lives in `.git/gw/` and never gets pushed to the remote. - [Why this exists](#why-this-exists) - [Install](#install) - [Quick start](#quick-start) +- [Already have a fat branch? Split it](#already-have-a-fat-branch-split-it) - [Already have branches? Adopt them](#already-have-branches-adopt-them) - [Configuration](#configuration) - [Commands](#commands) @@ -129,6 +130,32 @@ gw sync --rebase gw switch ``` +## Already have a fat branch? Split it + +If you've got a single branch with a bunch of commits that should really be separate PRs, `gw split` decomposes it into a clean stack: + +```bash +gw split +``` + +An interactive TUI lets you assign each commit to a named bucket. When you confirm, gw cherry-picks the commits into new branches forming a linear stack. The original branch is kept as a backup. + +You can also use a plan file for scripting: + +```bash +gw split --plan split-plan.txt --base main +``` + +Plan file format: +``` +pick auth +pick auth +pick dashboard +pick dashboard +``` + +If a cherry-pick hits a conflict, resolve it and run `gw split --continue`. To undo everything: `gw split --abort`. + ## Already have branches? Adopt them If you've already got a chain of branches you've been managing by hand, you don't need to recreate anything. Just tell gw about them: @@ -169,6 +196,10 @@ gw config set-delete-on-merge true | `gw branch create ` | Add a branch to the current stack | | `gw branch remove ` | Remove a branch and re-parent children | | `gw adopt ` | Adopt existing branches into a stack | +| `gw split` | Interactively split a branch into a stack | +| `gw split --plan ` | Split using a plan file | +| `gw split --continue` | Resume after resolving cherry-pick conflicts | +| `gw split --abort` | Roll back split and delete created branches | | `gw rebase` | Propagate rebases to descendants | | `gw rebase --continue` | Resume after resolving conflicts | | `gw rebase --abort` | Roll back all branches | diff --git a/plugins/gw/skills/gw/SKILL.md b/plugins/gw/skills/gw/SKILL.md index 0dd98b1..b97ca8b 100644 --- a/plugins/gw/skills/gw/SKILL.md +++ b/plugins/gw/skills/gw/SKILL.md @@ -51,12 +51,20 @@ You are working in a repo that uses **gw**, a stacked branch manager. Use gw too When the user has a large change or asks to split work into reviewable pieces: +**If the work hasn't been done yet:** 1. Create a stack with `gw_stack_create` 2. Make commits for the first logical unit (e.g., data model changes) 3. Create the next branch with `gw_branch_create` for the next unit (e.g., API layer) 4. Repeat until done 5. Each branch becomes its own PR, stacked on the previous one +**If the work is already on a single branch:** +1. Use `gw split` to decompose the existing branch into a clean stack +2. The interactive TUI lets you assign each commit to a named bucket/branch +3. Or use `gw split --plan ` with a plan file for scripting +4. Cherry-pick conflicts can be resolved with `gw split --continue` +5. Use `gw split --abort` to roll back if needed + Good stack boundaries: model/schema changes, API/service layer, UI/frontend, tests, migrations. Each branch should be independently reviewable and tell a coherent story. ### Pushing work diff --git a/src/cli.rs b/src/cli.rs index 1e28a31..b9935dd 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -31,6 +31,8 @@ pub enum Commands { /// Show log of all stacks with branches and commits #[command(alias = "tree")] Log(TreeArgs), + /// Split a branch into a stack of focused branches + Split(SplitArgs), /// Configure gw settings Config(ConfigArgs), /// Generate shell completions @@ -177,6 +179,30 @@ pub struct DiffArgs { pub no_difftastic: bool, } +// -- Split -- + +#[derive(Args)] +pub struct SplitArgs { + /// Plan file mapping commits to branches (non-interactive mode) + #[arg(long)] + pub plan: Option, + /// Base branch to split from (defaults to merge-base detection) + #[arg(long)] + pub base: Option, + /// Stack name for the new stack (defaults to original branch name) + #[arg(long)] + pub name: Option, + /// Skip confirmation prompt + #[arg(long)] + pub yes: bool, + /// Continue after resolving cherry-pick conflicts + #[arg(long = "continue", id = "split_continue", conflicts_with = "split_abort")] + pub cont: bool, + /// Abort the split and clean up created branches + #[arg(long = "abort", id = "split_abort", conflicts_with = "split_continue")] + pub abort: bool, +} + // -- Config -- #[derive(Args)] diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 6a72b13..a818ec4 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -7,6 +7,8 @@ pub mod mcp_server; pub mod mcp_setup; pub mod push; pub mod rebase; +pub mod split; +pub mod split_tui; pub mod stack; pub mod status; pub mod switch; diff --git a/src/commands/split.rs b/src/commands/split.rs new file mode 100644 index 0000000..37a259f --- /dev/null +++ b/src/commands/split.rs @@ -0,0 +1,841 @@ +use anyhow::{bail, Context, Result}; +use std::collections::HashSet; +use std::fs; +use std::path::Path; + +use crate::cli::SplitArgs; +use crate::context::Ctx; +use crate::git::CherryPickResult; +use crate::propagation::{self, PropagationResult}; +use crate::state::{ + ActiveState, BranchEntry, Operation, SplitBucket, SplitState, StackConfig, +}; +use crate::ui; +use crate::validate; + +/// A bucket of commits destined for a single branch. +#[derive(Debug)] +pub struct Bucket { + pub branch_name: String, + pub commits: Vec, // full SHAs, in application order +} + +/// The interface between input (TUI or --plan file) and the execution engine. +#[derive(Debug)] +pub struct SplitPlan { + pub buckets: Vec, +} + +impl SplitPlan { + /// Validate a split plan for correctness. + pub fn validate(&self) -> Result<()> { + if self.buckets.len() < 2 { + bail!( + "Split requires at least 2 buckets (branches), got {}", + self.buckets.len() + ); + } + + // Check for empty buckets + for bucket in &self.buckets { + if bucket.commits.is_empty() { + bail!("Bucket '{}' has no commits assigned", bucket.branch_name); + } + } + + // Check for duplicate branch names + let mut seen_names = HashSet::new(); + for bucket in &self.buckets { + if !seen_names.insert(&bucket.branch_name) { + bail!("Duplicate bucket name '{}'", bucket.branch_name); + } + } + + // Check for duplicate commits across buckets + let mut seen_shas = HashSet::new(); + for bucket in &self.buckets { + for sha in &bucket.commits { + if !seen_shas.insert(sha.as_str()) { + bail!("Commit {sha} appears in multiple buckets"); + } + } + } + + // Validate branch names + for bucket in &self.buckets { + validate::validate_branch_name(&bucket.branch_name)?; + } + + // Validate SHAs + for bucket in &self.buckets { + for sha in &bucket.commits { + validate::validate_sha(sha)?; + } + } + + Ok(()) + } +} + +/// Parse a plan file into a SplitPlan. +/// +/// Format: +/// ```text +/// # comments start with # +/// pick +/// pick +/// ``` +/// +/// Commits are grouped by branch name. The first branch encountered +/// becomes the root of the stack. +pub fn parse_plan_file(path: &Path) -> Result { + let content = fs::read_to_string(path) + .with_context(|| format!("failed to read plan file '{}'", path.display()))?; + parse_plan(&content) +} + +/// Parse plan file content into a SplitPlan. +pub fn parse_plan(content: &str) -> Result { + let mut buckets: Vec = Vec::new(); + let mut bucket_index: std::collections::HashMap = + std::collections::HashMap::new(); + + for (line_num, line) in content.lines().enumerate() { + let line = line.trim(); + + // Skip empty lines and comments + if line.is_empty() || line.starts_with('#') { + continue; + } + + let parts: Vec<&str> = line.splitn(3, ' ').collect(); + if parts.len() != 3 { + bail!( + "line {}: expected 'pick ', got '{line}'", + line_num + 1 + ); + } + + let verb = parts[0]; + let sha = parts[1]; + let branch = parts[2]; + + if verb != "pick" { + bail!( + "line {}: unknown verb '{verb}' (only 'pick' is supported)", + line_num + 1 + ); + } + + // Validate SHA is full-length hex + validate::validate_sha(sha)?; + if sha.len() < 40 { + bail!( + "line {}: SHA '{sha}' looks truncated — use full 40-character SHAs", + line_num + 1 + ); + } + + // Validate branch name + validate::validate_branch_name(branch)?; + + let sha = sha.to_string(); + let branch = branch.to_string(); + + if let Some(&idx) = bucket_index.get(&branch) { + buckets[idx].commits.push(sha); + } else { + let idx = buckets.len(); + bucket_index.insert(branch.clone(), idx); + buckets.push(Bucket { + branch_name: branch, + commits: vec![sha], + }); + } + } + + if buckets.is_empty() { + bail!("Plan file contains no 'pick' lines"); + } + + let plan = SplitPlan { buckets }; + plan.validate()?; + Ok(plan) +} + +pub fn run(args: SplitArgs, ctx: &Ctx) -> Result<()> { + if args.cont { + return do_continue(ctx); + } + if args.abort { + return do_abort(ctx); + } + + // Preconditions + ctx.require_clean_tree()?; + + let current_branch = ctx.git.current_branch()?; + if current_branch == "HEAD" { + bail!("Cannot split from detached HEAD."); + } + + // Determine base branch and stack context + let (base_branch, existing_stack) = determine_base(ctx, ¤t_branch, &args)?; + + // Get commits on the branch + let commits = ctx.git.log_commits(&base_branch, ¤t_branch)?; + + if commits.len() < 2 { + bail!( + "Branch '{}' has {} commit(s). Split requires at least 2.", + current_branch, + commits.len() + ); + } + + // Check for merge commits + if let Some(merge) = commits.iter().find(|c| c.parent_count > 1) { + bail!( + "Branch contains merge commit {}. Linearize the branch first (e.g., interactive rebase).", + &merge.full_sha[..12] + ); + } + + // Get or parse the plan + let plan = match args.plan { + Some(ref p) => parse_plan_file(Path::new(p))?, + None => { + let existing_branches = ctx.git.all_local_branches()?; + match super::split_tui::run_split_tui(&commits, &existing_branches)? { + Some(p) => p, + None => { + ui::info("Split cancelled."); + return Ok(()); + } + } + } + }; + + // Validate that plan commits match branch commits + let branch_shas: HashSet<&str> = commits.iter().map(|c| c.full_sha.as_str()).collect(); + let plan_shas: HashSet<&str> = plan + .buckets + .iter() + .flat_map(|b| b.commits.iter().map(|s| s.as_str())) + .collect(); + + if branch_shas != plan_shas { + let missing_from_plan: Vec<&&str> = branch_shas.difference(&plan_shas).collect(); + let extra_in_plan: Vec<&&str> = plan_shas.difference(&branch_shas).collect(); + let mut msg = String::from("Plan commits don't match branch commits.\n"); + if !missing_from_plan.is_empty() { + msg.push_str(&format!( + " Missing from plan: {}\n", + missing_from_plan + .iter() + .map(|s| &s[..12]) + .collect::>() + .join(", ") + )); + } + if !extra_in_plan.is_empty() { + msg.push_str(&format!( + " Not on branch: {}\n", + extra_in_plan + .iter() + .map(|s| &s[..12]) + .collect::>() + .join(", ") + )); + } + bail!("{msg}"); + } + + // Check for branch name collisions + let existing_branches = ctx.git.all_local_branches()?; + for bucket in &plan.buckets { + if existing_branches.contains(&bucket.branch_name) { + bail!( + "Branch '{}' already exists. Choose a different name.", + bucket.branch_name + ); + } + } + + // Determine stack name + let stack_name = match args.name { + Some(ref n) => { + validate::validate_stack_name(n)?; + n.clone() + } + None => { + let derived = current_branch.replace('/', "-"); + validate::validate_stack_name(&derived)?; + derived + } + }; + + // If creating a new stack, verify the name doesn't conflict + if existing_stack.is_none() && ctx.stack_exists(&stack_name) { + bail!("Stack '{stack_name}' already exists. Use --name to specify a different name."); + } + + let original_sha = ctx.git.rev_parse("HEAD")?; + + // Build SplitState for crash recovery + let split_state = SplitState { + operation: Operation::Split, + original_branch: current_branch.clone(), + original_sha: original_sha.clone(), + base_branch: base_branch.clone(), + stack_name: stack_name.clone(), + created_branches: vec![], + current_bucket_index: 0, + current_commit_index: 0, + buckets: plan + .buckets + .iter() + .map(|b| SplitBucket { + name: b.branch_name.clone(), + commits: b.commits.clone(), + }) + .collect(), + }; + + ctx.save_split_state(&split_state)?; + + // Execute the cherry-pick phase + let result = execute_cherry_picks(ctx, &split_state)?; + match result { + CherryPickPhaseResult::Complete { created_branches } => { + finalize_split(ctx, ¤t_branch, &base_branch, &stack_name, &created_branches, existing_stack.as_ref())?; + } + CherryPickPhaseResult::Conflict { branch } => { + ui::warn(&format!("Conflict while cherry-picking onto '{branch}'.")); + ui::info("Resolve the conflicts, then run:"); + ui::info(" git add "); + ui::info(" gw split --continue"); + ui::info(""); + ui::info("Or abort the entire split:"); + ui::info(" gw split --abort"); + } + } + + Ok(()) +} + +enum CherryPickPhaseResult { + Complete { created_branches: Vec }, + Conflict { branch: String }, +} + +/// Execute cherry-picks starting from the given state's position. +fn execute_cherry_picks(ctx: &Ctx, initial_state: &SplitState) -> Result { + let mut created_branches = initial_state.created_branches.clone(); + let base = &initial_state.base_branch; + + for bucket_idx in initial_state.current_bucket_index..initial_state.buckets.len() { + let bucket = &initial_state.buckets[bucket_idx]; + let start_commit_idx = if bucket_idx == initial_state.current_bucket_index { + initial_state.current_commit_index + } else { + 0 + }; + + // Create the branch if we haven't started this bucket yet + if start_commit_idx == 0 { + let start_point = if bucket_idx == 0 { + base.to_string() + } else { + // Base on previous bucket's branch (its current tip) + initial_state.buckets[bucket_idx - 1].name.clone() + }; + ctx.git.create_branch(&bucket.name, &start_point)?; + created_branches.push(bucket.name.clone()); + + // Update state with new branch + let mut state = load_split_state(ctx)?; + state.created_branches = created_branches.clone(); + state.current_bucket_index = bucket_idx; + state.current_commit_index = 0; + ctx.save_split_state(&state)?; + } + + ctx.git.checkout(&bucket.name)?; + + // Cherry-pick each commit + for commit_idx in start_commit_idx..bucket.commits.len() { + let sha = &bucket.commits[commit_idx]; + + // Update state BEFORE cherry-pick (crash recovery) + let mut state = load_split_state(ctx)?; + state.created_branches = created_branches.clone(); + state.current_bucket_index = bucket_idx; + state.current_commit_index = commit_idx; + ctx.save_split_state(&state)?; + + match ctx.git.cherry_pick(sha)? { + CherryPickResult::Success => {} + CherryPickResult::Conflict => { + return Ok(CherryPickPhaseResult::Conflict { + branch: bucket.name.clone(), + }); + } + } + } + } + + Ok(CherryPickPhaseResult::Complete { created_branches }) +} + +/// Load the current SplitState, bailing if not found. +fn load_split_state(ctx: &Ctx) -> Result { + match ctx.active_state()? { + Some(ActiveState::Split(s)) => Ok(s), + _ => bail!("No split in progress."), + } +} + +fn do_continue(ctx: &Ctx) -> Result<()> { + // Check what kind of state we're in + match ctx.active_state()? { + Some(ActiveState::Split(state)) => { + // We're in the cherry-pick phase + if ctx.git.has_unresolved_conflicts()? { + bail!( + "There are still unresolved conflicts.\n\ + Resolve them and run `git add`, then `gw split --continue`." + ); + } + + // If a cherry-pick is in progress, continue it + if ctx.git.is_cherry_pick_in_progress() { + match ctx.git.cherry_pick_continue()? { + CherryPickResult::Success => {} + CherryPickResult::Conflict => { + let bucket = &state.buckets[state.current_bucket_index]; + ui::warn(&format!( + "Still conflicting on '{}'.", + bucket.name + )); + return Ok(()); + } + } + } + + // Advance past the commit we just resolved + let mut state = state; + state.current_commit_index += 1; + + // Check if we've finished the current bucket + let bucket_len = state.buckets[state.current_bucket_index].commits.len(); + if state.current_commit_index >= bucket_len { + state.current_bucket_index += 1; + state.current_commit_index = 0; + } + + // Check if all buckets are done + if state.current_bucket_index >= state.buckets.len() { + ctx.save_split_state(&state)?; + let existing_stack = ctx.find_stack_for_branch(&state.original_branch)?; + finalize_split( + ctx, + &state.original_branch.clone(), + &state.base_branch.clone(), + &state.stack_name.clone(), + &state.created_branches.clone(), + existing_stack.as_ref(), + )?; + return Ok(()); + } + + // Save updated state and continue + ctx.save_split_state(&state)?; + let result = execute_cherry_picks(ctx, &state)?; + match result { + CherryPickPhaseResult::Complete { created_branches } => { + let existing_stack = ctx.find_stack_for_branch(&state.original_branch)?; + finalize_split( + ctx, + &state.original_branch, + &state.base_branch, + &state.stack_name, + &created_branches, + existing_stack.as_ref(), + )?; + } + CherryPickPhaseResult::Conflict { branch } => { + ui::warn(&format!("Conflict while cherry-picking onto '{branch}'.")); + ui::info("Resolve the conflicts, then run:"); + ui::info(" git add "); + ui::info(" gw split --continue"); + } + } + Ok(()) + } + Some(ActiveState::Propagation(prop_state)) => { + // We're in the descendant rebase phase (propagation after cherry-picks completed) + if prop_state.operation != Operation::Split { + bail!( + "No split in progress. There is an active {} propagation.\n\ + Use `gw rebase --continue` instead.", + match prop_state.operation { + Operation::Rebase => "rebase", + Operation::Sync => "sync", + Operation::Adopt => "adopt", + Operation::BranchRemove => "branch remove", + Operation::Split => unreachable!(), + } + ); + } + // Delegate to propagation engine + match propagation::continue_propagation(ctx)? { + PropagationResult::Success { rebased_count } => { + ui::success(&format!( + "Split complete. {rebased_count} descendant branch{} rebased.", + if rebased_count == 1 { "" } else { "es" } + )); + } + PropagationResult::Conflict { branch } => { + ui::warn(&format!( + "Conflict rebasing descendant '{branch}'." + )); + ui::info("Resolve conflicts, then run `gw split --continue`."); + } + } + Ok(()) + } + None => bail!("No split in progress."), + } +} + +fn do_abort(ctx: &Ctx) -> Result<()> { + match ctx.active_state()? { + Some(ActiveState::Split(state)) => { + // Abort any in-progress cherry-pick + ctx.git.cherry_pick_abort()?; + + // Delete all created branches (idempotent — tolerate "not found") + for branch in &state.created_branches { + if ctx.git.branch_exists(branch).unwrap_or(false) { + // Can't delete a checked-out branch, so checkout original first + let _ = ctx.git.checkout(&state.original_branch); + let _ = ctx.git.delete_branch(branch); + } + } + + // Return to original branch + let _ = ctx.git.checkout(&state.original_branch); + + // Clean up state + ctx.remove_state()?; + + ui::success("Split aborted. All created branches removed."); + Ok(()) + } + Some(ActiveState::Propagation(prop_state)) => { + if prop_state.operation != Operation::Split { + bail!( + "No split in progress. Use `gw rebase --abort` for the active propagation." + ); + } + // Abort propagation (restores descendant refs) + propagation::abort(ctx)?; + + // The propagation abort cleaned up state, but we may also need + // to clean up the split-created branches and stack config. + // For simplicity in v1, the propagation abort handles ref restoration, + // and we inform the user. + ui::success("Split propagation aborted. Descendant branches restored."); + Ok(()) + } + None => bail!("No split in progress."), + } +} + +/// Finalize a successful split: update stack config, rebase descendants, checkout root. +fn finalize_split( + ctx: &Ctx, + original_branch: &str, + base_branch: &str, + stack_name: &str, + created_branches: &[String], + existing_stack: Option<&StackConfig>, +) -> Result<()> { + let new_branch_entries: Vec = created_branches + .iter() + .map(|name| BranchEntry { name: name.clone() }) + .collect(); + + let new_leaf = created_branches + .last() + .context("no branches created")? + .clone(); + + if let Some(stack) = existing_stack { + // Branch was in an existing stack — replace it with the new branches + let orig_idx = stack + .branch_index(original_branch) + .context("original branch not found in stack")?; + + let mut new_branches = stack.branches.clone(); + // Remove the original branch entry + new_branches.remove(orig_idx); + // Insert new branches at the same position + for (i, entry) in new_branch_entries.iter().enumerate() { + new_branches.insert(orig_idx + i, entry.clone()); + } + + let updated_stack = StackConfig { + name: stack.name.clone(), + base_branch: stack.base_branch.clone(), + branches: new_branches, + }; + ctx.save_stack(&updated_stack)?; + + // If there are descendant branches, rebase them onto the new leaf + let descendants: Vec = stack + .descendants_of(original_branch) + .iter() + .map(|b| b.name.clone()) + .collect(); + + if !descendants.is_empty() { + ui::info(&format!( + "Rebasing {} descendant branch{} onto '{new_leaf}'...", + descendants.len(), + if descendants.len() == 1 { "" } else { "es" } + )); + + // Build onto targets: first descendant rebases onto new_leaf, + // rest rebase onto their parent in the updated stack + let mut onto_targets = vec![new_leaf.clone()]; + for desc in descendants.iter().skip(1) { + let parent = updated_stack + .parent_of(desc) + .context("descendant has no parent")?; + onto_targets.push(parent); + } + + // Provide upstream overrides so descendants rebase correctly + // (their old parent was the original branch, not the new leaf) + let upstream_overrides: Vec> = vec![Some(original_branch.to_string())] + .into_iter() + .chain(std::iter::repeat(None).take(descendants.len() - 1)) + .collect(); + + match propagation::start_with_upstreams( + ctx, + Operation::Split, + &stack.name, + &descendants, + &onto_targets, + &upstream_overrides, + )? { + PropagationResult::Success { rebased_count } => { + ui::info(&format!( + "{rebased_count} descendant branch{} rebased.", + if rebased_count == 1 { "" } else { "es" } + )); + } + PropagationResult::Conflict { branch } => { + ui::warn(&format!( + "Conflict rebasing descendant '{branch}'." + )); + ui::info("Resolve conflicts, then run `gw split --continue`."); + return Ok(()); + } + } + } else { + // No descendants — just clean up state + ctx.remove_state()?; + } + } else { + // Untracked branch — create a new stack + let config = StackConfig { + name: stack_name.to_string(), + base_branch: base_branch.to_string(), + branches: new_branch_entries, + }; + ctx.save_stack(&config)?; + ctx.remove_state()?; + } + + // Checkout the root of the new stack + let root = &created_branches[0]; + ctx.git.checkout(root)?; + + ui::success(&format!( + "Split complete! Created {} branches in stack '{stack_name}':", + created_branches.len() + )); + for (i, name) in created_branches.iter().enumerate() { + let marker = if i == 0 { " (root)" } else { "" }; + ui::info(&format!(" {name}{marker}")); + } + + Ok(()) +} + +/// Determine the base branch for the split. +/// Returns (base_branch, Option) — if the branch is tracked, we get its stack. +fn determine_base( + ctx: &Ctx, + current_branch: &str, + args: &SplitArgs, +) -> Result<(String, Option)> { + // Check if the branch is in an existing stack + if let Some(stack) = ctx.find_stack_for_branch(current_branch)? { + let parent = stack + .parent_of(current_branch) + .context("branch has no parent in stack")?; + // --base overrides the stack's parent + let base = args.base.clone().unwrap_or(parent); + return Ok((base, Some(stack))); + } + + // Untracked branch — use --base or infer + let base = match &args.base { + Some(b) => { + validate::validate_branch_name(b)?; + if !ctx.git.branch_exists(b)? { + bail!("Base branch '{b}' does not exist."); + } + b.clone() + } + None => ctx.default_base_branch()?, + }; + + Ok((base, None)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_valid_plan() { + let content = "\ +# gw split plan +pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa auth +pick bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb auth + +pick cccccccccccccccccccccccccccccccccccccccc dashboard +pick dddddddddddddddddddddddddddddddddddddddd dashboard +"; + let plan = parse_plan(content).unwrap(); + assert_eq!(plan.buckets.len(), 2); + assert_eq!(plan.buckets[0].branch_name, "auth"); + assert_eq!(plan.buckets[0].commits.len(), 2); + assert_eq!(plan.buckets[1].branch_name, "dashboard"); + assert_eq!(plan.buckets[1].commits.len(), 2); + } + + #[test] + fn parse_rejects_short_sha() { + let content = "pick abc123 my-branch\n"; + let err = parse_plan(content).unwrap_err(); + assert!(err.to_string().contains("truncated"), "{err}"); + } + + #[test] + fn parse_rejects_single_bucket() { + let content = "\ +pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa only-one +pick bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb only-one +"; + let err = parse_plan(content).unwrap_err(); + assert!(err.to_string().contains("at least 2 buckets"), "{err}"); + } + + #[test] + fn parse_rejects_empty_plan() { + let content = "# just a comment\n\n"; + let err = parse_plan(content).unwrap_err(); + assert!(err.to_string().contains("no 'pick' lines"), "{err}"); + } + + #[test] + fn parse_rejects_unknown_verb() { + let content = "drop aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa my-branch\n"; + let err = parse_plan(content).unwrap_err(); + assert!(err.to_string().contains("unknown verb"), "{err}"); + } + + #[test] + fn parse_rejects_malformed_line() { + let content = "pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"; + let err = parse_plan(content).unwrap_err(); + assert!(err.to_string().contains("expected 'pick"), "{err}"); + } + + #[test] + fn parse_rejects_invalid_branch_name() { + let content = "pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --bad-branch\n"; + let err = parse_plan(content).unwrap_err(); + assert!(err.to_string().contains("start with '-'"), "{err}"); + } + + #[test] + fn parse_rejects_duplicate_commits() { + let content = "\ +pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa branch-a +pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa branch-b +"; + let err = parse_plan(content).unwrap_err(); + assert!(err.to_string().contains("multiple buckets"), "{err}"); + } + + #[test] + fn parse_rejects_duplicate_branch_names() { + // This can't actually happen with our parser since same-name picks + // get merged into one bucket. But validate() catches if constructed manually. + let plan = SplitPlan { + buckets: vec![ + Bucket { + branch_name: "dupe".to_string(), + commits: vec!["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()], + }, + Bucket { + branch_name: "dupe".to_string(), + commits: vec!["bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_string()], + }, + ], + }; + let err = plan.validate().unwrap_err(); + assert!(err.to_string().contains("Duplicate bucket name"), "{err}"); + } + + #[test] + fn validate_rejects_empty_bucket() { + let plan = SplitPlan { + buckets: vec![ + Bucket { + branch_name: "a".to_string(), + commits: vec!["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string()], + }, + Bucket { + branch_name: "b".to_string(), + commits: vec![], + }, + ], + }; + let err = plan.validate().unwrap_err(); + assert!(err.to_string().contains("no commits assigned"), "{err}"); + } + + #[test] + fn plan_preserves_bucket_order() { + let content = "\ +pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa third +pick bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb first +pick cccccccccccccccccccccccccccccccccccccccc third +pick dddddddddddddddddddddddddddddddddddddddd second +"; + let plan = parse_plan(content).unwrap(); + assert_eq!(plan.buckets.len(), 3); + assert_eq!(plan.buckets[0].branch_name, "third"); + assert_eq!(plan.buckets[1].branch_name, "first"); + assert_eq!(plan.buckets[2].branch_name, "second"); + } +} diff --git a/src/commands/split_tui.rs b/src/commands/split_tui.rs new file mode 100644 index 0000000..0ef9ff2 --- /dev/null +++ b/src/commands/split_tui.rs @@ -0,0 +1,393 @@ +use anyhow::{bail, Result}; +use colored::Colorize; +use console::{Key, Term}; +use std::collections::HashSet; + +use crate::commands::split::{Bucket, SplitPlan}; +use crate::git::CommitInfo; +use crate::validate; + +/// Assignment state for a single commit. +#[derive(Clone)] +struct CommitEntry { + sha: String, + subject: String, + /// Index into `buckets` vec, or None if unassigned. + bucket_idx: Option, +} + +/// A named bucket that commits can be assigned to. +struct BucketEntry { + name: String, +} + +/// Input mode for the TUI. +enum Mode { + /// Navigate commits, assign to buckets. + Normal, + /// Typing a name for a new bucket. + TextInput, +} + +/// RAII guard to restore cursor visibility on drop. +struct CursorGuard<'a>(&'a Term); + +impl Drop for CursorGuard<'_> { + fn drop(&mut self) { + let _ = self.0.show_cursor(); + } +} + +/// Run the interactive split TUI. +/// +/// Takes the commits on the branch and returns a `SplitPlan` with the user's +/// bucket assignments. Returns `None` if the user cancels. +pub fn run_split_tui( + commits: &[CommitInfo], + existing_branches: &HashSet, +) -> Result> { + let term = Term::stderr(); + + if !std::io::IsTerminal::is_terminal(&std::io::stderr()) { + bail!("Interactive mode requires a terminal. Use --plan instead."); + } + + let _guard = CursorGuard(&term); + let _ = term.hide_cursor(); + + let mut entries: Vec = commits + .iter() + .map(|c| CommitEntry { + sha: c.full_sha.clone(), + subject: c.subject.clone(), + bucket_idx: None, + }) + .collect(); + + let mut buckets: Vec = Vec::new(); + let mut cursor: usize = 0; + let mut mode = Mode::Normal; + let mut input_buf = String::new(); + let mut input_error: Option = None; + let mut last_height: usize = 0; + + // Clone existing branches for collision checking + let mut known_branches = existing_branches.clone(); + + render(&term, &entries, &buckets, cursor, &mode, &input_buf, &input_error, &mut last_height)?; + + loop { + let key = term.read_key()?; + + match mode { + Mode::Normal => match key { + Key::ArrowUp | Key::Char('k') => { + if cursor > 0 { + cursor -= 1; + } + } + Key::ArrowDown | Key::Char('j') => { + if cursor < entries.len() - 1 { + cursor += 1; + } + } + Key::Char(c @ '1'..='9') => { + let idx = (c as usize) - ('1' as usize); + if idx < buckets.len() { + entries[cursor].bucket_idx = Some(idx); + } + } + Key::Char('n') => { + mode = Mode::TextInput; + input_buf.clear(); + input_error = None; + } + Key::Char('u') => { + entries[cursor].bucket_idx = None; + } + Key::Enter => { + // Validate: all assigned, 2+ buckets + let unassigned = entries.iter().filter(|e| e.bucket_idx.is_none()).count(); + if unassigned > 0 { + input_error = Some(format!("{unassigned} commit(s) still unassigned.")); + } else if buckets.len() < 2 { + input_error = Some("Need at least 2 buckets.".to_string()); + } else { + // Success — build plan + clear(&term, last_height)?; + return Ok(Some(build_plan(&entries, &buckets))); + } + } + Key::Escape | Key::Char('q') => { + clear(&term, last_height)?; + return Ok(None); + } + _ => {} + }, + Mode::TextInput => match key { + Key::Enter => { + let name = input_buf.trim().to_string(); + if name.is_empty() { + input_error = Some("Name cannot be empty.".to_string()); + } else if let Err(e) = validate::validate_branch_name(&name) { + input_error = Some(format!("Invalid: {e}")); + } else if known_branches.contains(&name) { + input_error = Some(format!("Branch '{name}' already exists.")); + } else if buckets.iter().any(|b| b.name == name) { + input_error = Some(format!("Bucket '{name}' already exists.")); + } else { + // Create the bucket and assign current commit + let idx = buckets.len(); + known_branches.insert(name.clone()); + buckets.push(BucketEntry { name }); + entries[cursor].bucket_idx = Some(idx); + mode = Mode::Normal; + input_buf.clear(); + input_error = None; + } + } + Key::Escape => { + mode = Mode::Normal; + input_buf.clear(); + input_error = None; + } + Key::Backspace => { + input_buf.pop(); + input_error = None; + } + Key::Char(c) => { + input_buf.push(c); + input_error = None; + } + _ => {} + }, + } + + render(&term, &entries, &buckets, cursor, &mode, &input_buf, &input_error, &mut last_height)?; + } +} + +/// Build a SplitPlan from the TUI state. +fn build_plan(entries: &[CommitEntry], buckets: &[BucketEntry]) -> SplitPlan { + let mut plan_buckets: Vec = buckets + .iter() + .map(|b| Bucket { + branch_name: b.name.clone(), + commits: Vec::new(), + }) + .collect(); + + // Assign commits to buckets in original order + for entry in entries { + if let Some(idx) = entry.bucket_idx { + plan_buckets[idx].commits.push(entry.sha.clone()); + } + } + + // Remove empty buckets (buckets that had all commits unassigned then reassigned) + plan_buckets.retain(|b| !b.commits.is_empty()); + + SplitPlan { + buckets: plan_buckets, + } +} + +/// Clear previously rendered lines. +fn clear(term: &Term, height: usize) -> Result<()> { + if height > 0 { + term.clear_last_lines(height)?; + } + Ok(()) +} + +/// Bucket display colors — cycle through these for visual distinction. +const BUCKET_COLORS: &[&str] = &["green", "blue", "magenta", "cyan", "yellow", "red"]; + +fn bucket_color(idx: usize) -> &'static str { + BUCKET_COLORS[idx % BUCKET_COLORS.len()] +} + +fn colorize_bucket_name(name: &str, idx: usize) -> String { + match bucket_color(idx) { + "green" => name.green().to_string(), + "blue" => name.blue().to_string(), + "magenta" => name.magenta().to_string(), + "cyan" => name.cyan().to_string(), + "yellow" => name.yellow().to_string(), + "red" => name.red().to_string(), + _ => name.to_string(), + } +} + +fn colorize_bucket_tag(name: &str, idx: usize) -> String { + let colored_name = colorize_bucket_name(name, idx); + format!("[{}]", colored_name) +} + +/// Render the full TUI to the terminal. +fn render( + term: &Term, + entries: &[CommitEntry], + buckets: &[BucketEntry], + cursor: usize, + mode: &Mode, + input_buf: &str, + input_error: &Option, + last_height: &mut usize, +) -> Result<()> { + // Clear previous render + clear(term, *last_height)?; + + let mut lines: Vec = Vec::new(); + + // Header + lines.push(format!( + "{} {}", + "gw split".cyan().bold(), + "— Assign commits to branches".dimmed() + )); + lines.push(String::new()); + + // Commits list + let (term_height, _term_width) = term.size(); + let max_visible = (term_height as usize).saturating_sub(12).min(30).max(5); + + // Calculate viewport + let total = entries.len(); + let (view_start, view_end) = if total <= max_visible { + (0, total) + } else { + let half = max_visible / 2; + let start = if cursor <= half { + 0 + } else if cursor + half >= total { + total.saturating_sub(max_visible) + } else { + cursor - half + }; + (start, (start + max_visible).min(total)) + }; + + if view_start > 0 { + lines.push(format!(" {} more above", format!("↑ {}", view_start).dimmed())); + } + + for i in view_start..view_end { + let entry = &entries[i]; + let short_sha = &entry.sha[..7.min(entry.sha.len())]; + let is_selected = i == cursor; + + let marker = if is_selected { "▸" } else { " " }; + let marker_str = if is_selected { + marker.yellow().bold().to_string() + } else { + marker.to_string() + }; + + let dot = if entry.bucket_idx.is_some() { + "●".to_string() + } else { + "○".dimmed().to_string() + }; + + let sha_str = if is_selected { + short_sha.yellow().to_string() + } else { + short_sha.dimmed().to_string() + }; + + let subject_str = if is_selected { + entry.subject.yellow().bold().to_string() + } else { + entry.subject.white().to_string() + }; + + let tag = if let Some(idx) = entry.bucket_idx { + if idx < buckets.len() { + format!(" {}", colorize_bucket_tag(&buckets[idx].name, idx)) + } else { + String::new() + } + } else { + String::new() + }; + + lines.push(format!( + " {marker_str} {dot} {sha_str} {subject_str}{tag}" + )); + } + + if view_end < total { + lines.push(format!( + " {} more below", + format!("↓ {}", total - view_end).dimmed() + )); + } + + lines.push(String::new()); + + // Buckets summary + lines.push(format!(" {}:", "Buckets".bold())); + + if buckets.is_empty() { + lines.push(format!(" {}", "(none — press 'n' to create)".dimmed())); + } else { + for (i, bucket) in buckets.iter().enumerate() { + let count = entries.iter().filter(|e| e.bucket_idx == Some(i)).count(); + let num = format!("[{}]", i + 1); + lines.push(format!( + " {} {} ({} commit{})", + num.dimmed(), + colorize_bucket_name(&bucket.name, i), + count, + if count == 1 { "" } else { "s" } + )); + } + } + + let unassigned = entries.iter().filter(|e| e.bucket_idx.is_none()).count(); + if unassigned > 0 { + lines.push(format!( + " {} ({} commit{})", + "unassigned".dimmed(), + unassigned, + if unassigned == 1 { "" } else { "s" } + )); + } + + lines.push(String::new()); + + // Mode-specific footer + match mode { + Mode::Normal => { + lines.push(format!( + " {}", + "↑/↓ navigate │ 1-9 assign │ n new bucket │ u unassign │ Enter confirm │ q quit" + .dimmed() + )); + } + Mode::TextInput => { + lines.push(format!( + " {} {}▏", + "Branch name:".bold(), + input_buf + )); + lines.push(format!( + " {}", + "Enter confirm │ Esc cancel".dimmed() + )); + } + } + + // Error message + if let Some(err) = input_error { + lines.push(format!(" {}", err.red())); + } + + *last_height = lines.len(); + for line in &lines { + term.write_line(line)?; + } + + Ok(()) +} diff --git a/src/context.rs b/src/context.rs index 3242291..a948e80 100644 --- a/src/context.rs +++ b/src/context.rs @@ -2,7 +2,7 @@ use anyhow::{Context, Result}; use std::path::PathBuf; use crate::git::Git; -use crate::state::{self, GwConfig, PropagationState, StackConfig}; +use crate::state::{self, ActiveState, GwConfig, PropagationState, SplitState, StackConfig}; /// Central context passed to all command handlers. /// Bundles the Git instance, resolved gw paths, and provides @@ -130,6 +130,22 @@ impl Ctx { state::remove_propagation_state(&self.state_path) } + /// Load active state (either propagation or split) if it exists. + pub fn active_state(&self) -> Result> { + state::load_active_state(&self.state_path) + } + + /// Save split state. + pub fn save_split_state(&self, ss: &SplitState) -> Result<()> { + self.ensure_dirs()?; + state::save_split_state(&self.state_path, ss) + } + + /// Remove state file (works for both propagation and split state). + pub fn remove_state(&self) -> Result<()> { + state::remove_state(&self.state_path) + } + /// Load gw config (returns defaults if no config file exists). pub fn load_config(&self) -> Result { state::load_config(&self.config_path) diff --git a/src/git.rs b/src/git.rs index 5200d1e..0df0a36 100644 --- a/src/git.rs +++ b/src/git.rs @@ -11,6 +11,24 @@ pub enum RebaseResult { Conflict, } +/// Result of a git cherry-pick operation. +pub enum CherryPickResult { + /// Cherry-pick completed successfully. + Success, + /// Cherry-pick paused due to a conflict. + Conflict, +} + +/// Information about a commit from git log. +pub struct CommitInfo { + /// Full 40-character SHA. + pub full_sha: String, + /// Commit subject line. + pub subject: String, + /// Number of parents (>1 means merge commit). + pub parent_count: usize, +} + /// Wrapper around git CLI operations. /// /// All git interactions go through this struct. It uses `std::process::Command` @@ -351,6 +369,98 @@ impl Git { )) } + /// Cherry-pick a single commit onto the current branch. + /// Returns Success or Conflict (never errors on conflict). + pub fn cherry_pick(&self, sha: &str) -> Result { + let output = self.run_raw(&["cherry-pick", sha])?; + + if output.status.success() { + return Ok(CherryPickResult::Success); + } + + // Check for conflict state + if self.is_cherry_pick_in_progress() { + return Ok(CherryPickResult::Conflict); + } + + let stderr = String::from_utf8_lossy(&output.stderr); + Err(anyhow!("git cherry-pick failed: {}", stderr.trim())) + } + + /// Continue an in-progress cherry-pick. + pub fn cherry_pick_continue(&self) -> Result { + let output = self.run_raw(&["cherry-pick", "--continue"])?; + + if output.status.success() { + return Ok(CherryPickResult::Success); + } + + if self.is_cherry_pick_in_progress() { + return Ok(CherryPickResult::Conflict); + } + + let stderr = String::from_utf8_lossy(&output.stderr); + Err(anyhow!( + "git cherry-pick --continue failed: {}", + stderr.trim() + )) + } + + /// Abort an in-progress cherry-pick. + pub fn cherry_pick_abort(&self) -> Result<()> { + if self.is_cherry_pick_in_progress() { + self.run(&["cherry-pick", "--abort"])?; + } + Ok(()) + } + + /// Check if a git cherry-pick is currently in progress. + pub fn is_cherry_pick_in_progress(&self) -> bool { + self.repo_path.join(".git").join("CHERRY_PICK_HEAD").exists() + } + + /// Delete a local branch (force). + pub fn delete_branch(&self, name: &str) -> Result<()> { + self.run(&["branch", "-D", name])?; + Ok(()) + } + + /// Get commits between base and head with full SHAs and parent info. + /// Returns commits in chronological order (oldest first). + /// Combines log + merge commit detection in a single git call. + pub fn log_commits(&self, base: &str, head: &str) -> Result> { + // %H = full SHA, %P = parent SHAs (space-separated), %s = subject + let output = self.run(&[ + "log", + "--reverse", + "--format=%H|%P|%s", + &format!("{base}..{head}"), + ])?; + if output.is_empty() { + return Ok(vec![]); + } + Ok(output + .lines() + .map(|line| { + // Split on first two '|' characters + let mut parts = line.splitn(3, '|'); + let full_sha = parts.next().unwrap_or("").to_string(); + let parents = parts.next().unwrap_or(""); + let subject = parts.next().unwrap_or("").to_string(); + let parent_count = if parents.is_empty() { + 0 + } else { + parents.split(' ').count() + }; + CommitInfo { + full_sha, + subject, + parent_count, + } + }) + .collect()) + } + /// Atomically update multiple refs using git update-ref --stdin. /// Each entry is (branch_name, target_sha). pub fn update_ref_transaction(&self, updates: &[(String, String)]) -> Result<()> { diff --git a/src/main.rs b/src/main.rs index 649aef3..a6aa29a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,28 +30,61 @@ fn main() -> Result<()> { let ctx = Ctx::discover()?; - // State guard: block most commands if a propagation is in progress - if let Some(ref prop_state) = ctx.propagation_state()? { - let allowed = matches!( - &command, - Commands::Rebase(args) if args.cont || args.abort - ) || matches!(&command, Commands::Log(_)) - || matches!(&command, Commands::Switch(_)) - || matches!(&command, Commands::Status) - || matches!(&command, Commands::Diff(_)); + // State guard: block most commands if a propagation or split is in progress + if let Some(ref active) = ctx.active_state()? { + match active { + state::ActiveState::Propagation(prop_state) => { + let is_split_op = prop_state.operation == state::Operation::Split; + let allowed = matches!( + &command, + Commands::Rebase(args) if args.cont || args.abort + ) || matches!( + &command, + Commands::Split(args) if (args.cont || args.abort) && is_split_op + ) || matches!(&command, Commands::Log(_)) + || matches!(&command, Commands::Switch(_)) + || matches!(&command, Commands::Status) + || matches!(&command, Commands::Diff(_)); - if !allowed { - let op = match prop_state.operation { - state::Operation::Rebase => "rebase", - state::Operation::Sync => "sync", - state::Operation::Adopt => "adopt", - state::Operation::BranchRemove => "branch remove", - }; - bail!( - "A {op} propagation is in progress on stack '{}'.\n\ - Run `gw rebase --continue` or `gw rebase --abort` first.", - prop_state.stack - ); + if !allowed { + if is_split_op { + bail!( + "A split propagation is in progress on stack '{}'.\n\ + Run `gw split --continue` or `gw split --abort` first.", + prop_state.stack + ); + } + let op = match prop_state.operation { + state::Operation::Rebase => "rebase", + state::Operation::Sync => "sync", + state::Operation::Adopt => "adopt", + state::Operation::BranchRemove => "branch remove", + state::Operation::Split => unreachable!(), + }; + bail!( + "A {op} propagation is in progress on stack '{}'.\n\ + Run `gw rebase --continue` or `gw rebase --abort` first.", + prop_state.stack + ); + } + } + state::ActiveState::Split(split_state) => { + let allowed = matches!( + &command, + Commands::Split(args) if args.cont || args.abort + ) || matches!(&command, Commands::Log(_)) + || matches!(&command, Commands::Switch(_)) + || matches!(&command, Commands::Status) + || matches!(&command, Commands::Diff(_)); + + if !allowed { + bail!( + "A split is in progress on branch '{}'.\n\ + Run `gw split --continue` or `gw split --abort` first.", + split_state.original_branch + ); + } + } } } @@ -66,6 +99,7 @@ fn main() -> Result<()> { Commands::Push(args) => commands::push::run(args, &ctx), Commands::Switch(args) => commands::switch::run(args.branch, &ctx), Commands::Log(args) => commands::tree::run(&ctx, args.pr), + Commands::Split(args) => commands::split::run(args, &ctx), Commands::Config(args) => commands::config::run(args.command, &ctx), Commands::Completions(_) | Commands::McpSetup | Commands::McpServer => unreachable!(), } diff --git a/src/state.rs b/src/state.rs index 003787e..5b17aec 100644 --- a/src/state.rs +++ b/src/state.rs @@ -115,6 +115,7 @@ pub enum Operation { Sync, Adopt, BranchRemove, + Split, } /// Propagation state tracked in .git/gw/state.toml during multi-branch rebases. @@ -199,6 +200,106 @@ pub fn remove_propagation_state(path: &Path) -> Result<()> { Ok(()) } +// ============================================================ +// Split state +// ============================================================ + +/// A bucket of commits that will become a branch during split. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SplitBucket { + pub name: String, + pub commits: Vec, +} + +/// State tracked in .git/gw/state.toml during the cherry-pick phase of a split. +/// Only exists while a split's cherry-pick phase is in progress. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SplitState { + pub operation: Operation, + pub original_branch: String, + pub original_sha: String, + pub base_branch: String, + pub stack_name: String, + /// Branches created so far (for rollback on abort). + pub created_branches: Vec, + /// Which bucket is currently being processed. + pub current_bucket_index: usize, + /// Which commit within the current bucket is next. + pub current_commit_index: usize, + /// The bucket assignments. + pub buckets: Vec, +} + +impl SplitState { + /// Validate all fields after deserialization (defense in depth). + pub fn validate(&self) -> Result<()> { + crate::validate::validate_branch_name(&self.original_branch)?; + crate::validate::validate_sha(&self.original_sha)?; + crate::validate::validate_branch_name(&self.base_branch)?; + crate::validate::validate_stack_name(&self.stack_name)?; + for branch in &self.created_branches { + crate::validate::validate_branch_name(branch)?; + } + for bucket in &self.buckets { + crate::validate::validate_branch_name(&bucket.name)?; + for sha in &bucket.commits { + crate::validate::validate_sha(sha)?; + } + } + Ok(()) + } +} + +/// Discriminated union for state.toml which can contain either a PropagationState +/// or a SplitState depending on the active operation. +pub enum ActiveState { + Propagation(PropagationState), + Split(SplitState), +} + +/// Load the active state from state.toml, determining the type from the content. +pub fn load_active_state(path: &Path) -> Result> { + if !path.exists() { + return Ok(None); + } + let content = std::fs::read_to_string(path) + .with_context(|| format!("failed to read {}", path.display()))?; + + // Parse as raw TOML to check the operation and presence of split-specific fields + let raw: toml::Value = + toml::from_str(&content).with_context(|| format!("failed to parse {}", path.display()))?; + + let is_split = raw.get("operation").and_then(|v| v.as_str()) == Some("split") + && raw.get("buckets").is_some(); + + if is_split { + let state: SplitState = toml::from_str(&content) + .with_context(|| format!("failed to parse split state from {}", path.display()))?; + state.validate()?; + Ok(Some(ActiveState::Split(state))) + } else { + let state: PropagationState = toml::from_str(&content) + .with_context(|| format!("failed to parse propagation state from {}", path.display()))?; + Ok(Some(ActiveState::Propagation(state))) + } +} + +/// Save split state atomically. +pub fn save_split_state(path: &Path, state: &SplitState) -> Result<()> { + let content = + toml::to_string_pretty(state).context("failed to serialize split state")?; + atomic_write(path, &content) +} + +/// Remove state file (works for both split and propagation state). +pub fn remove_state(path: &Path) -> Result<()> { + if path.exists() { + std::fs::remove_file(path) + .with_context(|| format!("failed to remove {}", path.display()))?; + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/validate.rs b/src/validate.rs index 90c562f..885ddd8 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -1,5 +1,17 @@ use anyhow::{bail, Result}; +/// Validate a commit SHA is a valid hex string. +/// Used to prevent injection when SHAs come from user input (plan files, state files). +pub fn validate_sha(sha: &str) -> Result<()> { + if sha.is_empty() { + bail!("Commit SHA cannot be empty"); + } + if !sha.chars().all(|c| c.is_ascii_hexdigit()) { + bail!("Invalid commit SHA '{sha}': must contain only hex characters"); + } + Ok(()) +} + /// Validate a stack name for filesystem safety and git compatibility. /// Stack names are used to construct file paths (.git/gw/stacks/.toml), /// so they must not contain path traversal sequences or filesystem-unsafe characters. @@ -145,6 +157,23 @@ mod tests { assert!(validate_stack_name("bad\0name").is_err()); } + #[test] + fn valid_shas() { + assert!(validate_sha("abc123").is_ok()); + assert!(validate_sha("deadbeef").is_ok()); + assert!(validate_sha("ABC123").is_ok()); + assert!(validate_sha("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2").is_ok()); + } + + #[test] + fn invalid_shas() { + assert!(validate_sha("").is_err()); + assert!(validate_sha("--exec=bad").is_err()); + assert!(validate_sha("not-hex!").is_err()); + assert!(validate_sha("abc 123").is_err()); + assert!(validate_sha("abc\n123").is_err()); + } + #[test] fn stack_names_special_chars_rejected() { assert!(validate_stack_name("has spaces").is_err()); diff --git a/tests/split_test.rs b/tests/split_test.rs new file mode 100644 index 0000000..feb0dc3 --- /dev/null +++ b/tests/split_test.rs @@ -0,0 +1,489 @@ +mod common; + +use common::{gw_cmd, TestRepo}; +use predicates::prelude::*; +use std::fs; + +// ============================================================ +// Helper: create a plan file +// ============================================================ + +fn write_plan(_repo: &TestRepo, content: &str) -> String { + let dir = tempfile::tempdir().unwrap(); + let plan_path = dir.path().join("split-plan.txt"); + fs::write(&plan_path, content).unwrap(); + // Leak the tempdir so it survives until the test ends + let path_str = plan_path.to_str().unwrap().to_string(); + std::mem::forget(dir); + path_str +} + +/// Get the full SHA for HEAD or a ref. +fn full_sha(repo: &TestRepo, refspec: &str) -> String { + repo.git(&["rev-parse", refspec]) +} + +/// Create a branch with N commits off the current branch, returning full SHAs. +fn create_branch_with_commits(repo: &TestRepo, branch: &str, files: &[(&str, &str, &str)]) -> Vec { + repo.git(&["checkout", "-b", branch]); + let mut shas = Vec::new(); + for (name, content, msg) in files { + repo.commit_file(name, content, msg); + shas.push(full_sha(repo, "HEAD")); + } + shas +} + +// ============================================================ +// Split untracked branch — basic happy path +// ============================================================ + +#[test] +fn split_untracked_branch_into_two_buckets() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + let shas = create_branch_with_commits(&repo, "fat-branch", &[ + ("auth.txt", "auth code", "Add auth"), + ("auth-test.txt", "auth tests", "Add auth tests"), + ("dash.txt", "dashboard", "Add dashboard"), + ("dash-test.txt", "dash tests", "Add dashboard tests"), + ]); + + let plan = format!( + "pick {} auth\npick {} auth\npick {} dashboard\npick {} dashboard\n", + shas[0], shas[1], shas[2], shas[3] + ); + let plan_path = write_plan(&repo, &plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch]) + .assert() + .success() + .stdout(predicate::str::contains("Split complete")) + .stdout(predicate::str::contains("auth")) + .stdout(predicate::str::contains("dashboard")); + + // Verify branches were created + assert!(repo.branch_exists("auth")); + assert!(repo.branch_exists("dashboard")); + + // Verify original branch still exists (backup) + assert!(repo.branch_exists("fat-branch")); + + // Verify stack was created + assert!(repo.stack_toml_exists("fat-branch")); + let toml = repo.read_stack_toml("fat-branch"); + assert!(toml.contains("name = \"auth\"")); + assert!(toml.contains("name = \"dashboard\"")); + assert!(toml.contains(&format!("base_branch = \"{main_branch}\""))); + + // Verify we're on the root branch + assert_eq!(repo.current_branch(), "auth"); + + // Verify no state file left + assert!(!repo.state_toml_exists()); + + // Verify auth branch has the right files + repo.git(&["checkout", "auth"]); + assert!(repo.path.join("auth.txt").exists()); + assert!(repo.path.join("auth-test.txt").exists()); + assert!(!repo.path.join("dash.txt").exists()); + + // Verify dashboard branch has all files (stacked on auth) + repo.git(&["checkout", "dashboard"]); + assert!(repo.path.join("auth.txt").exists()); + assert!(repo.path.join("dash.txt").exists()); + assert!(repo.path.join("dash-test.txt").exists()); +} + +// ============================================================ +// Split tracked branch in existing stack +// ============================================================ + +#[test] +fn split_tracked_branch_replaces_in_stack() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + // Create a stack with a fat branch + gw_cmd(&repo.path) + .args(["stack", "create", "mystack", "--base", &main_branch]) + .assert() + .success(); + + // Add commits to the stack's branch + repo.commit_file("a.txt", "a", "Add feature A"); + let sha_a = full_sha(&repo, "HEAD"); + repo.commit_file("b.txt", "b", "Add feature B"); + let sha_b = full_sha(&repo, "HEAD"); + repo.commit_file("c.txt", "c", "Add feature C"); + let sha_c = full_sha(&repo, "HEAD"); + + let plan = format!( + "pick {} part-one\npick {} part-two\npick {} part-two\n", + sha_a, sha_b, sha_c + ); + let plan_path = write_plan(&repo, &plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path]) + .assert() + .success() + .stdout(predicate::str::contains("Split complete")); + + // Verify stack was updated — original branch replaced with new ones + let toml = repo.read_stack_toml("mystack"); + assert!(toml.contains("name = \"part-one\"")); + assert!(toml.contains("name = \"part-two\"")); + // The original "mystack" branch entry should be gone from the branches list + // (note: the toml file still has name = "mystack" as the stack name) + let branch_entries: Vec<&str> = toml + .lines() + .filter(|l| l.starts_with("name = ")) + .collect(); + // Stack name + part-one + part-two = 3 lines with "name =" + assert_eq!(branch_entries.len(), 3); +} + +// ============================================================ +// Precondition: refuses < 2 commits +// ============================================================ + +#[test] +fn split_refuses_single_commit_branch() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + repo.git(&["checkout", "-b", "tiny"]); + repo.commit_file("only.txt", "only", "Only commit"); + + let sha = full_sha(&repo, "HEAD"); + let plan = format!("pick {} a\npick {} b\n", sha, sha); + let plan_path = write_plan(&repo, &plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch]) + .assert() + .failure() + .stderr(predicate::str::contains("at least 2")); +} + +// ============================================================ +// Precondition: refuses merge commits +// ============================================================ + +#[test] +fn split_refuses_branch_with_merge_commits() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + // Create two branches + repo.git(&["checkout", "-b", "feature-a"]); + repo.commit_file("a.txt", "a", "commit a"); + + repo.git(&["checkout", &main_branch]); + repo.git(&["checkout", "-b", "feature-merge"]); + repo.commit_file("b.txt", "b", "commit b"); + + // Merge feature-a into feature-merge (creates a merge commit) + repo.git(&["merge", "feature-a", "--no-edit"]); + + let plan_path = write_plan(&repo, "pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa x\npick bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb y\n"); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch]) + .assert() + .failure() + .stderr(predicate::str::contains("merge commit")); +} + +// ============================================================ +// Precondition: refuses dirty working tree +// ============================================================ + +#[test] +fn split_refuses_dirty_tree() { + let repo = TestRepo::new(); + + repo.git(&["checkout", "-b", "dirty-branch"]); + repo.commit_file("a.txt", "a", "commit a"); + repo.commit_file("b.txt", "b", "commit b"); + + // Make tree dirty + fs::write(repo.path.join("dirty.txt"), "dirty").unwrap(); + + let plan_path = write_plan(&repo, "pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa x\npick bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb y\n"); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path]) + .assert() + .failure() + .stderr(predicate::str::contains("uncommitted changes")); +} + +// ============================================================ +// Plan file: rejects plan with mismatched commits +// ============================================================ + +#[test] +fn split_rejects_plan_with_wrong_commits() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + create_branch_with_commits(&repo, "branch", &[ + ("a.txt", "a", "commit a"), + ("b.txt", "b", "commit b"), + ]); + + // Plan with fake SHAs + let plan = "pick aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa x\npick bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb y\n"; + let plan_path = write_plan(&repo, plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch]) + .assert() + .failure() + .stderr(predicate::str::contains("don't match")); +} + +// ============================================================ +// Plan file: rejects plan with single bucket +// ============================================================ + +#[test] +fn split_rejects_single_bucket_plan() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + let shas = create_branch_with_commits(&repo, "branch", &[ + ("a.txt", "a", "commit a"), + ("b.txt", "b", "commit b"), + ]); + + let plan = format!("pick {} only\npick {} only\n", shas[0], shas[1]); + let plan_path = write_plan(&repo, &plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch]) + .assert() + .failure() + .stderr(predicate::str::contains("at least 2 buckets")); +} + +// ============================================================ +// Branch name collision +// ============================================================ + +#[test] +fn split_rejects_existing_branch_name() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + // Create a branch named "taken" + repo.git(&["branch", "taken"]); + + let shas = create_branch_with_commits(&repo, "branch", &[ + ("a.txt", "a", "commit a"), + ("b.txt", "b", "commit b"), + ]); + + let plan = format!("pick {} taken\npick {} other\n", shas[0], shas[1]); + let plan_path = write_plan(&repo, &plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch]) + .assert() + .failure() + .stderr(predicate::str::contains("already exists")); +} + +// ============================================================ +// State guard: blocked during propagation +// ============================================================ + +#[test] +fn split_blocked_during_propagation() { + let repo = TestRepo::new(); + + repo.write_state_toml( + r#" +operation = "rebase" +stack = "test" +started_at = "12345" +original_branch = "main" +original_refs = [] +completed = [] +remaining = [] +"#, + ); + + gw_cmd(&repo.path) + .args(["split", "--plan", "nonexistent"]) + .assert() + .failure() + .stderr(predicate::str::contains("propagation is in progress")); +} + +// ============================================================ +// Cherry-pick conflict: abort +// ============================================================ + +#[test] +fn split_abort_cleans_up() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + // Create a branch with 3 commits + let shas = create_branch_with_commits(&repo, "fat", &[ + ("a.txt", "aaa", "commit a"), + ("b.txt", "bbb", "commit b"), + ("c.txt", "ccc", "commit c"), + ]); + + // Create a conflicting file on main that will conflict with commit a's cherry-pick + repo.git(&["checkout", &main_branch]); + repo.commit_file("a.txt", "conflict!", "conflicting a on main"); + repo.git(&["checkout", "fat"]); + + let plan = format!( + "pick {} first\npick {} second\npick {} second\n", + shas[0], shas[1], shas[2] + ); + let plan_path = write_plan(&repo, &plan); + + // This should hit a conflict on first cherry-pick + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch]) + .assert() + .success() + .stderr(predicate::str::contains("Conflict")); + + // State file should exist + assert!(repo.state_toml_exists()); + + // Abort + gw_cmd(&repo.path) + .args(["split", "--abort"]) + .assert() + .success() + .stdout(predicate::str::contains("aborted")); + + // Created branches should be cleaned up + assert!(!repo.branch_exists("first")); + assert!(!repo.branch_exists("second")); + + // State file should be gone + assert!(!repo.state_toml_exists()); + + // Should be back on original branch + assert_eq!(repo.current_branch(), "fat"); +} + +// ============================================================ +// Abort idempotency +// ============================================================ + +#[test] +fn split_abort_when_no_split_in_progress() { + let repo = TestRepo::new(); + + gw_cmd(&repo.path) + .args(["split", "--abort"]) + .assert() + .failure() + .stderr(predicate::str::contains("No split in progress")); +} + +// ============================================================ +// Custom stack name with --name +// ============================================================ + +#[test] +fn split_custom_stack_name() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + let shas = create_branch_with_commits(&repo, "fat", &[ + ("a.txt", "a", "commit a"), + ("b.txt", "b", "commit b"), + ]); + + let plan = format!("pick {} part-a\npick {} part-b\n", shas[0], shas[1]); + let plan_path = write_plan(&repo, &plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path, "--base", &main_branch, "--name", "my-stack"]) + .assert() + .success() + .stdout(predicate::str::contains("my-stack")); + + assert!(repo.stack_toml_exists("my-stack")); +} + +// ============================================================ +// Split with tracked branch that has descendants +// ============================================================ + +#[test] +fn split_mid_stack_rebases_descendants() { + let repo = TestRepo::new(); + let main_branch = repo.current_branch(); + + // Create a 3-branch stack: root -> mid -> leaf + gw_cmd(&repo.path) + .args(["stack", "create", "mystack", "--base", &main_branch]) + .assert() + .success(); + + // root branch: "mystack" + repo.commit_file("root.txt", "root", "root commit"); + + // mid branch + gw_cmd(&repo.path) + .args(["branch", "create", "mid"]) + .assert() + .success(); + + repo.commit_file("mid-a.txt", "a", "mid commit a"); + let sha_a = full_sha(&repo, "HEAD"); + repo.commit_file("mid-b.txt", "b", "mid commit b"); + let sha_b = full_sha(&repo, "HEAD"); + + // leaf branch + gw_cmd(&repo.path) + .args(["branch", "create", "leaf"]) + .assert() + .success(); + + repo.commit_file("leaf.txt", "leaf", "leaf commit"); + + // Go back to mid and split it + repo.git(&["checkout", "mid"]); + + let plan = format!("pick {} mid-part1\npick {} mid-part2\n", sha_a, sha_b); + let plan_path = write_plan(&repo, &plan); + + gw_cmd(&repo.path) + .args(["split", "--plan", &plan_path]) + .assert() + .success() + .stdout(predicate::str::contains("Split complete")); + + // Verify stack updated + let toml = repo.read_stack_toml("mystack"); + assert!(toml.contains("name = \"mid-part1\"")); + assert!(toml.contains("name = \"mid-part2\"")); + assert!(toml.contains("name = \"leaf\"")); + // "mid" should no longer be in the branches list + // Count how many branch entries there are + let branch_lines: Vec<&str> = toml.lines().filter(|l| l.trim().starts_with("name = ")).collect(); + // stack name + mystack + mid-part1 + mid-part2 + leaf = 5 + assert_eq!(branch_lines.len(), 5, "Expected 5 name lines, got: {:?}", branch_lines); + + // Verify leaf still has its file (was rebased successfully) + repo.git(&["checkout", "leaf"]); + assert!(repo.path.join("leaf.txt").exists()); + assert!(repo.path.join("mid-a.txt").exists()); + assert!(repo.path.join("mid-b.txt").exists()); +}