Compare commits

34 Commits
Author SHA1 Message Date
beefcarver 6dff7700e1 docs(agents): document Homebrew resource blocks and --check drift reporting 2026-11-15 11:30:33 -05:00
beefcarver 4c2f498e41 feat(packaging): check Homebrew formula has a resource per runtime dependency 2026-11-15 11:30:29 -05:00
beefcarver 86b22226e2 build: bump tap to vendored resources 2026-11-15 11:24:48 -05:00
beefcarver fffeb7f227 chore(homebrew): bump tap submodule to the 1.2.5 formula 2026-11-15 10:17:01 -05:00
beefcarver 4d5156f7d3 build(aur): bump to 1.2.5 and build from the release sdist 2026-11-15 10:16:58 -05:00
beefcarver 4fd688e673 fix(packaging): verify the release download against a CA bundle that exists
python-build-standalone's OpenSSL has default trust paths that need not
exist on the host, so urlopen failed with "unable to get local issuer
certificate" while browsers and curl accepted the same chain.  Fall back
to certifi when OpenSSL's default cafile is missing, and name the bundle
in use when verification still fails so the next occurrence is one line
to diagnose.
2026-11-15 09:51:01 -05:00
beefcarver 512c9a663f fix(packaging): resolve repo root from script directory 2026-11-15 09:45:48 -05:00
beefcarver 86da224448 chore(release): 1.2.5 2026-11-15 09:18:45 -05:00
beefcarver 29d2b75209 chore(tools): drop the unused ansi_art generator 2026-11-15 09:07:51 -05:00
beefcarver e000b296b5 chore(tools): move bump_packaging.py to the repository root 2026-11-15 09:07:42 -05:00
beefcarver cbce35441d ci(release): publish the release to tildeforge as well 2026-11-15 09:07:37 -05:00
beefcarver 11ae0e2f7d chore(release): 1.2.4 2026-11-14 17:28:24 -05:00
beefcarver 4d9058b9b2 ci(release): let a re-run override the existing release 2026-11-14 17:27:40 -05:00
beefcarver bdc9594408 chore(release): 1.2.3 2026-11-14 17:05:22 -05:00
beefcarver e493b02796 docs: document the packaging bump tool 2026-11-14 17:05:22 -05:00
beefcarver 77a7e2b513 feat(tools): add bump_packaging to sync the AUR package and tap 2026-11-14 17:05:22 -05:00
beefcarver a597aef8cd ci(release): publish the sdist and wheel with each release 2026-11-14 17:05:22 -05:00
beefcarver ba41a426cc docs(readme): document uv tool install into ~/.local/bin 2026-11-14 16:40:45 -05:00
beefcarver 94c9363e1f ci: add Forgejo workflows for tests and tagged releases 2026-11-14 09:35:17 -05:00
beefcarver 456f6afa44 docs(tools): note that ansi_art heroes must opt out of the gradient 2026-11-14 09:35:10 -05:00
beefcarver 06ae18a17d docs: document the contrib layout, tap submodule and developer workflow 2026-11-14 09:35:05 -05:00
beefcarver a2b5771922 build(contrib): move packaging under contrib and track the tap as a submodule 2026-11-14 09:34:55 -05:00
beefcarver 499f99113f test(header): assert every catalogue follows the palette gradient 2026-11-14 09:34:53 -05:00
beefcarver 6aac4f4085 refactor(providers): paint every hero with the palette gradient 2026-11-14 09:34:52 -05:00
beefcarver e6684ddbbd docs(readme): document makepkg install while AUR sign-ups are closed 2026-11-04 17:07:14 -05:00
beefcarver d06a94f388 build(aur): add generated .SRCINFO metadata 2026-11-04 17:05:04 -05:00
beefcarver 1f686ce7ba build(homebrew): add Homebrew tap formula and publishing notes 2026-11-04 17:04:52 -05:00
beefcarver cbcdfae8bf build(aur): add AUR packaging 2026-11-04 17:04:47 -05:00
beefcarver ffd67fc90d docs(readme): document Arch Linux AUR installation 2026-11-04 17:04:38 -05:00
beefcarver 941c744638 docs(readme): trim licence section to the licence reference 2026-11-04 16:22:54 -05:00
beefcarver 2753a7b6ba chore(release): bump version to 1.2.2 2026-11-04 16:20:38 -05:00
beefcarver dc6ed00abe docs(readme): document Nix installation, modules and the flake dev shell 2026-11-04 16:20:38 -05:00
beefcarver 12792b1265 build(nix): add flake with package, dev shell and NixOS/Home Manager modules 2026-11-04 16:20:38 -05:00
beefcarver 4346f75eac test: spawn fake mpv and parec helpers with sys.executable 2026-11-04 16:20:38 -05:00
29 changed files with 1245 additions and 348 deletions

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
name: release
on:
push:
tags:
- 'v*'
jobs:
tests:
uses: ./.forgejo/workflows/tests.yml
release:
needs: tests
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Check the tag matches the package version
run: |
python3 - <<'PY'
import os, tomllib
from pathlib import Path
pyproject = tomllib.loads(Path("pyproject.toml").read_text())["project"]["version"]
namespace = {}
exec(Path("beefy_player/__init__.py").read_text(), namespace)
tag = os.environ["FORGEJO_REF_NAME"].removeprefix("v")
assert pyproject == namespace["__version__"] == tag, (
pyproject, namespace["__version__"], tag
)
PY
- name: Setup uv
uses: astral-sh/[email protected]
# No `submodules:` on the checkout above, so the tap is empty here and the
# sdist below differs from a local `uv build` with the submodule populated.
# The published asset is therefore the authority: bump_packaging.py
# hashes the download, never a rebuild.
- name: Build the sdist and wheel
run: |
uv build --out-dir dist/release
# PKGBUILD and the tap formula name this exact file.
test -f "dist/release/beefy_player-${FORGEJO_REF_NAME#v}.tar.gz"
- name: Generate release notes
run: |
previous="$(git describe --tags --abbrev=0 "${FORGEJO_REF_NAME}^" 2>/dev/null || true)"
{
echo "beefy-player ${FORGEJO_REF_NAME#v}"
echo
if [ -n "$previous" ]; then
echo "Changes since $previous:"
git log --pretty='- %s (%h)' "$previous..$FORGEJO_REF_NAME"
else
echo "First tagged release."
fi
} > dist/notes.md
- name: Publish the release
uses: actions/forgejo-release@v2
with:
direction: upload
# A re-run finds the release it made last time and would otherwise die
# on `curl: (22) ... 409` when it tries to create it again. Override
# deletes and recreates the release (the tag survives, since it still
# matches the triggered SHA), so re-running this workflow is safe.
override: true
tag: ${{ forgejo.ref_name }}
title: ${{ forgejo.ref_name }}
release-notes-file: dist/notes.md
# Every packaging channel (AUR, the Homebrew tap and the flake) downloads
# its source from tildeforge, so the release is published there as well.
# That repository is not a mirror of this one: nothing reaches it unless
# it is pushed, hence the tag push before the upload. Pushing a tag that
# is already there and identical is a no-op, so this stays re-runnable.
- name: Push the tag to tildeforge
env:
TILDEFORGE_TOKEN: ${{ secrets.TILDEFORGE_TOKEN }}
run: |
git push \
"https://beefcarver:${TILDEFORGE_TOKEN}@tildeforge.dev/beefcarver/beefy-player.git" \
"refs/tags/${FORGEJO_REF_NAME}"
- name: Publish the release to tildeforge
uses: actions/forgejo-release@v2
with:
direction: upload
url: https://tildeforge.dev
repo: beefcarver/beefy-player
token: ${{ secrets.TILDEFORGE_TOKEN }}
override: true
tag: ${{ forgejo.ref_name }}
title: ${{ forgejo.ref_name }}
release-notes-file: dist/notes.md
+23
View File
@@ -0,0 +1,23 @@
name: tests
on:
push:
branches:
- '**'
workflow_call:
jobs:
pytest:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
- name: Setup uv
uses: astral-sh/[email protected]
- name: Install dependencies
run: uv sync --frozen
- name: Run the test suite
run: uv run --frozen pytest
+3
View File
@@ -0,0 +1,3 @@
[submodule "contrib/homebrew"]
path = contrib/homebrew
url = https://tildeforge.dev/beefcarver/homebrew
+35 -1
View File
@@ -31,8 +31,42 @@ synced `.venv/bin/python` explicitly.
```bash ```bash
uv sync # resync the environment (do this first) uv sync # resync the environment (do this first)
git submodule update --init # contrib/homebrew, the Homebrew tap
uv run pytest # full test suite uv run pytest # full test suite
uvx ruff check . # lint (ruff is not a project dependency) uvx ruff check . # lint (ruff is not a project dependency)
uv run beefy-player --list # station ids for the current catalogue uv run beefy-player --list # station ids for the current catalogue
uv run python tools/ansi_art.py ... # regenerate a provider's header art
``` ```
`uvx ruff check .` is the enforced lint and must pass. `ruff format` is **not**
enforced: the tree is not format-clean (54 files would change), so never run a
repo-wide reformat as a side effect of an unrelated change.
## Packaging
`contrib/` holds the two distribution channels, and they work differently:
- **`contrib/aur/`** — plain tracked files (`PKGBUILD`, `.SRCINFO`), edited
here. The package is not published in the AUR (sign-ups are closed), so
`makepkg -si` from a checkout is the only route. `_commit` pins the archive
the package builds from and must move with each release.
- **`contrib/homebrew/`** — a **git submodule** of the tap at
`https://tildeforge.dev/beefcarver/homebrew`, not a copy. Formula changes
belong in the tap repository; commit them there and bump the gitlink here.
Never add loose files under that path. The formula's Python dependencies are
vendored as `resource` blocks: Homebrew installs the sdist with `--no-deps`,
so a dependency that has no block (or whose constraint changed in
`pyproject.toml`) is simply missing at runtime. Regenerate them in the tap
with `brew update-python-resources Formula/b/beefy-player.rb`;
`uv run python bump_packaging.py <version> --check` reports a dependency
without one.
## Releases
`.forgejo/workflows/release.yml` fires on a `v*` tag: it asserts that the tag,
the `pyproject.toml` version and `beefy_player.__version__` all agree, then
publishes release notes. It does **not** touch packaging, so run
`uv run python bump_packaging.py <version>` after publishing: it rewrites
`contrib/aur/PKGBUILD` and regenerates its `.SRCINFO` from it, rewrites the tap
formula in `contrib/homebrew`, and with `--commit` commits the tap first and
then this repository. Both channels build the sdist attached to the release,
so they hash the same asset.
+175 -11
View File
@@ -46,6 +46,154 @@ as you type. Press `p` to switch catalogue without restarting.
## Installation ## Installation
### Nix
The flake builds the package, runs the test suite and wraps everything the app
calls at runtime (`mpv`, `ffmpeg`, and PulseAudio's `parec`/`pactl` — PipeWire
speaks the same protocol):
```bash
nix run git+https://tildeforge.dev/beefcarver/beefy-player # try it
nix profile install git+https://tildeforge.dev/beefcarver/beefy-player # install it
```
In a NixOS configuration:
```nix
{
inputs.beefy-player.url = "git+https://tildeforge.dev/beefcarver/beefy-player";
outputs = { nixpkgs, beefy-player, ... }: {
nixosConfigurations.myhost = nixpkgs.lib.nixosSystem {
modules = [
beefy-player.nixosModules.default
{
programs.beefy-player.enable = true;
}
];
};
};
}
```
Or, for a single user with Home Manager:
```nix
{
inputs.beefy-player.url = "git+https://tildeforge.dev/beefcarver/beefy-player";
outputs = { home-manager, beefy-player, ... }: {
homeConfigurations.me = home-manager.lib.homeManagerConfiguration {
modules = [
beefy-player.homeModules.default
{
programs.beefy-player.enable = true;
}
];
};
};
}
```
Both modules add one option, `programs.beefy-player.package`, so a pinned or
overridden build can be substituted for the flake's own. The raw package
(`packages.${system}.default`) and an overlay (`overlays.default`) are exported
too. From a checkout, `nix develop` gives you `uv`, `ruff` and the audio tools
for the usual `uv sync` / `uv run pytest` workflow; `nix build` builds and
tests the package.
### Homebrew
A tap lives at **[tildeforge.dev/beefcarver/homebrew](https://tildeforge.dev/beefcarver/homebrew)**.
Homebrew's one-argument `brew tap` assumes GitHub, so point it at the tap URL
and trust the formula explicitly:
```bash
brew tap beefcarver/homebrew https://tildeforge.dev/beefcarver/homebrew.git
brew trust --formula beefcarver/homebrew/beefy-player
brew install beefcarver/homebrew/beefy-player
```
`brew update` refreshes the tap and `brew upgrade` picks up new versions like
any other formula. The formula builds from source, with `numpy`, `pillow`,
`mpv` and `ffmpeg` pulled in as Homebrew dependencies.
No release is tagged yet, so the formula still carries a placeholder checksum
and cannot install from a tarball. Until the first `v*` tag is published, use
`brew install --HEAD beefcarver/homebrew/beefy-player`.
The tap is a git submodule at `contrib/homebrew`, so the formula and its
maintenance notes live in the tap repository itself; after cloning this one,
run `git submodule update --init` to check it out.
### Arch Linux
The `contrib/aur/PKGBUILD` here is AUR-ready, but the package is not published
in the AUR: the AUR has closed new sign-ups, so there is no account to push it
to. Build and install it from a checkout instead:
```bash
git clone https://tildeforge.dev/beefcarver/beefy-player
cd beefy-player/contrib/aur
makepkg -si # needs base-devel; builds, runs the test suite, installs
```
Once the AUR accepts new accounts again, the package can be published and
`paru -S beefy-player` / `yay -S beefy-player` will work; until then `makepkg`
is the only route. The `contrib/aur/PKGBUILD` is tracked and kept in sync with
every release either way.
The Python side is pulled in automatically. For audio, the output-synced
spectrum and image passthrough through tmux, install the optional tools too:
```bash
sudo pacman -S mpv ffmpeg libpulse tmux
```
### Standalone binary (no Nix, no packaging step)
`uv` can build the package and drop the executable in `~/.local/bin` — this is
the `pip install --user`-style install, without touching a system or project
environment:
```bash
uv tool install git+https://tildeforge.dev/beefcarver/beefy-player
# or, from a checkout:
uv tool install .
```
That creates its own isolated environment under `~/.local/share/uv/tools/` and
symlinks `beefy-player` into `~/.local/bin` (uv's default, which is also where
`pip install --user` writes on Linux). If uv warns that the directory is not on
your `PATH`:
```bash
uv tool update-shell # or add ~/.local/bin to PATH by hand
```
Then run `beefy-player` from anywhere. `uv tool upgrade beefy-player`
re-installs the current source; `uv tool uninstall beefy-player` removes it.
`pipx install git+https://tildeforge.dev/beefcarver/beefy-player` is the
`pipx` equivalent and lands in the same place.
Only the Python side is installed this way, so `mpv` / `ffmpeg` (and `parec`
for the synced spectrum) still come from your package manager; without them the
app runs but has no audio.
> On macOS, note that `~/.local/bin` is uv's and pipx's choice, not Python's:
> a `pip install --user` against Homebrew's Python uses
> `~/Library/Python/3.x/bin` instead.
### From source
`uv sync` installs into a project virtualenv, so the executable is
`.venv/bin/beefy-player` and is not on your `PATH`:
```bash
uv sync
uv run beefy-player # or: .venv/bin/beefy-player
```
## Usage ## Usage
```bash ```bash
@@ -172,20 +320,36 @@ These stay in the usual XDG locations on every platform, macOS included;
## Development ## Development
```bash ```bash
uv sync # create the environment uv sync # create the environment
uv run pytest # test suite git submodule update --init # contrib/homebrew, the Homebrew tap
uvx ruff check . # lint uv run pytest # test suite
uvx ruff check . # lint
``` ```
Each catalogue is a self-contained provider module under Each catalogue is a self-contained provider module under
`beefy_player/providers/`; `base.py` documents the interface. `tools/ansi_art.py` `beefy_player/providers/`; `base.py` documents the interface. Every catalogue's
converts a PNG logo into half-block ANSI art. On NixOS, `shell.nix` provides an header is a wordmark from the shared half-block font, and the header paints it
FHS shell for the same `uv sync` / `uv run` workflow. with the active palette gradient (`hero_gradient`, on by default) so all
thirteen follow the terminal's colours.
`uvx ruff check .` is the enforced lint. The tree is not `ruff format`-clean (54
files would change), so do not reformat it wholesale.
`uv run python bump_packaging.py <version>` keeps the AUR package and the Homebrew tap
formula in step with a release — it rewrites `PKGBUILD`, regenerates
`.SRCINFO` from it (no makepkg needed), rewrites the formula, and `--commit`s
both. `--check` reports drift without writing.
Pushes run the test suite (`.forgejo/workflows/tests.yml`); a `v*` tag runs
`release.yml`, which checks that the tag, `pyproject.toml` and
`beefy_player.__version__` agree and then publishes the release notes. It does
not touch packaging, so `contrib/aur/PKGBUILD` and the tap's formula are bumped
by hand for each release.
On NixOS, `nix develop` (or the older `shell.nix`) provides the same `uv sync` /
`uv run` workflow.
## Licence ## Licence
WTFPL — Do What The Fuck You Want To Public License, Version 2. See WTFPL — Do What The Fuck You Want To Public License, Version 2.
[LICENSE](LICENSE). SomaFM and its channel names are trademarks of See [LICENSE](LICENSE).
SomaFM.com, LLC. tilderadio belongs to the tildeverse community.
Terminal image rendering uses [Pillow](https://python-pillow.org/).
+1 -1
View File
@@ -1,3 +1,3 @@
"""Beefy Player — a flashy terminal player for internet radio.""" """Beefy Player — a flashy terminal player for internet radio."""
__version__ = "1.2.1" __version__ = "1.2.5"
+4 -3
View File
@@ -107,9 +107,10 @@ class RadioProvider(ABC):
#: Rows of header art drawn at the top left (rich markup is allowed). #: Rows of header art drawn at the top left (rich markup is allowed).
hero: tuple[str, ...] = () hero: tuple[str, ...] = ()
#: Paint :attr:`hero` with the app's spectrum gradient (a wordmark) instead #: Paint :attr:`hero` with the app's active palette gradient instead of the
#: of the colours the art carries itself (a picture). #: colours the art carries itself. On by default so every catalogue's
hero_gradient: bool = False #: wordmark follows the terminal's palette; a picture hero can turn it off.
hero_gradient: bool = True
#: Short lines printed beside the hero, top to bottom. #: Short lines printed beside the hero, top to bottom.
hero_lines: tuple[str, ...] = () hero_lines: tuple[str, ...] = ()
+2 -2
View File
@@ -29,8 +29,8 @@ class BassdriveProvider(RadioProvider):
station_source = "bassdrive.com + icecast status" station_source = "bassdrive.com + icecast status"
history_source = "icecast status (rolling)" history_source = "icecast status (rolling)"
# The wordmark in the station's own two blues, in the shared half-block # The wordmark in the shared half-block font, painted with the app's
# font; the caption is the station's own description. # palette gradient; the caption is the station's own description.
hero = hero_art.HERO hero = hero_art.HERO
hero_lines = ( hero_lines = (
"BASSDRIVE", "BASSDRIVE",
+4 -7
View File
@@ -1,14 +1,11 @@
"""Bassdrive's header hero: its wordmark in the station's two blues. """Bassdrive's header hero: its wordmark in the shared half-block font.
The logo paints "BASS" in the pale blue and "DRIVE" in the deeper one; those The header paints it with the app's active palette gradient, like every other
map onto the stock palette's bright cyan and cyan, so the wordmark still reads catalogue's wordmark, so the logo follows the terminal's colours.
as Bassdrive without hard-coded RGB.
""" """
from __future__ import annotations from __future__ import annotations
from ..wordmark import render from ..wordmark import render
HERO: tuple[str, ...] = render( HERO: tuple[str, ...] = render("BASSDRIVE")
"BASSDRIVE", ["bright_cyan"] * 4 + ["cyan"] * 5
)
@@ -30,7 +30,6 @@ class SomaFMProvider(RadioProvider):
history_source = "songs/<station>.json" history_source = "songs/<station>.json"
hero = hero_art.LOGO hero = hero_art.LOGO
hero_gradient = True
hero_lines = hero_art.TAGLINES hero_lines = hero_art.TAGLINES
@property @property
+3 -3
View File
@@ -1,9 +1,9 @@
"""SomaFM's header hero: the block-letter wordmark and the three lines beside it. """SomaFM's header hero: the block-letter wordmark and the three lines beside it.
The glyphs come from the shared half-block font The glyphs come from the shared half-block font
(:mod:`beefy_player.providers.wordmark`); the header paints them with the app's (:mod:`beefy_player.providers.wordmark`); the header paints every catalogue's
spectrum gradient (``hero_gradient``), so the logo takes on the terminal's own wordmark with the app's active palette gradient, so the logo takes on the
colours instead of carrying RGB values around. terminal's own colours instead of carrying RGB values around.
""" """
from __future__ import annotations from __future__ import annotations
@@ -29,8 +29,8 @@ class TilderadioProvider(RadioProvider):
station_source = "tilderadio.org/api/now/" station_source = "tilderadio.org/api/now/"
history_source = "now_playing + history[]" history_source = "now_playing + history[]"
# The station's own radio icon, converted to half blocks by # The station's wordmark in the shared half-block font, painted with the
# ``tools/ansi_art.py``; the caption is the tildeverse's motto. # app's palette gradient; the caption is the tildeverse's motto.
hero = hero_art.HERO hero = hero_art.HERO
hero_lines = ( hero_lines = (
"TILDERADIO", "TILDERADIO",
+3 -2
View File
@@ -1,7 +1,8 @@
"""tilderadio's header hero: its name in the shared half-block font. """tilderadio's header hero: its name in the shared half-block font.
No colours of its own — the wordmark inherits the terminal's default The shared half-block font; the header paints it with the app's active
foreground, so it looks like part of the chrome rather than a logo pasted in. palette gradient, so the wordmark follows the terminal's colours like the rest
of the chrome.
""" """
from __future__ import annotations from __future__ import annotations
+6 -34
View File
@@ -2,9 +2,9 @@
Every shipped catalogue draws its brand the same way: four-column capitals, Every shipped catalogue draws its brand the same way: four-column capitals,
six pixels tall, emitted as three rows of half blocks (``▀``/``▄``/``█``) — the six pixels tall, emitted as three rows of half blocks (``▀``/``▄``/``█``) — the
same shape as the original SomaFM logo. Catalogues differ only in the word same shape as the original SomaFM logo. The header paints every wordmark with
they spell and the ANSI colours they paint it with, so the font lives here and the app's active palette gradient, so catalogues differ only in the word they
each provider's ``hero.py`` is one line of data. spell; the font lives here and each provider's ``hero.py`` is one line of data.
Glyphs are 6x4 bitmaps (``M`` is 6x5). Two pixel rows become one text row, so Glyphs are 6x4 bitmaps (``M`` is 6x5). Two pixel rows become one text row, so
a wordmark is always three rows tall and the header keeps a fixed height. a wordmark is always three rows tall and the header keeps a fixed height.
@@ -12,8 +12,6 @@ a wordmark is always three rows tall and the header keeps a fixed height.
from __future__ import annotations from __future__ import annotations
from collections.abc import Sequence
#: 6-row bitmap per capital; all rows of one glyph are the same width. #: 6-row bitmap per capital; all rows of one glyph are the same width.
GLYPHS: dict[str, tuple[str, ...]] = { GLYPHS: dict[str, tuple[str, ...]] = {
"A": (".##.", "#..#", "####", "#..#", "#..#", "#..#"), "A": (".##.", "#..#", "####", "#..#", "#..#", "#..#"),
@@ -65,36 +63,10 @@ def _glyph_rows(char: str) -> tuple[str, ...]:
) )
def render(text: str, styles: Sequence[str | None] | None = None) -> tuple[str, ...]: def render(text: str) -> tuple[str, ...]:
"""Spell ``text`` as three rows of half blocks. """Spell ``text`` as three rows of half blocks."""
``styles`` gives one rich-markup style per character (``None`` leaves it in
the terminal's default colour). Contiguous runs of the same style share a
markup span, so ``render("BASSDRIVE", ...)`` paints the first four letters
and the last five separately.
"""
if styles is not None and len(styles) != len(text):
raise ValueError("styles must provide one entry per character")
glyphs = [_glyph_rows(char.upper()) for char in text] glyphs = [_glyph_rows(char.upper()) for char in text]
rows: list[str] = [] rows: list[str] = []
for row in range(ROWS): for row in range(ROWS):
cells: list[tuple[str | None, str]] = [] rows.append(_GAP.join(glyph[row] for glyph in glyphs).rstrip())
for index, glyph in enumerate(glyphs):
style = styles[index] if styles is not None else None
if index:
cells.append((style, _GAP))
cells.extend((style, char) for char in glyph[row])
while cells and cells[-1][1] == " ":
cells.pop()
segments: list[tuple[str | None, str]] = []
for style, char in cells:
if segments and segments[-1][0] == style:
segments[-1] = (style, segments[-1][1] + char)
else:
segments.append((style, char))
rows.append(
"".join(f"[{style}]{body}[/]" if style else body for style, body in segments)
)
return tuple(rows) return tuple(rows)
+4 -1
View File
@@ -35,8 +35,11 @@ def _hero_line(
line.no_wrap = True line.no_wrap = True
return line return line
# Iterate the *text* of the row, not its markup: a hero is allowed to
# carry styles of its own, and those brackets are not cells to paint.
plain = Text.from_markup(markup).plain
line = Text(no_wrap=True) line = Text(no_wrap=True)
for column, char in enumerate(markup): for column, char in enumerate(plain):
position = (column / max(1, width - 1) + index * 0.055) % 1.0 position = (column / max(1, width - 1) + index * 0.055) % 1.0
line.append(char, style=f"bold {gradient(stops, position)}") line.append(char, style=f"bold {gradient(stops, position)}")
return line return line
+539
View File
@@ -0,0 +1,539 @@
#!/usr/bin/env python3
"""Sync the AUR package and the Homebrew tap formula with a tagged release.
A release carries its version in six places: `pyproject.toml`,
`beefy_player.__version__`, `flake.nix`, `contrib/aur/PKGBUILD`,
`contrib/aur/.SRCINFO` and the tap's formula. Only the first three are edited
by hand; this tool writes the rest from the published release.
Both packagers build the sdist attached to the release, not a forge-generated
archive of the tag: an uploaded asset is immutable, so the checksum recorded in
`PKGBUILD` and the formula keeps matching, which is not guaranteed for archives
generated on the fly. The sdist's root directory is hatchling's PEP 503 name
(`beefy_player-<version>`), so the `PKGBUILD` cds into `$_srcname` rather than
`$pkgname`.
Usage:
python bump_packaging.py 1.2.3 # download the release asset
python bump_packaging.py 1.2.3 --asset dist/beefy_player-1.2.3.tar.gz
python bump_packaging.py 1.2.3 --commit # also commit both repos
python bump_packaging.py 1.2.3 --check # verify, write nothing
`.SRCINFO` is never edited directly; it is regenerated by evaluating
`PKGBUILD` in bash and serialising it in makepkg's field order. That keeps it
honest without needing makepkg (or an Arch host) at hand.
After `--commit`, the tap has to be pushed before this repository: its commit
is new, and a gitlink pointing at a commit the tap's remote does not have yet
breaks every fresh clone with `--recurse-submodules`.
"""
from __future__ import annotations
import argparse
import hashlib
import os
import re
import ssl
import subprocess
import sys
import tarfile
import tempfile
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent
PYPROJECT = ROOT / "pyproject.toml"
INIT = ROOT / "beefy_player/__init__.py"
FLAKE = ROOT / "flake.nix"
AUR = ROOT / "contrib/aur"
PKGBUILD = AUR / "PKGBUILD"
SRCINFO = AUR / ".SRCINFO"
TAP = ROOT / "contrib/homebrew"
FORMULA = TAP / "Formula/b/beefy-player.rb"
HOMEPAGE = "https://tildeforge.dev/beefcarver/beefy-player"
#: The sdist's own name, as hatchling builds it (PEP 503: underscores).
ASSET_NAME = "beefy_player"
RELEASE_ASSET = HOMEPAGE + "/releases/download/v{version}/{name}-{version}.tar.gz"
#: The fields `PKGBUILD` may define, in the order `makepkg --printsrcinfo`
#: emits them. A field outside this list is an error, not something to
#: silently drop.
SRCINFO_ORDER = (
"pkgdesc",
"pkgver",
"pkgrel",
"epoch",
"url",
"arch",
"license",
"groups",
"depends",
"makedepends",
"checkdepends",
"optdepends",
"provides",
"conflicts",
"replaces",
"backup",
"options",
"install",
"changelog",
"source",
"noextract",
"validpgpkeys",
"sha256sums",
)
#: Evaluates PKGBUILD (it is valid shell) and dumps the metadata as tab
#: separated `key\tvalue` pairs, so quoting and `$var` expansion are the
#: real ones rather than whatever a hand-rolled parser guesses.
PKGBUILD_DUMP = r"""
set -euo pipefail
source "$1"
for v in pkgname pkgdesc pkgver pkgrel url; do
printf '%s\t%s\n' "$v" "${!v}"
done
for field in arch license groups depends makedepends checkdepends optdepends \
provides conflicts replaces backup options source noextract \
validpgpkeys sha256sums; do
eval "values=(\"\${${field}[@]}\")"
for v in "${values[@]}"; do
printf '%s\t%s\n' "$field" "$v"
done
done
"""
#: Replaces the `_commit`-pinned git-archive source with the release asset.
ASSET_SOURCE = (
"# The sdist attached to the v$pkgver release. bump_packaging.py keeps\n"
"# this and sha256sums in step with the tag; build/check/package use\n"
"# $_srcname because the sdist unpacks to hatchling's PEP 503 name.\n"
'_srcname="beefy_player-$pkgver"\n'
'source=("$pkgname-$pkgver.tar.gz::$url/releases/download/v$pkgver/$_srcname.tar.gz")\n'
)
class BumpError(SystemExit):
"""A precondition failed; nothing was written."""
def say(message: str) -> None:
print(message, flush=True)
def fail(message: str) -> BumpError:
return BumpError(f"bump_packaging: {message}")
def git(*args: str, cwd: Path = ROOT) -> str:
result = subprocess.run(
["git", *args], cwd=cwd, check=True, text=True, capture_output=True
)
return result.stdout.strip()
def git_ok(*args: str, cwd: Path = ROOT) -> bool:
"""Run a git query whose non-zero exit is an answer, not a failure."""
return subprocess.run(["git", *args], cwd=cwd, capture_output=True).returncode == 0
def normalise(version: str) -> str:
"""Accept `1.2.3` or the tag spelling `v1.2.3`."""
version = version.removeprefix("v")
if not re.fullmatch(r"\d+\.\d+\.\d+(?:[abrc][\w.]*|\.post\d+)?", version):
raise fail(f"{version!r} is not a version")
return version
def declared_versions() -> dict[str, str]:
"""The three places the version is written by hand."""
patterns = {
str(PYPROJECT.relative_to(ROOT)): (PYPROJECT, r'(?m)^version = "([^"]+)"'),
str(INIT.relative_to(ROOT)): (INIT, r'(?m)^__version__ = "([^"]+)"'),
str(FLAKE.relative_to(ROOT)): (FLAKE, r'(?m)^\s*version = "([^"]+)"'),
}
found = {}
for label, (path, pattern) in patterns.items():
match = re.search(pattern, path.read_text())
if match is None:
raise fail(f"no version found in {label}")
found[label] = match.group(1)
return found
def check_versions(version: str) -> None:
"""The tag, pyproject and __version__ must agree before packaging moves."""
declared = declared_versions()
stale = {label: value for label, value in declared.items() if value != version}
if stale:
detail = ", ".join(f"{label} has {value}" for label, value in stale.items())
raise fail(f"version {version} is not released yet: {detail}")
say(f"version {version} agrees in {len(declared)} files")
def sdist_version(asset: Path) -> str:
"""The version the sdist says it is, from its root directory name."""
with tarfile.open(asset) as archive:
first = next(iter(archive), None)
if first is None:
raise fail(f"{asset} is empty")
root = first.name.split("/", 1)[0]
prefix = f"{ASSET_NAME}-"
if not root.startswith(prefix):
raise fail(f"{asset} unpacks to {root!r}, expected {prefix}<version>")
return root[len(prefix) :]
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def ca_file() -> str | None:
"""The CA bundle to verify with, or None to let OpenSSL use its own default.
`uv python install` fetches a python-build-standalone interpreter whose
OpenSSL is compiled with default trust paths that need not exist on the
host (on macOS, and on distros that keep certs only in
/etc/ssl/certs/ca-certificates.crt, they often do not). Verification then
fails with `unable to get local issuer certificate` for every site, even
though curl and browsers are happy. Fall back to certifi, which `httpx`
already puts in the environment.
"""
if os.environ.get("SSL_CERT_FILE"):
return None # ssl honours the variable itself; do not second-guess it
paths = ssl.get_default_verify_paths()
for candidate in (paths.cafile, paths.openssl_cafile):
if candidate and Path(candidate).is_file():
return None
try:
import certifi
except ModuleNotFoundError:
return None
return certifi.where()
def fetch_asset(version: str, override: Path | None) -> Path:
if override is not None:
if not override.is_file():
raise fail(f"no such asset: {override}")
return override
url = RELEASE_ASSET.format(version=version, name=ASSET_NAME)
say(f"downloading {url}")
cafile = ca_file()
context = ssl.create_default_context(cafile=cafile)
target = Path(tempfile.mkdtemp()) / f"{ASSET_NAME}-{version}.tar.gz"
try:
with urllib.request.urlopen(url, context=context) as response, target.open(
"wb"
) as handle:
handle.write(response.read())
except urllib.error.URLError as error:
# urlopen wraps socket/SSL failures; the cause is in `.reason`.
if isinstance(error.reason, ssl.SSLCertVerificationError):
bundle = cafile or ssl.get_default_verify_paths().cafile or "no bundle found"
raise fail(
f"cannot fetch the release asset ({error.reason.verify_message or error.reason}); "
f"verified against {bundle}. If that bundle is stale, point SSL_CERT_FILE "
"at a current one (on Arch and Debian that is "
"/etc/ssl/certs/ca-certificates.crt)"
) from error
raise fail(f"cannot fetch the release asset ({error.reason}); is the tag published?") from error
except OSError as error:
raise fail(f"cannot fetch the release asset ({error}); is the tag published?") from error
return target
def replace_line(text: str, pattern: str, replacement: str, what: str) -> str:
"""Substitute a single line, insisting the pattern occurs exactly once."""
new, count = re.subn(pattern, replacement, text, flags=re.MULTILINE)
if count != 1:
raise fail(f"expected exactly one {what} in PKGBUILD, found {count}")
return new
def migrate_source(text: str) -> str:
"""Turn the `_commit`-pinned git archive into a release-asset source."""
if "releases/download/v$pkgver" in text:
return text
lines = text.splitlines(keepends=True)
pinned = [index for index, line in enumerate(lines) if line.startswith("_commit=")]
if not pinned:
raise fail("PKGBUILD has neither a release asset nor a _commit pin")
# Take the comment block that explains the pin with it.
start = pinned[0]
while start > 0 and lines[start - 1].startswith("#"):
start -= 1
sums = [index for index, line in enumerate(lines) if line.startswith("sha256sums=")]
if not sums:
raise fail("PKGBUILD has no sha256sums line")
say("migrating PKGBUILD from the _commit archive to the release asset")
replaced = [*lines[:start], ASSET_SOURCE, *lines[sums[0] :]]
return "".join(replaced)
def bump_pkgbuild(version: str, checksum: str) -> None:
text = migrate_source(PKGBUILD.read_text())
text = replace_line(
text, r"^pkgver=.*$", f"pkgver={version}", "pkgver assignment"
)
text = replace_line(text, r"^pkgrel=.*$", "pkgrel=1", "pkgrel assignment")
text = replace_line(
text,
r"^sha256sums=\(.*\)$",
f"sha256sums=('{checksum}')",
"sha256sums assignment",
)
if 'cd "$pkgname"' in text:
# The sdist unpacks to beefy_player-<version>, not beefy-player.
text = text.replace('cd "$pkgname"', 'cd "$_srcname"')
say("pointed build/check/package at $_srcname (the sdist's root directory)")
if "_srcname=" not in text:
raise fail("PKGBUILD has no _srcname; rerun after adding the release asset source")
if 'releases/download/v$pkgver' not in text:
raise fail("PKGBUILD does not source the release asset")
PKGBUILD.write_text(text)
say("wrote contrib/aur/PKGBUILD")
def render_srcinfo() -> str:
"""Regenerate .SRCINFO from PKGBUILD the way makepkg --printsrcinfo does."""
result = subprocess.run(
["bash", "-c", PKGBUILD_DUMP, "bash", str(PKGBUILD)],
cwd=AUR,
check=True,
text=True,
capture_output=True,
)
fields: dict[str, list[str]] = {}
for line in result.stdout.splitlines():
key, _, value = line.partition("\t")
fields.setdefault(key, []).append(value)
name = fields.pop("pkgname", [None])[0]
if name is None:
raise fail("PKGBUILD defines no pkgname")
unknown = sorted(set(fields) - set(SRCINFO_ORDER))
if unknown:
raise fail(f"PKGBUILD defines {unknown}; add them to SRCINFO_ORDER first")
body = [f"\t{key} = {value}" for key in SRCINFO_ORDER for value in fields.get(key, [])]
return "\n".join([f"pkgbase = {name}", *body]) + f"\n\npkgname = {name}\n"
def bump_srcinfo() -> None:
rendered = render_srcinfo()
if SRCINFO.read_text() == rendered:
say("contrib/aur/.SRCINFO already matches PKGBUILD")
return
SRCINFO.write_text(rendered)
say("regenerated contrib/aur/.SRCINFO")
#: Names that may appear as `resource` blocks in the formula. A Python
#: dependency without one is silently skipped at install time because Homebrew
#: installs the sdist `--no-deps`, which surfaces as an ImportError on launch
#: rather than as a packaging error.
RESOURCE_LINE = re.compile(r'(?m)^ resource "([^"]+)" do$')
def pypi_name(name: str) -> str:
"""PEP 503 name: lowercase, runs of -_. collapsed to a single hyphen."""
return re.sub(r"[-_.]+", "-", name).lower()
def runtime_dependencies() -> list[str]:
"""The distribution names in `pyproject.toml`'s `[project] dependencies`."""
block = re.search(r"(?ms)^dependencies = \[(.*?)^\]$", PYPROJECT.read_text())
if block is None:
raise fail("no dependencies array in pyproject.toml")
return re.findall(r'^\s*"([A-Za-z0-9._-]+)', block.group(1), re.MULTILINE)
def formula_excluded_resources() -> set[str]:
"""Dependencies the formula deliberately leaves to other formulae."""
match = re.search(r'pypi_packages .*exclude_packages: "([^"]*)"', FORMULA.read_text())
if match is None:
return set()
return {pypi_name(name.strip()) for name in match.group(1).split(",") if name.strip()}
def check_formula_resources(problems: list[str]) -> None:
"""Every runtime dependency needs a `resource`, unless another formula has it."""
resources = {pypi_name(name) for name in RESOURCE_LINE.findall(FORMULA.read_text())}
if not resources:
problems.append("formula vendors no Python resources; it would install --no-deps")
excluded = formula_excluded_resources()
for dependency in runtime_dependencies():
name = pypi_name(dependency)
if name in excluded or name in resources:
continue
problems.append(
f"formula has no resource for {name}"
" (run `brew update-python-resources Formula/b/beefy-player.rb` in the tap)"
)
def bump_formula(version: str, checksum: str) -> None:
text = FORMULA.read_text()
url = RELEASE_ASSET.format(version=version, name=ASSET_NAME)
text = replace_line(text, r'^ url ".*"$', f' url "{url}"', "url line")
text = replace_line(
text, r'^ sha256 "[0-9a-f]{64}".*$', f' sha256 "{checksum}"', "sha256 line"
)
# The default branch is master, and --HEAD is only useful if it resolves.
text = text.replace('branch: "main"', 'branch: "master"')
# The `resource` blocks pin versions, not the release: they only go stale
# when pyproject.toml's dependencies change, which `--check` reports.
FORMULA.write_text(text)
say("wrote contrib/homebrew/Formula/b/beefy-player.rb")
def require_clean(path: Path, label: str) -> None:
"""Refuse to edit on top of uncommitted work; ignore untracked files.
Untracked files cannot end up in the bump commit because `commit` stages
explicit paths, so a stray `dist/` or scratch note is not a reason to stop.
"""
dirty = git("status", "--porcelain", "--untracked-files=no", cwd=path)
if dirty:
raise fail(f"{label} has uncommitted changes:\n{dirty}")
def preflight(commit_too: bool) -> None:
"""Checks that must pass before anything is written."""
require_clean(ROOT, "this repository")
require_clean(TAP, "the tap submodule")
if commit_too and not git_ok("symbolic-ref", "--short", "-q", "HEAD", cwd=TAP):
# A fresh clone checks submodules out at the recorded commit, where a
# commit would be unreachable and silently dropped by the next update.
say("submodule is in detached HEAD; checking out master")
git("checkout", "master", cwd=TAP)
def commit(version: str) -> None:
if not git_ok("merge-base", "--is-ancestor", "origin/master", "HEAD", cwd=TAP):
raise fail("the tap's master is not an ancestor of HEAD; fetch and rebase first")
if not git("status", "--porcelain", cwd=TAP):
say("tap formula unchanged; nothing to commit there")
else:
git("add", str(FORMULA.relative_to(TAP)), cwd=TAP)
staged = set(git("diff", "--cached", "--name-only", cwd=TAP).splitlines())
if staged != {str(FORMULA.relative_to(TAP))}:
raise fail(f"unexpected staged files in the tap: {sorted(staged)}")
git("commit", "-m", f"feat(beefy-player): {version}", cwd=TAP)
say(f'committed tap: "feat(beefy-player): {version}"')
expected = {str(PKGBUILD.relative_to(ROOT)), str(SRCINFO.relative_to(ROOT))}
git("add", *expected, cwd=ROOT)
git("add", str(TAP.relative_to(ROOT)), cwd=ROOT) # record the new gitlink
expected.add(str(TAP.relative_to(ROOT)))
staged = set(git("diff", "--cached", "--name-only", cwd=ROOT).splitlines())
if staged != expected:
raise fail(f"unexpected staged files here: {sorted(staged)}")
git("commit", "-m", f"build(release): packaging for v{version}", cwd=ROOT)
say(f'committed here: "build(release): packaging for v{version}"')
say(
"\nPush the tap first, then this repository:\n"
f" git -C {TAP.relative_to(ROOT)} push\n"
" git push\n"
"A gitlink whose commit is missing from the tap's remote breaks every\n"
"clone that uses --recurse-submodules."
)
def check(version: str) -> int:
"""Report drift without writing anything."""
problems: list[str] = []
text = PKGBUILD.read_text()
def field(name: str) -> str:
match = re.search(rf"^{name}=(.*)$", text, re.MULTILINE)
if match is None:
problems.append(f"PKGBUILD has no {name}")
return ""
return match.group(1).strip("'\"")
if field("pkgver") != version:
problems.append(f"PKGBUILD pkgver is {field('pkgver') or 'unset'}, expected {version}")
if field("pkgrel") != "1":
problems.append(f"PKGBUILD pkgrel is {field('pkgrel')}, expected 1")
if "releases/download/v$pkgver" not in text:
problems.append("PKGBUILD still sources a _commit archive, not the release asset")
if 'cd "$_srcname"' not in text:
problems.append("PKGBUILD cds into $pkgname, which the sdist does not unpack to")
info = re.search(r"(?m)^\tpkgver = (.*)$", SRCINFO.read_text())
if info is None or info.group(1) != version:
problems.append(f".SRCINFO pkgver is {info.group(1) if info else 'missing'}, expected {version}")
if SRCINFO.read_text() != render_srcinfo():
problems.append(".SRCINFO does not match PKGBUILD (regenerate it)")
formula = FORMULA.read_text()
asset = RELEASE_ASSET.format(version=version, name=ASSET_NAME)
if f'url "{asset}"' not in formula:
problems.append(f"formula url is not {asset}")
if 'branch: "main"' in formula:
problems.append('formula head branch is "main"; this repository uses master')
if re.search(r'sha256 "0{64}"', formula):
problems.append("formula still has the placeholder sha256")
check_formula_resources(problems)
for problem in problems:
say(f"drift: {problem}")
if problems:
say(f"\n{len(problems)} problem(s) for {version}")
return 1
say(f"packaging is in sync with {version}")
return 0
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("version", help="release version, with or without the v prefix")
parser.add_argument(
"--asset",
type=Path,
help="hash a local sdist instead of downloading the release asset",
)
parser.add_argument(
"--commit",
action="store_true",
help="commit the tap and the packaging bump when done",
)
parser.add_argument(
"--check",
action="store_true",
help="report drift and exit; writes nothing",
)
args = parser.parse_args(argv)
version = normalise(args.version)
if args.check:
return check(version)
check_versions(version)
preflight(commit_too=args.commit)
asset = fetch_asset(version, args.asset)
measured = sdist_version(asset)
if measured != version:
raise fail(f"{asset} is the sdist of {measured}, not {version}")
checksum = sha256(asset)
say(f"{asset.name} sha256 {checksum}")
bump_pkgbuild(version, checksum)
bump_srcinfo()
bump_formula(version, checksum)
if args.commit:
commit(version)
else:
say("\nfiles written; rerun with --commit to record them")
return 0
if __name__ == "__main__":
sys.exit(main())
+28
View File
@@ -0,0 +1,28 @@
pkgbase = beefy-player
pkgdesc = Flashy terminal player for internet radio with a live spectrum analyser
pkgver = 1.2.5
pkgrel = 1
url = https://tildeforge.dev/beefcarver/beefy-player
arch = any
license = WTFPL
depends = python
depends = python-dbus-next
depends = python-httpx
depends = python-numpy
depends = python-pillow
depends = python-rich
depends = python-textual
makedepends = python-build
makedepends = python-hatchling
makedepends = python-installer
makedepends = python-wheel
checkdepends = python-pytest
checkdepends = python-pytest-asyncio
optdepends = ffmpeg: decode the stream for the spectrum analyser, and ffplay as the audio fallback
optdepends = libpulse: capture the output monitor so the analyser follows what you hear (parec/pactl)
optdepends = mpv: preferred audio backend
optdepends = tmux: detect the outer terminal for kitty graphics passthrough inside tmux
source = beefy-player-1.2.5.tar.gz::https://tildeforge.dev/beefcarver/beefy-player/releases/download/v1.2.5/beefy_player-1.2.5.tar.gz
sha256sums = 344f2266cb63d05bf294349599ecef636b3c8c25c8b29bcf0eff8818394b5f74
pkgname = beefy-player
+57
View File
@@ -0,0 +1,57 @@
# Maintainer: beefy-player contributors <[email protected]>
pkgname=beefy-player
pkgver=1.2.5
pkgrel=1
pkgdesc="Flashy terminal player for internet radio with a live spectrum analyser"
arch=('any')
url="https://tildeforge.dev/beefcarver/beefy-player"
license=('WTFPL')
depends=(
'python'
'python-dbus-next'
'python-httpx'
'python-numpy'
'python-pillow'
'python-rich'
'python-textual'
)
makedepends=(
'python-build'
'python-hatchling'
'python-installer'
'python-wheel'
)
checkdepends=(
'python-pytest'
'python-pytest-asyncio'
)
optdepends=(
'ffmpeg: decode the stream for the spectrum analyser, and ffplay as the audio fallback'
'libpulse: capture the output monitor so the analyser follows what you hear (parec/pactl)'
'mpv: preferred audio backend'
'tmux: detect the outer terminal for kitty graphics passthrough inside tmux'
)
# The sdist attached to the v$pkgver release. bump_packaging.py keeps
# this and sha256sums in step with the tag; build/check/package use
# $_srcname because the sdist unpacks to hatchling's PEP 503 name.
_srcname="beefy_player-$pkgver"
source=("$pkgname-$pkgver.tar.gz::$url/releases/download/v$pkgver/$_srcname.tar.gz")
sha256sums=('344f2266cb63d05bf294349599ecef636b3c8c25c8b29bcf0eff8818394b5f74')
build() {
cd "$_srcname"
python -m build --wheel --no-isolation
}
check() {
cd "$_srcname"
# The suite is offline: catalogues are fixtures, mpv/parec are faked.
python -m pytest -q
}
package() {
cd "$_srcname"
python -m installer --destdir="$pkgdir" dist/*.whl
}
+1
Submodule contrib/homebrew added at c958da0067.
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1793726008,
"narHash": "sha256-jQp1wKvbwWdLBASTXkSi/VYmDJ5AbBi1WvcMt9HWJC8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "1d060086d60cb76a40cf37109f979d88a5bd6396",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+188
View File
@@ -0,0 +1,188 @@
{
description = "beefy-player — a flashy terminal player for internet radio";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs =
{ self, nixpkgs }:
let
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
# Things the app shells out to at runtime: mpv for audio, ffmpeg for the
# spectrum capture, and parec/pactl from PulseAudio for the monitor source
# (PipeWire speaks the same protocol).
runtimeDeps =
pkgs:
with pkgs;
[
mpv
ffmpeg
]
++ lib.optionals stdenv.hostPlatform.isLinux [ pulseaudio ];
beefy-player =
pkgs:
let
py = pkgs.python3Packages;
in
py.buildPythonApplication {
pname = "beefy-player";
version = "1.2.5";
pyproject = true;
src = self;
build-system = [ py.hatchling ];
dependencies =
with py;
[
textual
rich
httpx
numpy
pillow
]
++ pkgs.lib.optionals pkgs.stdenv.hostPlatform.isLinux [ dbus-next ];
nativeBuildInputs = [ pkgs.makeWrapper ];
nativeCheckInputs = with py; [
pytestCheckHook
pytest-asyncio
];
# The suite is offline (catalogues are cached fixtures).
doCheck = true;
pythonImportsCheck = [ "beefy_player" ];
makeWrapperArgs = [
"--prefix"
"PATH"
":"
(pkgs.lib.makeBinPath (runtimeDeps pkgs))
];
meta = {
description = "Flashy terminal player for internet radio, with a live spectrum analyser";
homepage = "https://tildeforge.dev/beefcarver/beefy-player";
license = pkgs.lib.licenses.wtfpl;
mainProgram = "beefy-player";
platforms = pkgs.lib.platforms.unix;
};
};
# One module body, two install targets: a NixOS system adds the package
# to environment.systemPackages, Home Manager to home.packages.
mkModule =
install:
{
config,
lib,
pkgs,
...
}:
let
cfg = config.programs.beefy-player;
in
{
options.programs.beefy-player = {
enable = lib.mkEnableOption "beefy-player, a terminal radio player";
package = lib.mkOption {
type = lib.types.package;
default = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
defaultText = lib.literalMD "the `beefy-player` package from this flake";
description = "The beefy-player package to use.";
};
};
config = lib.mkIf cfg.enable (lib.setAttrByPath install [ cfg.package ]);
};
in
{
packages = forAllSystems (
pkgs:
let
pkg = beefy-player pkgs;
in
{
default = pkg;
beefy-player = pkg;
}
);
apps = forAllSystems (pkgs: {
default = {
type = "app";
program = "${beefy-player pkgs}/bin/beefy-player";
meta.description = "Flashy terminal player for internet radio";
};
});
checks = forAllSystems (pkgs: {
beefy-player = beefy-player pkgs;
});
devShells = forAllSystems (
pkgs:
let
inherit (pkgs) lib;
in
{
# No FHS needed here: `nix develop` puts libstdc++ on LD_LIBRARY_PATH
# so uv's manylinux wheels load, unlike the plain `nix-shell` case in
# shell.nix.
default = pkgs.mkShell {
packages = runtimeDeps pkgs ++ [
pkgs.python3
pkgs.uv
pkgs.ruff
pkgs.git
pkgs.cacert
];
env = {
UV_PYTHON = "${pkgs.python3}/bin/python3";
UV_PYTHON_DOWNLOADS = "never";
UV_PROJECT_ENVIRONMENT = "${toString ./.}/.venv";
UV_LINK_MODE = "copy";
SSL_CERT_FILE = "${pkgs.cacert}/etc/ssl/certs/ca-bundle.crt";
};
LD_LIBRARY_PATH = lib.makeLibraryPath [
pkgs.stdenv.cc.cc.lib
pkgs.zlib
];
shellHook = ''
echo "beefy-player dev shell — uv sync, uv run pytest, uv run beefy-player"
'';
};
}
);
nixosModules.default = mkModule [
"environment"
"systemPackages"
];
nixosModules.beefy-player = self.nixosModules.default;
homeModules.default = mkModule [
"home"
"packages"
];
homeModules.beefy-player = self.homeModules.default;
formatter = forAllSystems (pkgs: pkgs.nixfmt);
overlays.default = final: _prev: {
beefy-player = beefy-player final;
};
};
}
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "beefy-player" name = "beefy-player"
version = "1.2.1" version = "1.2.5"
description = "A flashy terminal player for internet radio — live spectrum analyser, MPRIS / macOS Now Playing support, song history and pluggable station catalogues (SomaFM, Radio Paradise, dublab, Rinse FM and more)" description = "A flashy terminal player for internet radio — live spectrum analyser, MPRIS / macOS Now Playing support, song history and pluggable station catalogues (SomaFM, Radio Paradise, dublab, Rinse FM and more)"
readme = "README.md" readme = "README.md"
license = "WTFPL" license = "WTFPL"
+3 -1
View File
@@ -255,7 +255,9 @@ def test_provider_describes_its_catalogue() -> None:
assert provider.has_schedule is True assert provider.has_schedule is True
assert provider.bandcamp is False assert provider.bandcamp is False
assert len(provider.hero) == 3 assert len(provider.hero) == 3
assert "bright_cyan" in "".join(provider.hero) # the header paints the wordmark with the palette gradient
assert provider.hero_gradient is True
assert "[" not in "".join(provider.hero)
assert provider.hero_lines == ( assert provider.hero_lines == (
"BASSDRIVE", "BASSDRIVE",
"WORLDWIDE DRUM & BASS", "WORLDWIDE DRUM & BASS",
+29 -6
View File
@@ -6,6 +6,7 @@ import types
import pytest import pytest
from rich.cells import cell_len from rich.cells import cell_len
from beefy_player.palettes import DEFAULT_PALETTE, PALETTES
from beefy_player.providers import PROVIDERS from beefy_player.providers import PROVIDERS
from beefy_player.providers.somafm import SomaFMProvider from beefy_player.providers.somafm import SomaFMProvider
from beefy_player.providers.wordmark import render from beefy_player.providers.wordmark import render
@@ -71,6 +72,17 @@ def hero_styles(provider) -> list[str]:
] ]
def hero_colours(provider) -> set[str]:
"""Palette names the header actually painted the hero glyphs with."""
palette = set(PALETTES[DEFAULT_PALETTE])
return {
colour
for style in hero_styles(provider)
for colour in palette
if style.endswith(f" {colour}")
}
def test_the_i_and_t_have_thin_stems() -> None: def test_the_i_and_t_have_thin_stems() -> None:
"""Two-pixel stems make an I look like an H and a T look like a block.""" """Two-pixel stems make an I look like an H and a T look like a block."""
assert render("I") == ("▀█▀", " █", "▄█▄") assert render("I") == ("▀█▀", " █", "▄█▄")
@@ -108,27 +120,38 @@ def test_every_catalogue_has_a_three_row_wordmark() -> None:
assert provider.hero_lines, slug assert provider.hero_lines, slug
def test_tilderadio_spells_its_own_name_in_the_default_colour() -> None: def test_tilderadio_spells_its_own_name_in_the_palette_gradient() -> None:
provider = PROVIDERS["tilderadio"] provider = PROVIDERS["tilderadio"]
lines = render_header(143, height=len(provider.hero), provider=provider) lines = render_header(143, height=len(provider.hero), provider=provider)
assert len(lines) == 3 assert len(lines) == 3
assert "TILDERADIO" in lines[0] # the wordmark assert "TILDERADIO" in lines[0] # the wordmark
assert "STREAMED BY / FOR USERS OF THE" in lines[1] assert "STREAMED BY / FOR USERS OF THE" in lines[1]
assert "TILDEVERSE" in lines[2] assert "TILDEVERSE" in lines[2]
# no colour of its own: the art inherits the terminal foreground # the art carries no colours; the header itself paints the gradient
assert all("[" not in row for row in provider.hero) assert all("[" not in row for row in provider.hero)
assert not {"bright_cyan", "cyan"} & set(hero_styles(provider)) assert provider.hero_gradient
assert len(hero_colours(provider)) > 1
assert all("SOMA" not in line for line in lines) assert all("SOMA" not in line for line in lines)
def test_bassdrive_spells_its_name_in_its_own_two_blues() -> None: def test_bassdrive_spells_its_name_in_the_palette_gradient() -> None:
provider = PROVIDERS["bassdrive"] provider = PROVIDERS["bassdrive"]
lines = render_header(143, height=len(provider.hero), provider=provider) lines = render_header(143, height=len(provider.hero), provider=provider)
assert "BASSDRIVE" in lines[0] assert "BASSDRIVE" in lines[0]
assert "WORLDWIDE DRUM & BASS" in lines[1] assert "WORLDWIDE DRUM & BASS" in lines[1]
assert "LIVE SHOWS 24/7" in lines[2] assert "LIVE SHOWS 24/7" in lines[2]
styles = hero_styles(provider) assert provider.hero_gradient
assert "bright_cyan" in styles and "cyan" in styles assert len(hero_colours(provider)) > 1
# no stale markup leaks into the painted rows
assert all("[" not in line for line in lines)
@pytest.mark.parametrize("slug", sorted(PROVIDERS))
def test_every_catalogue_paints_its_wordmark_with_the_palette(slug: str) -> None:
"""Every hero follows the active palette, not a colour of its own."""
provider = PROVIDERS[slug]
assert provider.hero_gradient, slug
assert len(hero_colours(provider)) > 1, slug
def _fake(provider): def _fake(provider):
+2 -2
View File
@@ -2,13 +2,13 @@ from __future__ import annotations
import os import os
import queue import queue
import sys
import time import time
from pathlib import Path from pathlib import Path
from beefy_player.player import Player from beefy_player.player import Player
FAKE_MPV = '''#!/usr/bin/env python3 FAKE_MPV = f"#!{sys.executable}\n" + '''import json, os, socket, sys, time
import json, os, socket, sys, time
sock_path = None sock_path = None
volume = 70 volume = 70
+1 -1
View File
@@ -154,7 +154,7 @@ def test_tilderadio_replaces_the_station_list_with_a_schedule() -> None:
provider = TilderadioProvider() provider = TilderadioProvider()
assert provider.has_schedule is True assert provider.has_schedule is True
# the SomaFM wordmark's slot now holds tilderadio's own art and motto # the SomaFM wordmark's slot now holds tilderadio's own art and motto
assert provider.hero and not provider.hero_gradient assert provider.hero and provider.hero_gradient
assert provider.hero_lines == ( assert provider.hero_lines == (
"TILDERADIO", "TILDERADIO",
"STREAMED BY / FOR USERS OF THE", "STREAMED BY / FOR USERS OF THE",
+4 -4
View File
@@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import sys
import time import time
from pathlib import Path from pathlib import Path
@@ -8,8 +9,7 @@ import numpy as np
from beefy_player import spectrum as spectrum_module from beefy_player import spectrum as spectrum_module
from beefy_player.spectrum import Frame, SpectrumEngine from beefy_player.spectrum import Frame, SpectrumEngine
PCM_SCRIPT = """#!/usr/bin/env python3 PCM_SCRIPT = f"#!{sys.executable}\n" + """import math, struct, sys, time
import math, struct, sys, time
sr = 44100 sr = 44100
samples = [int(0.6 * 32767 * math.sin(2 * math.pi * 1000 * i / sr)) for i in range(4096)] samples = [int(0.6 * 32767 * math.sin(2 * math.pi * 1000 * i / sr)) for i in range(4096)]
chunk = struct.pack("<%dh" % len(samples), *samples) chunk = struct.pack("<%dh" % len(samples), *samples)
@@ -303,7 +303,7 @@ def test_tap_audio_is_downmixed_and_retuned() -> None:
def test_dead_monitor_falls_back_instead_of_flat_bars(tmp_path) -> None: def test_dead_monitor_falls_back_instead_of_flat_bars(tmp_path) -> None:
script = tmp_path / "silent-parec" script = tmp_path / "silent-parec"
script.write_text( script.write_text(
"#!/usr/bin/env python3\n" f"#!{sys.executable}\n"
"import sys\n" "import sys\n"
"block = b'\\0' * 4096\n" "block = b'\\0' * 4096\n"
"for _ in range(1000):\n" "for _ in range(1000):\n"
@@ -333,7 +333,7 @@ def test_monitor_survives_silence_after_audio(tmp_path, monkeypatch) -> None:
# replaced by the drifting stream tap) for the rest of the session. # replaced by the drifting stream tap) for the rest of the session.
script = tmp_path / "parec" script = tmp_path / "parec"
script.write_text( script.write_text(
"#!/usr/bin/env python3\n" f"#!{sys.executable}\n"
"import math, struct, sys, time\n" "import math, struct, sys, time\n"
"sr = 44100\n" "sr = 44100\n"
"n = 2048\n" "n = 2048\n"
-264
View File
@@ -1,264 +0,0 @@
#!/usr/bin/env python3
"""Turn a logo into half-block ANSI art for the header hero.
The header hero is a handful of text rows, so an image has to survive a brutal
downsample: two pixels per cell (upper/lower half block), one ANSI colour per
half. Colours are quantised to the stock 16-colour ANSI palette on purpose —
the rest of the UI never emits RGB, and a hero built from palette names still
reads as the station's art in any terminal theme.
Usage:
python tools/ansi_art.py logo.png --cols 22 --rows 7
python tools/ansi_art.py --url https://tilderadio.org/logos/tilderadio.png \\
--cols 22 --rows 7 --module beefy_player/providers/tilderadio/hero.py
``--preview out.png`` draws what the cells will look like, which is much easier
to judge than a wall of ▀ and ▄.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from PIL import Image, ImageDraw
#: The stock xterm colours the names below resolve to in a terminal.
ANSI16: dict[str, tuple[int, int, int]] = {
"black": (0, 0, 0),
"red": (170, 0, 0),
"green": (0, 170, 0),
"yellow": (170, 85, 0),
"blue": (0, 0, 170),
"magenta": (170, 0, 170),
"cyan": (0, 170, 170),
"white": (170, 170, 170),
"bright_black": (85, 85, 85),
"bright_red": (255, 85, 85),
"bright_green": (85, 255, 85),
"bright_yellow": (255, 255, 85),
"bright_blue": (85, 85, 255),
"bright_magenta": (255, 85, 255),
"bright_cyan": (85, 255, 255),
"bright_white": (255, 255, 255),
}
#: Below this alpha a half-cell counts as empty (terminal background).
ALPHA_CUTOFF = 110
#: Ink weaker than this is treated as fringe when cropping the image.
CROP_CUTOFF = 96
def nearest_colour(rgb: tuple[int, int, int]) -> str:
best, best_distance = "white", float("inf")
for name, reference in ANSI16.items():
distance = sum((a - b) ** 2 for a, b in zip(rgb, reference, strict=True))
if distance < best_distance:
best, best_distance = name, distance
return best
def key_white(image: Image.Image, tolerance: int) -> Image.Image:
"""Make near-white pixels transparent.
A logo exported on a white background (or one whose anti-aliasing bleeds
white) otherwise survives the downsample as a glaring box.
"""
image = image.copy()
pixels = image.load()
width, height = image.size
threshold = 255 - max(0, tolerance)
for y in range(height):
for x in range(width):
red, green, blue, alpha = pixels[x, y]
if alpha and min(red, green, blue) >= threshold:
pixels[x, y] = (red, green, blue, 0)
return image
def resize_premultiplied(image: Image.Image, size: tuple[int, int]) -> Image.Image:
"""Resize in premultiplied alpha, so transparent pixels cannot bleed in.
Plain ``Image.resize`` averages the RGB of fully transparent pixels (often
white) with the surrounding ink, which is how a clean logo turns into a
grey haze at 20x14.
"""
import numpy as np
data = np.asarray(image.convert("RGBA"), dtype=np.float32)
alpha = data[..., 3:4] / 255.0
premultiplied = np.concatenate([data[..., :3] * alpha, data[..., 3:4]], axis=-1)
small = Image.fromarray(premultiplied.astype(np.uint8), "RGBA").resize(
size, Image.LANCZOS
)
out = np.asarray(small, dtype=np.float32)
out_alpha = out[..., 3:4] / 255.0
rgb = out[..., :3] / np.maximum(out_alpha, 1e-6)
return Image.fromarray(
np.concatenate([np.clip(rgb, 0, 255), out[..., 3:4]], axis=-1).astype(np.uint8),
"RGBA",
)
def load_image(
path: Path | None, url: str | None, key_white_background: bool = False
) -> Image.Image:
if path is None and url:
import httpx
response = httpx.get(url, follow_redirects=True, timeout=30.0)
response.raise_for_status()
from io import BytesIO
image = Image.open(BytesIO(response.content))
elif path is not None:
image = Image.open(path)
else: # pragma: no cover - argparse enforces one of the two
raise SystemExit("pass an image path or --url")
image = image.convert("RGBA")
if key_white_background:
image = key_white(image, 24)
# Trim the transparent margin: the art should fill the box it is given.
opaque = image.getchannel("A").point(lambda value: 255 if value > CROP_CUTOFF else 0)
box = opaque.getbbox()
return image.crop(box) if box else image
def art_rows(image: Image.Image, cols: int, rows: int) -> list[list[tuple[str, str, str]]]:
"""(glyph, foreground, background) per cell, two source pixels per cell."""
small = resize_premultiplied(image, (cols, rows * 2))
pixels = small.load()
grid: list[list[tuple[str, str, str]]] = []
for row in range(rows):
cells: list[tuple[str, str, str]] = []
for column in range(cols):
top = pixels[column, row * 2]
bottom = pixels[column, row * 2 + 1]
top_ink = top[3] >= ALPHA_CUTOFF
bottom_ink = bottom[3] >= ALPHA_CUTOFF
if not top_ink and not bottom_ink:
cells.append((" ", "", ""))
elif top_ink and bottom_ink:
cells.append(("▀", nearest_colour(top[:3]), nearest_colour(bottom[:3])))
elif top_ink:
cells.append(("▀", nearest_colour(top[:3]), ""))
else:
cells.append(("▄", nearest_colour(bottom[:3]), ""))
grid.append(cells)
return grid
def markup(grid: list[list[tuple[str, str, str]]]) -> list[str]:
"""One rich-markup string per row, run-length encoded by style."""
lines: list[str] = []
for cells in grid:
line: list[str] = []
index = 0
while index < len(cells):
glyph, foreground, background = cells[index]
if not background and glyph == " ":
line.append(" ")
index += 1
continue
run = [glyph]
index += 1
while index < len(cells) and cells[index] == (glyph, foreground, background):
run.append(cells[index][0])
index += 1
style = " ".join(
part for part in (foreground, f"on {background}" if background else "") if part
)
body = "".join(run)
line.append(f"[{style}]{body}[/]" if style else body)
lines.append("".join(line).rstrip())
return lines
def preview(grid: list[list[tuple[str, str, str]]], path: Path, cell: tuple[int, int]) -> None:
width, height = cell
image = Image.new("RGB", (len(grid[0]) * width, len(grid) * height), (24, 24, 24))
draw = ImageDraw.Draw(image)
for row, cells in enumerate(grid):
for column, (glyph, foreground, background) in enumerate(cells):
x, y = column * width, row * height
if background:
draw.rectangle([x, y, x + width - 1, y + height - 1], fill=ANSI16[background])
if glyph == " ":
continue
colour = ANSI16.get(foreground, (140, 140, 140))
if glyph == "▀":
box = [x, y, x + width - 1, y + height // 2 - 1]
else:
box = [x, y + height // 2, x + width - 1, y + height - 1]
draw.rectangle(box, fill=colour)
image.resize((image.width * 3, image.height * 3), Image.NEAREST).save(path)
MODULE_TEMPLATE = '''"""Generated header art — do not edit by hand.
{provenance}
Regenerate with::
{command}
Each row is rich markup; ``▀`` is a half block whose foreground is the top
pixel and whose background is the pixel below it. Colours are stock ANSI
palette names, so the art keeps the terminal's own palette.
"""
from __future__ import annotations
HERO: tuple[str, ...] = (
{rows}
)
'''
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("image", nargs="?", type=Path, help="local image file")
parser.add_argument("--url", help="fetch the image from this URL instead")
parser.add_argument("--cols", type=int, default=22, help="terminal columns (default 22)")
parser.add_argument("--rows", type=int, default=7, help="terminal rows (default 7)")
parser.add_argument("--module", type=Path, help="write a Python module with HERO")
parser.add_argument("--preview", type=Path, help="write a PNG preview of the cells")
parser.add_argument("--provenance", default="", help="source note for the module header")
parser.add_argument(
"--key-white",
action="store_true",
help="treat near-white pixels as transparent (logos on white)",
)
args = parser.parse_args(argv)
image = load_image(args.image, args.url, args.key_white)
grid = art_rows(image, args.cols, args.rows)
rows = markup(grid)
if args.preview:
preview(grid, args.preview, (10, 20))
if args.module:
source = args.provenance or args.url or str(args.image)
command = "uv run python tools/ansi_art.py " + " ".join(sys.argv[1:])
body = "\n".join(f" {row!r}," for row in rows)
args.module.write_text(
MODULE_TEMPLATE.format(
provenance=f"Source: {source}",
command=command,
rows=body,
),
encoding="utf-8",
)
print(f"wrote {args.module} ({len(rows)} rows x {args.cols} cols)")
else:
print("\n".join(rows))
return 0
if __name__ == "__main__":
raise SystemExit(main())
Generated
+1 -1
View File
@@ -32,7 +32,7 @@ wheels = [
[[package]] [[package]]
name = "beefy-player" name = "beefy-player"
version = "1.2.1" version = "1.2.5"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [
{ name = "dbus-next", marker = "sys_platform == 'linux'" }, { name = "dbus-next", marker = "sys_platform == 'linux'" },