GitHub の Pull Request 発行をもっとスマートに


モチベーション

  • コマンド一発・スクリプト実行で Pull Request を発行する

事前準備

hub コマンドのインストール

Mac へ

$ brew install hub

CentOS へ

cd /tmp
git clone https://github.com/github/hub.git
cd hub/
./script/build
cp hub /usr/local/bin/
  • go がないとエラーになる。その場合は、下記コマンドを実行し、go を入れる。
$ cd /tmp
$ curl https://storage.googleapis.com/golang/go1.4.linux-amd64.tar.gz 
$ sudo tar -C /usr/local -xzf  go1.4.linux-amd64.tar.gz

# .bash_profile に記載
export PATH=$PATH:/usr/local/go/bin
$ source ~/.bash_profile

コマンドラインからの Pull Request 発行

Pull Request のテンプレートファイルを用意

  • 下記のようなテンプレートファイルを用意する
    • プロジェクトに応じて好きなフォーマットを用意
.pullreqmessage.txt
[#ticket-no][WIP][Task/Bug]

## 対象チケット
https://github.com/user-name/hogehoge/ticket-no

## 対応内容

### PR ステータス
 - [ ] 実装完了
 - [ ] レビュー
 - [ ] レビュー指摘対応
 - [ ] 完了

master に対して Pull Request 実行

$ git branch
* work_branch
  master
  • Pull Request を発行(ちょっと長いがコマンド一発)
# user-name はリポジトリのある user-name に適宜変更する
$ hub pull-request --browse -F ~/.pullreqmessage.txt -b user-name:master -h user-name:$(git symbolic-ref --short HEAD)
# symbolic-ref の --short オプションが使用できない場合は下記
$ hub pull-request --browse -F ~/.pullreqmessage.txt -b user-name:master -h user-name:$(git rev-parse --abbrev-ref HEAD)

script 化

  • Redmine などのバグトラッキングシステムの使用を考慮し、スクリプト実行時にチケット番号を引数に渡すことで Pull Request のタイトルや本文にチケット番号を挿入するようにする
create_pullreq.sh
#!/bin/sh

if [ $# -ne 1 ]; then
  echo "指定された引数は$#個です。"
  echo "引数にチケット番号を渡してください。"
  exit 1
fi

if expr "$1" : '[0-9]*' > /dev/null ; then
  echo "チケット番号 $1 の Pull Request を作成します。"
else
  echo "チケット番号が不正です。数値を入力してください。"
  exit 1
fi


echo 'Create temporary format file.'
sed -e "s/ticket-no/$1/g" ~/.pullreqmessage.txt > ~/.pullreqmessage_temp.txt

echo 'Exec Pull Request'
hub pull-request --browse -F ~/.pullreqmessage_temp.txt -b user-name:master -h user-name:$(git symbolic-ref --short HEAD)

echo 'Delete temporary format file.'
rm ~/.pullreqmessage_temp.txt

スクリプトの実行 (使い方)

# 例: チケット番号 0000 用の Pull Request を作成する場合
$ sh create_pullreq.sh 0000

コマンド実行後

  • Pull Request を作成し、ページが表示される

SSH 接続先のサーバなどブラウザを開けない環境の場合

  • export BROWSER=echo を ~/.bash_profile に記載しておくと、ページを表示する代わりに Pull Request の URL を標準出力するよう変更できる。

参考