CLI for SidePulse
Python
Add simple installer and calendar releases
Peter Kuhar8edca48a3df5
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 89ff3ca..50373bc 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -1,7 +1,7 @@name: Publish to PyPI# Publishes to PyPI via OIDC trusted publishing (no API token stored).-# Triggers when a version tag is pushed, e.g. `git tag v0.1.0 && git push --tags`.+# Triggers when a calendar-version tag is pushed, for example v1.20260901.67530.on:push:tags:@@ -21,17 +21,31 @@ jobs:- uses: actions/setup-python@v5with:python-version: "3.12"- # Publishing v0.2.0 from a tree that still says 0.1.0 produces a release- # nobody can reference correctly, and PyPI uploads cannot be replaced.- - name: Verify tag matches package version+ # Calendar-version tags are both the release identifier and Python version.+ # Passing the validated value explicitly also keeps shallow checkouts+ # independent of Git tag-discovery behavior.+ - name: Validate calendar versionrun: |- tag="${GITHUB_REF_NAME#v}"- pkg="$(python -c "import tomllib, pathlib; print(tomllib.loads(pathlib.Path('pyproject.toml').read_text())['project']['version'])")"- if [ "$tag" != "$pkg" ]; then- echo "::error::tag $GITHUB_REF_NAME implies version $tag, but pyproject.toml declares $pkg"- exit 1- fi- echo "tag and package version agree: $pkg"+ version="${GITHUB_REF_NAME#v}"+ python - "$version" <<'PY'+ from datetime import datetime+ import sys++ value = sys.argv[1]+ try:+ major, date, seconds = value.split(".")+ if major != "1" or len(date) != 8 or not date.isdigit():+ raise ValueError+ datetime.strptime(date, "%Y%m%d")+ if not seconds.isdigit() or str(int(seconds)) != seconds:+ raise ValueError+ if not 0 <= int(seconds) < 86400:+ raise ValueError+ except (TypeError, ValueError):+ raise SystemExit(f"tag must be v1.YYYYMMDD.SECONDS, got v{value}")+ PY+ echo "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_SIDEPULSE=$version" >> "$GITHUB_ENV"+ echo "release version: $version"- name: Build sdist and wheelrun: |python -m pip install --upgrade builddiff --git a/MANIFEST.in b/MANIFEST.innew file mode 100644index 0000000..35ff3fe--- /dev/null+++ b/MANIFEST.in@@ -0,0 +1,18 @@+include LEDS_FORMAT.md+include LICENSE+include README.md+include pyproject.toml+recursive-include src *.c *.LED *.py *.wasm+recursive-include tests *.py++prune .github+prune data+prune examples+prune experiments+prune ios+prune media+prune packaging+prune profiles+prune scripts+global-exclude .DS_Store+global-exclude *.py[cod]diff --git a/README.md b/README.mdindex 5775f7f..0f4122f 100644--- a/README.md+++ b/README.md@@ -18,8 +18,38 @@ The device mounts as a disk drive. You can control the LEDs by writing to `LEDS.The LED control DSL is described in [`LEDS_FORMAT.md`](LEDS_FORMAT.md).-### TLDR+## Installation++Choose the level that fits how you want to use SidePulse.++### 1. One-command setup++```sh+curl -fsSL https://sidepulse.io/setup.sh | bash+```++The [setup script](scripts/setup.sh) creates an isolated environment under+`~/.local/share/sidepulse/venv`, installs SidePulse from GitHub, links the CLI+at `~/.local/bin/sidepulse`, and runs `sidepulse setup`. Run the same command+again to upgrade to the newest version.++### 2. Install into your own Python environment++If you already manage your own Python 3.10+ environment:++```sh+python3 -m pip install --upgrade \+ "git+https://github.com/inteliwear/sidepulse.git"+sidepulse setup+```++### 3. Clone it for development++Use an editable installation when you want to modify or hack on SidePulse:+```sh+git clone https://github.com/inteliwear/sidepulse.git+cd sidepulsepython3 -m pip install -e .sidepulse setup```@@ -612,15 +642,30 @@ iterating; CI always runs them.### Releasing-`git tag v0.1.0 && git push --tags` runs the full suite, checks the tag against-the version in `pyproject.toml`, builds, publishes, and then reinstalls the-release **from PyPI** on clean macOS and Linux runners to re-run the clean-room-tests against the artifact users actually download.+Build and verify the wheel and source archive locally:++```sh+./scripts/release.sh+```++The script generates a sortable calendar version such as `1.20260901.67530`:+major version `1`, UTC date `20260901`, and seconds since UTC midnight `67530`.+It runs the test suite in an isolated environment, builds the wheel and source+archive, checks their package metadata, installs the wheel into a clean+environment for a smoke test, and writes SHA-256 checksums beside the artifacts+in `dist/`. It prints the exact tag to push, but never tags, publishes, or+pushes itself. Use `--skip-tests` only when the suite has already passed in the+same checkout.++Pushing the printed tag, for example+`git tag v1.20260901.67530 && git push origin v1.20260901.67530`, runs the full+suite, uses the tag as the package version, builds, publishes, and then+reinstalls the release **from PyPI** on a clean macOS runner to re-run the+clean-room tests against the artifact users actually download.-Bump the version in both `pyproject.toml` and `src/sidepulse/__init__.py` — a-test fails if they disagree, and the tag guard fails if the tag disagrees with-either. To point the clean-room tests at any other build:+The version comes from the tag, so no source files need a version bump. To+point the clean-room tests at any published build:```sh-SIDEPULSE_INSTALL_SPEC='sidepulse==0.1.0' python3 -m pytest tests/test_environment.py -v+SIDEPULSE_INSTALL_SPEC='sidepulse==1.20260901.67530' python3 -m pytest tests/test_environment.py -v```diff --git a/packaging/build_macos_pkg.sh b/packaging/build_macos_pkg.shindex 131241d..d43ee23 100755--- a/packaging/build_macos_pkg.sh+++ b/packaging/build_macos_pkg.sh@@ -2,20 +2,19 @@set -euo pipefailROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"-VERSION="$(sed -n 's/^version = "\([^"]*\)"/\1/p' "$ROOT_DIR/pyproject.toml" | head -1)"ARCH="$(uname -m)"BUILD_DIR="$ROOT_DIR/build/macos-pkg"DIST_DIR="$ROOT_DIR/dist"VENV_DIR="$BUILD_DIR/venv"APP_PATH="$BUILD_DIR/pyinstaller/SidePulse.app"COMPONENT_PKG="$BUILD_DIR/SidePulse-component.pkg"-OUTPUT_PKG="$DIST_DIR/SidePulse-${VERSION}-${ARCH}.pkg"APP_ID="${APP_ID:-io.sidepulse.cli}"APP_SIGN_IDENTITY="${APP_SIGN_IDENTITY:-}"INSTALLER_SIGN_IDENTITY="${INSTALLER_SIGN_IDENTITY:-}"NOTARY_PROFILE="${NOTARY_PROFILE:-}"ALLOW_UNSIGNED="${ALLOW_UNSIGNED:-0}"+SIDEPULSE_VERSION="${SIDEPULSE_VERSION:-}"if { [ -z "$APP_SIGN_IDENTITY" ] || [ -z "$INSTALLER_SIGN_IDENTITY" ]; } && [ "$ALLOW_UNSIGNED" != "1" ]; thenecho "Set APP_SIGN_IDENTITY to a Developer ID Application identity and" >&2@@ -27,7 +26,12 @@ rm -rf "$BUILD_DIR"mkdir -p "$BUILD_DIR" "$DIST_DIR"python3 -m venv "$VENV_DIR""$VENV_DIR/bin/python" -m pip install --upgrade pip+if [ -n "$SIDEPULSE_VERSION" ]; then+ export SETUPTOOLS_SCM_PRETEND_VERSION_FOR_SIDEPULSE="$SIDEPULSE_VERSION"+fi"$VENV_DIR/bin/python" -m pip install 'pyinstaller>=6.10' "$ROOT_DIR"+VERSION="$("$VENV_DIR/bin/python" -c 'from importlib.metadata import version; print(version("sidepulse"))')"+OUTPUT_PKG="$DIST_DIR/SidePulse-${VERSION}-${ARCH}.pkg""$VENV_DIR/bin/pyinstaller" \--noconfirm --clean --windowed \diff --git a/pyproject.toml b/pyproject.tomlindex f76a247..0afe0ea 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,10 +1,10 @@[build-system]-requires = ["setuptools>=77"]+requires = ["setuptools>=77", "setuptools-scm>=8"]build-backend = "setuptools.build_meta"[project]name = "sidepulse"-version = "0.1.0"+dynamic = ["version"]description = "Command-line and macOS tools for SidePulse Pro and SidePulse Dot."readme = "README.md"requires-python = ">=3.10"@@ -62,3 +62,6 @@ include = ["sidepulse*", "agent_monitor*", "sidepulse_cli*"][tool.setuptools.package-data]"sidepulse.resources" = ["sd_eject_guard.c", "sdled.wasm", "animations/*.LED"]++[tool.setuptools_scm]+fallback_version = "0"diff --git a/scripts/release.sh b/scripts/release.shnew file mode 100755index 0000000..e9f902f--- /dev/null+++ b/scripts/release.sh@@ -0,0 +1,193 @@+#!/bin/bash+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"+PYTHON_BIN="${PYTHON_BIN:-python3}"+OUTPUT_DIR="$ROOT_DIR/dist"+RUN_TESTS=1+RELEASE_VERSION=""++usage() {+ cat <<'EOF'+Build a verified SidePulse Python release.++Usage: ./scripts/release.sh [options]++Options:+ --output-dir DIR Write the wheel, source archive, and checksums to DIR.+ Default: ./dist+ --version VALUE Use VALUE instead of generating a calendar version.+ VALUE must have the form 1.YYYYMMDD.SECONDS.+ --skip-tests Skip the repository test suite. Artifact checks still run.+ -h, --help Show this help.++Environment:+ PYTHON_BIN Python 3.10+ interpreter to use. Default: python3++This command builds release files only. It does not tag, publish, or push.+EOF+}++while [ "$#" -gt 0 ]; do+ case "$1" in+ --output-dir)+ if [ "$#" -lt 2 ]; then+ echo "release: --output-dir requires a directory" >&2+ exit 2+ fi+ OUTPUT_DIR="$2"+ shift 2+ ;;+ --skip-tests)+ RUN_TESTS=0+ shift+ ;;+ --version)+ if [ "$#" -lt 2 ]; then+ echo "release: --version requires 1.YYYYMMDD.SECONDS" >&2+ exit 2+ fi+ RELEASE_VERSION="$2"+ shift 2+ ;;+ -h|--help)+ usage+ exit 0+ ;;+ *)+ echo "release: unknown option: $1" >&2+ usage >&2+ exit 2+ ;;+ esac+done++if ! "$PYTHON_BIN" -c 'import sys; raise SystemExit(sys.version_info < (3, 10))'; then+ echo "release: SidePulse requires Python 3.10 or newer" >&2+ exit 1+fi++if [ -z "$RELEASE_VERSION" ]; then+ case "${GITHUB_REF_NAME:-}" in+ v*) RELEASE_VERSION="${GITHUB_REF_NAME#v}" ;;+ *)+ RELEASE_VERSION="$("$PYTHON_BIN" <<'PY'+from datetime import datetime, timezone++now = datetime.now(timezone.utc)+seconds = now.hour * 3600 + now.minute * 60 + now.second+print(f"1.{now:%Y%m%d}.{seconds}")+PY+)"+ ;;+ esac+fi+if ! "$PYTHON_BIN" - "$RELEASE_VERSION" <<'PY'+from datetime import datetime+import sys++try:+ major, date, seconds = sys.argv[1].split(".")+ if major != "1" or len(date) != 8 or not date.isdigit():+ raise ValueError+ datetime.strptime(date, "%Y%m%d")+ if not seconds.isdigit() or str(int(seconds)) != seconds:+ raise ValueError+ if not 0 <= int(seconds) < 86400:+ raise ValueError+except (TypeError, ValueError):+ raise SystemExit(1)+PY+then+ echo "release: version must have the form 1.YYYYMMDD.SECONDS with a real UTC date" >&2+ exit 2+fi++# setuptools-scm normally reads this version from a Git tag. Providing the+# same value here lets a local preflight build happen before the tag exists.+export SETUPTOOLS_SCM_PRETEND_VERSION_FOR_SIDEPULSE="$RELEASE_VERSION"++temporary_dir="$(mktemp -d "${TMPDIR:-/tmp}/sidepulse-release.XXXXXX")"+trap 'rm -rf "$temporary_dir"' EXIT+build_venv="$temporary_dir/build-venv"+build_output="$temporary_dir/artifacts"+smoke_venv="$temporary_dir/smoke-venv"+mkdir -p "$build_output"++echo "SidePulse $RELEASE_VERSION release"+echo "Creating an isolated build environment..."+"$PYTHON_BIN" -m venv "$build_venv"+"$build_venv/bin/python" -m pip install --quiet --upgrade pip build twine++if [ "$RUN_TESTS" -eq 1 ]; then+ echo "Installing test dependencies..."+ "$build_venv/bin/python" -m pip install --quiet -e "$ROOT_DIR[test]"+ echo "Running tests..."+ "$build_venv/bin/python" -m pytest "$ROOT_DIR/tests" -q+else+ echo "Skipping repository tests."+fi++echo "Building wheel and source archive..."+"$build_venv/bin/python" -m build "$ROOT_DIR" --outdir "$build_output"++echo "Checking package metadata..."+"$build_venv/bin/python" -m twine check "$build_output"/*++wheel_path="$(find "$build_output" -maxdepth 1 -type f -name '*.whl' -print -quit)"+source_path="$(find "$build_output" -maxdepth 1 -type f -name '*.tar.gz' -print -quit)"+if [ -z "$wheel_path" ] || [ -z "$source_path" ]; then+ echo "release: the build did not produce both a wheel and source archive" >&2+ exit 1+fi++echo "Smoke-testing the built wheel..."+"$PYTHON_BIN" -m venv "$smoke_venv"+"$smoke_venv/bin/python" -m pip install --quiet --upgrade pip+"$smoke_venv/bin/python" -m pip install --quiet "$wheel_path"+(+ cd "$temporary_dir"+ "$smoke_venv/bin/python" -c \+ "import sidepulse; assert sidepulse.__version__ == '$RELEASE_VERSION'"+ "$smoke_venv/bin/sidepulse" --help >/dev/null+)++mkdir -p "$OUTPUT_DIR"+for artifact in "$wheel_path" "$source_path"; do+ destination="$OUTPUT_DIR/$(basename "$artifact")"+ if [ -e "$destination" ]; then+ echo "release: refusing to overwrite existing artifact: $destination" >&2+ exit 1+ fi+done++checksum_name="sidepulse-$RELEASE_VERSION-SHA256SUMS.txt"+checksum_path="$OUTPUT_DIR/$checksum_name"+if [ -e "$checksum_path" ]; then+ echo "release: refusing to overwrite existing checksums: $checksum_path" >&2+ exit 1+fi++cp "$wheel_path" "$source_path" "$OUTPUT_DIR/"+(+ cd "$OUTPUT_DIR"+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$(basename "$wheel_path")" "$(basename "$source_path")"+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$(basename "$wheel_path")" "$(basename "$source_path")"+ else+ echo "release: need sha256sum or shasum to create checksums" >&2+ exit 1+ fi > "$checksum_name"+)++echo+echo "Release artifacts are ready:"+echo " $OUTPUT_DIR/$(basename "$wheel_path")"+echo " $OUTPUT_DIR/$(basename "$source_path")"+echo " $checksum_path"+echo+echo "Nothing was published. To release these sources as this exact version:"+echo " git tag v$RELEASE_VERSION"+echo " git push origin v$RELEASE_VERSION"diff --git a/scripts/setup.sh b/scripts/setup.shnew file mode 100755index 0000000..5ffc605--- /dev/null+++ b/scripts/setup.sh@@ -0,0 +1,18 @@+#!/bin/sh+set -eu++VENV="$HOME/.local/share/sidepulse/venv"+BIN_DIR="$HOME/.local/bin"++python3 -m venv "$VENV"+"$VENV/bin/python" -m pip install --upgrade \+ "git+https://github.com/inteliwear/sidepulse.git"++mkdir -p "$BIN_DIR"+ln -sf "$VENV/bin/sidepulse" "$BIN_DIR/sidepulse"+ln -sf "$VENV/bin/agent-monitor" "$BIN_DIR/agent-monitor"++"$VENV/bin/sidepulse" setup++printf '\nSidePulse is installed.\n'+printf 'Command: %s\n' "$BIN_DIR/sidepulse"diff --git a/src/sidepulse/__init__.py b/src/sidepulse/__init__.pyindex fa63c1e..e3125a8 100644--- a/src/sidepulse/__init__.py+++ b/src/sidepulse/__init__.py@@ -64,4 +64,9 @@ __all__ = ["write_mode_to_leds",]-__version__ = "0.1.0"+try:+ from importlib.metadata import version++ __version__ = version("sidepulse")+except Exception: # pragma: no cover - only an unpackaged source tree.+ __version__ = "0+unknown"diff --git a/tests/test_environment.py b/tests/test_environment.pyindex 8ef29b3..5106e29 100644--- a/tests/test_environment.py+++ b/tests/test_environment.py@@ -11,7 +11,8 @@ but ``pyproject.toml``, and then exercise the result. A dependency that is notdeclared is simply absent, so the failure is real rather than theoretical.The same tests double as a post-publish smoke test. Set-``SIDEPULSE_INSTALL_SPEC`` to a requirement string (``sidepulse==0.1.0``) and+``SIDEPULSE_INSTALL_SPEC`` to a requirement string+(``sidepulse==1.20260901.67530``) andthey install that from PyPI instead of the local tree, which checks theartifact users actually download rather than the one built here.@@ -24,7 +25,6 @@ from __future__ import annotationsimport jsonimport os-import reimport subprocessimport sysimport tempfile@@ -64,15 +64,13 @@ def is_local_install() -> bool:def expected_version() -> str:"""The version the install is expected to report.- Taken from the requirement pin when smoke-testing a release, otherwise- from the source tree being installed.+ Taken from the requirement pin when smoke-testing a release. Local builds+ use a tag-derived development version, so only internal agreement matters."""spec = os.environ.get("SIDEPULSE_INSTALL_SPEC")if spec and "==" in spec:return spec.split("==", 1)[1].strip()- text = (REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")- match = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE)- return match.group(1) if match else ""+ return ""@unittest.skipIf(@@ -202,11 +200,13 @@ class CleanInstallTests(unittest.TestCase):)self.assertEqual(0, result.returncode, result.stderr)metadata_version, dunder_version = result.stdout.split()- self.assertEqual(- expected_version(),- metadata_version,- f"installed {self.install_spec} reports version {metadata_version}",- )+ expected = expected_version()+ if expected:+ self.assertEqual(+ expected,+ metadata_version,+ f"installed {self.install_spec} reports version {metadata_version}",+ )self.assertEqual(metadata_version,dunder_version,diff --git a/tests/test_install_user.py b/tests/test_install_user.pyindex 83855be..7ecc983 100644--- a/tests/test_install_user.py+++ b/tests/test_install_user.py@@ -26,6 +26,25 @@ class UserInstallerTests(unittest.TestCase):)self.assertEqual(result.returncode, 0, result.stderr)+ def test_curl_setup_installs_github_checkout_in_local_venv(self) -> None:+ root = Path(__file__).resolve().parents[1]+ script = root / "scripts" / "setup.sh"+ text = script.read_text()+ self.assertIn('$HOME/.local/share/sidepulse/venv', text)+ self.assertIn('git+https://github.com/inteliwear/sidepulse.git', text)+ self.assertIn('"$VENV/bin/sidepulse" setup', text)+ self.assertNotIn("sudo", text)++ def test_curl_setup_shell_syntax(self) -> None:+ root = Path(__file__).resolve().parents[1]+ result = subprocess.run(+ ["sh", "-n", str(root / "scripts" / "setup.sh")],+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+if __name__ == "__main__":unittest.main()diff --git a/tests/test_packaging.py b/tests/test_packaging.pyindex 84edb5a..5eb5889 100644--- a/tests/test_packaging.py+++ b/tests/test_packaging.py@@ -372,25 +372,22 @@ class EntryPointTests(unittest.TestCase):class VersionTests(unittest.TestCase):- """The version is declared twice and must not drift.+ """Tag-derived package metadata and the runtime version must not drift.A published wheel whose metadata disagrees with ``sidepulse.__version__``makes bug reports impossible to place."""- def test_pyproject_and_dunder_version_agree(self):- import sidepulse+ def test_version_is_dynamic(self):+ project = load_pyproject()["project"]+ self.assertIn("version", project["dynamic"])+ self.assertNotIn("version", project)- declared = load_pyproject()["project"]["version"]- self.assertEqual(- declared,- sidepulse.__version__,- "pyproject.toml version and sidepulse.__version__ disagree; "- "update both when releasing",- )-- def test_installed_metadata_matches_source(self):- """Guards against testing a stale install of the package."""+ def test_metadata_and_dunder_version_agree(self):+ try:+ import sidepulse+ except ModuleNotFoundError:+ self.skipTest("sidepulse is not installed in this environment")from importlib.metadata import versiontry:@@ -398,10 +395,9 @@ class VersionTests(unittest.TestCase):except PackageNotFoundError:self.skipTest("sidepulse is not installed in this environment")self.assertEqual(- load_pyproject()["project"]["version"],installed,- "the installed sidepulse is a different version than this "- "source tree; reinstall with `pip install -e .`",+ sidepulse.__version__,+ "installed metadata and sidepulse.__version__ disagree",)diff --git a/tests/test_release_script.py b/tests/test_release_script.pynew file mode 100644index 0000000..3e25265--- /dev/null+++ b/tests/test_release_script.py@@ -0,0 +1,61 @@+from __future__ import annotations++import subprocess+import unittest+from pathlib import Path+++class ReleaseScriptTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls) -> None:+ cls.root = Path(__file__).resolve().parents[1]+ cls.script = cls.root / "scripts" / "release.sh"++ def test_shell_syntax(self) -> None:+ result = subprocess.run(+ ["bash", "-n", str(self.script)],+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)++ def test_help_describes_safe_scope(self) -> None:+ result = subprocess.run(+ ["bash", str(self.script), "--help"],+ cwd=self.root,+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("wheel", result.stdout)+ self.assertIn("source archive", result.stdout)+ self.assertIn("1.YYYYMMDD.SECONDS", result.stdout)+ self.assertIn("does not tag, publish, or push", result.stdout)++ def test_unknown_option_fails_without_building(self) -> None:+ result = subprocess.run(+ ["bash", str(self.script), "--not-a-real-option"],+ cwd=self.root,+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 2)+ self.assertIn("unknown option", result.stderr)++ def test_invalid_calendar_version_fails_without_building(self) -> None:+ result = subprocess.run(+ ["bash", str(self.script), "--version", "1.20260230.3600"],+ cwd=self.root,+ check=False,+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 2)+ self.assertIn("real UTC date", result.stderr)+++if __name__ == "__main__":+ unittest.main()