diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..424a313 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,308 @@ +--- +# SPDX-License-Identifier: BSD-3-Clause +# +# Core CI checks for sof-utils: +# - python-tools : py_compile, unittest suites, wheel install & CLI/import smoke tests +# - remote-server-linux : GCC & Clang builds via Make, CMake, and -DNO_ALSA check +# - remote-server-android : Android NDK cross-compilation (arm64-v8a & x86_64) +# - packaging : .deb & .rpm build, DESTDIR install/uninstall, dpkg install/remove + +name: CI + +# yamllint disable-line rule:truthy +on: + push: + branches: + - 'main' + pull_request: + branches: + - 'main' + workflow_dispatch: + +permissions: {} + +concurrency: + group: "${{ github.workflow }}-${{ github.event_name }}-\ + ${{ github.event_name == 'pull_request' && github.ref || github.run_id }}" + cancel-in-progress: true + +jobs: + python-tools: + name: Python Tools (sof-builder, sof-ucm, sof-top) + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install Python, GTK4, and desktop validation dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + python3 \ + python3-gi \ + python3-gi-cairo \ + python3-pip \ + python3-setuptools \ + python3-venv \ + python3-wheel \ + gir1.2-gtk-4.0 \ + gir1.2-pango-1.0 \ + desktop-file-utils \ + xvfb + + - name: Run make check (py_compile and unit tests) + env: + GDK_BACKEND: x11 + GSK_RENDERER: cairo + run: xvfb-run -a make check + + - name: Discover and run all Python unittest suites + env: + GDK_BACKEND: x11 + GSK_RENDERER: cairo + run: | + set -euo pipefail + for test_dir in */tests; do + if [ -d "$test_dir" ]; then + tool_dir="${test_dir%/tests}" + echo "==> Running unit tests in ${tool_dir}" + (cd "$tool_dir" && xvfb-run -a python3 -B -m unittest discover -s tests -v) + fi + done + + - name: Verify Python wheel packaging, isolated imports, and CLI entrypoints + run: | + set -euo pipefail + venv_dir="$(mktemp -d)" + trap 'rm -rf "$venv_dir"' EXIT + python3 -m venv --system-site-packages "$venv_dir" + "$venv_dir/bin/pip" install --no-deps --no-build-isolation \ + ./sof-builder ./sof-ucm ./sof-top + ( + cd /tmp + "$venv_dir/bin/sof-builder" --help >/dev/null + "$venv_dir/bin/sof-ucm" --help >/dev/null + "$venv_dir/bin/sof-top" --help >/dev/null + "$venv_dir/bin/sof-top-cli" --help >/dev/null + "$venv_dir/bin/python" - <<'PYEOF' + import sof_builder.model + import sof_builder.parser + import sof_builder.serializer + import sof_builder.tplg_ipc4 + import sof_builder.compiler + import sof_builder.testbench + import sof_ucm.model + import sof_ucm.ucm_parser + import sof_ucm.ucm_serializer + import sof_ucm.tplg_loader + import sof_ucm.graph_builder + import sof_ucm.discovery + import backend + import widgets_cairo + print("All packaged Python modules imported cleanly") + PYEOF + ) + + - name: Validate .desktop files + run: | + set -euo pipefail + find . -maxdepth 3 -name '*.desktop' -print0 \ + | xargs -0 -r desktop-file-validate + + remote-server-linux: + name: Remote Server Linux (${{ matrix.compiler }}) + runs-on: ubuntu-24.04 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + compiler: [gcc, clang] + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install C build dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + build-essential \ + clang \ + cmake \ + ninja-build \ + libasound2-dev + + - name: Build and smoke-test with Make + env: + COMPILER: ${{ matrix.compiler }} + run: | + set -euo pipefail + make -C sof-remote-server CC="$COMPILER" WORK_DIR="$PWD" all + (./sof-remote-server/sof-remote -h 2>&1 || true) | grep -q "Usage:" + (./sof-remote-server/sof_remote_server -h 2>&1 || true) | grep -q "Usage:" + make -C sof-remote-server clean + + - name: Build and smoke-test with CMake + env: + COMPILER: ${{ matrix.compiler }} + run: | + set -euo pipefail + cmake -G Ninja -S sof-remote-server -B build-remote-cmake \ + -DCMAKE_C_COMPILER="$COMPILER" + cmake --build build-remote-cmake + (./build-remote-cmake/sof-remote -h 2>&1 || true) | grep -q "Usage:" + (./build-remote-cmake/sof_remote_server -h 2>&1 || true) | grep -q "Usage:" + + - name: Verify -DNO_ALSA compilation + env: + COMPILER: ${{ matrix.compiler }} + run: | + set -euo pipefail + "$COMPILER" -O2 -Wall -Wextra -DNO_ALSA -fsyntax-only \ + sof-remote-server/sof_remote_server.c \ + sof-remote-server/audio_backend_alsa.c \ + sof-remote-server/audio_backend_tinyalsa.c \ + sof-remote-server/audio_backend_compress.c \ + sof-remote-server/dapm_inspector.c \ + sof-remote-server/sof_remote_cli.c + + remote-server-android: + name: Remote Server Android NDK Cross-Compile + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install CMake and Ninja + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends cmake ninja-build file + + - name: Cross-compile with Make (arm64-v8a and x86_64) + run: | + set -euo pipefail + test -n "${ANDROID_NDK_LATEST_HOME:-}" + test -d "${ANDROID_NDK_LATEST_HOME}" + for abi in arm64-v8a x86_64; do + echo "==> Building Android sof-remote-server for ${abi}" + make -C sof-remote-server \ + WORK_DIR="$PWD" \ + ANDROID_NDK_HOME="$ANDROID_NDK_LATEST_HOME" \ + ANDROID_ABI="$abi" \ + ANDROID_API=34 \ + android + file "sof-remote-server/build-android-${abi}/sof_remote_server" + file "sof-remote-server/build-android-${abi}/sof-remote" + done + file sof-remote-server/build-android-arm64-v8a/sof_remote_server | grep -q "ARM aarch64" + file sof-remote-server/build-android-x86_64/sof_remote_server | grep -q "x86-64" + + - name: Cross-compile with CMake Android toolchain (arm64-v8a) + run: | + set -euo pipefail + toolchain="${ANDROID_NDK_LATEST_HOME}/build/cmake/android.toolchain.cmake" + cmake -G Ninja -S sof-remote-server -B build-android-cmake \ + -DCMAKE_TOOLCHAIN_FILE="$toolchain" \ + -DANDROID_ABI=arm64-v8a \ + -DANDROID_PLATFORM=android-34 + cmake --build build-android-cmake + file build-android-cmake/sof_remote_server | grep -q "ARM aarch64" + file build-android-cmake/sof-remote | grep -q "ARM aarch64" + + packaging: + name: Packaging (.deb, .rpm, install/uninstall) + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install build, packaging, and runtime dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + build-essential \ + cmake \ + libasound2-dev \ + python3 \ + python3-gi \ + python3-gi-cairo \ + gir1.2-gtk-4.0 \ + gir1.2-pango-1.0 \ + alsa-utils \ + rpm \ + rsync \ + desktop-file-utils \ + xvfb + + - name: Build .deb and .rpm packages + env: + GDK_BACKEND: x11 + GSK_RENDERER: cairo + run: | + set -euo pipefail + xvfb-run -a make WORK_DIR="$PWD" WITH_TESTBENCH=0 deb + xvfb-run -a make WORK_DIR="$PWD" WITH_TESTBENCH=0 RPMBUILD="rpmbuild --nodeps" rpm + dpkg-deb -I dist/sof-utils_*.deb + dpkg-deb -c dist/sof-utils_*.deb + rpm -qlp dist/sof-utils-*.rpm + + - name: Verify DESTDIR install and clean uninstall + env: + GDK_BACKEND: x11 + GSK_RENDERER: cairo + run: | + set -euo pipefail + stage="$(mktemp -d)" + trap 'rm -rf "$stage"' EXIT + xvfb-run -a make WORK_DIR="$PWD" WITH_TESTBENCH=0 DESTDIR="$stage" PREFIX=/usr install + make WORK_DIR="$PWD" WITH_TESTBENCH=0 DESTDIR="$stage" PREFIX=/usr uninstall + leftover="$(find "$stage" -type f -o -type l)" + if [ -n "$leftover" ]; then + echo "ERROR: files left behind by make uninstall:" + echo "$leftover" + exit 1 + fi + + - name: Verify .deb system installation and clean removal + run: | + set -euo pipefail + sudo dpkg -i dist/sof-utils_*.deb + dpkg -s sof-utils + for bin in sof-builder sof-ucm sof-top sof-top-cli sof_remote_server sof-remote; do + test -x "/usr/bin/${bin}" + done + test -L /usr/bin/sof-remote-server + ( + cd /tmp + /usr/bin/sof-builder --help >/dev/null + /usr/bin/sof-ucm --help >/dev/null + /usr/bin/sof-top --help >/dev/null + /usr/bin/sof-top-cli --help >/dev/null + (/usr/bin/sof-remote -h 2>&1 || true) | grep -q "Usage:" + (/usr/bin/sof_remote_server -h 2>&1 || true) | grep -q "Usage:" + ) + desktop-file-validate /usr/share/applications/org.thesofproject.Sof*.desktop + sudo dpkg -r sof-utils + for bin in sof-builder sof-ucm sof-top sof-top-cli sof_remote_server \ + sof-remote-server sof-remote; do + test ! -e "/usr/bin/${bin}" + test ! -L "/usr/bin/${bin}" + done diff --git a/.github/workflows/codestyle.yml b/.github/workflows/codestyle.yml new file mode 100644 index 0000000..29d94ad --- /dev/null +++ b/.github/workflows/codestyle.yml @@ -0,0 +1,159 @@ +--- +# SPDX-License-Identifier: BSD-3-Clause +# +# Static hygiene and lint checks for sof-utils: +# - yamllint : strict YAML lint for workflows and west.yml +# - spdx-check : verify SPDX-License-Identifier headers on tracked source/build files +# - shell-syntax : bash -n syntax validation for shell scripts +# - python-lint : ruff fatal syntax & undefined-name checks (E9, F63, F7, F82) +# - commit-messages : subject format, 75-char wrap, and Signed-off-by trailer check + +name: codestyle + +# yamllint disable-line rule:truthy +on: + push: + branches: + - 'main' + pull_request: + branches: + - 'main' + workflow_dispatch: + +permissions: {} + +concurrency: + group: "${{ github.workflow }}-${{ github.event_name }}-\ + ${{ github.event_name == 'pull_request' && github.ref || github.run_id }}" + cancel-in-progress: true + +jobs: + yamllint: + name: YAML lint + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install yamllint + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends yamllint + + - name: Run yamllint + env: + yamllint_config: '{extends: default, rules: {line-length: {max: 100}}}' + run: | + yamllint -f parsable -d "$yamllint_config" --strict \ + .github/workflows/*.yml *.yml + + spdx-check: + name: SPDX license headers + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Verify SPDX-License-Identifier headers + run: | + set -euo pipefail + missing=0 + while IFS= read -r f; do + case "$f" in + LICENSE|*.md|*.desktop|*.txt|.gitignore|\ + debian/changelog|debian/control|debian/copyright|\ + sof-remote-server/sepolicy/*|sof-remote-server/Android.bp|\ + sof-remote-server/sof_remote_server.rc|\ + sof-testbench/arch/host/configs/*) + continue + ;; + esac + if ! head -n 5 "$f" | grep -q "SPDX-License-Identifier:"; then + echo "ERROR: missing SPDX-License-Identifier header in $f" + missing=1 + fi + done < <(git ls-files) + exit "$missing" + + shell-syntax: + name: Shell script syntax + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check bash syntax on tracked shell scripts + run: | + set -euo pipefail + while IFS= read -r f; do + echo "Checking $f" + bash -n "$f" + done < <(git ls-files '*.sh') + + python-lint: + name: Python fatal lint (ruff) + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run ruff fatal checks + uses: astral-sh/ruff-action@278981a28ce3188b1e39527901f38254bf3aac89 # v4.1.0 + with: + args: "check --select E9,F63,F7,F82" + src: >- + . sof-builder/sof-builder sof-ucm/sof-ucm + sof-top/sof-top sof-top/sof-top-cli + + commit-messages: + name: Commit messages (subject, wrap, SoB) + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Check commit messages + env: + EVENT_NAME: ${{ github.event_name }} + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PUSH_BEFORE: ${{ github.event.before }} + PUSH_AFTER: ${{ github.event.after }} + run: | + set -euo pipefail + if [ "$EVENT_NAME" = "pull_request" ]; then + rev_range="${PR_BASE_SHA}..${PR_HEAD_SHA}" + elif [ "$EVENT_NAME" = "push" ] && [ -n "$PUSH_BEFORE" ] \ + && [ "$PUSH_BEFORE" != "0000000000000000000000000000000000000000" ]; then + rev_range="${PUSH_BEFORE}..${PUSH_AFTER}" + else + rev_range="HEAD~1..HEAD" + fi + echo "Checking commit range: ${rev_range}" + python3 scripts/check_commits.py "$rev_range" diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 0000000..46b28e6 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,41 @@ +--- +# SPDX-License-Identifier: BSD-3-Clause + +name: "Zizmor GitHub Actions Analysis" + +# yamllint disable-line rule:truthy +on: + push: + branches: + - 'main' + pull_request: + branches: + - 'main' + workflow_dispatch: + +permissions: {} + +concurrency: + group: "${{ github.workflow }}-${{ github.event_name }}-\ + ${{ github.event_name == 'pull_request' && github.ref || github.run_id }}" + cancel-in-progress: true + +jobs: + zizmor: + name: Analyze workflows with zizmor + runs-on: ubuntu-24.04 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run zizmor + uses: zizmorcore/zizmor-action@5f14fd08f7cf1cb1609c1e344975f152c7ee938d # v0.5.6 + with: + inputs: .github/workflows/ + advanced-security: false + annotations: true diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..1c6246e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,75 @@ +# SOF Utilities (`sof-utils`) Agent Workflows and Rules + +This document outlines the rules AI agents must follow when checking out branches, writing code, documenting features, packaging tools, and running checks in `sof-utils`. Follow these rules carefully: + +## Repository Overview + +* `sof-builder/` — GTK4 Topology2 visual graph editor, IPC4 `.tplg` compiler, and testbench studio (Python / GTK4). +* `sof-ucm/` — GTK4 end-to-end audio pipeline visualizer and ALSA UCM2 editor (Python / GTK4, with `tests/`). +* `sof-top/` — GTK4 live DSP resource, SRAM/DRAM memory, and task monitor plus `sof-top-cli` (Python / GTK4). +* `sof-remote-server/` — C TCP telemetry and control daemon (`sof_remote_server`) and CLI (`sof-remote`) for Linux (ALSA) and Android (Bionic / `NO_ALSA` / TinyALSA / TinyCompress). +* `sof-testbench/` — Multi-core LL/DP host DSP simulator (`sof-testbench4`), `sof-tb-ctl`, host runtime (`arch/host/`, `platform/library/`), and 5-tier test suite (`run_test_suite.sh`). +* `sof-tplg-parser/` — ALSA topology (`.tplg`) IPC3/IPC4 parser library (`libsof_tplg_parser.a`). +* `Makefile`, `CMakeLists.txt`, `west.yml`, `debian/`, `packaging/rpm/`, `.github/workflows/` — Top-level build, West manifest, packaging, and CI workflows. + +## Development Standards + +### Commitment and Sign-off Rules +* **Commit Subject:** Must be 75 characters or fewer, must not end with a period, and must follow the format `tool: short description` (or `tool: component: short description`) matching the `sof-utils` git history. Use `git log --oneline -10 -- ` to determine the appropriate prefix. Examples: + * `sof-top: look up the DSP clock from the PCI ID` + * `sof-remote-server: fix SOF card selection and boot wake` + * `sof-builder: add binary .tplg opening and ABI version matching` + * `sof-ucm: guard GTK4 widget unit test when headless` +* **Patch Scope:** Keep each commit small and focused on one logical change (or tightly bound helpers), ensuring every commit compiles cleanly and passes checks for easy review and bisection. Avoid bundling unrelated tool, packaging, testbench, or CI changes into a single commit. +* **Commit Body & Line Wrap:** Separate the subject and body with a blank line, describe the changes and rationale clearly, and wrap body lines at 75 characters or fewer (trailers and URLs are exempt). Enforced by CI via `scripts/check_commits.py`. +* **Sign-off:** All commits must carry a `Signed-off-by: Name ` trailer matching the local git config identity (`git commit -s`). When an AI agent creates or updates commits on the developer's behalf, it SHOULD include `Signed-off-by:` using the developer's configured git identity (`git commit -s`) unless the developer instructs otherwise. + +### Documentation and Licensing Requirements +* **SPDX Headers:** All new source, script, build, and workflow files must include an `SPDX-License-Identifier:` header in the first 5 lines (`BSD-3-Clause` across the repo, or `(GPL-2.0-only OR BSD-3-Clause)` in `sof-remote-server/`). This is enforced by CI. +* **C API Comments:** Any new public C functions, structs, or wire protocol definitions (`sof_remote_proto.h`, `sof-tplg-parser/include/`, `sof-testbench/include/`) should include clear Doxygen-style comments. +* **Documentation Consistency:** When adding or modifying features, CLI options, environment variables, or build/packaging targets, review and update the corresponding tool `README.md` and top-level `README.md` so documentation stays in sync with code. + +### Codestyle and Linting +* **C Code (`sof-remote-server/`, `sof-testbench/`, `sof-tplg-parser/`):** Use `clangd` and compiler warnings (`-Wall -Wextra`; `sof-testbench` and `sof-tplg-parser` build with `-Werror`) instead of `checkpatch`. Keep `sof-remote-server` compiling cleanly under both GCC and Clang, both Make and CMake, and both ALSA and `-DNO_ALSA` / Android NDK builds. +* **Python Code (`sof-builder/`, `sof-ucm/`, `sof-top/`):** Must pass bytecode compilation (`make check`) and `ruff check --select E9,F63,F7,F82` with zero fatal syntax or undefined-name errors (including deferred type annotations). +* **YAML, Shell, and Desktop Files:** + * `.github/workflows/*.yml` and `west.yml` must start with `---` and pass `yamllint -f parsable -d '{extends: default, rules: {line-length: {max: 100}}}' --strict`. + * Shell scripts (`*.sh`) must pass `bash -n`. + * Desktop entry files (`*.desktop`) must pass `desktop-file-validate`. + +### Packaging, Protocol, and Headless Test Rules +* **Keep Packaging and Install Targets Synchronized:** Whenever adding a new Python module, script, `.desktop` file, or tool directory, update all of: + * the tool's `pyproject.toml` (`py-modules` / packages / scripts), + * the tool's `Makefile` (`check`, `install`, `uninstall`) and top-level `Makefile`, + * `debian/control` and `packaging/rpm/sof-utils.spec`. + Verify that installed wheels and `/usr/bin/*` entrypoints work from outside the repository tree (e.g., from `/tmp`) and that `make uninstall` leaves no orphaned files. +* **Headless-Safe GTK4 Unit Tests:** Any unit test that instantiates a `Gtk.Widget` subclass must call `Gtk.init_check()` and skip cleanly if `Gdk.Display.get_default() is None` so headless builds do not segfault. In CI, GTK4 test suites run under `xvfb-run -a` with `GDK_BACKEND=x11` and `GSK_RENDERER=cairo`. +* **Wire & Telemetry Protocol Consistency:** Any change to `SOFR` / `TEL2` / `PMW2` / `SOFZ` protocol definitions (`sof-remote-server/sof_remote_proto.h`, `sof-testbench/include/testbench/sof_remote_proto.h`) must keep `sof-remote-server`, `sof-top`, `sof-builder`, and `sof-testbench` in sync. +* **GitHub Actions Security:** Pin third-party actions to full 40-character commit SHAs with version comments, use least-privilege `permissions`, set `persist-credentials: false` on checkouts, and keep `.github/workflows/` clean under `zizmor`. + +### Local Verification Before Opening a PR +Run the checks matching the files you modified (these mirror `.github/workflows/ci.yml` and `.github/workflows/codestyle.yml`): + +```bash +# Commit message validation (subject, 75-char wrap, Signed-off-by) +python3 scripts/check_commits.py origin/main..HEAD + +# Python syntax and unit tests +make check + +# Fatal Python lint (including extensionless CLI entrypoints) +ruff check --select E9,F63,F7,F82 . sof-builder/sof-builder sof-ucm/sof-ucm sof-top/sof-top sof-top/sof-top-cli + +# C remote server build (Make and CMake) +make -C sof-remote-server all +cmake -G Ninja -S sof-remote-server -B build-remote-cmake && cmake --build build-remote-cmake + +# YAML, shell, and desktop validation +yamllint -f parsable -d '{extends: default, rules: {line-length: {max: 100}}}' --strict .github/workflows/*.yml *.yml +bash -n sof-testbench/run_test_suite.sh +find . -maxdepth 3 -name '*.desktop' -print0 | xargs -0 -r desktop-file-validate + +# Packaging verification (pass RPMBUILD="rpmbuild --nodeps" on Debian/Ubuntu hosts) +make WITH_TESTBENCH=0 deb +make WITH_TESTBENCH=0 RPMBUILD="rpmbuild --nodeps" rpm +``` diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..589e02c --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Lines starting with '#' are comments. +# Each line is a file pattern followed by one or more owners. +# Order is important: the last matching pattern has the highest precedence. +# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners + +# Default owner for everything in the repository +* @lgirdwood + +# Co-ownership overrides +/sof-testbench/ @lgirdwood @singalsu diff --git a/scripts/check_commits.py b/scripts/check_commits.py new file mode 100755 index 0000000..098660c --- /dev/null +++ b/scripts/check_commits.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: BSD-3-Clause +"""Validate git commit messages against sof-utils conventions. + +Checks enforced for each non-merge commit in the requested git revision range: + 1. Subject line: + - Non-empty and at most 75 characters (exempting 'Revert "..."' commits). + - Follows ': ' (e.g. 'sof-top: ...', + 'sof-builder: parser: ...', 'build, packaging: ...'). + - Does not start with 'WIP', 'fixup!', or 'squash!' prefixes. + - Does not end with a trailing period. + 2. Separator line: + - Line 2 must be blank when a commit body or trailer is present. + 3. Body line wrap: + - Body lines must be at most 75 characters, exempting standard git + trailers (Signed-off-by, Co-authored-by, Reviewed-by, Fixes, Link, + etc.), lines containing URLs, and single unbreakable tokens. + - Rejects stray Gerrit 'Change-Id:' lines. + 4. Sign-off (DCO): + - Must contain a valid 'Signed-off-by: Full Name ' trailer. +""" + +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +from typing import List, Sequence, Tuple + +MAX_SUBJECT_LEN = 75 +MAX_BODY_LINE_LEN = 75 + +# Prefix format: ': ' (supports nested 'a: b: desc' and +# comma-separated multi-tool prefixes like 'sof-top, sof-remote-server: desc'). +SUBJECT_PREFIX_RE = re.compile(r"^([^:\s][^:]*):\s+(\S.*)$") +FORBIDDEN_PREFIX_RE = re.compile(r"^(?:wip\b|fixup!|squash!|amend!)", re.IGNORECASE) +SOB_RE = re.compile(r"^Signed-off-by:\s+\S+(?:\s+\S+)+\s+<[^<>\s@]+@[^<>\s@]+\.[^<>\s@]+>$") +TRAILER_EXEMPT_RE = re.compile( + r"^(?:Signed-off-by|Co-authored-by|Reviewed-by|Acked-by|Tested-by|" + r"Reported-by|Suggested-by|Fixes|Closes|Link|Cc|Helped-by):", + re.IGNORECASE, +) +URL_RE = re.compile(r"https?://\S+") +BLOCKED_TAG_RE = re.compile(r"^\s*Change-Id:", re.IGNORECASE) + + +def validate_commit_message(sha: str, raw_message: str) -> List[str]: + """Validate a single commit message and return a list of error strings.""" + errors: List[str] = [] + lines = raw_message.rstrip("\n").splitlines() + if not lines or not lines[0].strip(): + return [f"{sha}: commit subject is empty"] + + subject = lines[0] + is_revert = subject.startswith('Revert "') + + if FORBIDDEN_PREFIX_RE.match(subject): + errors.append( + f"{sha}: line 1: subject contains forbidden prefix (WIP/fixup!/squash!): {subject!r}" + ) + + if not is_revert: + if len(subject) > MAX_SUBJECT_LEN: + errors.append( + f"{sha}: line 1: subject exceeds {MAX_SUBJECT_LEN} characters " + f"({len(subject)} > {MAX_SUBJECT_LEN}): {subject!r}" + ) + if not SUBJECT_PREFIX_RE.match(subject): + errors.append( + f"{sha}: line 1: subject must follow ': ' " + f"(e.g. 'sof-top: short description'): {subject!r}" + ) + if subject.endswith("."): + errors.append( + f"{sha}: line 1: subject must not end with a trailing period: {subject!r}" + ) + + if len(lines) >= 2 and lines[1].strip() != "": + errors.append( + f"{sha}: line 2: expected a blank line between subject and body, " + f"got {lines[1]!r}" + ) + + has_valid_sob = False + has_malformed_sob = False + + for idx, line in enumerate(lines[1:], start=2): + if BLOCKED_TAG_RE.match(line): + errors.append(f"{sha}: line {idx}: blocked tag 'Change-Id:' found") + + if line.lower().startswith("signed-off-by:"): + if SOB_RE.match(line): + has_valid_sob = True + else: + has_malformed_sob = True + errors.append( + f"{sha}: line {idx}: malformed Signed-off-by trailer " + f"(expected 'Signed-off-by: Full Name '): {line!r}" + ) + continue + + if len(line) > MAX_BODY_LINE_LEN: + if TRAILER_EXEMPT_RE.match(line) or URL_RE.search(line): + continue + # Allow a single unbreakable token (e.g., long path or identifier) + if len(line.strip().split()) <= 1: + continue + errors.append( + f"{sha}: line {idx}: body line exceeds {MAX_BODY_LINE_LEN} characters " + f"({len(line)} > {MAX_BODY_LINE_LEN}): {line!r}" + ) + + if not has_valid_sob and not has_malformed_sob: + errors.append( + f"{sha}: missing 'Signed-off-by: Full Name ' trailer " + "(use 'git commit -s')" + ) + + return errors + + +def iter_commits(rev_range: str) -> List[Tuple[str, str, str]]: + """Return list of (short_sha, author_name, commit_message) for rev_range.""" + sep = "\x1e" + field_sep = "\x1f" + cmd = [ + "git", + "log", + "--no-merges", + f"--format=%h{field_sep}%an{field_sep}%B{sep}", + rev_range, + ] + res = subprocess.run(cmd, capture_output=True, text=True, check=True) + commits: List[Tuple[str, str, str]] = [] + for entry in res.stdout.split(sep): + entry = entry.strip("\n") + if not entry: + continue + parts = entry.split(field_sep, 2) + if len(parts) != 3: + continue + commits.append((parts[0], parts[1], parts[2])) + return commits + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Check git commit messages for subject format, 75-char wrap, and Signed-off-by." + ) + parser.add_argument( + "rev_range", + nargs="?", + default="origin/main..HEAD", + help="Git revision range to validate (default: origin/main..HEAD)", + ) + args = parser.parse_args(argv) + + try: + commits = iter_commits(args.rev_range) + except subprocess.CalledProcessError as exc: + print(f"ERROR: git log failed for {args.rev_range!r}: {exc.stderr.strip()}", file=sys.stderr) + return 2 + + if not commits: + print(f"No non-merge commits found in range {args.rev_range!r}.") + return 0 + + all_errors: List[str] = [] + checked = 0 + for sha, author, msg in commits: + if author == "dependabot[bot]": + continue + checked += 1 + all_errors.extend(validate_commit_message(sha, msg)) + + if all_errors: + print(f"Commit message check FAILED ({len(all_errors)} issue(s) across {checked} commit(s)):\n") + for err in all_errors: + print(f" - {err}") + return 1 + + print(f"Commit message check PASSED ({checked} commit(s) in {args.rev_range}).") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/tests/test_check_commits.py b/scripts/tests/test_check_commits.py new file mode 100644 index 0000000..db870be --- /dev/null +++ b/scripts/tests/test_check_commits.py @@ -0,0 +1,87 @@ +# SPDX-License-Identifier: BSD-3-Clause +"""Unit tests for scripts/check_commits.py.""" + +from __future__ import annotations + +import os +import sys +import unittest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) + +from check_commits import validate_commit_message + + +class TestCheckCommits(unittest.TestCase): + def test_valid_commit(self) -> None: + msg = ( + "sof-top: Add DSP max clock database keyed by PCI ID\n" + "\n" + "The SOF telemetry interface does not publish the DSP core clock.\n" + "See https://github.com/thesofproject/sof-utils/pull/12/very/long/url/example\n" + "\n" + "Signed-off-by: Liam Girdwood \n" + ) + self.assertEqual(validate_commit_message("abc1234", msg), []) + + def test_valid_subject_and_sob_only(self) -> None: + msg = ( + "sof-top: Document DSP clock lookup and add make test\n" + "\n" + "Signed-off-by: Kai Vehmanen \n" + ) + self.assertEqual(validate_commit_message("abc1234", msg), []) + + def test_rejects_missing_prefix_and_long_subject_and_period(self) -> None: + msg = ( + "Add a very long commit subject without a subsystem prefix that exceeds seventy-five chars.\n" + "\n" + "Signed-off-by: Liam Girdwood \n" + ) + errs = validate_commit_message("abc1234", msg) + self.assertTrue(any("exceeds 75" in e for e in errs)) + self.assertTrue(any(": " in e for e in errs)) + self.assertTrue(any("trailing period" in e for e in errs)) + + def test_rejects_missing_blank_line_and_long_body(self) -> None: + msg = ( + "ci: Add commit message check\n" + "Missing blank line after subject and also a very long unwrapped line exceeding seventy-five characters.\n" + "\n" + "Signed-off-by: Liam Girdwood \n" + ) + errs = validate_commit_message("abc1234", msg) + self.assertTrue(any("blank line" in e for e in errs)) + self.assertTrue(any("body line exceeds 75" in e for e in errs)) + + def test_rejects_missing_or_malformed_sob(self) -> None: + no_sob = "ci: Add check\n\nBody text.\n" + self.assertTrue(any("missing 'Signed-off-by:" in e for e in validate_commit_message("a", no_sob))) + + bad_sob = "ci: Add check\n\nSigned-off-by: singleword \n" + self.assertTrue(any("malformed Signed-off-by" in e for e in validate_commit_message("a", bad_sob))) + + def test_rejects_wip_and_change_id(self) -> None: + msg = ( + "WIP: test change\n" + "\n" + "Change-Id: I1234567890abcdef\n" + "Signed-off-by: Liam Girdwood \n" + ) + errs = validate_commit_message("abc1234", msg) + self.assertTrue(any("forbidden prefix" in e for e in errs)) + self.assertTrue(any("Change-Id" in e for e in errs)) + + def test_allows_revert_commit_over_75_chars(self) -> None: + msg = ( + 'Revert "sof-builder: Add a long previously merged commit subject that exceeds 75 characters"\n' + "\n" + "This reverts commit 1234567890.\n" + "\n" + "Signed-off-by: Liam Girdwood \n" + ) + self.assertEqual(validate_commit_message("abc1234", msg), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/sof-builder/sof_builder/testbench.py b/sof-builder/sof_builder/testbench.py index 16c0516..261da12 100644 --- a/sof-builder/sof_builder/testbench.py +++ b/sof-builder/sof_builder/testbench.py @@ -21,7 +21,7 @@ import time import wave from dataclasses import dataclass, field -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, List, Optional, Set, Tuple import gi gi.require_version("Gdk", "4.0") diff --git a/sof-builder/sof_builder/window.py b/sof-builder/sof_builder/window.py index 701d961..2f80846 100644 --- a/sof-builder/sof_builder/window.py +++ b/sof-builder/sof_builder/window.py @@ -51,6 +51,7 @@ serialize_graph_for_save, ) from .testbench import ( + ComponentPerfItem, KcontrolTelemetryItem, SOF_CDEV_WIN_DEBUG, SOF_CDEV_WIN_FW_REGS, diff --git a/sof-ucm/tests/test_tplg_and_graph.py b/sof-ucm/tests/test_tplg_and_graph.py index e41135a..fef70e5 100644 --- a/sof-ucm/tests/test_tplg_and_graph.py +++ b/sof-ucm/tests/test_tplg_and_graph.py @@ -261,6 +261,12 @@ def test_ssh_transport_cmd_hardening(self) -> None: self.assertTrue(ctl_opt.endswith("/ssh-%C")) def test_edge_texture_key_distinguishes_equal_length_traces(self) -> None: + from gi.repository import Gdk, Gtk + + Gtk.init_check() + if Gdk.Display.get_default() is None: + self.skipTest("No GDK display available for GTK4 widget instantiation") + snap = MachineAudioSnapshot( target_label="trace-key", card=SoundCardInfo(card_id=0, id="c0", driver="sof", name="c0", longname="c0", components=""), diff --git a/west.yml b/west.yml index ab5d619..bbde0f3 100644 --- a/west.yml +++ b/west.yml @@ -1,3 +1,4 @@ +--- # SPDX-License-Identifier: BSD-3-Clause # # West manifest for standalone sof-utils development.