Created
February 26, 2015 04:43
-
-
Save yhara/99d1dfd3564afa1d0b08 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# | |
# `git pr-get 37` => Fetch Pull Resuest #37 and create branch `pr-37` | |
# | |
# Requirements: | |
# Ruby | |
# | |
# Install: | |
# $ chmod +x git-pr-get | |
# $ mv git-pr-get (somewhere listed in PATH) | |
# $ gem i git octokit | |
# $ git pr-get # List open PRs | |
# $ git pr-get 37 # Fetch PR #37 and create branch `pr-37` | |
# | |
require 'git' | |
require 'octokit' | |
require 'pp' | |
def error(msg) | |
warn "Error: #{msg}" | |
exit | |
end | |
# Detect github repo from git remote origin | |
def get_repo(g) | |
remote = g.remotes.find{|x| x.name == "origin"} | |
if remote.nil? | |
error "remote `origin` not found" | |
end | |
url = remote.url | |
if url !~ %r{\Ahttps://github.com/(.*?).git\z} | |
error "remote `origin` not a github repo: #{url}" | |
end | |
return $1 | |
end | |
def show_pr(pr) | |
printf "- #%d %s (by @%s)\n", | |
pr[:number], pr[:title], pr[:user][:login] | |
end | |
g = Git.open(".") | |
repo = get_repo(g) | |
if ARGV.size == 0 | |
puts "Usage: git pr-get NUMBER" | |
# Show existing pull requests | |
prs = Octokit.pull_requests(repo, state: "open") | |
prs.each{|pr| show_pr(pr)} | |
else | |
# Fetch info about the PR | |
n = ARGV[0].to_i | |
pr = Octokit.pull_request(repo, n) | |
show_pr(pr) | |
git_url = pr[:head][:repo][:git_url] | |
unless git_url =~ %r{git://github.com/(.*?)/(.*?).git} | |
error "could not parse git_url: #{git_url.inspect}" | |
end | |
owner, name = $1, $2 | |
# Create remote by author name | |
remote = g.remotes.find{|x| x.name == owner} | |
unless remote | |
clone_url = pr[:head][:repo][:clone_url] | |
g.add_remote(owner, clone_url) | |
puts "Added remote `#{owner}` (#{clone_url})" | |
end | |
# Create local PR branch | |
remote.fetch | |
system "git", "checkout", "-b", "pr-#{n}", pr[:head][:sha] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment