Last active
August 29, 2015 14:09
-
-
Save mkamakura/9400294d68c97ae324ab to your computer and use it in GitHub Desktop.
デプロイ用Pull Request作成のHubotスクリプト
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
## WEB+DB PRESS Vol82. p116の写経です | |
## typoあると思います。(動くか確認してません) | |
GitHubApi = require 'github' | |
async = require 'async' | |
_ = require 'underscore' | |
module.exports = (robot) -> | |
config = | |
user: 'naoya' # 対象ユーザーは本スクリプトでは固定 | |
# どこからどこへpull requestするのか設定 | |
branch: | |
staging: | |
form: 'master' | |
to: 'deployment/staging' | |
production: | |
from: 'master' | |
to: 'deployment/production' | |
# 環境変数からAPIトークンを取得 | |
token = process.env.HUBOT_GITHUB_TOKEN | |
if !token | |
return robot.logger.error """ | |
deploy.coffee is not loaded due to missing cofiguraion | |
""" | |
# hubot deploy repo to productionに反応 | |
robot.respond /deploy ([\w-\.]+) to (\w+)/i, (msg) -> | |
github = new GitHubApi version: "3.0.0" | |
github.authenticate type: "oauth", token: token | |
repo = msg.match[1] | |
env = msg.match[2] | |
if not config.branch[env] | |
msg.send "No such environment: #{env}" | |
return | |
source_branch = config.branch[env].from | |
development_branch = config.branch[env].to | |
# asyncで非同期処理フローを簡潔に実装 | |
async.waterfall [ | |
(callback) -> | |
msg.send "Createing Pull Request: #{source_branch} -> #{deployment_branch}" | |
# Pull Requestの作成 | |
github.pullRequests.create | |
user: config.user | |
repo: repo | |
title: "#{new Date().toYMD('.')} #{env} deployment by #{msg.message.user.name}" | |
head: "#{config.user}:#{source_branch}" | |
base: deployment_branch | |
, (err, res) -> | |
if err? | |
callback err | |
else | |
callback null, { "response": res } | |
(context, callback) -> | |
# コミットログを取得して、チャットに出力 | |
github.pullRequests.getCommits | |
user: config.user | |
repo: repo | |
number: context["response"].number | |
per_page: 100 | |
, (err, res) -> | |
if err? | |
callback err | |
else | |
message = _.map res, (object) -> | |
message = object.commit.message.split("\n")[0] | |
return " #{object.author.login}: #{message}" | |
msg.send "#{res.length} commits will be deployed: \n" + messages.join("\n") | |
callback null, context | |
], (err, res) -> | |
if err? | |
msg.send "An error occured while deploying #{repo}: \n" + err.message | |
## ここまで | |
## 以下補足 | |
# Node.jsのgithubモジュールでGitHubAPIを叩いてPull Requestの作成、およびコミットログの取得を行う | |
# それらを非同期処理として順番に実行するためにasyncモジュールを利用する | |
# npmからgithub,async,underscoreのモジュールをインストールする | |
# 環境変数HUBOT_GITHUB_TOKENにGitHubAPIトークンを設定する | |
# > hubot deploy private-codes to production |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment