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

changed-files

Effortlessly track all changed files and directories relative to a target branch, the current branch (preceding commit or the last remote commit), multiple branches, or custom commits returning relative paths from the project root using this GitHub action.

Note

Table of contents

Features ๐Ÿš€

  • Fast execution, averaging 0-10 seconds.
  • Leverages either Github's REST API orโ€ฆ

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!

Top comments (0)