0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel Pintの実行をGitHub Actionsで自動化

Last updated at Posted at 2024-10-02

はじめに

個人開発アプリ作成において、Laravel Pintの実行をGitHub Actionsで自動化してみたので、そのソースコードや躓いた内容を記載します。Laravelのソースコードの整形を自動化したい方には参考になるかもしれません。

Laravel Pintとは

Laravelのコードスタイルの自動整形ツールです。
Readoubleでは、下記のように記載されています。

Laravel Pint(ピント:PHP+lint)は、ミニマリストのための主張を持ったPHPコードスタイルフィクサです。PintはPHP-CS-Fixer上に構築されており、あなたのコードスタイルがクリーンで一貫したものになるよう、シンプルにします。
Pintは、すべての新しいLaravelアプリケーションに自動的にインストールされますので、すぐに使い始めることができます。デフォルトで、Pintは設定を必要とせず、Laravelの主張を取り入れたコーディングスタイルに従い、コードスタイルの問題を修正します。

下記のコマンドを実行すると、コードスタイルの修正が行われます。

./vendor/bin/pint

始めてPintを実行する場合、大量にコードが修正されることがあるため、--testオプションを付けることを推奨します。

./vendor/bin/pint --test

GitHub Actionsとは

あらかじめ定義した処理と条件の組合せ(=ワークフロー/Workflow)を自動化するGitHub公式の機能です。
GitHub Actionsではリポジトリに対するプッシュなどの処理をトリガーとして、専用のWorkflowに定義しておいた処理を自動で実行します。

GitHub Actions は、ビルド、テスト、デプロイのパイプラインを自動化できる継続的インテグレーションと継続的デリバリー (CI/CD) のプラットフォームです。 リポジトリに対するすべての pull request をビルドしてテストしたり、マージされた pull request を運用環境にデプロイしたりするワークフローを作成できます。

用語(ワークフロー、ジョブ、ステップなど)の説明は省きます。
下記の記事がわかりやすかったです。

ソースコード

実際に私が記載したソースコードを共有します。

.github/workflows/pint.yml
name: Run Laravel Pint

on: [pull_request]

jobs:
  pint:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.ref }}

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.2'
          extensions: bcmath, ctype, curl, dom, fileinfo, gd, intl, json, mbstring, openssl, pdo_mysql, pdo_pgsql, tokenizer, xml
          tools: composer:v2.5.4

      - name: Install Composer dependencies
        run: composer install --prefer-dist --no-progress --no-suggest --ansi

      - name: Run Laravel Pint
        run: vendor/bin/pint

      - name: Commit and Push changes
        run: |
          git config --global user.name "GitHub Actions[bot]"
          git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add -A
          git commit -m "Automated code format" || exit 0
          git push
  • name: Run Laravel Pint
    このワークフローに「Run Laravel Pint」という名前を付けています。
  • on: [pull_request]
    プルリクエストが作成された際にワークフローが実行されます。
  • jobs:
    「pint」というジョブが定義されています。
    • runs-on: ubuntu-latest
      ジョブはubuntu-latestという最新のUbuntu環境で実行されます。
    • steps:
      ジョブ内で実行される各ステップが定義されています。
      • - name: Checkout
        GitHub Actionsがリポジトリのコードをチェックアウトします。actions/checkout@v4アクションを使用してリポジトリの内容を取得します。
        ref: ${{ github.event.pull_request.head.ref }}により、プルリクエストのブランチを取得し、そのブランチをチェックアウトします。
      • - name: Setup PHP
        PHPのセットアップを行います。shivammathur/setup-php@v2アクションを使用してPHP 8.2をインストールします。
        extensionsでは拡張機能をインストールします。
        toolsではComposerのバージョンを指定し、ここではcomposer:v2.5.4をインストールします。
      • - name: Install Composer dependencies
        依存パッケージをインストールします。composer install --prefer-dist --no-progress --no-suggest --ansiコマンドを使用して、Composerの依存関係をインストールします。
        --prefer-distは、ソースコードではなく、事前にパッケージ化されたファイルを優先的に使用するオプションです。
        --no-progress, --no-suggestは、ログ出力を軽減するためのオプションです。
      • - name: Run Laravel Pint
        実際にLaravel Pintを実行します。vendor/bin/pintコマンドを実行し、コードのフォーマットチェックや自動整形を行います。
      • - name: Commit and Push changes
        フォーマットされた変更を自動的にコミットし、リモートリポジトリにプッシュします。
        git config --globalで、GitHub Actionsのbotユーザーとしての名前とメールアドレスを設定します。
        git add -Aで全ての変更をステージングし、git commit -m "Automated code format"でコミットします。|| exit 0は、コミットが失敗してもジョブを終了させないための保険として使用されています(フォーマットの変更がない場合、git commitは何もせずにエラーを返すため)。
        最後にgit pushでリモートリポジトリに変更をプッシュします。

躓いたエラー・不具合

インデントを間違えていた

ymlファイルは、インデントの位置によりデータ構造が決まります。インデントを間違えると、当然エラーになります。

エラー詳細

スクリーンショット 2024-10-02 15.05.20.png

Invalid workflow file
No steps defined in `steps` and no workflow called in `uses` for the following jobs: pint

スクリーンショット 2024-10-02 15.06.39.png

Invalid workflow file
You have an error in your yaml syntax on line 10
エラー解消

No steps defined in 'steps' and no workflow called in 'uses' for the following jobs: pintを解消
スクリーンショット 2024-10-02 15.52.10.png

You have an error in your yaml syntax on line 10を解消
スクリーンショット 2024-10-02 15.53.22.png

phpのバージョンを間違えていた

PHPのセットアップのステップでPHPのバージョンが正しく設定されていないとエラーになります。

エラー詳細

スクリーンショット 2024-10-02 15.15.00.png

Run composer install --prefer-dist --no-progress --no-suggest --ansi
You are using the deprecated option "--no-suggest". It has no effect and will break in Composer 3.
Installing dependencies from lock file (including require-dev)
Verifying lock file contents can be installed on current platform.
Your lock file does not contain a compatible set of packages. Please run composer update.

  Problem 1
    - carbonphp/carbon-doctrine-types is locked to version 3.2.0 and an update of this package was not requested.
    - carbonphp/carbon-doctrine-types 3.2.0 requires php ^8.1 -> your php version (8.0.30) does not satisfy that requirement.
Error: Your lock file does not contain a compatible set of packages. Please run composer update.
エラー解消

リポジトリで使用されているPHPのバージョンと、pint.ymlのPHPのバージョンを一致させれば解消できます。php -vコマンドでPHPのバージョンを確認し、ソースコードを修正しましょう。
スクリーンショット 2024-10-02 15.59.34.png

Laravel Pint実行時、--testオプションを付けるとエラーになる場合がある

ワークフロー自体が正常に実行されている(Laravel Pintによるチェックは正常に実行されている)場合でも、vendor/bin/pintコマンドに--testオプションを付けるとエラーになる場合があります。
コードスタイルに問題があると、ワークフローは「失敗(エラー)」として記録されます。(コードスタイルに問題ない場合は「成功」となります。)

エラー詳細

スクリーンショット 2024-10-02 16.13.06.png

Run vendor/bin/pint --test

  .........................⨯...⨯..⨯⨯⨯⨯..⨯..........⨯⨯⨯.⨯................⨯.....
  ⨯...................⨯..⨯..⨯⨯...⨯..⨯..⨯⨯⨯.⨯...⨯..⨯..⨯⨯⨯..................⨯.⨯⨯
  ⨯

  ──────────────────────────────────────────────────────────────────── Laravel  
    FAIL   ........................................ 153 files, 32 style issues  
  ⨯ app/Http/Controllers/Admin/Auth/NewPasswordController.php method_chaining…  
  ⨯ app/Http/Controllers/Admin/Auth/PasswordResetLinkController.php method_ch…  
  ⨯ app/Http/Controllers/Admin/InquiryController.php method_chaining_indentat…  
  ⨯ app/Http/Controllers/Admin/OwnersController.php method_chaining_indentati…  
  ⨯ app/Http/Controllers/Owner/Auth/NewPasswordController.php method_chaining…  
  ⨯ app/Http/Controllers/Owner/Auth/PasswordResetLinkController.php method_ch…  
  ⨯ app/Http/Controllers/Owner/ImageController.php method_chaining_indentatio…  
  ⨯ app/Http/Controllers/Owner/ProductController.php method_chaining_indentat…  
  ⨯ app/Http/Controllers/Owner/ShopController.php method_chaining_indentation…  
  ⨯ app/Http/Controllers/ProfileController.php     method_chaining_indentation  
  ⨯ app/Http/Controllers/User/Auth/NewPasswordController.php method_chaining_…  
  ⨯ app/Http/Controllers/User/Auth/PasswordResetLinkController.php method_cha…  
  ⨯ app/Http/Controllers/User/CartController.php method_chaining_indentation,…  
  ⨯ app/Http/Controllers/User/InquiryController.php method_chaining_indentati…  
  ⨯ app/Http/Controllers/User/ItemController.php method_chaining_indentation,…  
  ⨯ app/Jobs/SendOrderedMail.php                   method_chaining_indentation  
  ⨯ app/Jobs/SendThanksMail.php                    method_chaining_indentation  
  ⨯ app/Models/Product.php method_chaining_indentation, unary_operator_spaces…  
  ⨯ app/Models/User.php                            method_chaining_indentation  
  ⨯ app/Services/CartService.php                   method_chaining_indentation  
  ⨯ app/Services/ImageService.php                                 concat_space  
  ⨯ database/migrations/2023_05_05_074226_create_shops_table.php class_defini…  
  ⨯ database/migrations/2023_05_11_102827_create_images_table.php class_defin…  
  ⨯ database/migrations/2023_05_12_085706_create_categories_table.php class_d…  
  ⨯ database/migrations/2023_05_12_101634_create_products_table.php class_def…  
  ⨯ database/migrations/2023_05_14_095122_create_stocks_table.php class_defin…  
  ⨯ database/migrations/2023_05_22_110715_create_carts_table.php class_defini…  
  ⨯ database/migrations/2023_06_06_115055_create_inquiries_table.php class_de…  
  ⨯ routes/admin.php        method_chaining_indentation, statement_indentation  
  ⨯ routes/auth.php                                method_chaining_indentation  
  ⨯ routes/owner.php        method_chaining_indentation, statement_indentation  
  ⨯ routes/web.php                                       statement_indentation  

Error: Process completed with exit code 1.
エラー解消

実行コマンドの--testオプションを削除した上で、GitHubの設定を追加すれば解消できます。

大量のソースコードが修正される場合があるので、要注意。

スクリーンショット 2024-10-02 16.16.40.png

権限不足によるエラー

権限が不足しているとエラーになるので、設定変更を行いましょう。

エラー詳細
Run git config --global user.name "GitHub Actions[bot]"
[automating_laravel_pint 79fbcac] Automated code format
 32 files changed, 202 insertions(+), 203 deletions(-)
remote: Permission to yuuhei-koutoku/laravel-ecsite.git denied to github-actions[bot].
fatal: unable to access 'https://github.com/yuuhei-koutoku/laravel-ecsite/': The requested URL returned error: 403
Error: Process completed with exit code 128.
エラー解消
  1. リポジトリのSettingsを押下
  2. Actionsのgeneralを押下
  3. Workflow permissionsのRead and write permissionsを選択し、Saveを押下

スクリーンショット 2024-10-02 16.26.13.png

成功時

Pull requests

プルリクエスト作成直後、ワークフローが実行されます。
スクリーンショット 2024-10-04 14.21.33.png

しばらく時間が経ち、All checks have passedが表示されればOKです。
スクリーンショット 2024-10-04 14.21.59.png

実際にコードスタイルの修正が行われた場合は、自動的にコミットされます。
スクリーンショット 2024-10-04 14.31.39.png
スクリーンショット 2024-10-04 14.32.29.png

Actions

ワークフローが成功すると、緑色のチェックマークが表示されます。👏
スクリーンショット 2024-10-02 16.46.51.png

さいごに

今まではプッシュを行う前に./vendor/bin/pintコマンドを実行していたのですが、それをGitHub Actionsを用いて自動化することで、かなり楽になりました。
費用対効果は高いので、取り組んでみて良かったと感じています。
GitHub Actionsは始めて使ってみました。
間違った説明やソースコードの改善点などあれば、ご指摘いただけると幸いです。
最後まで読んでいただき、ありがとうございました!

参考文献

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?