Skip to content

Instantly share code, notes, and snippets.

@harsh183
Created March 30, 2026 17:56
Show Gist options
  • Select an option

  • Save harsh183/7d098272e9555dac725fde5a323557a7 to your computer and use it in GitHub Desktop.

Select an option

Save harsh183/7d098272e9555dac725fde5a323557a7 to your computer and use it in GitHub Desktop.
Quick command to automatically find the parent branch to stack as a base branch when creating a PR on GitHub
#!/usr/bin/env ruby
current = `git branch --show-current`.strip
branches = `git for-each-ref --format='%(refname:short)' refs/heads/`.split
branches.reject! { |b| b == current }
base = branches
.map { |b| [b, `git rev-list --count #{b}..#{current}`.strip.to_i] }
.min_by { |_, count| count }
&.first
if base
puts "Base: #{base}"
exec "gh", "pr", "create", "-B", base, *ARGV
else
exec "gh", "pr", "create", *ARGV
end
@harsh183

Copy link
Copy Markdown
Author

Usage:

$ gh_stack
Base: prev_branch
[gh pr interactive cli]

instead of

$ gh pr create -B prev_branch
[gh pr interactive cli]

@harsh183

harsh183 commented Mar 30, 2026

Copy link
Copy Markdown
Author

This also works if the base branch is master

$ gh_stack
Base: master
[gh pr interactive cli]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment