DEV Community

Carlos V.
Carlos V.

Posted on

GitHub Action to run mypy on changed files only

Recently, I needed a way to perform Python static type checking using mypy only on "changed" files for a GitHub Pull Request.

So I googled a bit and found out this super useful action that you can use it in your workflow right away.

GitHub logo tj-actions / changed-files

:octocat: Github action to retrieve all (added, copied, modified, deleted, renamed, type changed, unmerged, unknown) files and directories.

Ubuntu Mac OS Windows Public workflows that use this action.

Codacy Badge CI Update release version.

All Contributors

Screen Shot 2021-11-19 at 4 59 21 PM

changed-files

Retrieve all changed files and directories relative to a target branch, preceeding commit or the last remote commit returning a relative paths from the project root.

Table of contents

Features

  • Fast execution (0-10 seconds on average).
  • Easy to debug.
  • Scales to large repositories.
  • Supports Git submodules.
  • Escaped JSON output which can be used to run matrix jobs based on changed files.
  • List changed directories.
  • Restrict the max depth of changed directories.
  • Write outputs to a .txt or .json file at a specified location for further processing.
  • Monorepos (Fetches a fixed number of commits).
  • Supports all platforms (Linux, MacOS, Windows).
  • GitHub-hosted runners support
  • GitHub Enterprise Server support.
  • self-hosted runners support.
  • List all files and directories that have changed
    • Between the current pull request branch and the last commit on the…

And after customizing some options like filter only *.py files, I was able to run mypy passing the changed files as argument.

It's worth to mention that I needed to include --ignore-missing-imports argument to mypy because I'm not scanning the whole repo, only some files. The goal of course is to check them all. However, a lot of fixes should be made before it's ready.

This solution can be very useful to you if you want to include static type checking for new files on a legacy project where existing files will be fixed little by little.

name: "mypy check"
on: [pull_request]

jobs:

  static-type-check:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - uses: actions/setup-python@v3
      with:
        python-version: '3.x'
    - run: pip install mypy  # you can pin your preferred version
    - name: Get Python changed files
      id: changed-py-files
      uses: tj-actions/changed-files@v23
      with:
        files: |
          *.py
          **/*.py
    - name: Run if any of the listed files above is changed
      if: steps.changed-py-files.outputs.any_changed == 'true'
      run: mypy ${{ steps.changed-py-files.outputs.all_changed_files }} --ignore-missing-imports

Enter fullscreen mode Exit fullscreen mode

Happy type-safety!

Oldest comments (0)