Search code examples
pythonyamlpytestgithub-actionstravis-ci

Pass environment variable to PyTest based on Github commit message


In .yml we can do

jobs:
    build-conda:
        if: "! contains(toJSON(github.event.commits.*.message), '[skip ci]')"

to skip a build if commit message contains [skip ci]. Likewise, I'd like to pass an environment variable to the Python test scripts, like so (pseudocode):

if "[my msg]" in github_commit_message:
    os.environ["MY_VAR"] = "1"
else:
    os.environ["MY_VAR"] = "0"

or just pass the whole github_commit_message to the env var. I'm using Github actions, but Travis is an option.


Solution

  • You can set a workflow environment variable based on whether the commit message contains a certain substring.

    For the example below, the variable CONTAINS_PYTHON is set to 'true' if the commit message contains the string [python].

    In the run step, the value is printed using python. Note that this assumes it is run on a runner that has python installed and on the PATH. This is the case for ubuntu-latest, but possibly not for self-hosted runners. Therefore, if you get a message like "python not found", make sure to also include the setup-python action.

    on: push
    
    jobs:
      test:
        runs-on: ubuntu-latest
        env:
          CONTAINS_PYTHON: ${{ contains(toJSON(github.event.commits.*.message), '[python]') }}
        steps:
          - run: python -c 'import os; print(os.getenv("CONTAINS_PYTHON"))'