Skip to content

Instantly share code, notes, and snippets.

@huguesbr
Last active August 29, 2015 14:07
Show Gist options
  • Save huguesbr/d53dd2d74e6a60a4ecfa to your computer and use it in GitHub Desktop.
Save huguesbr/d53dd2d74e6a60a4ecfa to your computer and use it in GitHub Desktop.
create a pull request based on an issue number
#!/usr/bin/ruby
#
# create a pull request for current branch
#
# configure
# create a github token
# https://github.com/settings/applications#personal-access-tokens
# export GITHUB_TOKEN="xx"
# export GITHUB_USER="huguesbr"
# export GITHUB_REPO="xx/yy" (optional, otherwise use origin url)
#
# install
# sudo install ./pull-request.rb /usr/local/bin/pull-request
require 'Octokit'
require 'git'
require 'launchy'
abort('please set env GITHUB_TOKEN') if ENV['GITHUB_TOKEN'].nil?
g = Git.open(Dir.pwd)
options = {}
options[:branch] = g.current_branch
banner = "Usage: #{__FILE__} [options]"
OptionParser.new do |opts|
opts.banner = banner
opts.on("-b", "--branch branch_name", "Branch Name") do |b|
options[:branch] = b
end
end.parse!
branch_name = options[:branch]
if match = /^([^\/]+\/)?(?<issue_id>[0-9]+)-/.match(branch_name)
issue_id = match[:issue_id]
end
url = g.config('remote.origin.url')
origin = (match = /^git@github\.com:(.+)\.git/.match(url)) && match[1]
repo_name = [ENV['GITHUB_REPO'],origin].compact.first
client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN'])
client.agent.allow_undefined_methods = true
abort("please set env GITHUB_REPO (or fix origin)") if !repo_name
repo = client.repo repo_name
# issue
issues = repo.rels[:issues]
issue = issues.get(:uri => {:number => issue_id}).data
abort("unable to find issue #{issue_id}") if issue[:number].to_i != issue_id.to_i
labels = issue[:labels] + ['pending review']
issues.patch({labels: labels}, uri: {number: issue_id})
# pull request
pulls = repo.rels[:pulls]
pull = pulls.post({title: issue[:title], labels: labels, base: 'develop', head: branch_name, body: "#{issue[:body]} (##{issue_id})"}).data
Launchy.open(pull[:html_url])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment