StorybookをCIでビルドしてPull Requestにコメントさせたらレビュー効率がアップする
最近Reactコンポーネントを実装、修正する機会が多い。コードレビューのときにコード的には大丈夫そうだけど見た目がどんな動きをするか気になるときがあり、レビュー時にStorybookを確認したい場面が増えた。
branchをcheckoutすれば手元で見れるが、自分も修正途中のときに面倒くさい。
https://circleci.com/docs/2.0/artifacts/ 現在利用しているCircleCIにはartifactsという成果物を一定期間永続化できる機能がある。
解決方法として、StorybookをビルドしたHTMLファイルをartifactsに置き、index.htmlまでのURLをプルリクエストにコメントするという方法をとった。
ほぼこちらを参考に実装。https://qiita.com/resessh/items/38ef6492d0cf21facec8
手順としては以下。
- 環境変数からPull Request番号を取得
- GitHubのAPIからPull Requestのターゲット(マージ先)ブランチを取得
- ターゲットブランチとのgit diffにコンポーネントの修正があるか判断
- 修正があればStorybookをビルドする
- GitHub APIを叩いてStorybookまでのURLをPull Requestにコメント
上記のリンクではPull RequestへのコメントはJavaScriptで行っているが、全部shell scriptで書いた。
#!/bin/sh
set -eu
PULL_REQUEST_ID=$(echo ${CIRCLE_PULL_REQUEST} | awk -F'/' '{print $NF}')if [ -z "${PULL_REQUEST_ID}" ]; then
echo "Skip building storybook."
exit 0
fi
# Get pull request target branch
TARGET_BRANCH=$(curl -H "Authorization: Bearer ${GITHUB_TOKEN}" "<https://api.github.com/repos/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}/pulls/${PULL_REQUEST_ID}>" | jq '.base.ref' | tr -d '"')# Check fixed components in git diff
git fetch origin ${TARGET_BRANCH}
COMPONENT_FIXED=0
git diff origin/${TARGET_BRANCH}...HEAD --name-only | grep 'client/components/' || COMPONENT_FIXED=$?
if [ "${COMPONENT_FIXED}" != "0" ]; then
echo "Skip building storybook because components not fixed."
exit 0
fi
# build Storybook
$(npm bin)/build-storybook -c client/.storybook -o public/storybook --quiet
# add comment to pull request
COMMENT=":link: [Storybook](<https://$>{CIRCLE_BUILD_NUM}-${REPO_NUMBER}-gh.circle-artifacts.com/0/storybook/index.html)";
curl -X POST \\
-H "Content-type: application/json" -H "Accept: application/json" \\
-H "Authorization: Bearer ${GITHUB_TOKEN}" \\
-d "{ \\"body\\": \\"${COMMENT}\\" }" \\
"<https://api.github.com/repos/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}/issues/${PULL_REQUEST_ID}/comments>"
version: 2.0
jobs:
build_storybook:
docker:
- image: circleci/node:10.13.0-browsers
resource_class: small
steps:
- checkout
- run:
name: Build Storybook
command: |
npm install
client/bin/build_storybook.sh
environment:
REPO_NUMBER: [CircleCI repository number]
- store_artifacts:
path: public/storybook
destination: storybook
workflows:
version: 2
build:
jobs:
- build_storybook
ちなみにGitHub Actionsはartifactsはあるもののzipでのダウンロードにしか対応していないので今のところ実現できない。今後に期待。https://github.com/actions/upload-artifact/issues/3