LoginSignup
26
25

More than 5 years have passed since last update.

Slack から Hubot 経由で GitHub のプルリクを作る

Last updated at Posted at 2015-04-27

Slack から Hubot 経由で GitHub のプルリクを作れるようにしました。【ChatOps用】Github上のプルリクを作るHubotスクリプト を参考にさせていただきながら、ブランチが階層掘ってある場合に対応させて、リポジトリも指定できるようにしています。

Hubot スクリプト

githubot を使うのでいれておく。
$ npm install githubot --save

github-create-pull.coffee
#
# Description:
#   create pull requests in a Github repository
#
# Dependencies:
#   "githubot": "0.4.x"
#
# Configuration:
#   HUBOT_GITHUB_TOKEN
#   HUBOT_GITHUB_API
#
# Commands:
#   hubot pr <base> from <compare> [repo:<repo_name>]
#

module.exports = (robot) ->

  github = require("githubot")(robot)

  unless (url_api_base = process.env.HUBOT_GITHUB_API)?
    url_api_base = "https://api.github.com"

  _getDate = ->
    theDate = new Date
    yyyy = theDate.getFullYear()
    mm = theDate.getMonth()+1 #January is 0!
    if mm < 10
      mm = "0" + mm
    dd = theDate.getDate()
    if dd < 10
      dd = "0" + dd
    yyyy + "." + mm + "." + dd

  robot.respond /pr (([-_\.0-9a-zA-Z]+\/)?([-_\.a-zA-z0-9\/]+)) from (([-_\.0-9a-zA-Z]+\/)?([-_\.a-zA-z0-9\/]+))(\srepo\:([-_\.0-9a-zA-Z]+))?$/i, (msg)->
    repo = msg.match[8] || "<デフォルトのリポジトリ>"
    head = msg.match[4]
    base = msg.match[1]
    environment = msg.match[1]

    url = "#{url_api_base}/repos/<自分のGitHubアカウント>/#{repo}/pulls" #GitHubAPIのURL

    account_name = msg.envelope.user.name || "anonymous" #このスクリプトを呼び出した人のSlackアカウント名
    channel_name = msg.envelope.room || "anonymous" #このスクリプトを呼び出したSlackのChannel

    title = "#{_getDate()} #{environment} deployment by #{account_name}"

    body = """
      ・Created By #{account_name} on #{channel_name} Channel
    """

    data = {
      "title": title
      "body": body
      "head": head
      "base": base
    }

    github.post url, data, (pull) ->
      msg.send "プルリク作ったよ! " + pull.html_url

<デフォルトのリポジトリ>、<自分のGitHubアカウント> をそれぞれ設定。

使い方

hubot pr <base> from <compare> [repo:<repo_name>]
例:hubot pr deployment/production from master repo:my-repo

<base><compare> はそれぞれブランチ名。オプションの repo:<repo_name> でリポジトリ指定ができます。repo:<repo_name> が省略されている場合は <デフォルトのリポジトリ> を対象リポジトリとします。

記法は GitHub 上でプルリクを作った時「into <base> from <compare>」という形で表示されるので、それにならいました。

おわり

Slack からプルリクを作ると次のようなメリットがあるかな~と思ってます。

  • プルリクしたときのタイトルなどが自動で設定できてルールの統一がしやすい
  • 誰かがプルリク作ったのに気づきやすい
  • プルリクに不慣れな人でもコマンド辞書登録でもしておけばなんとでもなる

リポジトリやブランチが固定でよい場合はそのあたりハードコーディングしてしまって、もう少し短いコマンドでプルリクができるようにしてもいいかもしれません。自分の環境ではブランチが固定ではないのでこのようにしました。

余談

テスト環境用のブランチに変更があった場合 dploy.io から自動でテストサーバーへデプロイされるようにしています。Slack からプルリク -> GitHub でマージ -> デプロイされる、という流れで、さらにテストサーバーへデプロイされたら dploy から Slack へ通知が飛ぶようにしています。便利。デプロイ目的のシンプルな運用なら CI 回さず dploy あたりもいいなと思います。

slack-pr.png

参考

26
25
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
25