Black formatter with GitHub Actions

Also, what are Github Actions and how to use them?

Daria Kolodzey
2 min readFeb 27, 2021

This post is an intro to GitHub Actions which features setup for black formatter for Python. Let’s dive in!

What are GitHub Actions?

GitHub Actions is a feature of GitHub that allows you to run workflows when something happens. For example, run formatter check on pull request.

How to add workflows to my repo?

Just put the descriptions of your workflows inside .github/workflows folder. Yes, you can have multiple workflows in one repo. Description of a workflow is a .yml file. You can find a minimal example with explanations in GitHub Actions documentation.

Let’s dive into black example!

I’ve created an example repo with a workflow that runs black. I’ve also created an example pull request with badly formatted code. You can see a failing check. Another pull request contains good code and the check passes.

The repo has the following structure:

black-example
├── .github
│ └── workflows
│ └── black.yml
├── LICENSE
├── README.md
└── requirements.txt

The files of interest are black.yml (our workflow) and requirements.txt (we use it inside our workflow). The workflow file contents is:

name: black
on: pull_request
jobs:
black:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v1
with:
python-version: 3.9
- run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- run: |
black --check --verbose .

The requirements.txt should contain black as one of the requirements. I’ve created the requrements.txt as follows:

python3.9 -m venv ~/.venvs/black-example
source ~/.venvs/black-example/bin/activate
pip install black
pip freeze > requirements.txt

I. e. created a virtual environment, installed black there and then generated requrements.txt with pip freeze.

Now we can see checks like this in pull requests to our repo:

Checks result for a pull request

--

--

No responses yet