Check for code quality issues inside your CI/CD pipelines


Python Clean Code Tip:

Check the quality of your code inside your CI pipeline.

Use:

  1. flake8 - style guide enforcer
  2. black - code formatting
  3. isort - optimize imports
  4. bandit - check for security vulnerabilities
  5. safety - check for security vulnerabilities of dependencies

Github Actions Example 👇

name: Check code quality
on: [push]

jobs:
  code-quality:
    strategy:
      fail-fast: false
    matrix:
      python-version: [3.9]
      poetry-version: [1.1.8]
      os: [ubuntu-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v2
      - uses:
        with:   actions/setup-python@v2
           python-version:   ${{ matrix. python-version }}
      - name: Run image
        uses: abatilo/[email protected]
        with:
          poetry-version: ${{ matrix. poetry-version }}
      - name: Install dependencies
        run: poetry install
      - name: Run black
        run: poetry run black . --check
      - name: Run isort
        run: poetry run isort . --check-only --profile black
      - name: Run flake8
        run: poetry run flake8 .
      - name: Run bandit
        run: poetry run bandit .
      - name: Run saftey
        run: poetry run safety check

It's a good idea to couple this with pre-commit hooks:

  • pre-commit - format code with black and isort
  • CI pipeline - run black and isort with check flags to ensure that code has been properly formatted

In other words, you shouldn't actually format any code in the CI pipeline. You just want to verify that formatting happened via pre-commit.