Skip to main content

brash

Codemods that hold a Python codebase to its conventions. A linter can only report that a module constant is not Final or that a parameter is typed list where Iterable would do; brash rewrites the file. It is built on LibCST, which keeps every comment and blank line a rewrite does not touch.

brash is meant to run twice in a project, as a formatter does: once to apply (brash ., in the step that formats) and once to check (brash --check ., in the lint), so the repository stays as the codemods leave it and a change that drifts fails CI with the diff that fixes it. It came out of canopy, whose own code is held to it.

Install

brash needs Python 3.12 or later. Add it to a project as a dev dependency, or run it without installing:

uv add --dev brash        # or: pip install brash
uvx brash --check .       # run it once, installing nothing

Usage

brash .                                   # rewrite every Python file under the directory
brash --check .                           # change nothing: print the diff, exit 1 if there is one
brash --only final-constants src/app.py   # one codemod, one file; give --only again for each
brash --list                              # the codemods, brash's own and the project's

A directory gives its .py files and its scripts that open with a Python shebang, but nothing under a hidden directory, node_modules, site-packages, a venv, or a build's output. A file named outright is taken as it is, whatever its name, which is how a git hook runs brash on a commit's files.

The exit code is 0 when there is nothing to report, 1 when --check found a file a codemod would rewrite or a file could not be rewritten (a syntax error, say, reported by name), and 2 for a usage error.

Run brash before the formatter: a codemod adds an import where LibCST puts it and writes code unformatted, and ruff check --select I --fix and ruff format (or isort and black) then put both right. In a Makefile:

fmt:
	uv run brash .
	uv run ruff check --select I --fix .
	uv run ruff format .

lint:
	uv run ruff format --check .
	uv run ruff check .
	uv run brash --check .

Every codemod runs by default, and there is no configuration to turn one off: name the ones you want with --only.

The codemods

  • final-constants annotates every module constant Final, so the type checker refuses a second assignment: LIMIT = 3 becomes LIMIT: Final = 3, and NAMES: Sequence[str] = () becomes NAMES: Final[Sequence[str]] = (). A constant is an UPPER_CASE name bound once, by an assignment among the module's own statements. It leaves alone a lowercase name, which is how a module spells an object with state of its own (_log, router); a name bound again anywhere in the module (a second assignment, +=, del, a function's global); an object made to hold state whatever its name, such as a logger or a lock; and a TypeVar or an explicit TypeAlias.
  • type-aliases spells an implicit type alias as a type statement, which ruff does only for one annotated TypeAlias: Outcome = Literal["packed", "failed"] becomes type Outcome = Literal["packed", "failed"]. An alias is a CamelCase name bound once, among the module's own statements, to a Literal, a tuple, a Callable, or a union of types. A type statement makes a TypeAliasType, not the type it names, so it leaves alone a name the module reads outside an annotation (passed to get_args or isinstance, called, subclassed, held in another assignment); an Annotated[...] alias, whose metadata frameworks read as the program runs; and a union that may be of values, with no None, subscript, or builtin type in it. It sees one module at a time: where another module reads a rewritten alias at run time, that reader takes its __value__.
  • doc-comments writes the comment directly above a name as a Sphinx doc comment, which editors and doc tools attach to the name: # How often a run is resumed. above MAX_RESUMES: Final = 3 becomes #: How often a run is resumed.. The names are a module's constants and type aliases, among its own statements, and the fields of a @dataclass, a NamedTuple, or an enum. It leaves alone a field of any other class, since a pydantic model's description is the docstring below its field and a # above one is a note kept out of the schema; a comment above a function, an import, or a lowercase module object; a block that holds a #: line already, a directive to a tool (# noqa, # type:, # fmt:), or a section's banner; and a comment a blank line separates from the name. It cannot tell what a name is from why the code is so, so a note of the second kind is written with a blank line below it, or beside the value. The colon can push a line past the line length, which the lint then reports.
  • general-params widens a parameter annotated list, dict, set, or frozenset that its function only reads to the most general type its reads need: def total(costs: list[float]) whose body only sums costs becomes def total(costs: Iterable[float]). One pass is Iterable; len, in, a truth test, or more than one pass is Collection; indexing, slicing, or reversed of a list is Sequence; a dict only read is Mapping; and a set tested with in is AbstractSet, never Collection. It is deliberately narrow, since a wrong widening fails the type checker at a call site: it leaves alone a parameter used in any way it does not know to be a read (mutated, stored, returned, yielded, compared, or passed to any call but a few builtins whose names the module does not bind), one bound again or named by a nested function, one never read, one whose function returns the type it takes, every parameter of a function with a decorator but a few plain ones (a click command, an override), and a method of a class with a base, or of one the module derives another class from, which may override or be overridden. The import goes under if TYPE_CHECKING: where the module has that block and postpones its annotations.

Each is opinionated, and each is conservative: where it cannot be sure a rewrite is right, it leaves the code alone and reports nothing. The cases each one is held to are Python snippets, before and after, in tests/cases/.

Your project's own codemods

A convention that only your project has, such as naming an enum's member where its code compares a bare string, is a codemod of your own that brash runs with its own. Register it in the project's pyproject.toml, under the name the command line takes, as the module that holds it and the class's name there:

[tool.brash.codemods]
no-print = "codemods.no_print:NoPrint"

brash reads the nearest pyproject.toml, in the directory it runs from or one above it. The module is imported as any other is: from the environment brash runs in, or from the directory that holds the pyproject.toml, which brash puts last on the import path, so codemods/no_print.py beside it is found without being installed. A project's codemods run after brash's own, in the table's order, and --only and --list take them as they take brash's.

The class is a brash.command.Command, which is a libcst.codemod.VisitorBasedCodemodCommand: its visit_ and leave_ methods rewrite the tree, and AddImportsVisitor.add_needed_import adds an import it needs.

import libcst as cst
from brash.command import Command


class NoPrint(Command):
    """Remove every `print(...)` statement."""

    DESCRIPTION = "Remove `print` statements."

    @classmethod
    def wants(cls, source: str) -> bool:
        return "print(" in source

    def leave_Expr(self, original_node: cst.Expr, updated_node: cst.Expr) -> cst.Expr | cst.RemovalSentinel:
        match updated_node.value:
            case cst.Call(func=cst.Name(value="print")):
                return cst.RemoveFromParent()
            case _:
                return updated_node

Two rules keep the check honest and quick, for your codemods as for brash's:

  • A codemod leaves alone what it wrote. --check fails on any diff, so a second run over its own output must change nothing, also once the formatter has sorted the imports and formatted the result.
  • Say cheaply when a file is not yours. Parsing a module with LibCST and visiting it takes a few hundred times as long as reading it, and the lint runs every codemod over every file. Command.wants(source) answers from the text alone, before anything is parsed: final-constants decides from the stdlib's ast, so a file with no constant left to annotate is never parsed by LibCST. A codemod without a wants parses every file on every lint. A codemod held to some files alone says which in Command.covers(filename), asked before the text is read.

To test one, run a module's text through it: brash.run.rewrite(source, ["no-print"], codemods={"no-print": NoPrint}) gives the text back rewritten.

A rewrite to run once, such as a migration off an API, needs no entry: LibCST's own python -m libcst.tool codemod runs it, and you commit the result.

Adding a codemod to brash

A codemod belongs in brash when it holds code to a convention any Python project could adopt, and reads nothing but the module it rewrites.

  1. Write a module in src/brash/ holding a subclass of command.Command, with a DESCRIPTION.
  2. Add it to registry.CODEMODS under the name the command line takes.
  3. Test it in tests/, with its cases as Python snippets in tests/cases/<name>.md: under a ### heading, two python blocks are a module's text before and after, and one is text it must leave alone. helpers.cases(name) reads them for the test module, which runs each through run.rewrite(source, [name]). ruff does not format that file, so a snippet stays as the codemod writes it.
  4. Describe it in this README, under The codemods.
  5. Run make fmt and commit what it rewrote, since brash runs on its own code and the lint fails from then on wherever it would still change a file.

Development

uv sync      # install brash and its dev tools
make fmt     # brash on its own code, then ruff and rumdl
make lint    # every formatter's check, ruff, brash --check, pyrefly, rumdl, actionlint, zizmor
make test    # pytest

AGENTS.md holds the conventions. A release is a v* tag: the Publish workflow builds it, with the tag as its version, and publishes it to PyPI. The Tag workflow, run by hand, creates the tag on the head of main or a branch it is given: the next major, minor or patch version, or an exact tag.

License

MIT.

Metadata

Release files for brash 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for brash 0.1.0
File Size Uploaded Provenance Actions
brash-0.1.0.tar.gz 70.4 kB With provenance Details for brash-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for brash 0.1.0
File Interpreter ABI Platform Actions
brash-0.1.0-py3-none-any.whl Python 3 none any Details for brash-0.1.0-py3-none-any.whl

Total release size: 101.4 kB

Release files / brash-0.1.0.tar.gz

Download URL brash-0.1.0.tar.gz
Size 70.4 kB
Tags Source
SHA-256 checksum
How to use checksums
d0af90c8cea5870d149588045d1717a8a904fcb88bb6f7841b2af48d8ed3bbb8
BLAKE2b-256 checksum
How to use checksums
48a5054843647f8603f9bf8556f2f55dbeff577544ce00639e7029a179695ff5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / brash-0.1.0-py3-none-any.whl

Download URL brash-0.1.0-py3-none-any.whl
Size 30.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ac645d0aca036059bef1e99fd99bdad08229dd3c7225653be937ab6bb8d026d6
BLAKE2b-256 checksum
How to use checksums
1a845ada785f1055fd751722a98177a51e465457d6419aa85e633e9295663e78
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for brash 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for brash-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page