Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ This repo contains `gw`, a CLI tool for managing stacked branches with GitHub's

### Creating a stack and adding branches
```bash
gw stack create <name> # creates stack + root branch, checks it out
gw stack create <name> # creates stack, prompts for root branch name
gw stack create <name> --branch <branch> # creates stack with specific root branch
# ... do work, commit ...
gw branch create <next-branch> # adds child branch, checks it out
# ... do work, commit ...
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ There's also the force push problem. Most stacking tools auto-rebase your entire

**ghstack** rewrites your branches into synthetic ones for GitHub to display as individual PRs. What's on your machine doesn't match what's on GitHub, and that gets confusing when you're debugging a rebase or a PR diff doesn't look like what you see locally.

**git-branchless** Is close but I found the squash merge detection falls over most of the time, which leaves you doing the manual cleanup work anyways. It's also a different mental model entirely, inspired by Mercurial and Phabricator, and if your team already does one-branch-per-PR with squash merges that abstraction doesn't map cleanly.
**git-branchless** is close to what you want but the squash merge detection falls over most of the time, which leaves you doing the manual cleanup work anyways. It's also a different mental model entirely, inspired by Mercurial and Phabricator, and if your team already does one-branch-per-PR with squash merges that abstraction doesn't map cleanly.

### What gw does

Expand Down Expand Up @@ -105,9 +105,12 @@ If you'd rather just get the MCP tools without the plugin system, run `gw mcp-se
# Set your base branch (if not main)
gw config set-base dev

# Create a stack
# Create a stack (prompts for root branch name, defaults to stack name)
gw stack create auth

# Or specify the branch name directly
gw stack create auth --branch auth-login

# Do work, commit, then add the next branch
gw branch create auth-tests

Expand Down Expand Up @@ -190,7 +193,8 @@ gw config set-delete-on-merge true
| `gw` | Show all stacks (alias for `gw log`) |
| `gw log` | Show all stacks with branches and commits |
| `gw log --pr` | Include PR status from GitHub |
| `gw stack create <name>` | Create a new stack off the base branch |
| `gw stack create <name>` | Create a new stack (prompts for root branch name) |
| `gw stack create <name> --branch <branch>` | Create a new stack with a specific root branch name |
| `gw stack delete <name>` | Remove stack metadata (branches stay) |
| `gw stack list` | List all stacks |
| `gw branch create <name>` | Add a branch to the current stack |
Expand Down
5 changes: 4 additions & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,11 @@ pub struct StackArgs {
pub enum StackCommands {
/// Create a new stack
Create {
/// Name for the stack (also creates a branch with this name)
/// Name for the stack
name: String,
/// Root branch name (prompts interactively if omitted)
#[arg(long)]
branch: Option<String>,
/// Base branch to stack off of (defaults to current branch)
#[arg(long)]
base: Option<String>,
Expand Down
7 changes: 4 additions & 3 deletions src/commands/completions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ _gw() {
subcmd) _describe 'subcommand' stack_commands ;;
stack_args)
case $words[1] in
create) _arguments '1:name:' '--base[Base branch]:branch:_gw_branches' ;;
create) _arguments '1:name:' '--branch[Root branch name]:branch:_gw_branches' '--base[Base branch]:branch:_gw_branches' ;;
delete) _arguments '1:name:_gw_stacks' ;;
esac
;;
Expand Down Expand Up @@ -206,10 +206,10 @@ _gw() {
case "${words[2]}" in
delete) COMPREPLY=($(compgen -W "$(_gw_stacks)" -- "$cur")) ;;
create)
if [[ "$prev" == "--base" ]]; then
if [[ "$prev" == "--base" || "$prev" == "--branch" ]]; then
COMPREPLY=($(compgen -W "$(_gw_branches)" -- "$cur"))
else
COMPREPLY=($(compgen -W "--base" -- "$cur"))
COMPREPLY=($(compgen -W "--base --branch" -- "$cur"))
fi
;;
esac
Expand Down Expand Up @@ -333,6 +333,7 @@ complete -c gw -f -n '__gw_using_command stack' -a create -d 'Create a new stack
complete -c gw -f -n '__gw_using_command stack' -a delete -d 'Delete a stack'
complete -c gw -f -n '__gw_using_command stack' -a list -d 'List all stacks'
complete -c gw -f -n '__gw_using_subcommand stack delete' -a '(__gw_stacks)'
complete -c gw -f -n '__gw_using_subcommand stack create' -l branch -d 'Root branch name' -ra '(__gw_branches)'
complete -c gw -f -n '__gw_using_subcommand stack create' -l base -d 'Base branch' -ra '(__gw_branches)'

# branch subcommands
Expand Down
7 changes: 6 additions & 1 deletion src/commands/mcp_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,13 @@ impl GwServer {
#[tool(param)]
#[schemars(description = "Name for the stack")]
name: String,
#[tool(param)]
#[schemars(description = "Root branch name (defaults to the stack name)")]
branch: Option<String>,
) -> String {
gw(&["stack", "create", &name]).unwrap_or_else(|e| format!("{e}"))
let branch_name = branch.unwrap_or_else(|| name.clone());
gw(&["stack", "create", &name, "--branch", &branch_name])
.unwrap_or_else(|e| format!("{e}"))
}

#[tool(description = "Delete a stack (branches are NOT deleted)")]
Expand Down
39 changes: 29 additions & 10 deletions src/commands/stack.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use anyhow::{bail, Result};
use anyhow::{bail, Context, Result};

use crate::cli::StackCommands;
use crate::context::Ctx;
Expand All @@ -8,23 +8,40 @@ use crate::ui;

pub fn run(cmd: StackCommands, ctx: &Ctx) -> Result<()> {
match cmd {
StackCommands::Create { name, base } => create(ctx, &name, base.as_deref()),
StackCommands::Create {
name,
branch,
base,
} => create(ctx, &name, branch.as_deref(), base.as_deref()),
StackCommands::Delete { name } => delete(ctx, &name),
StackCommands::List => list(ctx),
}
}

fn create(ctx: &Ctx, name: &str, base: Option<&str>) -> Result<()> {
fn create(ctx: &Ctx, name: &str, branch: Option<&str>, base: Option<&str>) -> Result<()> {
validate::validate_stack_name(name)?;
validate::validate_branch_name(name)?; // name is also used as branch name

if ctx.stack_exists(name) {
bail!("Stack '{name}' already exists. Use `gw stack delete {name}` first.");
}

if ctx.git.branch_exists(name)? {
let branch_name = match branch {
Some(b) => b.to_string(),
None => {
let input = ui::prompt("Root branch name", Some(name))
.context("Failed to read branch name")?;
if input.is_empty() {
bail!("Branch name cannot be empty.");
}
input
}
};

validate::validate_branch_name(&branch_name)?;

if ctx.git.branch_exists(&branch_name)? {
bail!(
"Branch '{name}' already exists. Use `gw adopt {name}` to track it, or choose a different name."
"Branch '{branch_name}' already exists. Use `gw adopt {branch_name}` to track it, or choose a different name."
);
}

Expand All @@ -34,25 +51,27 @@ fn create(ctx: &Ctx, name: &str, base: Option<&str>) -> Result<()> {
};

let head = ctx.git.rev_parse(&format!("refs/heads/{base_branch}"))?;
ctx.git.create_branch(name, &head)?;
ctx.git.create_branch(&branch_name, &head)?;

let config = StackConfig {
name: name.to_string(),
base_branch,
branches: vec![BranchEntry {
name: name.to_string(),
name: branch_name.clone(),
}],
};

ctx.save_stack(&config)?;
ctx.git.checkout(name)?;
ctx.git.checkout(&branch_name)?;

let short_sha = &head[..7.min(head.len())];
ui::success(&format!(
"Created stack '{}' off {} @ {}",
config.name, config.base_branch, short_sha
));
ui::info(&format!("Created and checked out branch '{name}' (root)"));
ui::info(&format!(
"Created and checked out branch '{branch_name}' (root)"
));

Ok(())
}
Expand Down
34 changes: 34 additions & 0 deletions src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,40 @@ pub fn error(msg: &str) {
eprintln!("{}", msg.red());
}

/// Prompt the user for text input with an optional default value.
/// In non-interactive mode (stdin is not a TTY), returns the default if provided,
/// otherwise returns an error.
pub fn prompt(message: &str, default: Option<&str>) -> io::Result<String> {
if !atty_check() {
return match default {
Some(d) => Ok(d.to_string()),
None => Err(io::Error::new(
io::ErrorKind::Other,
"non-interactive mode and no default provided",
)),
};
}

match default {
Some(d) => print!("{message} [{d}]: "),
None => print!("{message}: "),
}
io::stdout().flush().ok();

let mut input = String::new();
io::stdin().lock().read_line(&mut input)?;

let input = input.trim();
if input.is_empty() {
match default {
Some(d) => Ok(d.to_string()),
None => Ok(String::new()),
}
} else {
Ok(input.to_string())
}
}

/// Print an info message.
pub fn info(msg: &str) {
println!("{msg}");
Expand Down