GitHub Actions から git で commit & push

Update: 2022/4/13

actions/checkout/v3 の破壊的変更対応版

name: CI

on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - main
    paths-ignore:
      - "docs/**"

permissions:
  contents: write
  pull-requests: write

jobs:
  setup:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout repo
      uses: actions/checkout@v3
      with:
        fetch-depth: 0
        ref: ${{ github.event.pull_request.head.ref }}

    - name: Setup Node.js environment
      uses: actions/setup-node@v3
      with:
        node-version: 16

    - name: Setup development environment
      run: |
        npm install -g npm@8
        npm install

    - name: Commit updated files
      run: |
        git config core.filemode false
        if ! git diff --exit-code --quiet
        then
          git add -A
          git config user.name github-actions
          git config user.email action@github.com
          git commit -m "Commit updated files"
          git push
        fi

(以下は actions/checkout/v2 までの実装)

GitHub Actions で dotnet ef dbcontext scaffold した結果、差分があればそのまま commit しちゃいたいなーと思ったので。

- name: git commit & push
  run: |
    git config core.filemode false
    if ! git diff --exit-code --quiet
    then
      git add --update
      git config user.name github-actions
      git config user.email action@github.com
      git commit -m "Commit by github-actions"
      git push https://${{github.actor}}:${{secrets.GITHUB_TOKEN}}@github.com/${{github.repository}}.git HEAD:${{github.ref}}
    fi
  • git config core.filemode false: ファイルのパーミッション変更を無視。
  • if ! git diff --exit-code --quiet: git diff で何らかの差分がある時のみ実行。標準出力は --quiet で抑制。
  • git add --update: バージョン管理対象のファイルで差分があったものを全てインデックスに追加。
  • ${{github.actor}}: ワークフローの実行を開始したユーザー。
  • ${{github.ref}}: ワークフローの実行をトリガーしたブランチまたはタグ。