🖤

GitHub ActionsでPR作成時にblackで自動フォーマットする

2021/08/28に公開

まとめ

下記を.github/workflowsにおいてcommitする

name: Code Formatter with black
on: [pull_request]
jobs:
  Format-Code:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v1
        with:
          ref: ${{ github.head_ref }}
      - name: setup black
        id: setup-black
        run: pip3 install black
      - name: execute black
        id: execute-black
        run: black .
      - name: check for modified files
        id: git-check
        run: echo ::set-output name=modified::$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi)
      - name: push changes
        id: push-changes
        if: steps.git-check.outputs.modified == 'true'
        run: |
          git config --global user.email "bot@example.com"
          git config --global user.name "bot"
          git remote set-url origin https://x-access-token:${{secrets.GITHUB_TOKEN}}@github.com/${{github.repository}}
          git commit -am "Automated changes"
          git push origin HEAD:${{github.event.pull_request.head.ref}}

user.emailとuser.nameはよしなに差し替えてください。

参考

Discussion