🐈

GitHub Actionsでgofumptを実行してcommitまで行い自動修正してもらう

に公開

モチベ

AI使わなくても機械的にAutoFixできる部分はガンガンやっていきたい。

.github/workflows/autofix-gofumpt.yml

name: Autofix Gofumpt

on:
  pull_request:
    types: [ opened, synchronize ]

env:
  GO_VERSION: "1.22.6"

jobs:
  format:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.head_ref }}
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: ${{ env.GO_VERSION }}

      - name: Install gofumpt
        run: go install mvdan.cc/gofumpt@latest

      - name: Run gofumpt
        id: gofumpt
        run: |
          gofumpt -d -e -l -w .
          if [ -n "$(git status --porcelain)" ]; then
            echo "changes_detected=true" >> $GITHUB_OUTPUT
          else
            echo "changes_detected=false" >> $GITHUB_OUTPUT
          fi
      - name: Commit changes
        if: steps.gofumpt.outputs.changes_detected == 'true'
        run: |
          git config --global user.name 'github-actions[bot]'
          git config --global user.email 'github-actions[bot]@users.noreply.github.com'
          git add .
          git commit -m "style: apply gofumpt formatting"
          git push

Check

GitHub Actions が Trigger されない

無限ループを防ぐためにそういう仕様。

BotにPushさせる必要がある。

Discussion