GitHub Action で PR に何かして push する

先に結論

      - uses: actions/checkout@v2
        with:
          ref: ${{ github.event.pull_request.head.ref }}

やったこと

PR に対して特定の実行してそのPRにコミットしたい。 例えば code format とか

まぁ、最初 main とかでやるように雑にやってみた

      - name: Commit updated files
        run: |
          if ! git diff --exit-code --quiet
          then
            git add .
            git config --local user.email "nobody@example.com"
            git config --local user.name "File Update GitHub Workflow"
            git commit -m "Update Files"
            git push
          fi

で、まぁエラー

fatal: You are not currently on a branch.
To push the history leading to the current (detached HEAD)
state now, use

    git push origin HEAD:<name-of-remote-branch>

はいはい detached ね。みたいな気分で提案通り git push origin HEAD:<name-of-remote-branch> してみる

 git push origin HEAD:${GITHUB_REF#refs/heads/}

ダメだった

 ! [rejected]        HEAD -> xxxxxx (fetch first)
error: failed to push some refs to 'https://github.com/xxxxx/xxxxx'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

で、ちょっと調べてみる

Release v2.0.0 · actions/checkout · GitHub

  • Creates a local branch
    • No longer detached HEAD when checking out a branch
    • A local branch is created with the corresponding upstream branch set

checkout の action は detached しなくなってる。けど、まぁこれは main とかの話かなぁ

じゃぁなんで動かないんだと思ってさらに調べたら checkout 時に ref 指定できることを発見した。 ということで最初に書いた with ref 使えば動きました。

なんかネット調べてたら別途 checkout しろとかいろいろ情報錯綜してたのでちょっとハマった。