# Development

`btdl` follows the same tooling contract as
[binary-tidal-py](https://git.binarycollective.de/binary/binary-tidal-py):
`uv` as the only env manager, the four linters, mypy, pytest with a
coverage floor, Forgejo CI, tag-driven publishing.

## Layout

```default
src/btdl/
  app.py            the typer app, global options, group wiring
  command_util.py   guard (exit codes), the shared --json flag,
                    the run's Ctrl-C cancel scope
  context.py        Ctx (the per-invocation state)
  config.py         CliOptions + env fallbacks (BTDL_*)
  client.py         the TidalClient factory (tests point it at a fake)
  links.py          @file / stdin list expansion for the batch verbs
  output.py         emit/render_rows/render_table + the column
                    builders
  progress.py       the stderr progress-event renderer
  commands/         one module per command family, each
                    `register(app: typer.Typer) -> None`
tests/
  conftest.py       the client (MagicMock) + invoke fixtures
  test_cmd_*.py     per-family tests (the mocked-client layer)
  test_core.py      the core modules (guard, progress, config, app)
  test_e2e.py       the local Tidal stand-in (real TidalClient)
  test_e2e_*.py     the e2e families over the stand-in
```

## The gate

Everything must be green before committing:

```console
$ uv run ruff check . && uv run black --check . && uv run isort --check-only . \
    && uv run flake8 . && uv run mypy src/btdl && uv run pytest
```

- **black / isort / ruff / flake8** — line length 88, ruff mirrors
  flake8’s E/F/W plus import sorting, so the linters never disagree.
- **mypy** — `src/btdl`, `disallow_untyped_defs` on; it has caught
  real bugs in this codebase (typer’s parameter types, library
  signature drift), so new code must type-check.
- **pytest** — `--cov-fail-under=90`. Two layers: the per-command
  files run the *real* app (`CliRunner`) with the client factory
  monkeypatched to a `MagicMock` (the `client` + `invoke` fixtures in
  `tests/conftest.py`; model new command tests on
  `tests/test_cmd_ids.py`); the `test_e2e*.py` layer runs the real
  `TidalClient` against a local `ThreadingHTTPServer` stand-in on
  127.0.0.1 — no external network, no tokens. The stand-in’s media
  bytes are not audio, so the ffmpeg-bound passes (verification,
  remux, tags) are off by default; the real-audio pins are marked
  and run wherever ffmpeg/ffprobe are on PATH (CI carries neither
  and skips them).

Per-file while working (the full-suite coverage gate is mid-build):

```console
$ uv run pytest tests/test_cmd_search.py -q --no-cov
```

## The test surface

The e2e surface is audited and closed. Every leaf command (67 of
them) carries JSON-mode and human-mode e2e coverage; every global
flag has a functional pin (not just a fail-fast); and the download
family’s kind × verb × preview matrix is pinned in full — `plan`,
`list` (shallow and `--deep`) and `download` over track, album,
playlist, mix and artist links, with and without `--preview`,
including the preview file’s naming, receipt and superset rule. The
docs’ command tables and the README’s tree are audited against the
live click tree (zero drift).

The library-coverage contract is audited the same way: every public
`TidalClient` facade method of the installed
[binary-tidal-py](https://git.binarycollective.de/binary/binary-tidal-py)
is either a command or a deliberate non-command. The four
non-commands, each pinned at its own layer:

- `device_login` — the one-call convenience wrapper of the
  two-step `start_device_login` + `finish_device_login` pair the
  `auth device-login` command runs (the host surfaces the URL and
  code itself, between the steps);
- `cancel` — the run’s SIGINT seam (the cancel scope’s
  `client.cancel()`), pinned by a real subprocess-SIGINT e2e
  (exit 130, the cancellation report, nothing delivered) plus the
  unit twins;
- `close` — the atexit lifecycle (the client’s connection pool),
  pinned in the unit layer (released once, idempotent);
- `ensure_logged_in` — the library’s own guard, called by the
  facade’s methods, no host surface.

The three offline reference commands (`qualities`, `auth clients`,
`maintain presets`) expose the library’s quality module, the OAuth
client registry and the transcode presets — library data, not
facade calls.

What stays unpinned — deliberately, not by oversight:

- the `--download-workers > 1` overlap depth and interleaving: the
  per-track part pool’s overlap IS pinned (the stand-in sees
  several media requests in flight at once, in the serial and the
  pool runs alike), but the in-flight peak and the interleaved
  ordering vary with scheduling;
- the output-lock CAS race: a two-process property;
- the `playback_many` fallback-reason rows: dead in the library
  (the batch facade does not fill them);
- the real static-CDN cover fetch: no stand-in can serve
  `resources.tidal.com` (the cover seam pins everything downstream
  of the URL, the pipeline’s own `artwork_url` binding redirected
  to the stand-in).

## CI

`.forgejo/workflows/ci.yml`:

- **Lint** — ruff, black, isort, flake8, mypy (Python 3.13);
- **Test** — pytest on **3.13** (`requires-python` is `>=3.13`;
  the library dropped 3.12 in 0.2.9);
- **Docs** — `sphinx-build -b html -W` (warnings are errors).

One runner-env gotcha the tests are built around: the runner sets
`GITHUB_ACTIONS`, which typer honours by forcing a rich terminal
even on pipes — rendered help/usage output arrives ANSI-escaped and
width-wrapped. Assertions on rendered help compare content through
`test_help_surface._plain_text` (strips the escapes, folds the
wraps), never the raw `res.output`.

## Docs

This site: Sphinx + MyST Markdown + the [Shibuya](https://shibuya.lepture.com/)
theme (the binarycollective house style, same as the library docs).

```console
$ uv sync --group dev
$ uv run sphinx-build -b html -W --keep-going docs docs/_build/html
$ python -m http.server -d docs/_build/html 8000
```

The build also renders the LLM-facing Markdown twins
(`llms.txt`, `llms-full.txt`, a `.html.md` per page) via
`sphinx-llm`, and every page’s footer shows the build’s identity —
`vX.Y.Z-<shorthash>` whenever the commit is known.

**Deployment (Coolify):** a static nginx container —
`docs/Dockerfile` (two stages: Sphinx build, then nginx on port 80),
with `docs/docker-compose.yml` as a ready-made service definition.
No runtime environment variables: the container serves static
files. Two *optional build args* shape the footer: `BTDL_VERSION`
(the version to show; defaults to `pyproject.toml` in the build
context) and `GIT_COMMIT` (the short build hash; Coolify wires it
from the webhook’s `CI_COMMIT_SHA`). `docs/README.md` in the
repository covers the container, the footer, and local builds.

## Releases

The tag owns the version (the library’s convention):

1. on `master` with the gate green: `uv version X.Y.Z`, commit;
2. `git tag vX.Y.Z`;
3. push `master` **and** the tag.

`publish.yml` (tag-triggered) re-aligns `pyproject.toml` with the tag
(a no-op for a well-formed release, a fail-fast on anything else),
builds the dists, publishes them to the Forgejo package registry, and
cuts the release with the dists attached.

## Commits

Conventional (kept for a later changelog integration):
`feat`, `fix`, `docs`, `refactor`, `perf`, `test`, `build`, `ci`,
`chore`; `!` + a `BREAKING CHANGE:` footer for breaking changes.
Subject = what/why; the body may carry the test count and coverage.
