LoginSignup
5
0

More than 1 year has passed since last update.

phpcbfによる自動フォーマットをactionsでやる際のチップス

Posted at

概要

  • 前提
    • GitHubにpushしたらGitHub actionsでphpcsを実行する、自動フォーマットはしていない
  • この記事
    • phpcbfでフォーマットして問題なければgit commit実行に変更したい

actionsファイル解説

処理の流れは、コードをチェックアウトし、それに対してphpcbfでfix、修正しきれていないものがあればエラー、修正しきれていればコミットする。

モノレポやコード分量が多い場合は actions/checkout@v3 を使わずに自前でsparse-checkoutで変更分だけ持ってくると良い。

Setup PHP with tools

shivammathur/setup-php@v2で簡単にPHPと必要コンポーネントをざっくり導入する。

Format code

phpcbfで自動フォーマットする。
--standard オプションでphpcs.xmlにまとめたルールを実行できる。これがないとデフォルトのルールで実行されてしまう。

phpcbf --standard=phpcs.xml . || true

次に、末尾の || true について。
GitHub actionsは実行したコマンドのExit codeが0でないとエラー扱いでworkflowが終了してしまう。
https://docs.github.com/en/actions/creating-actions/setting-exit-codes-for-actions

phpcsの中の人によれば、phpcbf実行後のExit codeは以下の通りに分類される。
fixする対象のあるなしに関わらず先に進めたいので || true とした。
https://github.com/squizlabs/PHP_CodeSniffer/issues/1818#issuecomment-354420927

Exit code 0 is used to indicate that no fixable errors were found, so nothing was fixed
Exit code 1 is used to indicate that all fixable errors were fixed correctly
Exit code 2 is used to indicate that PHPCBF failed to fix some of the fixable errors it found
Exit code 3 is used for general script execution errors

参考

Lint

修正しきれなかったコードがあるかチェックする。
前のphpcbf実行時のExit code 2以上かのチェックができればここは不要だが今回はしなかった。

修正しきれなかった場合は手動で直して再pushする運用。
ここでエラーがなければ自動フォーマット分をcommitする

phpcs --standard=phpcs.xml .

Count changes

差分があればcommitするのでその確認。

実際のファイル

php-formatter.yml
name: php-Formatter
on: [push]
jobs:
  lint:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 1

      - name: Setup PHP with tools
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.0'
          tools: composer, phpcs, phpcbf

      - name: Format code
        run: |
          # fix対象ファイルがあればfixに成功してもExit code 1になるのでExit code 0にする
          phpcbf --standard=phpcs.xml . || true

      - name: Lint
        run: phpcs --standard=phpcs.xml .

      - name: Count changes
        id: changes
        run: |
          echo "::set-output name=count::$(git diff --name-only --diff-filter=AMR | wc -l)"
          git add $(git diff --name-only --diff-filter=AMR)

      - name: Commit and push
        if: steps.changes.outputs.count > 0
        run: |
          git config user.name github-actions
          git config user.email hogefuga@github.com
          git commit -m "fix php format"
          git push
5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0