This lesson uses Aspect’s rules_lint
to give automatic formatting and linting using ruff
, a fast Rust-based re-implementation of the black
formatter and flake8
.
Change the application code to contain some formatting and linting issues:
- Use a mix of single and double quotes, which the formatter can safely fix without asking.
- Add an unused import, which the formatter can auto-fix. However, since imports can have side effects, this may be unsafe.
- Make a mistaken formatting string,
{scheme
(missing the closing curly brace), which the linter points out but has to be fixed manually.
So the file should now look like this:
import requests
from mylib import say
import os
x = requests.get('{scheme://w3schools.com/python/demopage.htm'.format("https"))
say.moo_stamped(x.text)
Formatting
Before running the formatter, add the code to git
if you haven’t already. You only want to format files that are tracked by version control.
% git init
Now run the format target, using the syntax sugar for the //:format
label:
bazel run format
You can see the quotes are now consistently double-quotes in the file.
Linting
Run bazel lint app/...
to lint all targets beneath the app
folder.
The lint
command is provided by the Aspect CLI. If your org doesn’t use it, you can simulate a similar workflow with a script you check in.
You should see a result like the following. It reports both lint errors introduced, and offers to fix one of them.
You could choose “Show Diff” in this interactive prompt if you’d like to preview the change which is about to be applied. Choose “Yes” or “All” to update the source file. The unused import os
is now removed from the source file. The other lint error still appears if you run bazel lint app/...
again.
The exit code from bazel lint
is non-zero. This indicates that ruff has been configured to report these as errors, and would block your workflow if linting is run as a CI step for example. You can use the pyproject.toml
file to configure ruff differently.