I moved a small Python library from Travis CI to GitHub Actions this week. For a project like this, CI only needs to install dependencies, run a linter, and run the tests. On public repositories Actions does it for free with one YAML file.
.github/workflows/ci.yml:
name: ci
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ['3.6', '3.7', '3.8']
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- uses: actions/cache@v2
with:
path: ~/.cache/pip
key: pip-${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('requirements*.txt') }}
restore-keys: |
pip-${{ runner.os }}-${{ matrix.python-version }}-
- name: Install
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt -r requirements-dev.txt
- name: Lint
run: flake8 .
- name: Test
run: pytest -q
requirements-dev.txt holds flake8 and pytest.
The matrix has the oldest and newest Python I support. The code also runs on a Pi with Raspberry Pi OS Buster, which has 3.7, so 3.7 stays in. fail-fast: false means a failure on 3.6 does not cancel the 3.8 job, so I see both results. The cache key comes from the requirements files: when they change, the cache is rebuilt, and restore-keys lets the new key start from an older cache. Actions are pinned to @v2. With @master, a change in the action can break the build without any change in my code.
The set-env change
On 1 October 2020 GitHub announced that the set-env and add-path workflow commands are deprecated because of a security problem, and will be disabled (changelog). If your workflow has lines like these, change them now:
# old, deprecated
- run: echo "::set-env name=APP_ENV::test"
# new: write to the environment file
- run: echo "APP_ENV=test" >> $GITHUB_ENV
# old
- run: echo "::add-path::$HOME/.local/bin"
# new
- run: echo "$HOME/.local/bin" >> $GITHUB_PATH
Third-party actions may also call these commands, so update them to their latest versions.
Secrets
Use repository secrets for tokens, and pass them only to the step that needs them:
- name: Publish
if: github.ref == 'refs/heads/main'
env:
TOKEN: ${{ secrets.DEPLOY_TOKEN }}
run: ./deploy.sh
Secrets are not passed to workflows triggered by pull requests from forks. That is on purpose.
What is still missing
GitHub-hosted runners are x86_64, and some of my code runs on ARM. QEMU in Docker or a self-hosted runner on a Pi would cover that. A self-hosted runner on a public repository can run code from anyone’s pull request, though, so I am not doing that. Tests that need GPIO or a camera stay manual for now.