GitHubのマージ済のブランチをCircleCIで定期的に削除する

前置き

マージ済のブランチは基本的に消しても問題ないので、GitHub上には進行中のブランチだけがあるきれいな状態に保ちたいところ。

PRをマージした後にブランチを消すボタンが出るんですが、チームで開発してるとどうしても消し忘れる人が1人はいるので 1CircleCIで定期的に消すようにしました

前提

  • GitHub
  • CircleCI 2.0

準備

GitHubにpushするための権限が必要なので「Settings -> Checkout SSH keys」でuser keyを追加してください

circleci.png

設定ファイル

毎日18:30にマージ済のブランチを自動で消すための設定です

.circleci/config.yml
version: 2

jobs:
  remove_merged_branches:
    working_directory: ~/app
    docker:
      - image: circleci/ruby # gitが入っていればなんでもいい

    steps:
      - checkout

      - run:
          name: Remove merged remote branches
          command: git branch -r --merged origin/master | grep -v -e origin/master -e origin/develop | sed -e 's% *origin/%%' | xargs --no-run-if-empty -I% git push --delete origin %
          # デフォルトの/bin/bash -eo pipefailだとマージ済ブランチが1つもない場合にgrepでexit 1されてジョブが失敗するので上書きする
          shell: /bin/bash

workflows:
  version: 2

  daily_branch_cleaner:
    triggers:
      - schedule:
          # NOTE: CircleCIはUTCで動いてるのでJSTにしたければ-9時間した時間を書く
          cron: "30 9 * * *" # JST 18:30
          filters:
            branches:
              only: develop
    jobs:
      - remove_merged_branches

備考

  • cronの時間やbranchはよしなに変えてください
  • 万が一スクリプトがバグって消したくないブランチが消えても泣かないように、GitHubでProtected branchの設定をしておくと安全です

  1. 人間は忘れる生き物なので仕方ないです 

Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.