How to run github action tests when a python file (.py) anywhere in the project changed?

Viewed 663

How can I have a github action that runs pytest when ANY python file (.py file) anywhere in the project changes? This project contains a mix of different languages and I only want to run pytest if a python file changed somewhere in the project (in ANY directory at any level within the project).

name: Test Python Tests

on:
  push:
    paths:
      - what to put here???? 

jobs:
  build-and-run:
    steps:
    - uses: actions/checkout@v1
    - name: Update Conda environment with "requirements.yml"
      uses: matthewrmshin/conda-action@v1
      with:
        args: conda env update -f ./requirements.yml
    - name: Run "pytest" with the Conda environment
      uses: matthewrmshin/conda-action@v1
      with:
        args: pytest
2 Answers

Basically, what you need is the git diff information and read all changed files from there.

GitHub Actions' Push Event doesn't include a list of modified files. That means, you have to always trigger a workflow run on push and then check for the files that changed via the normal REST API. https://docs.github.com/en/actions/reference/events-that-trigger-workflows#push

Note: The webhook payload available to GitHub Actions does not include the added, removed, and modified attributes in the commit object. You can retrieve the full commit object using the REST API. For more information, see "Get a single commit"".

You could use a JavaScript Action in combination with the OctoKit Client (https://github.com/actions/toolkit). If you use the one from the toolkit, it will already be authenticated.

OctoKit can be used to make REST Calls fairly easy. See the default response 200 at https://docs.github.com/en/rest/reference/repos#get-a-commit

...
  "files": [
    {
      "filename": "file1.txt",
      "additions": 10,
      "deletions": 2,
      "changes": 12,
      "status": "modified",
      "raw_url": "https://github.com/octocat/Hello-World/raw/7ca483543807a51b6079e54ac4cc392bc29ae284/file1.txt",
      "blob_url": "https://github.com/octocat/Hello-World/blob/7ca483543807a51b6079e54ac4cc392bc29ae284/file1.txt",
      "patch": "@@ -29,7 +29,7 @@\n....."
    }
  ]
...

If the files-field contains a .py-file, cancel the workflow. You can cancel the workflow directly from the JS itself:

  core.setFailed(error.message);

With core being your OctoKit client.

Related