4
2

[Swift] PRをマージした時にSwiftFormatを実行するGithub Actionsを作成する

Last updated at Posted at 2023-09-23

PRがmainにマージされた時にSwiftFormatを実行したら思ったより便利だったので、備忘録として残しておきます。

実装

SwiftFormatを実行するためにMintを使用しています。

name: Format

on:
  push:
    branches:
      - main

jobs:
  format:
    name: SwiftFormat
    runs-on: macos-13
    env:
      MINT_PATH: mint/lib
      MINT_LINK_PATH: mint/bin
    steps:
      - uses: actions/checkout@v4
      
      - name: Select Xcode 15.0
        run: sudo xcode-select -s /Applications/Xcode_15.0.app
        
      - name: Install mint
        run: brew install mint
        
      - name: Cache Mint packages
        uses: actions/cache@v2
        with:
          path: mint
          key: ${{ runner.os }}-mint-${{ hashFiles('**/Mintfile') }}
          restore-keys: |
            ${{ runner.os }}-mint-
            
      - name: Format
        run: mint run swiftformat .
        
      - uses: stefanzweifel/git-auto-commit-action@v4
        with:
          commit_message: Run swift-format
          branch: 'main'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Mintのキャッシュの部分はこちらの記事を参考にさせていただきました🙇

MintでPackageをビルドするときのXcodeのバージョンを指定します

      - name: Select Xcode 15.0
        run: sudo xcode-select -s /Applications/Xcode_15.0.app

そしてHomebrewでMintをインストールします

      - name: Install mint
        run: brew install mint

ここでMintでビルド済みのパッケージをキャッシュします。キャッシュをしないとワークフローを実行するごとにSwiftFormatが再ビルドされてしまい、ワークフローの実行に3分ほどかかってしまいます(キャッシュをしたら20~40秒ほど).

      - name: Cache Mint packages
        uses: actions/cache@v2
        with:
          path: mint
          key: ${{ runner.os }}-mint-${{ hashFiles('**/Mintfile') }}
          restore-keys: |
            ${{ runner.os }}-mint-

そして最後にswiftformatを実行し、差分が出た場合はmainブランチにpushします。

     - uses: stefanzweifel/git-auto-commit-action@v4
        with:
          commit_message: Run swift-format
          branch: 'main'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

以上です!

PRをmainにマージする or mainにpushすることで、このようにSwiftFormatでコード整形をして、コミットをしてくれます。便利ですね。
スクリーンショット 2023-09-23 19.28.32.png

4
2
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
4
2