0
0

GitHub Actionsでpythonファイルの型チェック、文法エラーチェック、フォーマットチェックをする

Posted at

結論

以下のyamlを .github/workflows 以下に置く。

py_checker.yaml
name: 'Check python file'
run-name: 'Check types, syntax and format.'
on:
  push:
    branches:
      - "feature/*"
    paths: 'app.py'

jobs:
  mypy:
    runs-on: 'ubuntu-latest'

    steps:
      - name: 'Checkout repository'
        uses: 'actions/checkout@v4'
        with:
          submodules: false
          fetch-depth: 0

      - name: 'Set up python'
        uses: 'actions/setup-python@v5'
        with:
          python-version: '3.10'

      - name: 'Run image'
        uses: 'abatilo/actions-poetry@v2'
        with:
          poetry-version: '1.7.1'

      - name: 'Install dependencies'
        run: |
          poetry install --no-root

      - name: 'Check types'
        run: |
          mypy app.py
  flake8:
    runs-on: 'ubuntu-latest'

    steps:
      - name: 'Checkout repository'
        uses: 'actions/checkout@v4'
        with:
          submodules: false
          fetch-depth: 0

      - name: 'Set up python'
        uses: 'actions/setup-python@v5'
        with:
          python-version: '3.10'

      - name: 'Run image'
        uses: 'abatilo/actions-poetry@v2'
        with:
          poetry-version: '1.7.1'

      - name: 'Install dependencies'
        run: |
          poetry install --no-root

      - name: 'Apply linter'
        run: |
          flake8 --max-line-length 120 app.py
  black:
    runs-on: 'ubuntu-latest'

    steps:
      - name: 'Checkout repository'
        uses: 'actions/checkout@v4'
        with:
          submodules: false
          fetch-depth: 0

      - uses: 'rickstaa/action-black@v1'
        with:
          black_args: '--line-length 120 --skip-string-normalization --check --diff app.py'

注意点

  • 上記ファイルでは app.py だけをチェック対象にしているので、ソースコードが複数ファイルある場合は適切に指定する
  • 上記ファイルでは feature/* という命名のブランチのみを対象にしているので、必要ならそこも適宜書き換える
  • blackのコマンドも必要に応じて変える。ここではファイルに変更を加えない+文字列の引用符をシングルクオテーションからダブルクオテーションに直さない+1行の長さは120文字でフォーマットしている
0
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
0
0