Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions +plans/UV-MIGRATION.01.migrate-bec2format-from-poetry-to-uv.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Migrate bec2format from Poetry to uv

Replace Poetry with uv as project/dependency manager, following the setup of
the ToolSuite repo (tox only bootstraps `invoke` + `uv`, uv manages the project
venv from `uv.lock`, CI calls `uv run inv ...` directly via `astral-sh/setup-uv`).

This is commit 1 of 2: the locked package versions stay exactly as in the
current `poetry.lock`. Updating the dependencies follows in a separate commit
(`uv lock --upgrade`, GitHub Actions, MicroPython tag, invoke pin).

## Differences to ToolSuite

- bec2format is a library that others install (ToolSuite via
`bec2format @ git+https://github.com/baltech-ag/bec2format.git@...`, CI via
`pip install .`), so it needs a build backend. ToolSuite has none.
Backend: `uv_build` with `module-root = ""` (flat layout, no `src/`).
- `requires-python` stays a range (`>=3.10,<4.0`), not an exact version.
A `.python-version` file (`3.10`) makes uv create the dev venv with 3.10,
which is what CI tested before.

## Changes

1. `pyproject.toml`
- `[tool.poetry]` -> `[project]` (name, version, description, authors,
license, license-files, requires-python)
- `[tool.poetry.extras] aes` -> `[project.optional-dependencies] aes`
- `[tool.poetry.scripts]` -> `[project.scripts]`
- `[tool.poetry.dev-dependencies]` -> `[dependency-groups] dev`, plus `uv`
and `invoke` (as in ToolSuite); invoke limited to `>=2,<3`, which the tox
pin `invoke==2.0.0` enforced before (ToolSuite's dev group has no limit,
so its uv.lock already moved to invoke 3 while its tox.ini pins 2.2.0)
- build-system `poetry-core` -> `uv_build`, `[tool.uv.build-backend]
module-root = ""`
- lint excludes: add `.venv` / `.tox-venv` where the tools don't skip them
by default
2. `poetry.lock`, `poetry.toml` -> `uv.lock` (resolved with the versions from
`poetry.lock` pinned via a temporary `constraint-dependencies`), new
`.python-version`
3. `tox.ini`: ToolSuite pattern (`envdir = .tox-venv`, `skip_install`,
deps `invoke==2.0.0` + `uv`, command `uv run --all-extras inv {posargs}`).
`minversion` goes down from 4.4.12 to 3.28 (as in ToolSuite, `envlist`
instead of `env_list`): with tox 3 installed locally, a tox 4 minversion
makes tox 3 provision tox 4 into the `[testenv]` envdir `.tox-venv`, and
tox 4 then fails recreating its own running venv there.
4. `tasks.py`: `install` -> `uv sync --all-extras`, `poetry check` ->
`uv lock --check`
5. CI `verify-bec2format.yml`: `setup-python` + tox cache + tox replaced by
`astral-sh/setup-uv` (enable-cache) + `uv run`; the CPython interpreter in
the verify matrix becomes `.venv/bin/python`, and bec2format is installed
non-editable into it with `uv sync --all-extras --no-editable` (verifies the
uv_build package build)
6. `.gitignore`: `.venv/`, `.tox-venv/`; `.idea/watcherTasks.xml`: black/isort
from `.venv/Scripts`
7. `README.md`: add `uv add git+...@<tag>` as install option; fix the pip
line to `@<tag>` (pip ignores `#<tag>` and installs master HEAD; Poetry's
`#<tag>` is correct and stays)

## Verification

- Wheel built by uv_build contains the same files and metadata as the one built
by poetry-core (compare file list and METADATA).
- `tox -- test` and `tox -- lint` pass (same results as before the migration).
- `uv.lock` contains the same versions as `poetry.lock`.
- appnotes scripts run with `.venv` Python.
56 changes: 56 additions & 0 deletions +plans/UV-MIGRATION.02.switch-linting-to-ruff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Switch linting and formatting to ruff

Commit 2 on top of the uv migration, before the dependency update: replace
black, isort, flake8 and its plugins (flake8-awesome, flake8-simplify,
Flake8-pyproject) with ruff. mypy stays, ruff is no type checker.

Doing this before the update keeps the update simple: flake8-logging-format
(via flake8-awesome) imports `pkg_resources` without declaring setuptools, so
after `uv lock --upgrade` (setuptools no longer pulled in transitively,
`pkg_resources` removed in setuptools 82) it would need a `setuptools<82` pin;
Black 26 would need `target-version = ["py310"]`. Both tools are gone first.

## Changes

1. `pyproject.toml`
- dev group: drop black, isort, flake8, flake8-awesome, flake8-simplify,
Flake8-pyproject, add ruff
- `[tool.black]`, `[tool.isort]`, `[tool.flake8]` -> `[tool.ruff]`:
- excludes: vendored `ecdsa` / `pyaes` in the appnotes (Markdown is not
excluded: ruff also formats the Python code blocks in `README.md`)
- black's `skip-magic-trailing-comma = true` is not carried over: with
ruff's default a trailing comma keeps a collection split one entry per
line (otherwise everything that fits is joined into one line, e.g. the
dict in the README example). Doesn't change the formatting of the code;
isort's `split-on-trailing-comma` stays at its matching default too
- rule selection mapped from the flake8 plugins: E/W/F (pycodestyle,
pyflakes), I (isort), S (bandit), T10 (breakpoint), B (bugbear),
A (builtins), C4 (comprehensions), ERA (eradicate), G (logging-format),
T20 (print), PT (pytest-style), RET (return), N (pep8-naming),
SIM (simplify)
- ignore E501 (formatter handles line length), `tests/*`: S101
- B904 stays enabled (opt-in in flake8-bugbear, default in ruff)
- no ruff equivalent, dropped: flake8-annotations-complexity,
flake8-expression-complexity, flake8-pytest; flake8-requirements and
flake8-if-expr were already ignored (I900, IF100)
2. `tasks.py` `lint`: `ruff check [--fix]`, `ruff format [--check]`, mypy,
`uv lock --check`
3. `.idea/watcherTasks.xml`: black watcher -> `ruff format`, isort watcher ->
`ruff check --select I --fix` (same on-save behavior as before)
4. All files formatted once with `ruff format`:
- `README.md` code examples (blank line after the import, trailing
whitespace removed)
- `bec2file.py`: double space in the `typing` import removed (black
flagged this already); `bec2file.py`, `bf3file.py`, `configid.py`:
implicitly concatenated strings joined where they fit on one line (the one
style difference to black, not configurable)
5. `uv lock` without upgrade (60 -> 20 packages, no version changes, ruff
added at its latest version)

## Verification

- Fresh `.venv`: `tox -- test` passes.
- `tox -- lint`: findings equivalent to the flake8 run (plus B904, minus the
checks without ruff equivalent); `ruff format --check` flags the file black
flagged plus the implicit string concatenations ruff joins.
- No `.venv` / `.tox-venv` / vendored files are linted.
39 changes: 39 additions & 0 deletions +plans/UV-MIGRATION.03.resolve-ruff-findings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Resolve the ruff findings

Commit 3 on top of the uv migration and the ruff switch: bring `ruff check`
from 73 findings to zero. None of the findings is a bug; they all existed with
flake8 already. The mypy errors (44) follow in commit 4, lint in CI in
commit 5, the dependency update comes last (commit 7).

Constraint: bec2format also runs on MicroPython (typing is mocked, no
`contextlib` by default, `raise ... from err` prints "exception chaining not
supported" there, see `py/vm.c` `MP_BC_RAISE_FROM`).

## Changes

1. Intentional code, marked instead of changed:
- `bec2format/__init__.py` F401 (re-exports = public API, plus imports for
side effects): per-file ignore
- appnotes: example scripts assert and print on purpose -> per-file ignore
S101/T201; `import register_crypto_plugin` (registers the crypto
implementation, side effect) and `AES128 as AES128Base` -> `# noqa`
- N802 on public API names (`crc8404B`, `create_AES128`,
`register_AES128`, ...) -> `# noqa` at the definitions, the rule stays
active for new code
2. Style findings: RET505/RET506 via `ruff check --fix`, SIM102, C408, C417,
RET504 by hand
3. SIM105 (`contextlib.suppress`): `# noqa`, contextlib is not available on
MicroPython by default
4. SIM115 (open without `with`, 3x in `bf3file.py`): `# noqa`, the file is
only opened when a path is given and closed in `finally`
5. B904 (9x, `raise` inside `except` without `from`): rule switched off in
the config, as it was with flake8 (opt-in in flake8-bugbear). `from err`
would make MicroPython print "exception chaining not supported" whenever
such an error is raised, and CPython already shows the original error via
implicit chaining.

## Verification

- `ruff check` and `ruff format --check` pass
- `tox -- test` passes, appnotes scripts run with `.venv` Python
- mypy: still the same 44 errors
63 changes: 63 additions & 0 deletions +plans/UV-MIGRATION.04.fix-mypy-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Fix the mypy errors

Commit 4: bring mypy (1.17, the version before the dependency update) from
43 errors to zero, so `inv lint` passes completely. Commit 5 then adds lint
to CI, the dependency update (mypy 2) follows in commit 7.

None of the errors is a runtime bug; annotations don't match what the code
does. Constraint: `bec2format/` also runs on MicroPython, where `typing` is a
mock. Annotations are not evaluated there (MicroPython `py/compile.c`: the
annotation of `x: y` / `x: y = z` is ignored, a bare `x: y` is a no-op and
`x: y = z` compiles like `x = z`, also for attribute targets), but runtime
typing constructs are off limits (`cast()`, `TypeVar()` would crash;
`TYPE_CHECKING` would be truthy). Module-level aliases with builtin generics
(`tuple[...]`) are evaluated and would fail there, too.

## Changes

A. `crypto.py` registry (18 errors): annotations used the registry variables
(`Type[__AES128]`, `-> __AES128`) instead of the base classes -> annotate
with `AES128`, `PublicEccKey`, `PrivateEccKey`. `AES128` gets an
annotation-only `iv` declaration: `AesEncryptorMixin` sets `cipher.iv`
before each use, the bundled implementations read `_iv` (None = zero IV,
so behavior is identical); kept because implementations registered by
users may read `.iv` (ToolSuite registers none).
B. `bf3file.py` path-or-file-object (10 errors): narrow with `isinstance()`
directly in the `open(...) if ... else ...` expressions (mypy doesn't
narrow through a stored bool). The `is_file_path` flag is gone, the
`finally` blocks use the same `isinstance()` check (the parameters are
never reassigned).
C. `appnotes/install_dependencies.py` (1): `mip` exists only on MicroPython ->
mypy override `ignore_missing_imports`.
D. `configid.py` (4): `customer`/`device` annotated `Optional[int]` as in
`create_from_prj_settings`; `version: int` in the constructor (every caller
passes an int, also in ToolSuite; `str()` would crash on None anyway);
`__str__` keeps its `is_baltech_naming_scheme` check and uses the new
helper `_format_cfgid()`, which always returns `str` (shared with
`cfgid_str`, which returns None outside the Baltech naming scheme); `device_id = 0` instead of `"0000"` (same
output with `:04`). ToolSuite's `bal27/formats/test_configid.py`, which
tests bec2format's `ConfigId`, passes against the change.
E. `bf3file.py` others (4):
- `conf_dict_to_list` returns the deletion entries with `None` value or
content on purpose (handled by `conf_dict_to_tlv`) -> return type with
`Optional`, local lists annotated accordingly
- `bf2_unpack_payload`: no `None` start marker anymore, the first line of
each block sets its start address (`if not cur_block` / `elif gap`),
same logic; covered by `tests/test_bf2_unpack_payload.py`
F. `bec2file.py` (6):
- `InitEccAuthBlock.pack/unpack` narrowed `ext_encryptors` to
`KeySelectorEncryptor`, but `Bec2File` passes all encryptors ->
`Iterable[Encryptor]` as in the base class; the filter lambdas check
`isinstance(e, KeySelectorEncryptor)` (always true there, since
`select_encryptor` only filters `EccEncryptor` instances)
- `AUTH_BLOCK_CLS_MAP` as explicit dict (mypy joins the three classes to
`type` in the comprehension)
- `AuthBlock.tag` is never None (subclasses define `TAG`,
`UnknownAuthBlock` passes its tag) -> `self.tag: int` with a targeted
`# type: ignore[assignment]`

## Verification

- `tox -- lint` exit code 0 (ruff check, ruff format --check, mypy, uv lock)
- `tox -- test` passes on a fresh `.venv`, appnotes scripts run with `.venv`
Python, ToolSuite's ConfigId test passes
18 changes: 18 additions & 0 deletions +plans/UV-MIGRATION.05.lint-in-ci.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Run lint in CI

Commit 5: now that `inv lint` passes (ruff check, ruff format --check, mypy,
`uv lock --check`), run it in CI so new findings fail the build.

## Changes

- `.github/workflows/verify-bec2format.yml`: new job `lint`, set up like the
`test` job (checkout, `astral-sh/setup-uv` with cache, Python from
`.python-version`), running `uv run --all-extras inv lint`. `--all-extras`
because mypy needs `cryptography` for `bec2format/extras/aes.py`.
Same action versions and runner as the other jobs; the dependency update
(commit 7) bumps all jobs together.

## Verification

- Locally: `uv run --all-extras inv lint` exits with 0.
- CI only after a push (not part of this session).
23 changes: 23 additions & 0 deletions +plans/UV-MIGRATION.06.fix-micropython-spelling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Spell MicroPython consistently

Commit 6, before the dependency update (commit 7): write "MicroPython" (capital
P) wherever the project name appears in prose.

## Changes

- `README.md`: headings, the compatibility line, the CLI note
- `.github/workflows/verify-bec2format.yml`: step names
- `.github/workflows/build_micropython.sh`: comments
- `appnotes/install_dependencies.py`: error message
- `bec2format/cli.py`: module docstring

Unchanged on purpose, because they are identifiers, paths or names that are
lowercase by definition: `sys.implementation.name == "micropython"`, module and
function names (`micropython_compatibility_quirks`,
`install_micropython_dependencies`), the `micropython_tag` variable and
`cache-micropython` step id, the `micropython` binary and repository paths,
`$HOME/.micropython/lib` and URLs.

Two typos in the touched places are fixed along the way: `mananger` in the
error message and `install_depepencies.py` in the README's MicroPython
example (the script is `install_dependencies.py`).
73 changes: 73 additions & 0 deletions +plans/UV-MIGRATION.07.update-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Update dependencies

Commit 7, the last one on the branch: update all dependencies to their
latest versions, except invoke, which stays on major version 2. It comes
after the uv migration, the ruff switch, the ruff/mypy cleanup, the CI lint
job and the MicroPython spelling fix, so the risky part (new versions never run in CI before) can be
reverted on its own, and the new lint job checks it right away.

## Changes

1. `tox.ini`: `invoke==2.0.0` -> `invoke==2.2.1` (latest 2.x; the dev group
limit `invoke>=2,<3` is already part of the uv migration commit)
2. `uv lock --upgrade` (all other packages to latest; ruff is already current
from the ruff commit)
3. CI `verify-bec2format.yml`, all three jobs (test, lint, verify):
- `actions/checkout@v4` -> `@v7`
- `astral-sh/setup-uv@v8.1.0` -> `@v10.2.0` (no floating major tags since
v8; the v9/v10 breaking changes only change defaults of `prune-cache` and
`enable-cache: auto`, we set `enable-cache: true` explicitly)
- `micropython_tag` `v1.25.0` -> `v1.29.0`
- runner `ubuntu-24.04` -> `ubuntu-26.04`
4. Lint change caused by the new versions (lint passes with the old ones,
see commit 4): mypy 2 no longer treats
`bytearray` as `bytes` (strict bytes by default). `CustKeyEncryptor.encrypt()`
assigned a `bytearray` to the `bytes` parameter `plaintext` -> separate
`buffer` variable, converted once, no behavior change.

5. MicroPython v1.25.0 -> v1.29.0, release notes v1.26.0 to v1.29.0 checked.
The only breaking change that affects this project (v1.29.0):
`str.encode()`/`bytes.decode()` only accept "utf-8", "utf8" and "ascii"
and raise `LookupError` otherwise (before, unsupported encodings silently
fell back to UTF-8). The ecdsa copy in the appnotes defines
`b(s) = s.encode("latin-1")` (replacement for `six.b` from the MicroPython
port) in der.py, ecdsa.py, keys.py and util.py; it runs on import, so all
four appnotes failed on v1.29.0. `b()` now builds the bytes from the code
points (`bytes(ord(c) for c in s)`), i.e. latin-1 without the codec: same
result on CPython, and also fixes non-ASCII input on older MicroPython
versions (`b("\xff")` was `b"\xc3\xbf"` there). `bec2format/` itself
only uses `.decode()` without encoding (UTF-8).
Other breaking changes only concern hardware ports (esp32, stm32, nrf,
powerpc) and the unix port's MICROPY_FORCE_32BIT flag, which the build
script doesn't use; `__all__` in star imports (v1.26) and the check for
incompletely constructed exceptions (v1.28) don't apply (no star imports,
no custom exception `__init__`).
Verified by building the unix port v1.25.0 and v1.29.0 (WSL, Ubuntu
20.04) like CI and running the four appnotes on both: v1.29.0 failed
before the fix, all pass after it.
6. `README.md`: the "Tested with the Unix port" line only named v1.20.0 on
Ubuntu 20.04 (CI used that until 2024-10, then v1.24.1 and since 2025-05
v1.25.0, both on Ubuntu 24.04). It now lists all combinations CI tested,
plus v1.29.0 on Ubuntu 26.04 from this commit on. The current code runs on
all four MicroPython versions (unix port built in WSL/Ubuntu 20.04, all
appnotes pass), so "Compatible with MicroPython >= 1.20.0" still holds.

Switching to ruff first avoided two more adjustments this update would have
needed with the old tools (Black 26 `target-version`, and a `setuptools<82`
pin for flake8-logging-format's `pkg_resources` import).

## Not changed

- `uv_build` (`>=0.12.20,<0.13`) and pyaes 1.6.1 are already current.
- The ecdsa copy in `appnotes/register_crypto_plugin/ecdsa` (0.18.0, patched
for MicroPython) is not re-ported to 0.19.2: the only change relevant to the
appnotes is a DER truncation check (CVE-2026-33936), and the appnotes are not
shipped.

## Verification

- Fresh `.venv` (an exact sync; `uv run` keeps packages that dropped out of
the lock): `tox -- test` passes.
- `tox -- lint` passes with the new versions (ruff, mypy 2, lock check),
as it does in the CI lint job added in commit 5.
- appnotes scripts run with `.venv` Python.
6 changes: 3 additions & 3 deletions .github/workflows/build_micropython.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ cd "$base_path" || exit
# install dependencies
sudo apt-get install build-essential libffi-dev git pkg-config

# clone micropython
# clone MicroPython
git clone --branch $micropython_version https://github.com/micropython/micropython
cd micropython || exit

# compile micropython cross compiler
# compile MicroPython cross compiler
cd mpy-cross || exit
make
cd ..

# compile micropython unix port
# compile MicroPython unix port
cd ports/unix || exit
make submodules
make
Expand Down
Loading
Loading