Compare commits

23 Commits
Author SHA1 Message Date
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 1144 additions and 85 deletions

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
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: tools/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
+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
+30
View File
@@ -31,8 +31,38 @@ synced `.venv/bin/python` explicitly.
```bash
uv sync # resync the environment (do this first)
git submodule update --init # contrib/homebrew, the Homebrew tap
uv run pytest # full test suite
uvx ruff check . # lint (ruff is not a project dependency)
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 still carries a
placeholder `sha256`, so it only installs with `--HEAD`.
## 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
`tools/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.
+178 -11
View File
@@ -46,6 +46,154 @@ as you type. Press `p` to switch catalogue without restarting.
## 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
```bash
@@ -172,20 +320,39 @@ These stay in the usual XDG locations on every platform, macOS included;
## Development
```bash
uv sync # create the environment
uv run pytest # test suite
uvx ruff check . # lint
uv sync # create the environment
git submodule update --init # contrib/homebrew, the Homebrew tap
uv run pytest # test suite
uvx ruff check . # lint
```
Each catalogue is a self-contained provider module under
`beefy_player/providers/`; `base.py` documents the interface. `tools/ansi_art.py`
converts a PNG logo into half-block ANSI art. On NixOS, `shell.nix` provides an
FHS shell for the same `uv sync` / `uv run` workflow.
`beefy_player/providers/`; `base.py` documents the interface. Every catalogue's
header is a wordmark from the shared half-block font, and the header paints it
with the active palette gradient (`hero_gradient`, on by default) so all
thirteen follow the terminal's colours. `tools/ansi_art.py` converts a PNG logo
into half-block ANSI art that carries colours of its own; a provider using that
art must set `hero_gradient = False`, because the header would otherwise
repaint it with the gradient.
`uvx ruff check .` is the enforced lint. The tree is not `ruff format`-clean (54
files would change), so do not reformat it wholesale.
`tools/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
WTFPL — Do What The Fuck You Want To Public License, Version 2. See
[LICENSE](LICENSE). SomaFM and its channel names are trademarks of
SomaFM.com, LLC. tilderadio belongs to the tildeverse community.
Terminal image rendering uses [Pillow](https://python-pillow.org/).
WTFPL — Do What The Fuck You Want To Public License, Version 2.
See [LICENSE](LICENSE).
+1 -1
View File
@@ -1,3 +1,3 @@
"""Beefy Player — a flashy terminal player for internet radio."""
__version__ = "1.2.1"
__version__ = "1.2.4"
+4 -3
View File
@@ -107,9 +107,10 @@ class RadioProvider(ABC):
#: Rows of header art drawn at the top left (rich markup is allowed).
hero: tuple[str, ...] = ()
#: Paint :attr:`hero` with the app's spectrum gradient (a wordmark) instead
#: of the colours the art carries itself (a picture).
hero_gradient: bool = False
#: Paint :attr:`hero` with the app's active palette gradient instead of the
#: colours the art carries itself. On by default so every catalogue's
#: 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.
hero_lines: tuple[str, ...] = ()
+2 -2
View File
@@ -29,8 +29,8 @@ class BassdriveProvider(RadioProvider):
station_source = "bassdrive.com + icecast status"
history_source = "icecast status (rolling)"
# The wordmark in the station's own two blues, in the shared half-block
# font; the caption is the station's own description.
# The wordmark in the shared half-block font, painted with the app's
# palette gradient; the caption is the station's own description.
hero = hero_art.HERO
hero_lines = (
"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
map onto the stock palette's bright cyan and cyan, so the wordmark still reads
as Bassdrive without hard-coded RGB.
The header paints it with the app's active palette gradient, like every other
catalogue's wordmark, so the logo follows the terminal's colours.
"""
from __future__ import annotations
from ..wordmark import render
HERO: tuple[str, ...] = render(
"BASSDRIVE", ["bright_cyan"] * 4 + ["cyan"] * 5
)
HERO: tuple[str, ...] = render("BASSDRIVE")
@@ -30,7 +30,6 @@ class SomaFMProvider(RadioProvider):
history_source = "songs/<station>.json"
hero = hero_art.LOGO
hero_gradient = True
hero_lines = hero_art.TAGLINES
@property
+3 -3
View File
@@ -1,9 +1,9 @@
"""SomaFM's header hero: the block-letter wordmark and the three lines beside it.
The glyphs come from the shared half-block font
(:mod:`beefy_player.providers.wordmark`); the header paints them with the app's
spectrum gradient (``hero_gradient``), so the logo takes on the terminal's own
colours instead of carrying RGB values around.
(:mod:`beefy_player.providers.wordmark`); the header paints every catalogue's
wordmark with the app's active palette gradient, so the logo takes on the
terminal's own colours instead of carrying RGB values around.
"""
from __future__ import annotations
@@ -29,8 +29,8 @@ class TilderadioProvider(RadioProvider):
station_source = "tilderadio.org/api/now/"
history_source = "now_playing + history[]"
# The station's own radio icon, converted to half blocks by
# ``tools/ansi_art.py``; the caption is the tildeverse's motto.
# The station's wordmark in the shared half-block font, painted with the
# app's palette gradient; the caption is the tildeverse's motto.
hero = hero_art.HERO
hero_lines = (
"TILDERADIO",
+3 -2
View File
@@ -1,7 +1,8 @@
"""tilderadio's header hero: its name in the shared half-block font.
No colours of its own — the wordmark inherits the terminal's default
foreground, so it looks like part of the chrome rather than a logo pasted in.
The shared half-block font; the header paints it with the app's active
palette gradient, so the wordmark follows the terminal's colours like the rest
of the chrome.
"""
from __future__ import annotations
+6 -34
View File
@@ -2,9 +2,9 @@
Every shipped catalogue draws its brand the same way: four-column capitals,
six pixels tall, emitted as three rows of half blocks (``▀``/``▄``/``█``) — the
same shape as the original SomaFM logo. Catalogues differ only in the word
they spell and the ANSI colours they paint it with, so the font lives here and
each provider's ``hero.py`` is one line of data.
same shape as the original SomaFM logo. The header paints every wordmark with
the app's active palette gradient, so catalogues differ only in the word they
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
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 collections.abc import Sequence
#: 6-row bitmap per capital; all rows of one glyph are the same width.
GLYPHS: dict[str, tuple[str, ...]] = {
"A": (".##.", "#..#", "####", "#..#", "#..#", "#..#"),
@@ -65,36 +63,10 @@ def _glyph_rows(char: str) -> tuple[str, ...]:
)
def render(text: str, styles: Sequence[str | None] | None = None) -> tuple[str, ...]:
"""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")
def render(text: str) -> tuple[str, ...]:
"""Spell ``text`` as three rows of half blocks."""
glyphs = [_glyph_rows(char.upper()) for char in text]
rows: list[str] = []
for row in range(ROWS):
cells: list[tuple[str | None, str]] = []
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)
)
rows.append(_GAP.join(glyph[row] for glyph in glyphs).rstrip())
return tuple(rows)
+4 -1
View File
@@ -35,8 +35,11 @@ def _hero_line(
line.no_wrap = True
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)
for column, char in enumerate(markup):
for column, char in enumerate(plain):
position = (column / max(1, width - 1) + index * 0.055) % 1.0
line.append(char, style=f"bold {gradient(stops, position)}")
return line
+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.2
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.2.tar.gz::https://tildeforge.dev/beefcarver/beefy-player/archive/941c7446384bf346e40d1438a7ce67939d9615df.tar.gz
sha256sums = 8ac568676ef5ef8345441c28e4f8f5d61fb06d5225e566ac578acae18672c778
pkgname = beefy-player
+59
View File
@@ -0,0 +1,59 @@
# Maintainer: beefy-player contributors <[email protected]>
pkgname=beefy-player
pkgver=1.2.2
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'
)
# Upstream does not tag releases yet, so the source is the archive of the
# commit that carries this version. Once a `v$pkgver` tag exists, switch to
#
# source=("$pkgname-$pkgver.tar.gz::$url/archive/v$pkgver.tar.gz")
#
_commit=941c7446384bf346e40d1438a7ce67939d9615df
source=("$pkgname-$pkgver.tar.gz::$url/archive/$_commit.tar.gz")
sha256sums=('8ac568676ef5ef8345441c28e4f8f5d61fb06d5225e566ac578acae18672c778')
build() {
cd "$pkgname"
python -m build --wheel --no-isolation
}
check() {
cd "$pkgname"
# The suite is offline: catalogues are fixtures, mpv/parec are faked.
python -m pytest -q
}
package() {
cd "$pkgname"
python -m installer --destdir="$pkgdir" dist/*.whl
}
+1
Submodule contrib/homebrew added at ad6fcc5732.
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.4";
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]
name = "beefy-player"
version = "1.2.1"
version = "1.2.4"
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"
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.bandcamp is False
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 == (
"BASSDRIVE",
"WORLDWIDE DRUM & BASS",
+29 -6
View File
@@ -6,6 +6,7 @@ import types
import pytest
from rich.cells import cell_len
from beefy_player.palettes import DEFAULT_PALETTE, PALETTES
from beefy_player.providers import PROVIDERS
from beefy_player.providers.somafm import SomaFMProvider
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:
"""Two-pixel stems make an I look like an H and a T look like a block."""
assert render("I") == ("▀█▀", " █", "▄█▄")
@@ -108,27 +120,38 @@ def test_every_catalogue_has_a_three_row_wordmark() -> None:
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"]
lines = render_header(143, height=len(provider.hero), provider=provider)
assert len(lines) == 3
assert "TILDERADIO" in lines[0] # the wordmark
assert "STREAMED BY / FOR USERS OF THE" in lines[1]
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 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)
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"]
lines = render_header(143, height=len(provider.hero), provider=provider)
assert "BASSDRIVE" in lines[0]
assert "WORLDWIDE DRUM & BASS" in lines[1]
assert "LIVE SHOWS 24/7" in lines[2]
styles = hero_styles(provider)
assert "bright_cyan" in styles and "cyan" in styles
assert provider.hero_gradient
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):
+2 -2
View File
@@ -2,13 +2,13 @@ from __future__ import annotations
import os
import queue
import sys
import time
from pathlib import Path
from beefy_player.player import Player
FAKE_MPV = '''#!/usr/bin/env python3
import json, os, socket, sys, time
FAKE_MPV = f"#!{sys.executable}\n" + '''import json, os, socket, sys, time
sock_path = None
volume = 70
+1 -1
View File
@@ -154,7 +154,7 @@ def test_tilderadio_replaces_the_station_list_with_a_schedule() -> None:
provider = TilderadioProvider()
assert provider.has_schedule is True
# 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 == (
"TILDERADIO",
"STREAMED BY / FOR USERS OF THE",
+4 -4
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import sys
import time
from pathlib import Path
@@ -8,8 +9,7 @@ import numpy as np
from beefy_player import spectrum as spectrum_module
from beefy_player.spectrum import Frame, SpectrumEngine
PCM_SCRIPT = """#!/usr/bin/env python3
import math, struct, sys, time
PCM_SCRIPT = f"#!{sys.executable}\n" + """import math, struct, sys, time
sr = 44100
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)
@@ -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:
script = tmp_path / "silent-parec"
script.write_text(
"#!/usr/bin/env python3\n"
f"#!{sys.executable}\n"
"import sys\n"
"block = b'\\0' * 4096\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.
script = tmp_path / "parec"
script.write_text(
"#!/usr/bin/env python3\n"
f"#!{sys.executable}\n"
"import math, struct, sys, time\n"
"sr = 44100\n"
"n = 2048\n"
+13 -2
View File
@@ -7,11 +7,18 @@ 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.
Shipped catalogues no longer use image art: each one renders a wordmark from
beefy_player/providers/wordmark.py, which the header repaints with the active
palette gradient (RadioProvider.hero_gradient, on by default). Art from this
tool carries colours of its own, so a provider that uses it must set
hero_gradient = False — otherwise the header repaints the art with the gradient
and the palette names below are wasted.
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
python tools/ansi_art.py --url https://example.org/logo.png \\
--cols 22 --rows 7 --module beefy_player/providers/<slug>/hero.py
``--preview out.png`` draws what the cells will look like, which is much easier
to judge than a wall of ▀ and ▄.
@@ -209,6 +216,10 @@ Regenerate with::
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.
The header paints every hero with the active palette gradient unless the
provider opts out, so the class using this art must set
``hero_gradient = False``.
"""
from __future__ import annotations
+450
View File
@@ -0,0 +1,450 @@
#!/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 tools/bump_packaging.py 1.2.3 # download the release asset
python tools/bump_packaging.py 1.2.3 --asset dist/beefy_player-1.2.3.tar.gz
python tools/bump_packaging.py 1.2.3 --commit # also commit both repos
python tools/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 re
import subprocess
import sys
import tarfile
import tempfile
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.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. tools/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 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}")
target = Path(tempfile.mkdtemp()) / f"{ASSET_NAME}-{version}.tar.gz"
try:
with urllib.request.urlopen(url) as response, target.open("wb") as handle:
handle.write(response.read())
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")
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"')
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")
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())
Generated
+1 -1
View File
@@ -32,7 +32,7 @@ wheels = [
[[package]]
name = "beefy-player"
version = "1.2.1"
version = "1.2.4"
source = { editable = "." }
dependencies = [
{ name = "dbus-next", marker = "sys_platform == 'linux'" },