From a83ce827ddc9b46bf808979008c32e839a9cfe20 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Fri, 27 Nov 2026 13:53:09 +0100 Subject: [PATCH 1/6] feat(packaging): add the shared nfpm action Builds rpm or deb packages from nfpm configurations, caches them and optionally uploads them. It relies on the variable expansion, the signing rule and the target option of nfpm instead of editing the configurations. --- .github/workflows/lint.yml | 45 +++++ README.md | 2 +- packaging/README.md | 97 ++++++++++ packaging/nfpm/action.yml | 112 ++++++++++++ packaging/nfpm/package.sh | 136 ++++++++++++++ packaging/tests/nfpm.bats | 307 ++++++++++++++++++++++++++++++++ packaging/tests/smoke/nfpm.yaml | 23 +++ 7 files changed, 721 insertions(+), 1 deletion(-) create mode 100644 packaging/nfpm/action.yml create mode 100755 packaging/nfpm/package.sh create mode 100644 packaging/tests/nfpm.bats create mode 100644 packaging/tests/smoke/nfpm.yaml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 4b10996..d013704 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -127,11 +127,23 @@ jobs: include: - name: debian image: debian:12@sha256:1d04200c2ece1d4d75a2a6f8e11ebce7d86a2ae28b34bb2c9cbb3ee9f4953e75 + distrib: bookworm + package: smoke-test_1.0.0-7+deb12u1_all.deb - name: almalinux image: almalinux:9@sha256:02df05719ef287ebd0df0a1eedb9172a00bd70703aed7b25660e426b8e0d6047 + distrib: el9 + package: smoke-test-1.0.0-7.el9.noarch.rpm container: image: ${{ matrix.image }} + env: + NFPM_VERSION: "2.43.4" + NFPM_SHA256: cafb544650cb0305d1b164fc0ab261eb77a81af324e18011282d326b326d20fb steps: + - name: Checkout sources + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Smoke test packaging/parse-distrib in a container id: parse-distrib-smoke uses: $/packaging/parse-distrib @@ -144,3 +156,36 @@ jobs: DISTRIB_FAMILY_MAJOR: ${{ steps.parse-distrib-smoke.outputs.distrib_family_major }} run: | [[ "$PACKAGE_DISTRIB_NAME" == "el9" && "$DISTRIB_FAMILY_MAJOR" == "el9" ]] + + - name: Install nfpm + run: | + if command -v apt-get > /dev/null; then + apt-get update + apt-get install --yes --no-install-recommends ca-certificates curl + fi + curl --fail --silent --show-error --location --output /tmp/nfpm.tar.gz \ + "https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_Linux_x86_64.tar.gz" + echo "${NFPM_SHA256} /tmp/nfpm.tar.gz" | sha256sum --check + tar --extract --gzip --file /tmp/nfpm.tar.gz --directory /usr/local/bin nfpm + + # a real, unsigned package, cached under a key nothing reads + - name: Smoke test packaging/nfpm in a container + uses: $/packaging/nfpm + with: + nfpm_file_pattern: packaging/tests/smoke/*.yaml + distrib: ${{ matrix.distrib }} + version: "1.0.0" + release: "7" + arch: all + commit_hash: ${{ github.sha }} + allow_unsigned: "true" + cache_key: smoke-test-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.distrib }} + + - name: Check the smoke-tested package + env: + PACKAGE: ${{ matrix.package }} + run: | + ls -l + [[ -f "$PACKAGE" ]] + # the signing key file never lands in the workspace + [[ -z "$(find . -name '*.gpg')" ]] diff --git a/README.md b/README.md index 49af88e..83f80d7 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ code. Each package documents its actions in its own `README.md`. | ------------------------------------------ | ------------------------------------------------------------------- | | [`pulp`](pulp/README.md) | `pulp/package-delivery`, `pulp/promote-to-stable`, `pulp/setup-cli` | | [`download-site`](download-site/README.md) | `download-site/sources-delivery`, `download-site/publication` | -| [`packaging`](packaging/README.md) | `packaging/parse-distrib` | +| [`packaging`](packaging/README.md) | `packaging/parse-distrib`, `packaging/nfpm` | ## Usage diff --git a/packaging/README.md b/packaging/README.md index d8f1b69..68e72cb 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -5,6 +5,7 @@ Actions shared by the packaging jobs. | Action | Purpose | | ------------------------- | ----------------------------------------------------------------------- | | `packaging/parse-distrib` | Give the package extension, the naming and the family of a distribution | +| `packaging/nfpm` | Build rpm or deb packages with nfpm, cache them and upload them | ## Parse distrib @@ -56,3 +57,99 @@ caller that needs the former value reads `distrib_family_major`. Add its line to `parse-distrib.sh`, to this table and to the tests, and to the table of the `pulp` package (`pulp/lib/parse-distrib.sh`), which keeps its own copy: a test fails when the two disagree. + +## Package with nfpm + +```yaml +- name: Package + uses: centreon/github-actions/packaging/nfpm@packaging/v1 + with: + nfpm_file_pattern: "packaging/*.yaml" + distrib: ${{ matrix.distrib }} + major_version: ${{ needs.get-environment.outputs.major_version }} + minor_version: ${{ needs.get-environment.outputs.minor_version }} + release: ${{ needs.get-environment.outputs.release }} + arch: all + commit_hash: ${{ github.sha }} + cache_key: ${{ github.run_id }}-${{ github.sha }}-${{ matrix.distrib }} + rpm_gpg_key: ${{ secrets.RPM_GPG_SIGNING_KEY }} + rpm_gpg_signing_key_id: ${{ secrets.RPM_GPG_SIGNING_KEY_ID }} + rpm_gpg_signing_passphrase: ${{ secrets.RPM_GPG_SIGNING_PASSPHRASE }} +``` + +The action builds one package per nfpm configuration matching `nfpm_file_pattern` (one +or several patterns) into the working directory, saves the packages in the cache under +`cache_key` and, with `upload_artifacts: "true"`, uploads them as an artifact kept one +day. `nfpm` must be installed: the packaging images provide it. + +This repository is public and holds no key: the signing key is an input, read from the +secrets of the calling repository. It is written outside the workspace and removed when +the step ends. An rpm without `rpm_gpg_key` fails the step, unless `allow_unsigned: +"true"` asks for unsigned packages; a deb is not signed. + +### What a configuration can read + +nfpm replaces `${NAME}` by the variable `NAME` in most fields of a configuration +(`version`, `release`, `description`, `depends`, the signature...), and in the `src` and +`dst` of a `contents` entry that sets `expand: true`. nfpm runs in the directory of the +configuration: its relative paths start there. The action gives it: + +| Variable | Value | +| -------------------------------------------------- | --------------------------------------------------------------------------------- | +| `${VERSION}` | `version`, or `major_version.minor_version` | +| `${RELEASE}` | `release`; for a deb, followed by the distribution (`7+deb12u1`) | +| `${DIST}` | For an rpm, the distribution (`.el9`); empty for a deb | +| `${ARCH}` | `arch` | +| `${COMMIT_HASH}` | `commit_hash` | +| `${MAJOR_VERSION}`, `${NEXT_MAJOR_VERSION}` | `major_version` and the one after it; only when `major_version` is given | +| `${RPM_SIGNING_KEY_FILE}`, `${RPM_SIGNING_KEY_ID}` | The signing key of an rpm; empty otherwise, which is how nfpm skips the signature | +| The variables of the job | As they are: set them with `env:` on the job, or through `$GITHUB_ENV` | + +`NEXT_MAJOR_VERSION` follows the versions of Centreon: six months later before 26.10 +(`24.04` then `24.10`), the next month since (`26.10` then `26.11`). + +```yaml +description: | + Centreon broker. + Commit: ${COMMIT_HASH} +contents: + - src: "./module.so" + dst: "/usr/lib64/lua/${LUA_VERSION}/module.so" + expand: true + file_info: + owner: "@APACHE_USER@" +``` + +nfpm does not read the owner of a file from the environment. That is the one thing the +action writes in a configuration: `@APACHE_USER@` and `@APACHE_GROUP@` become `apache` +for an rpm and `www-data` for a deb. Any other `@UPPERCASE@` placeholder fails the step, +and nothing is replaced inside the packaged files: a workflow that needs a value in an +installation script writes it there before calling the action. + +### Options + +| Input | Default | Effect | +| ---------------- | -------------------- | --------------------------------------------------------------------------------------------------- | +| `deb_release` | `release` | Release number of a deb, when it is not the one of an rpm | +| `allow_unsigned` | `false` | Builds unsigned rpm packages when there is no key, instead of failing | +| `deb_copyright` | `false` | Adds `copyright.`, or the `LICENSE.md` of the repository, to a deb as its `copyright` file | +| `artifact_name` | `packages-` | Name of the uploaded artifact; the default ends with `-` when `arch` is given | + +### Switching from a local copy + +The local `package-nfpm` and `package` actions replaced `@NAME@` placeholders with sed +and differ between repositories. Every repository changes `@COMMIT_HASH@` to +`${COMMIT_HASH}` in its configurations and stops passing `package_extension` and +`stability`. Then: + +| Local copy | Inputs | In the repository | +| --------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| centreon | `deb_copyright: "true"`, `allow_unsigned: "true"` | A step removes the development files, sets `PHP_MIN_VERSION` and `PHP_MAX_VERSION`, and writes the PHP version in the two installation scripts of centreon-web | +| centreon-modules | `deb_copyright: "true"` | Same step, with the four `PHP_*` variables; sourceguardian-loader reads `${PHP_MIN_VERSION}` and `${PHP_MODULE_API}` with `expand: true` | +| centreon-collect | `deb_copyright: "true"` | The Lua version of the `env/.env.` files moves to the configuration that reads it | +| centreon-plugins | `version`; `deb_release`: `release` on unstable and canary, `1` otherwise | Nothing else | +| centreon-stream-connector-scripts | `version`; `deb_release` like centreon-plugins where the release is not kept | A step sets `LUA_VERSION`; the configurations read `${LUA_VERSION}` and `${VERSION}` instead of `@luaver@` and `@VERSION@`, with `expand: true` on the entries using them. Its debs take the suffix of the other projects: `1+deb12u1` instead of `1~bookworm` | +| centreon-agent | `version` | Nothing else | + +The packaging of centreon-plugin-packs builds one package per pack from a template and +keeps its own action. diff --git a/packaging/nfpm/action.yml b/packaging/nfpm/action.yml new file mode 100644 index 0000000..725d224 --- /dev/null +++ b/packaging/nfpm/action.yml @@ -0,0 +1,112 @@ +name: "Package with nfpm" +description: "Build the rpm or deb packages of nfpm configurations, cache them and optionally upload them" +inputs: + nfpm_file_pattern: + description: "Pattern(s) of the nfpm configuration files, relative to the working directory" + required: true + distrib: + description: "Distribution name: el8, el9, el10, bookworm, trixie, jammy, noble, ..." + required: true + version: + description: "Package version. Give either this or major_version and minor_version" + required: false + default: "" + major_version: + description: "Major version (YY.MM). Also gives MAJOR_VERSION and NEXT_MAJOR_VERSION to the configurations" + required: false + default: "" + minor_version: + description: "Minor version, joined to major_version to make the package version" + required: false + default: "" + release: + description: "Package release number" + required: false + default: "" + arch: + description: "Package architecture" + required: false + default: "" + commit_hash: + description: "Commit the packages are built from, given to the configurations as COMMIT_HASH" + required: true + deb_release: + description: "Release number of a deb, when it is not the one of an rpm. Default: release" + required: false + default: "" + deb_copyright: + description: "Add the license file of the repository to a deb, as /usr/share/doc//copyright" + required: false + default: "false" + rpm_gpg_key: + description: "Private key signing the rpm packages" + required: false + default: "" + rpm_gpg_signing_key_id: + description: "Identifier of the signing key" + required: false + default: "" + rpm_gpg_signing_passphrase: + description: "Passphrase of the signing key" + required: false + default: "" + allow_unsigned: + description: "Build unsigned rpm packages when rpm_gpg_key is empty, instead of failing" + required: false + default: "false" + cache_key: + description: "Key the packages are cached under" + required: true + upload_artifacts: + description: "Also upload the packages as an artifact, kept one day" + required: false + default: "false" + artifact_name: + description: "Name of that artifact. Default: packages-, with the architecture when one is given" + required: false + default: "" + +runs: + using: "composite" + steps: + - name: Parse distrib name + id: parse-distrib + uses: $/packaging/parse-distrib + with: + distrib: ${{ inputs.distrib }} + + - name: Build the packages + shell: bash + env: + NFPM_FILE_PATTERN: ${{ inputs.nfpm_file_pattern }} + PACKAGE_EXTENSION: ${{ steps.parse-distrib.outputs.package_extension }} + PACKAGE_DISTRIB_SEPARATOR: ${{ steps.parse-distrib.outputs.package_distrib_separator }} + PACKAGE_DISTRIB_NAME: ${{ steps.parse-distrib.outputs.package_distrib_name }} + INPUT_VERSION: ${{ inputs.version }} + INPUT_MAJOR_VERSION: ${{ inputs.major_version }} + INPUT_MINOR_VERSION: ${{ inputs.minor_version }} + INPUT_RELEASE: ${{ inputs.release }} + INPUT_ARCH: ${{ inputs.arch }} + COMMIT_HASH: ${{ inputs.commit_hash }} + DEB_RELEASE: ${{ inputs.deb_release }} + DEB_COPYRIGHT: ${{ inputs.deb_copyright }} + RPM_GPG_KEY: ${{ inputs.rpm_gpg_key }} + RPM_GPG_SIGNING_KEY_ID: ${{ inputs.rpm_gpg_signing_key_id }} + RPM_GPG_SIGNING_PASSPHRASE: ${{ inputs.rpm_gpg_signing_passphrase }} + ALLOW_UNSIGNED: ${{ inputs.allow_unsigned }} + # the variable, not the context: only the variable is right in a container job + run: '"${GITHUB_ACTION_PATH}/package.sh"' + + - name: Cache the packages + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ./*.${{ steps.parse-distrib.outputs.package_extension }} + key: ${{ inputs.cache_key }} + + - name: Upload the packages + if: inputs.upload_artifacts == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.artifact_name || format('packages-{0}{1}', inputs.distrib, inputs.arch && format('-{0}', inputs.arch) || '') }} + path: ./*.${{ steps.parse-distrib.outputs.package_extension }} + retention-days: 1 diff --git a/packaging/nfpm/package.sh b/packaging/nfpm/package.sh new file mode 100755 index 0000000..3e3948a --- /dev/null +++ b/packaging/nfpm/package.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# Build the packages of every nfpm configuration matching a pattern, into the current +# directory. Inputs (env): see the step of action.yml. +set -euo pipefail + +error() { + echo "::error::$*" >&2 + exit 1 +} + +[[ -n "${NFPM_FILE_PATTERN:-}" ]] || error "the nfpm_file_pattern input is empty" +[[ -n "${COMMIT_HASH:-}" ]] || error "the commit_hash input is empty" +export COMMIT_HASH +[[ "$PACKAGE_EXTENSION" == "rpm" || "$PACKAGE_EXTENSION" == "deb" ]] || error "unknown package extension '${PACKAGE_EXTENSION}'" + +# ---- version, release and distribution, read by the nfpm configurations ---------------- +if [[ -n "${INPUT_VERSION:-}" ]]; then + export VERSION="$INPUT_VERSION" +elif [[ -n "${INPUT_MAJOR_VERSION:-}" ]]; then + export VERSION="${INPUT_MAJOR_VERSION}.${INPUT_MINOR_VERSION:-}" +else + error "give either version or major_version and minor_version" +fi +export RELEASE="${INPUT_RELEASE:-}" +export ARCH="${INPUT_ARCH:-}" + +DISTRIB_SUFFIX="${PACKAGE_DISTRIB_SEPARATOR}${PACKAGE_DISTRIB_NAME}" +if [[ "$PACKAGE_EXTENSION" == "rpm" ]]; then + export DIST="$DISTRIB_SUFFIX" + export APACHE_USER="apache" + export APACHE_GROUP="apache" +else + export DIST="" + RELEASE="${DEB_RELEASE:-$RELEASE}${DISTRIB_SUFFIX}" + export APACHE_USER="www-data" + export APACHE_GROUP="www-data" +fi + +# the major version after this one, for the dependencies bounded by it: versions were +# biannual (24.04, 24.10, ...) before 26.10 and are monthly since +if [[ -n "${INPUT_MAJOR_VERSION:-}" ]]; then + export MAJOR_VERSION="$INPUT_MAJOR_VERSION" + [[ "$MAJOR_VERSION" =~ ^([0-9]+)\.([0-9]+) ]] || error "major_version '${MAJOR_VERSION}' is not YY.MM" + major_left=${BASH_REMATCH[1]} + major_right=${BASH_REMATCH[2]} + if ((10#$major_left * 100 + 10#$major_right < 2610)); then + if [[ "$major_right" == "04" ]]; then + export NEXT_MAJOR_VERSION="${major_left}.10" + else + export NEXT_MAJOR_VERSION="$((major_left + 1)).04" + fi + elif [[ "$major_right" == "12" ]]; then + export NEXT_MAJOR_VERSION="$((major_left + 1)).01" + else + export NEXT_MAJOR_VERSION="${major_left}.$((10#$major_right + 1))" + fi +fi + +# ---- signing key of the rpm packages: nfpm signs when the key file variable is set, and +# reads the passphrase from its own variable. The file stays out of the workspace. ---- +export RPM_SIGNING_KEY_FILE="" +export RPM_SIGNING_KEY_ID="" +if [[ "$PACKAGE_EXTENSION" == "rpm" ]]; then + if [[ -n "${RPM_GPG_KEY:-}" ]]; then + KEY_DIRECTORY=$(mktemp -d "${RUNNER_TEMP:-/tmp}/nfpm-key.XXXXXX") + trap 'rm -rf "${KEY_DIRECTORY:?}"' EXIT + RPM_SIGNING_KEY_FILE="${KEY_DIRECTORY}/key.gpg" + (umask 077 && printf '%s' "$RPM_GPG_KEY" > "$RPM_SIGNING_KEY_FILE") + RPM_SIGNING_KEY_ID="${RPM_GPG_SIGNING_KEY_ID:-}" + export NFPM_RPM_PASSPHRASE="${RPM_GPG_SIGNING_PASSPHRASE:-}" + elif [[ "${ALLOW_UNSIGNED:-false}" == "true" ]]; then + echo "::warning::no signing key: the rpm packages are not signed" + else + error "no signing key: give rpm_gpg_key, or allow_unsigned to build unsigned rpm packages" + fi +fi + +# adds the license of the package to a deb, as /usr/share/doc//copyright +add_copyright() { + local config=$1 license source="" candidate package + license=$(sed -n 's/^license: *//p' "$config" | head -1 | sed 's/"//g' | xargs) + if [[ -f "${ROOT}/copyright.${license}" ]]; then + source="${ROOT}/copyright.${license}" + else + for candidate in "${ROOT}/LICENSE.md" "${ROOT}/LICENSE"; do + [[ -f "$candidate" ]] && source="$candidate" && break + done + fi + [[ -n "$source" ]] || return 0 + cp "$source" ./copyright + package=$(sed -n 's/^name: *//p' "$config" | head -1 | sed 's/"//g' | xargs) + # the entry closes the "contents:" list, or opens one when the configuration has none + awk -v pkg="$package" ' + function entry() { + print " - src: ./copyright" + print " dst: /usr/share/doc/" pkg "/copyright" + print " packager: deb" + } + BEGIN { in_contents = 0; injected = 0 } + /^contents:/ { in_contents = 1 } + in_contents && /^[a-z]/ && !/^contents:/ && !injected { entry(); injected = 1; in_contents = 0 } + { print } + END { if (!injected) { if (!in_contents) { print "contents:" } entry() } } + ' "$config" > "${config}.tmp" + mv "${config}.tmp" "$config" +} + +ROOT=$PWD +# the pattern is a list of globs, split and expanded on purpose +# shellcheck disable=SC2206 +FILES=($NFPM_FILE_PATTERN) +[[ -e "${FILES[0]}" ]] || error "no nfpm configuration matches '${NFPM_FILE_PATTERN}'" + +for file in "${FILES[@]}"; do + directory=$(dirname "$file") + config=$(basename "$file") + + cd "$directory" + + # the owner of a file is the one field nfpm does not read from the environment + sed -i -e "s/@APACHE_USER@/${APACHE_USER}/g" -e "s/@APACHE_GROUP@/${APACHE_GROUP}/g" "$config" + + if [[ "$PACKAGE_EXTENSION" == "deb" && "${DEB_COPYRIGHT:-false}" == "true" ]]; then + add_copyright "$config" + fi + + if grep -nE '@[A-Z][A-Z0-9_]*@' "$config"; then + echo "::error file=${file}::placeholder(s) left in the nfpm configuration: use \${NAME} variables" + exit 1 + fi + + nfpm package --config "$config" --packager "$PACKAGE_EXTENSION" --target "${ROOT}/" + cd "$ROOT" +done + +ls -lh ./*."${PACKAGE_EXTENSION}" diff --git a/packaging/tests/nfpm.bats b/packaging/tests/nfpm.bats new file mode 100644 index 0000000..655eafb --- /dev/null +++ b/packaging/tests/nfpm.bats @@ -0,0 +1,307 @@ +#!/usr/bin/env bats + +# package.sh runs in a small repository, with a stand-in of nfpm that records what it is +# given: the variables a configuration reads, the configuration and the signing key. + +setup() { + SCRIPT="${BATS_TEST_DIRNAME}/../nfpm/package.sh" + ROOT="${BATS_TEST_TMPDIR}/repository" + BIN="${BATS_TEST_TMPDIR}/bin" + CALLS="${BATS_TEST_TMPDIR}/calls" + export RUNNER_TEMP="${BATS_TEST_TMPDIR}/runner-temp" + mkdir -p "${ROOT}/packaging/scripts" "$BIN" "$CALLS" "$RUNNER_TEMP" + + cat > "${BIN}/nfpm" << STUB +#!/usr/bin/env bash +set -euo pipefail +while ((\$# > 0)); do + case \$1 in + --config) config=\$2; shift 2 ;; + --packager) packager=\$2; shift 2 ;; + --target) target=\$2; shift 2 ;; + *) shift ;; + esac +done +out="${CALLS}/\${config%.yaml}" +mkdir "\$out" +for name in VERSION RELEASE ARCH DIST MAJOR_VERSION NEXT_MAJOR_VERSION COMMIT_HASH RPM_SIGNING_KEY_FILE \ + RPM_SIGNING_KEY_ID NFPM_RPM_PASSPHRASE PHP_MIN_VERSION; do + printf '%s=%s\n' "\$name" "\${!name-unset}" +done > "\${out}/env" +[ -z "\$RPM_SIGNING_KEY_FILE" ] || cat "\$RPM_SIGNING_KEY_FILE" > "\${out}/key" +cp "\$config" "\${out}/config" +touch "\${target}\${config%.yaml}.\${packager}" +STUB + chmod +x "${BIN}/nfpm" + + cat > "${ROOT}/packaging/web.yaml" << 'CONFIG' +name: "centreon-web" +license: "Apache-2.0" +version: "${VERSION}" +description: "Commit: ${COMMIT_HASH}" +owner: "@APACHE_USER@:@APACHE_GROUP@" +contents: + - src: ./files + dst: /usr/share/centreon +rpm: + summary: web + signature: + key_file: ${RPM_SIGNING_KEY_FILE} + key_id: ${RPM_SIGNING_KEY_ID} +CONFIG + echo "apache license" > "${ROOT}/copyright.Apache-2.0" + echo "repository license" > "${ROOT}/LICENSE.md" + echo 'php @PHP_MIN_VERSION@' > "${ROOT}/packaging/scripts/postinstall.sh" +} + +# runs package.sh for a distribution, with the given NAME=value variables +package() { + local distrib=$1 extension separator name + shift + case "$distrib" in + el9) extension=rpm separator=. name=el9 ;; + bookworm) extension=deb separator=+ name=deb12u1 ;; + noble) extension=deb separator=- name=0ubuntu.24.04 ;; + esac + cd "$ROOT" + run env PATH="${BIN}:${PATH}" NFPM_FILE_PATTERN="packaging/*.yaml" COMMIT_HASH=abc123 DISTRIB="$distrib" \ + PACKAGE_EXTENSION="$extension" PACKAGE_DISTRIB_SEPARATOR="$separator" PACKAGE_DISTRIB_NAME="$name" \ + INPUT_VERSION=1.2.3 INPUT_RELEASE=7 INPUT_ARCH=all RPM_GPG_KEY=the-key RPM_GPG_SIGNING_KEY_ID=key-id \ + RPM_GPG_SIGNING_PASSPHRASE=secret "$@" "$SCRIPT" +} + +# a variable nfpm was given for a configuration +given() { + sed -n "s/^$2=//p" "${CALLS}/$1/env" +} + +# "! command" does not fail a bats test unless it is its last line: assert it +refute() { + if "$@"; then + echo "unexpectedly succeeded: $*" + return 1 + fi +} + +@test "an rpm carries the distribution in DIST and lands in the working directory" { + package el9 + [ "$status" -eq 0 ] + [ "$(given web VERSION)" = "1.2.3" ] + [ "$(given web RELEASE)" = "7" ] + [ "$(given web DIST)" = ".el9" ] + [ "$(given web ARCH)" = "all" ] + [ -f "${ROOT}/web.rpm" ] + [ ! -e "${ROOT}/packaging/web.rpm" ] +} + +@test "a deb carries the distribution in its release" { + package bookworm + [ "$status" -eq 0 ] + [ "$(given web RELEASE)" = "7+deb12u1" ] + [ "$(given web DIST)" = "" ] + [ -f "${ROOT}/web.deb" ] + rm -r "${CALLS}/web" + package noble + [ "$(given web RELEASE)" = "7-0ubuntu.24.04" ] +} + +@test "deb_release replaces the release of a deb only" { + package bookworm DEB_RELEASE=1 + [ "$(given web RELEASE)" = "1+deb12u1" ] + rm -r "${CALLS}/web" + package el9 DEB_RELEASE=1 + [ "$(given web RELEASE)" = "7" ] +} + +@test "the version is made of the major and minor versions when it is not given" { + package el9 INPUT_VERSION= INPUT_MAJOR_VERSION=26.10 INPUT_MINOR_VERSION=4 + [ "$status" -eq 0 ] + [ "$(given web VERSION)" = "26.10.4" ] + [ "$(given web MAJOR_VERSION)" = "26.10" ] +} + +@test "neither version nor major version fails" { + package el9 INPUT_VERSION= + [ "$status" -ne 0 ] + [[ "$output" == *"give either version or major_version"* ]] + [ ! -d "${CALLS}/web" ] +} + +@test "without a major version the next one is not set" { + package el9 + [ "$(given web MAJOR_VERSION)" = "unset" ] + [ "$(given web NEXT_MAJOR_VERSION)" = "unset" ] +} + +@test "the next major version is the next month since 26.10" { + package el9 INPUT_MAJOR_VERSION=26.10 + [ "$(given web NEXT_MAJOR_VERSION)" = "26.11" ] + rm -r "${CALLS}/web" + package el9 INPUT_MAJOR_VERSION=26.12 + [ "$(given web NEXT_MAJOR_VERSION)" = "27.01" ] + rm -r "${CALLS}/web" + package el9 INPUT_MAJOR_VERSION=27.08 + [ "$(given web NEXT_MAJOR_VERSION)" = "27.9" ] +} + +@test "the next major version is six months later before 26.10" { + package el9 INPUT_MAJOR_VERSION=24.04 + [ "$(given web NEXT_MAJOR_VERSION)" = "24.10" ] + rm -r "${CALLS}/web" + package el9 INPUT_MAJOR_VERSION=24.10 + [ "$(given web NEXT_MAJOR_VERSION)" = "25.04" ] + rm -r "${CALLS}/web" + package el9 INPUT_MAJOR_VERSION=25.10 + [ "$(given web NEXT_MAJOR_VERSION)" = "26.04" ] +} + +@test "a malformed major version fails" { + package el9 INPUT_MAJOR_VERSION=next + [ "$status" -ne 0 ] + [[ "$output" == *"is not YY.MM"* ]] + [ ! -d "${CALLS}/web" ] +} + +@test "the variables of the job reach the configurations" { + package el9 PHP_MIN_VERSION=8.4 + [ "$(given web PHP_MIN_VERSION)" = "8.4" ] +} + +@test "the commit hash is a variable the configurations read" { + package el9 + [ "$(given web COMMIT_HASH)" = "abc123" ] +} + +@test "the web server user owns the files it is given, by its name on the distribution" { + package el9 + grep -q '^owner: "apache:apache"$' "${CALLS}/web/config" +} + +@test "the web server user of a deb is www-data" { + package bookworm + grep -q '^owner: "www-data:www-data"$' "${CALLS}/web/config" +} + +@test "nothing else is edited in a configuration" { + cp "${ROOT}/packaging/web.yaml" "${BATS_TEST_TMPDIR}/before.yaml" + package el9 + run diff "${BATS_TEST_TMPDIR}/before.yaml" "${CALLS}/web/config" + [ "$(grep -c '^[<>]' <<< "$output")" -eq 2 ] + [[ "$output" == *'< owner: "@APACHE_USER@:@APACHE_GROUP@"'* ]] +} + +@test "a placeholder left in the configuration fails before nfpm runs" { + echo 'left: "@NOT_REPLACED@"' >> "${ROOT}/packaging/web.yaml" + package el9 + [ "$status" -ne 0 ] + [[ "$output" == *"placeholder(s) left"* ]] + [ ! -d "${CALLS}/web" ] +} + +@test "the signing key is given to nfpm from outside the workspace and removed" { + package el9 + [ "$status" -eq 0 ] + [ "$(cat "${CALLS}/web/key")" = "the-key" ] + [ "$(given web RPM_SIGNING_KEY_ID)" = "key-id" ] + [ "$(given web NFPM_RPM_PASSPHRASE)" = "secret" ] + [[ "$(given web RPM_SIGNING_KEY_FILE)" == "${RUNNER_TEMP}/"* ]] + [ ! -e "$(given web RPM_SIGNING_KEY_FILE)" ] + refute grep -rq "the-key" "$ROOT" +} + +@test "the signing key is removed when the build fails" { + printf '#!/bin/sh\necho "$RPM_SIGNING_KEY_FILE" > "%s/key-path"\nexit 3\n' "$CALLS" > "${BIN}/nfpm" + package el9 + [ "$status" -eq 3 ] + [ ! -e "$(cat "${CALLS}/key-path")" ] +} + +@test "an rpm without a key fails before anything is built" { + package el9 RPM_GPG_KEY= + [ "$status" -ne 0 ] + [[ "$output" == *"no signing key"* ]] + [ ! -d "${CALLS}/web" ] +} + +@test "allow_unsigned builds an rpm without a key, with no key file given to nfpm" { + package el9 ALLOW_UNSIGNED=true RPM_GPG_KEY= + [ "$status" -eq 0 ] + [[ "$output" == *"::warning::"*"not signed"* ]] + [ "$(given web RPM_SIGNING_KEY_FILE)" = "" ] + [ "$(given web RPM_SIGNING_KEY_ID)" = "" ] + [ -z "$(ls -A "$RUNNER_TEMP")" ] +} + +@test "a deb needs no key, and is never given one" { + package bookworm RPM_GPG_KEY= + [ "$status" -eq 0 ] + rm -r "${CALLS}/web" + package bookworm + [ "$(given web RPM_SIGNING_KEY_FILE)" = "" ] + [ -z "$(ls -A "$RUNNER_TEMP")" ] +} + +@test "deb_copyright adds the license matching the package to a deb" { + package bookworm DEB_COPYRIGHT=true + [ "$status" -eq 0 ] + [ "$(cat "${ROOT}/packaging/copyright")" = "apache license" ] + # the entry closes the contents list, before the next key + run grep -n -A3 "dst: /usr/share/centreon" "${CALLS}/web/config" + [[ "$output" == *"- src: ./copyright"*"dst: /usr/share/doc/centreon-web/copyright"*"packager: deb"* ]] + grep -q "^rpm:$" "${CALLS}/web/config" +} + +@test "deb_copyright falls back to the license of the repository" { + rm "${ROOT}/copyright.Apache-2.0" + package bookworm DEB_COPYRIGHT=true + [ "$(cat "${ROOT}/packaging/copyright")" = "repository license" ] +} + +@test "deb_copyright opens a contents list when the configuration has none" { + printf 'name: plain\ndescription: "${COMMIT_HASH}"\n' > "${ROOT}/packaging/web.yaml" + package bookworm DEB_COPYRIGHT=true + [ "$status" -eq 0 ] + [ "$(tail -n 4 "${CALLS}/web/config" | head -n 2)" = $'contents:\n - src: ./copyright' ] + grep -q "dst: /usr/share/doc/plain/copyright" "${CALLS}/web/config" +} + +@test "no copyright is added to an rpm, nor to a deb by default" { + package el9 DEB_COPYRIGHT=true + refute grep -q "copyright" "${CALLS}/web/config" + rm -r "${CALLS}/web" + package bookworm + refute grep -q "copyright" "${CALLS}/web/config" + [ ! -e "${ROOT}/packaging/copyright" ] +} + +@test "every configuration of every pattern is built" { + mkdir "${ROOT}/other" + printf 'name: one\ndescription: "${COMMIT_HASH}"\n' > "${ROOT}/packaging/one.yaml" + printf 'name: two\ndescription: "${COMMIT_HASH}"\n' > "${ROOT}/other/two.yaml" + package el9 NFPM_FILE_PATTERN="packaging/*.yaml other/two.yaml" + [ "$status" -eq 0 ] + [ -f "${ROOT}/web.rpm" ] && [ -f "${ROOT}/one.rpm" ] && [ -f "${ROOT}/two.rpm" ] +} + +@test "a configuration of the working directory itself is built in place" { + printf 'name: top\ndescription: "${COMMIT_HASH}"\n' > "${ROOT}/top.yaml" + package el9 NFPM_FILE_PATTERN="top.yaml" + [ "$status" -eq 0 ] + [ -f "${ROOT}/top.rpm" ] +} + +@test "a pattern matching nothing fails" { + package el9 NFPM_FILE_PATTERN="nowhere/*.yaml" + [ "$status" -ne 0 ] + [[ "$output" == *"no nfpm configuration matches"* ]] +} + +@test "an empty commit hash or pattern fails" { + package el9 COMMIT_HASH= + [ "$status" -ne 0 ] + [[ "$output" == *"commit_hash input is empty"* ]] + package el9 NFPM_FILE_PATTERN= + [ "$status" -ne 0 ] + [ ! -d "${CALLS}/web" ] +} + diff --git a/packaging/tests/smoke/nfpm.yaml b/packaging/tests/smoke/nfpm.yaml new file mode 100644 index 0000000..a32c059 --- /dev/null +++ b/packaging/tests/smoke/nfpm.yaml @@ -0,0 +1,23 @@ +# package built by the smoke test of packaging/nfpm, with the real nfpm +name: "smoke-test" +arch: "${ARCH}" +platform: "linux" +version: "${VERSION}" +release: "${RELEASE}${DIST}" +maintainer: "Smoke test " +description: "Built from ${COMMIT_HASH}" +license: "Apache-2.0" + +contents: + - src: "./nfpm.yaml" + dst: "/usr/share/doc/smoke-test-${VERSION}/nfpm.yaml" + expand: true + file_info: + owner: "@APACHE_USER@" + group: "@APACHE_GROUP@" + +rpm: + summary: "Smoke test" + signature: + key_file: ${RPM_SIGNING_KEY_FILE} + key_id: ${RPM_SIGNING_KEY_ID} From e35db832ccbcd53d08b8ddb8aadb6741ba61a567 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 30 Nov 2026 09:04:38 +0100 Subject: [PATCH 2/6] fix(packaging): refuse an nfpm too old to read variables in a description --- packaging/README.md | 3 ++- packaging/nfpm/package.sh | 9 +++++++++ packaging/tests/nfpm.bats | 22 +++++++++++++++++++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packaging/README.md b/packaging/README.md index 68e72cb..1e781e0 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -80,7 +80,8 @@ when the two disagree. The action builds one package per nfpm configuration matching `nfpm_file_pattern` (one or several patterns) into the working directory, saves the packages in the cache under `cache_key` and, with `upload_artifacts: "true"`, uploads them as an artifact kept one -day. `nfpm` must be installed: the packaging images provide it. +day. `nfpm` 2.39.0 or later must be installed (the packaging images provide it): it is +the first version reading variables in a description, and an older one fails the step. This repository is public and holds no key: the signing key is an input, read from the secrets of the calling repository. It is written outside the workspace and removed when diff --git a/packaging/nfpm/package.sh b/packaging/nfpm/package.sh index 3e3948a..3a71b6e 100755 --- a/packaging/nfpm/package.sh +++ b/packaging/nfpm/package.sh @@ -13,6 +13,15 @@ error() { export COMMIT_HASH [[ "$PACKAGE_EXTENSION" == "rpm" || "$PACKAGE_EXTENSION" == "deb" ]] || error "unknown package extension '${PACKAGE_EXTENSION}'" +# nfpm only reads variables in a description since 2.39.0: an older one would ship +# "${COMMIT_HASH}" as is +NFPM_MINIMUM_VERSION="2.39.0" +nfpm_version=$(nfpm --version 2> /dev/null | sed -n 's/^GitVersion: *v\{0,1\}//p' || true) +[[ "$nfpm_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+ ]] || error "nfpm is not installed, or does not give its version" +if [[ "$(printf '%s\n' "$NFPM_MINIMUM_VERSION" "$nfpm_version" | sort -V | head -1)" != "$NFPM_MINIMUM_VERSION" ]]; then + error "nfpm ${nfpm_version} is too old: ${NFPM_MINIMUM_VERSION} or later is needed" +fi + # ---- version, release and distribution, read by the nfpm configurations ---------------- if [[ -n "${INPUT_VERSION:-}" ]]; then export VERSION="$INPUT_VERSION" diff --git a/packaging/tests/nfpm.bats b/packaging/tests/nfpm.bats index 655eafb..1123031 100644 --- a/packaging/tests/nfpm.bats +++ b/packaging/tests/nfpm.bats @@ -14,6 +14,10 @@ setup() { cat > "${BIN}/nfpm" << STUB #!/usr/bin/env bash set -euo pipefail +if [[ "\$1" == "--version" ]]; then + echo "GitVersion: \${NFPM_VERSION:-2.43.4}" + exit 0 +fi while ((\$# > 0)); do case \$1 in --config) config=\$2; shift 2 ;; @@ -83,6 +87,22 @@ refute() { fi } +@test "an nfpm older than the first one reading variables in a description fails" { + package el9 NFPM_VERSION=2.38.0 + [ "$status" -ne 0 ] + [[ "$output" == *"nfpm 2.38.0 is too old: 2.39.0 or later is needed"* ]] + [ ! -d "${CALLS}/web" ] + package el9 NFPM_VERSION=2.39.0 + [ "$status" -eq 0 ] +} + +@test "a missing nfpm fails with its own message" { + rm "${BIN}/nfpm" + package el9 + [ "$status" -ne 0 ] + [[ "$output" == *"nfpm is not installed"* ]] +} + @test "an rpm carries the distribution in DIST and lands in the working directory" { package el9 [ "$status" -eq 0 ] @@ -210,7 +230,7 @@ refute() { } @test "the signing key is removed when the build fails" { - printf '#!/bin/sh\necho "$RPM_SIGNING_KEY_FILE" > "%s/key-path"\nexit 3\n' "$CALLS" > "${BIN}/nfpm" + printf '#!/bin/sh\n[ "$1" = "--version" ] && echo "GitVersion: 2.43.4" && exit 0\necho "$RPM_SIGNING_KEY_FILE" > "%s/key-path"\nexit 3\n' "$CALLS" > "${BIN}/nfpm" package el9 [ "$status" -eq 3 ] [ ! -e "$(cat "${CALLS}/key-path")" ] From dd687b4813abd06e8af906633b23b34753c2c572 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 30 Nov 2026 09:12:28 +0100 Subject: [PATCH 3/6] feat(packaging): add the shared check-descriptions action The check of centreon, centreon-collect and centreon-modules, unchanged: every nfpm package must have its own synopsis and rpm summary. --- .github/workflows/lint.yml | 4 + README.md | 10 +- packaging/README.md | 34 ++++- packaging/check-descriptions/action.yml | 22 ++++ .../check-descriptions/check-descriptions.py | 99 ++++++++++++++ packaging/check-descriptions/check.sh | 22 ++++ packaging/tests/check-descriptions.bats | 121 ++++++++++++++++++ 7 files changed, 303 insertions(+), 9 deletions(-) create mode 100644 packaging/check-descriptions/action.yml create mode 100755 packaging/check-descriptions/check-descriptions.py create mode 100755 packaging/check-descriptions/check.sh create mode 100644 packaging/tests/check-descriptions.bats diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index d013704..78c1342 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -114,6 +114,10 @@ jobs: [[ "$DESTINATION" == "s3://centreon-download/public/smoke-test/smoke-test-1.0.0.tar.gz" ]] tar tzf "$SOURCE_FILE" | grep -q "^smoke-test-1.0.0/sources-delivery/action.yml$" + # checks the one package definition of this repository, the smoke test of packaging/nfpm + - name: Smoke test the wiring of packaging/check-descriptions + uses: $/packaging/check-descriptions + # most callers of the packaging actions run in a container, where paths differ smoke-container: name: smoke (${{ matrix.name }}) diff --git a/README.md b/README.md index 83f80d7..1db13be 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,11 @@ The repository is a set of **packages**: a package is a top-level directory, ver and released on its own, that holds one action or several actions built on the same code. Each package documents its actions in its own `README.md`. -| Package | Actions | -| ------------------------------------------ | ------------------------------------------------------------------- | -| [`pulp`](pulp/README.md) | `pulp/package-delivery`, `pulp/promote-to-stable`, `pulp/setup-cli` | -| [`download-site`](download-site/README.md) | `download-site/sources-delivery`, `download-site/publication` | -| [`packaging`](packaging/README.md) | `packaging/parse-distrib`, `packaging/nfpm` | +| Package | Actions | +| ------------------------------------------ | --------------------------------------------------------------------------- | +| [`pulp`](pulp/README.md) | `pulp/package-delivery`, `pulp/promote-to-stable`, `pulp/setup-cli` | +| [`download-site`](download-site/README.md) | `download-site/sources-delivery`, `download-site/publication` | +| [`packaging`](packaging/README.md) | `packaging/parse-distrib`, `packaging/nfpm`, `packaging/check-descriptions` | ## Usage diff --git a/packaging/README.md b/packaging/README.md index 1e781e0..b5469d2 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -2,10 +2,11 @@ Actions shared by the packaging jobs. -| Action | Purpose | -| ------------------------- | ----------------------------------------------------------------------- | -| `packaging/parse-distrib` | Give the package extension, the naming and the family of a distribution | -| `packaging/nfpm` | Build rpm or deb packages with nfpm, cache them and upload them | +| Action | Purpose | +| ------------------------------ | ----------------------------------------------------------------------- | +| `packaging/parse-distrib` | Give the package extension, the naming and the family of a distribution | +| `packaging/nfpm` | Build rpm or deb packages with nfpm, cache them and upload them | +| `packaging/check-descriptions` | Check that every package has its own synopsis and rpm summary | ## Parse distrib @@ -154,3 +155,28 @@ and differ between repositories. Every repository changes `@COMMIT_HASH@` to The packaging of centreon-plugin-packs builds one package per pack from a template and keeps its own action. + +## Check package descriptions + +```yaml +- name: Check package descriptions + uses: centreon/github-actions/packaging/check-descriptions@packaging/v1 +``` + +A lint step, to run once per pull request after a checkout. It reads every tracked YAML +file that sits under a `packaging` directory and holds `name`, `arch` and `version`: the +nfpm package definitions. The first line of `description` is the synopsis of a deb (`apt +search`, `apt show`), and `rpm.summary` the one of an rpm, the synopsis standing for it +when it is not set. The step fails when: + +- a description is empty, or an rpm summary is blank; +- two packages share a synopsis or a summary, whatever the case; +- the synopsis or the summary of a `-debuginfo` package does not name + ``. + +`paths` limits the check to the files it lists, and `working_directory` runs it in +another directory. The script needs PyYAML: it uses the one of the runner, and installs +a pinned version in a temporary environment when there is none. + +It is the `check-package-descriptions.py` script of centreon, centreon-collect and +centreon-modules, unchanged: a repository replaces its copy with this step. diff --git a/packaging/check-descriptions/action.yml b/packaging/check-descriptions/action.yml new file mode 100644 index 0000000..7d0c6b1 --- /dev/null +++ b/packaging/check-descriptions/action.yml @@ -0,0 +1,22 @@ +name: "Check package descriptions" +description: "Check that every nfpm package of a repository has its own synopsis and rpm summary" +inputs: + paths: + description: "Files to check, separated by spaces or new lines. Default: every tracked YAML file" + required: false + default: "" + working_directory: + description: "Directory of the repository to check" + required: false + default: "." + +runs: + using: "composite" + steps: + - name: Check package descriptions + shell: bash + working-directory: ${{ inputs.working_directory }} + env: + PATHS: ${{ inputs.paths }} + # the variable, not the context: only the variable is right in a container job + run: '"${GITHUB_ACTION_PATH}/check.sh"' diff --git a/packaging/check-descriptions/check-descriptions.py b/packaging/check-descriptions/check-descriptions.py new file mode 100755 index 0000000..8045aa5 --- /dev/null +++ b/packaging/check-descriptions/check-descriptions.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Check the synopsis and summary of the nfpm package definitions. + +The first line of the nfpm description is the deb synopsis (apt search/show), +rpm.summary is the rpm one. Both must be unique within the repository. +""" + +import collections +import subprocess +import sys + +import yaml + + +class Loader(yaml.SafeLoader): + """SafeLoader ignoring custom tags (gorgone configuration uses !include).""" + + +Loader.add_multi_constructor("!", lambda loader, suffix, node: None) + +DEBUGINFO_SUFFIX = "-debuginfo" + + +def first_line(text): + lines = [line.strip() for line in str(text or "").splitlines()] + return next((line for line in lines if line), "") + + +def load_packages(paths): + """Return {path: nfpm definition} for the nfpm files found in paths.""" + packages = {} + for path in paths: + if "packaging" not in path.split("/")[:-1]: + continue + with open(path, encoding="utf-8") as stream: + content = yaml.load(stream, Loader=Loader) + if isinstance(content, dict) and all(key in content for key in ("name", "arch", "version")): + packages[path] = content + return packages + + +def check(packages): + """Return a list of (path, message) errors.""" + errors = [] + seen = {"synopsis": collections.defaultdict(list), "rpm summary": collections.defaultdict(list)} + + for path, package in sorted(packages.items()): + name = str(package["name"]) + synopsis = first_line(package.get("description")) + # nfpm uses the first description line when rpm.summary is not set + raw_summary = (package.get("rpm") or {}).get("summary") + summary = synopsis if raw_summary in (None, "") else first_line(raw_summary) + + if not synopsis: + errors.append((path, f"{name}: the description is empty")) + continue + if not summary: + errors.append((path, f"{name}: the rpm summary is blank")) + continue + + fields = {"synopsis": synopsis, "rpm summary": summary} + for field, value in fields.items(): + seen[field][value.casefold()].append((path, name)) + if name.endswith(DEBUGINFO_SUFFIX): + base_name = name[: -len(DEBUGINFO_SUFFIX)] + if base_name not in value.replace(",", " ").rstrip(".").split(): + errors.append((path, f"{name}: the {field} does not mention {base_name}: '{value}'")) + + for field, values in seen.items(): + for owners in values.values(): + if len(owners) < 2: + continue + names = ", ".join(name for _, name in owners) + for path, name in owners: + errors.append((path, f"{name}: the {field} is shared by several packages ({names})")) + + return errors + + +def main(): + paths = sys.argv[1:] or subprocess.run( + ["git", "ls-files", "*.yaml", "*.yml"], capture_output=True, text=True, check=True + ).stdout.splitlines() + + packages = load_packages(paths) + if not packages: + print("::error::no nfpm package definition found") + return 1 + + errors = check(packages) + for path, message in errors: + print(f"::error file={path}::{message}") + + print(f"{len(packages)} package definitions checked, {len(errors)} error(s)") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packaging/check-descriptions/check.sh b/packaging/check-descriptions/check.sh new file mode 100755 index 0000000..225111f --- /dev/null +++ b/packaging/check-descriptions/check.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Run check-descriptions.py, with PyYAML installed aside when the runner has none. +# Input (env): PATHS, the files to check; empty for every tracked YAML file. +set -euo pipefail + +PYYAML_VERSION="6.0.3" + +python="python3" +if ! python3 -c "import yaml" 2> /dev/null; then + environment=$(mktemp -d "${RUNNER_TEMP:-/tmp}/check-descriptions.XXXXXX") + if ! python3 -m venv "$environment" > /dev/null 2>&1 \ + || ! "${environment}/bin/pip" install --quiet --disable-pip-version-check "pyyaml==${PYYAML_VERSION}"; then + echo "::error::PyYAML is needed: install it (python3-yaml, or pip install pyyaml) before this step" + exit 1 + fi + echo "PyYAML ${PYYAML_VERSION} installed in a temporary environment" + python="${environment}/bin/python" +fi + +# a list of paths, split on purpose +# shellcheck disable=SC2086 +exec "$python" "$(dirname "$0")/check-descriptions.py" ${PATHS:-} diff --git a/packaging/tests/check-descriptions.bats b/packaging/tests/check-descriptions.bats new file mode 100644 index 0000000..8dcf66e --- /dev/null +++ b/packaging/tests/check-descriptions.bats @@ -0,0 +1,121 @@ +#!/usr/bin/env bats + +# check.sh runs in a small git repository holding nfpm package definitions. + +setup() { + CHECK="${BATS_TEST_DIRNAME}/../check-descriptions/check.sh" + REPO="${BATS_TEST_TMPDIR}/repository" + mkdir -p "${REPO}/broker/packaging" "${REPO}/engine/packaging" + git init --quiet "$REPO" + definition broker/packaging/broker.yaml centreon-broker "Centreon Broker." "Centreon Broker" + definition engine/packaging/engine.yaml centreon-engine "Centreon Engine." "Centreon Engine" +} + +# definition [rpm summary] +definition() { + { + printf 'name: "%s"\narch: "${ARCH}"\nversion: "${VERSION}"\n' "$2" + printf 'description: |\n %s\n Commit: ${COMMIT_HASH}\n' "$3" + if [[ $# -ge 4 ]]; then + printf 'rpm:\n summary: "%s"\n' "$4" + fi + } > "${REPO}/$1" +} + +check() { + git -C "$REPO" add -A + cd "$REPO" + run env PATHS="${PATHS:-}" "$CHECK" +} + +@test "packages with their own synopsis and summary pass" { + check + [ "$status" -eq 0 ] + [[ "$output" == *"2 package definitions checked, 0 error(s)"* ]] +} + +@test "the synopsis stands for a missing rpm summary" { + definition engine/packaging/engine.yaml centreon-engine "Centreon Engine." + check + [ "$status" -eq 0 ] +} + +@test "an empty description fails" { + printf 'name: "centreon-engine"\narch: all\nversion: "1"\ndescription: ""\n' > "${REPO}/engine/packaging/engine.yaml" + check + [ "$status" -ne 0 ] + [[ "$output" == *"::error file=engine/packaging/engine.yaml::centreon-engine: the description is empty"* ]] +} + +@test "a blank rpm summary fails" { + definition engine/packaging/engine.yaml centreon-engine "Centreon Engine." " " + check + [ "$status" -ne 0 ] + [[ "$output" == *"centreon-engine: the rpm summary is blank"* ]] +} + +@test "a synopsis shared by two packages fails for both, whatever its case" { + definition engine/packaging/engine.yaml centreon-engine "CENTREON BROKER." "Centreon Engine" + check + [ "$status" -ne 0 ] + [[ "$output" == *"file=broker/packaging/broker.yaml::centreon-broker: the synopsis is shared by several packages (centreon-broker, centreon-engine)"* ]] + [[ "$output" == *"file=engine/packaging/engine.yaml::centreon-engine: the synopsis is shared"* ]] +} + +@test "an rpm summary shared by two packages fails" { + definition engine/packaging/engine.yaml centreon-engine "Centreon Engine." "Centreon Broker" + check + [ "$status" -ne 0 ] + [[ "$output" == *"centreon-engine: the rpm summary is shared by several packages"* ]] +} + +@test "a debuginfo package must name the package it belongs to" { + definition broker/packaging/debuginfo.yaml centreon-broker-debuginfo "Debug symbols." "Debug symbols" + check + [ "$status" -ne 0 ] + [[ "$output" == *"centreon-broker-debuginfo: the synopsis does not mention centreon-broker"* ]] + definition broker/packaging/debuginfo.yaml centreon-broker-debuginfo "Debug symbols for centreon-broker." "Debug symbols for centreon-broker" + check + [ "$status" -eq 0 ] +} + +@test "YAML files that are not package definitions are ignored" { + mkdir -p "${REPO}/.github/workflows" + printf 'name: lint\non: push\n' > "${REPO}/.github/workflows/lint.yml" + printf 'key: value\n' > "${REPO}/broker/packaging/other.yaml" + # a definition outside a packaging directory is not one either + definition broker/duplicate.yaml centreon-other "Centreon Broker." "Centreon Broker" + check + [ "$status" -eq 0 ] + [[ "$output" == *"2 package definitions checked"* ]] +} + +@test "a definition using custom YAML tags is read" { + printf 'include: !include other.yaml\n' >> "${REPO}/broker/packaging/broker.yaml" + check + [ "$status" -eq 0 ] +} + +@test "untracked files are not checked by default" { + git -C "$REPO" add -A + definition engine/packaging/untracked.yaml centreon-untracked "Centreon Engine." "Centreon Engine" + cd "$REPO" + run env PATHS= "$CHECK" + [ "$status" -eq 0 ] +} + +@test "the paths input limits the check to the files it names" { + definition engine/packaging/engine.yaml centreon-engine "Centreon Broker." "Centreon Broker" + PATHS=$'broker/packaging/broker.yaml\n' check + [ "$status" -eq 0 ] + [[ "$output" == *"1 package definitions checked"* ]] + PATHS="broker/packaging/broker.yaml engine/packaging/engine.yaml" check + [ "$status" -ne 0 ] +} + +@test "a repository without any package definition fails" { + rm -r "${REPO}/broker" "${REPO}/engine" + check + [ "$status" -ne 0 ] + [[ "$output" == *"no nfpm package definition found"* ]] +} From ea27ab68fd75785cc3cc3fa75a4778aeb46491c6 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 30 Nov 2026 09:25:43 +0100 Subject: [PATCH 4/6] refactor(packaging): check the descriptions with bash and yq Same errors as the Python script, without PyYAML nor the temporary environment that installed it. --- packaging/README.md | 8 +- packaging/check-descriptions/action.yml | 2 +- .../check-descriptions/check-descriptions.py | 99 -------------- .../check-descriptions/check-descriptions.sh | 126 ++++++++++++++++++ packaging/check-descriptions/check.sh | 22 --- packaging/tests/check-descriptions.bats | 31 ++++- 6 files changed, 160 insertions(+), 128 deletions(-) delete mode 100755 packaging/check-descriptions/check-descriptions.py create mode 100755 packaging/check-descriptions/check-descriptions.sh delete mode 100755 packaging/check-descriptions/check.sh diff --git a/packaging/README.md b/packaging/README.md index b5469d2..fb660be 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -175,8 +175,8 @@ when it is not set. The step fails when: ``. `paths` limits the check to the files it lists, and `working_directory` runs it in -another directory. The script needs PyYAML: it uses the one of the runner, and installs -a pinned version in a temporary environment when there is none. +another directory. The step needs `yq`, which the GitHub-hosted runners provide. -It is the `check-package-descriptions.py` script of centreon, centreon-collect and -centreon-modules, unchanged: a repository replaces its copy with this step. +It gives the errors of the `check-package-descriptions.py` script of centreon, +centreon-collect and centreon-modules, without Python: a repository replaces its copy +with this step. diff --git a/packaging/check-descriptions/action.yml b/packaging/check-descriptions/action.yml index 7d0c6b1..79a69a3 100644 --- a/packaging/check-descriptions/action.yml +++ b/packaging/check-descriptions/action.yml @@ -19,4 +19,4 @@ runs: env: PATHS: ${{ inputs.paths }} # the variable, not the context: only the variable is right in a container job - run: '"${GITHUB_ACTION_PATH}/check.sh"' + run: '"${GITHUB_ACTION_PATH}/check-descriptions.sh"' diff --git a/packaging/check-descriptions/check-descriptions.py b/packaging/check-descriptions/check-descriptions.py deleted file mode 100755 index 8045aa5..0000000 --- a/packaging/check-descriptions/check-descriptions.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python3 -"""Check the synopsis and summary of the nfpm package definitions. - -The first line of the nfpm description is the deb synopsis (apt search/show), -rpm.summary is the rpm one. Both must be unique within the repository. -""" - -import collections -import subprocess -import sys - -import yaml - - -class Loader(yaml.SafeLoader): - """SafeLoader ignoring custom tags (gorgone configuration uses !include).""" - - -Loader.add_multi_constructor("!", lambda loader, suffix, node: None) - -DEBUGINFO_SUFFIX = "-debuginfo" - - -def first_line(text): - lines = [line.strip() for line in str(text or "").splitlines()] - return next((line for line in lines if line), "") - - -def load_packages(paths): - """Return {path: nfpm definition} for the nfpm files found in paths.""" - packages = {} - for path in paths: - if "packaging" not in path.split("/")[:-1]: - continue - with open(path, encoding="utf-8") as stream: - content = yaml.load(stream, Loader=Loader) - if isinstance(content, dict) and all(key in content for key in ("name", "arch", "version")): - packages[path] = content - return packages - - -def check(packages): - """Return a list of (path, message) errors.""" - errors = [] - seen = {"synopsis": collections.defaultdict(list), "rpm summary": collections.defaultdict(list)} - - for path, package in sorted(packages.items()): - name = str(package["name"]) - synopsis = first_line(package.get("description")) - # nfpm uses the first description line when rpm.summary is not set - raw_summary = (package.get("rpm") or {}).get("summary") - summary = synopsis if raw_summary in (None, "") else first_line(raw_summary) - - if not synopsis: - errors.append((path, f"{name}: the description is empty")) - continue - if not summary: - errors.append((path, f"{name}: the rpm summary is blank")) - continue - - fields = {"synopsis": synopsis, "rpm summary": summary} - for field, value in fields.items(): - seen[field][value.casefold()].append((path, name)) - if name.endswith(DEBUGINFO_SUFFIX): - base_name = name[: -len(DEBUGINFO_SUFFIX)] - if base_name not in value.replace(",", " ").rstrip(".").split(): - errors.append((path, f"{name}: the {field} does not mention {base_name}: '{value}'")) - - for field, values in seen.items(): - for owners in values.values(): - if len(owners) < 2: - continue - names = ", ".join(name for _, name in owners) - for path, name in owners: - errors.append((path, f"{name}: the {field} is shared by several packages ({names})")) - - return errors - - -def main(): - paths = sys.argv[1:] or subprocess.run( - ["git", "ls-files", "*.yaml", "*.yml"], capture_output=True, text=True, check=True - ).stdout.splitlines() - - packages = load_packages(paths) - if not packages: - print("::error::no nfpm package definition found") - return 1 - - errors = check(packages) - for path, message in errors: - print(f"::error file={path}::{message}") - - print(f"{len(packages)} package definitions checked, {len(errors)} error(s)") - return 1 if errors else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/packaging/check-descriptions/check-descriptions.sh b/packaging/check-descriptions/check-descriptions.sh new file mode 100755 index 0000000..fd36132 --- /dev/null +++ b/packaging/check-descriptions/check-descriptions.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Check the synopsis and the summary of the nfpm package definitions of a repository. +# +# The first line of the description of a package is the synopsis of a deb (apt search, +# apt show), rpm.summary the one of an rpm. Both must be unique within the repository. +# Input (env): PATHS, the files to check; empty for every tracked YAML file. +set -euo pipefail + +command -v yq > /dev/null || { + echo "::error::yq is needed to read the package definitions" + exit 1 +} + +if [[ -n "${PATHS//[[:space:]]/}" ]]; then + # a list of paths, split on purpose + # shellcheck disable=SC2206 + FILES=($PATHS) +else + mapfile -t FILES < <(git ls-files '*.yaml' '*.yml') +fi + +# what the check reads of a definition, one value per line: its name, its synopsis, +# whether it sets an rpm summary, the first line of that summary, and a closing word that +# keeps the empty values before it. In yq a comma binds less than a pipe, hence the list. +# shellcheck disable=SC2016 +READ=' + select(tag == "!!map") | select(has("name") and has("arch") and has("version")) + | [ + (.name | tostring), + ((.description // "" | tostring | split("\n") | map(trim) | map(select(. != "")) | .[0]) // ""), + ((.rpm.summary // "" | tostring | length) > 0 | tostring), + ((.rpm.summary // "" | tostring | split("\n") | map(trim) | map(select(. != "")) | .[0]) // ""), + "end" + ] + | .[] +' + +ERRORS=0 +PACKAGES=0 +declare -A OWNERS_SYNOPSIS=() OWNERS_SUMMARY=() +declare -a SHARED_KEYS=() + +error() { + echo "::error file=$1::$2" + ERRORS=$((ERRORS + 1)) +} + +# records who uses a synopsis or a summary, and checks a debuginfo package names its package +record() { + local field=$1 path=$2 name=$3 value=$4 key base words + key="${field}"$'\t'"${value,,}" + if [[ "$field" == "synopsis" ]]; then + OWNERS_SYNOPSIS[$key]+="${path}"$'\t'"${name}"$'\n' + else + OWNERS_SUMMARY[$key]+="${path}"$'\t'"${name}"$'\n' + fi + SHARED_KEYS+=("$key") + if [[ "$name" == *-debuginfo ]]; then + base=${name%-debuginfo} + words=" ${value//,/ } " + words="${words%"${words##*[![:space:].]}"} " + [[ "$words" == *" ${base} "* ]] || error "$path" "${name}: the ${field} does not mention ${base}: '${value}'" + fi +} + +mapfile -t SORTED < <(printf '%s\n' "${FILES[@]}" | LC_ALL=C sort) +for path in "${SORTED[@]}"; do + [[ -n "$path" && "/${path%/*}/" == */packaging/* ]] || continue + # read apart from mapfile: a file yq cannot read fails the check + values=$(yq --unwrapScalar "$READ" "$path") || { + echo "::error file=${path}::this file cannot be read as YAML" + exit 1 + } + mapfile -t fields <<< "$values" + [[ ${#fields[@]} -eq 5 ]] || continue + PACKAGES=$((PACKAGES + 1)) + name=${fields[0]} + synopsis=${fields[1]} + if [[ "${fields[2]}" == "true" ]]; then + summary=${fields[3]:-} + else + # nfpm uses the first description line when rpm.summary is not set + summary=$synopsis + fi + + if [[ -z "$synopsis" ]]; then + error "$path" "${name}: the description is empty" + continue + fi + if [[ -z "$summary" ]]; then + error "$path" "${name}: the rpm summary is blank" + continue + fi + record "synopsis" "$path" "$name" "$synopsis" + record "rpm summary" "$path" "$name" "$summary" +done + +if ((PACKAGES == 0)); then + echo "::error::no nfpm package definition found" + exit 1 +fi + +# a synopsis or a summary used by several packages is an error for each of them +declare -A REPORTED=() +for key in "${SHARED_KEYS[@]}"; do + [[ -z "${REPORTED[$key]:-}" ]] || continue + REPORTED[$key]=1 + field=${key%%$'\t'*} + if [[ "$field" == "synopsis" ]]; then + owners=${OWNERS_SYNOPSIS[$key]} + else + owners=${OWNERS_SUMMARY[$key]} + fi + mapfile -t lines <<< "${owners%$'\n'}" + ((${#lines[@]} > 1)) || continue + names="" + for line in "${lines[@]}"; do + names+="${names:+, }${line#*$'\t'}" + done + for line in "${lines[@]}"; do + error "${line%%$'\t'*}" "${line#*$'\t'}: the ${field} is shared by several packages (${names})" + done +done + +echo "${PACKAGES} package definitions checked, ${ERRORS} error(s)" +((ERRORS == 0)) diff --git a/packaging/check-descriptions/check.sh b/packaging/check-descriptions/check.sh deleted file mode 100755 index 225111f..0000000 --- a/packaging/check-descriptions/check.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# Run check-descriptions.py, with PyYAML installed aside when the runner has none. -# Input (env): PATHS, the files to check; empty for every tracked YAML file. -set -euo pipefail - -PYYAML_VERSION="6.0.3" - -python="python3" -if ! python3 -c "import yaml" 2> /dev/null; then - environment=$(mktemp -d "${RUNNER_TEMP:-/tmp}/check-descriptions.XXXXXX") - if ! python3 -m venv "$environment" > /dev/null 2>&1 \ - || ! "${environment}/bin/pip" install --quiet --disable-pip-version-check "pyyaml==${PYYAML_VERSION}"; then - echo "::error::PyYAML is needed: install it (python3-yaml, or pip install pyyaml) before this step" - exit 1 - fi - echo "PyYAML ${PYYAML_VERSION} installed in a temporary environment" - python="${environment}/bin/python" -fi - -# a list of paths, split on purpose -# shellcheck disable=SC2086 -exec "$python" "$(dirname "$0")/check-descriptions.py" ${PATHS:-} diff --git a/packaging/tests/check-descriptions.bats b/packaging/tests/check-descriptions.bats index 8dcf66e..5978584 100644 --- a/packaging/tests/check-descriptions.bats +++ b/packaging/tests/check-descriptions.bats @@ -1,9 +1,9 @@ #!/usr/bin/env bats -# check.sh runs in a small git repository holding nfpm package definitions. +# The check runs in a small git repository holding nfpm package definitions. setup() { - CHECK="${BATS_TEST_DIRNAME}/../check-descriptions/check.sh" + CHECK="${BATS_TEST_DIRNAME}/../check-descriptions/check-descriptions.sh" REPO="${BATS_TEST_TMPDIR}/repository" mkdir -p "${REPO}/broker/packaging" "${REPO}/engine/packaging" git init --quiet "$REPO" @@ -119,3 +119,30 @@ check() { [ "$status" -ne 0 ] [[ "$output" == *"no nfpm package definition found"* ]] } + +@test "a definition that is not valid YAML fails, naming the file" { + printf 'name: "broken\narch: [\n' > "${REPO}/engine/packaging/broken.yaml" + check + [ "$status" -ne 0 ] + [[ "$output" == *"::error file=engine/packaging/broken.yaml::this file cannot be read as YAML"* ]] +} + +@test "a multi-line summary is read by its first line" { + printf 'name: "centreon-engine"\narch: all\nversion: "1"\ndescription: >\n Centreon Engine\n in two lines.\nrpm:\n summary: |\n\n Centreon Broker\n and more\n' > "${REPO}/engine/packaging/engine.yaml" + check + [ "$status" -ne 0 ] + [[ "$output" == *"centreon-engine: the rpm summary is shared by several packages (centreon-broker, centreon-engine)"* ]] + [[ "$output" != *"the synopsis is shared"* ]] +} + +@test "a runner without yq fails with its own message" { + mkdir "${BATS_TEST_TMPDIR}/bin" + for tool in bash git env sort; do + ln -s "$(command -v "$tool")" "${BATS_TEST_TMPDIR}/bin/${tool}" + done + git -C "$REPO" add -A + cd "$REPO" + run env -i PATH="${BATS_TEST_TMPDIR}/bin" "$CHECK" + [ "$status" -ne 0 ] + [[ "$output" == *"yq is needed"* ]] +} From 81078599e9adaa5fc7264923002e4366c59af76b Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 30 Nov 2026 09:38:53 +0100 Subject: [PATCH 5/6] Revert "refactor(packaging): check the descriptions with bash and yq" This reverts commit ea27ab68fd75785cc3cc3fa75a4778aeb46491c6. --- packaging/README.md | 8 +- packaging/check-descriptions/action.yml | 2 +- .../check-descriptions/check-descriptions.py | 99 ++++++++++++++ .../check-descriptions/check-descriptions.sh | 126 ------------------ packaging/check-descriptions/check.sh | 22 +++ packaging/tests/check-descriptions.bats | 31 +---- 6 files changed, 128 insertions(+), 160 deletions(-) create mode 100755 packaging/check-descriptions/check-descriptions.py delete mode 100755 packaging/check-descriptions/check-descriptions.sh create mode 100755 packaging/check-descriptions/check.sh diff --git a/packaging/README.md b/packaging/README.md index fb660be..b5469d2 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -175,8 +175,8 @@ when it is not set. The step fails when: ``. `paths` limits the check to the files it lists, and `working_directory` runs it in -another directory. The step needs `yq`, which the GitHub-hosted runners provide. +another directory. The script needs PyYAML: it uses the one of the runner, and installs +a pinned version in a temporary environment when there is none. -It gives the errors of the `check-package-descriptions.py` script of centreon, -centreon-collect and centreon-modules, without Python: a repository replaces its copy -with this step. +It is the `check-package-descriptions.py` script of centreon, centreon-collect and +centreon-modules, unchanged: a repository replaces its copy with this step. diff --git a/packaging/check-descriptions/action.yml b/packaging/check-descriptions/action.yml index 79a69a3..7d0c6b1 100644 --- a/packaging/check-descriptions/action.yml +++ b/packaging/check-descriptions/action.yml @@ -19,4 +19,4 @@ runs: env: PATHS: ${{ inputs.paths }} # the variable, not the context: only the variable is right in a container job - run: '"${GITHUB_ACTION_PATH}/check-descriptions.sh"' + run: '"${GITHUB_ACTION_PATH}/check.sh"' diff --git a/packaging/check-descriptions/check-descriptions.py b/packaging/check-descriptions/check-descriptions.py new file mode 100755 index 0000000..8045aa5 --- /dev/null +++ b/packaging/check-descriptions/check-descriptions.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Check the synopsis and summary of the nfpm package definitions. + +The first line of the nfpm description is the deb synopsis (apt search/show), +rpm.summary is the rpm one. Both must be unique within the repository. +""" + +import collections +import subprocess +import sys + +import yaml + + +class Loader(yaml.SafeLoader): + """SafeLoader ignoring custom tags (gorgone configuration uses !include).""" + + +Loader.add_multi_constructor("!", lambda loader, suffix, node: None) + +DEBUGINFO_SUFFIX = "-debuginfo" + + +def first_line(text): + lines = [line.strip() for line in str(text or "").splitlines()] + return next((line for line in lines if line), "") + + +def load_packages(paths): + """Return {path: nfpm definition} for the nfpm files found in paths.""" + packages = {} + for path in paths: + if "packaging" not in path.split("/")[:-1]: + continue + with open(path, encoding="utf-8") as stream: + content = yaml.load(stream, Loader=Loader) + if isinstance(content, dict) and all(key in content for key in ("name", "arch", "version")): + packages[path] = content + return packages + + +def check(packages): + """Return a list of (path, message) errors.""" + errors = [] + seen = {"synopsis": collections.defaultdict(list), "rpm summary": collections.defaultdict(list)} + + for path, package in sorted(packages.items()): + name = str(package["name"]) + synopsis = first_line(package.get("description")) + # nfpm uses the first description line when rpm.summary is not set + raw_summary = (package.get("rpm") or {}).get("summary") + summary = synopsis if raw_summary in (None, "") else first_line(raw_summary) + + if not synopsis: + errors.append((path, f"{name}: the description is empty")) + continue + if not summary: + errors.append((path, f"{name}: the rpm summary is blank")) + continue + + fields = {"synopsis": synopsis, "rpm summary": summary} + for field, value in fields.items(): + seen[field][value.casefold()].append((path, name)) + if name.endswith(DEBUGINFO_SUFFIX): + base_name = name[: -len(DEBUGINFO_SUFFIX)] + if base_name not in value.replace(",", " ").rstrip(".").split(): + errors.append((path, f"{name}: the {field} does not mention {base_name}: '{value}'")) + + for field, values in seen.items(): + for owners in values.values(): + if len(owners) < 2: + continue + names = ", ".join(name for _, name in owners) + for path, name in owners: + errors.append((path, f"{name}: the {field} is shared by several packages ({names})")) + + return errors + + +def main(): + paths = sys.argv[1:] or subprocess.run( + ["git", "ls-files", "*.yaml", "*.yml"], capture_output=True, text=True, check=True + ).stdout.splitlines() + + packages = load_packages(paths) + if not packages: + print("::error::no nfpm package definition found") + return 1 + + errors = check(packages) + for path, message in errors: + print(f"::error file={path}::{message}") + + print(f"{len(packages)} package definitions checked, {len(errors)} error(s)") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packaging/check-descriptions/check-descriptions.sh b/packaging/check-descriptions/check-descriptions.sh deleted file mode 100755 index fd36132..0000000 --- a/packaging/check-descriptions/check-descriptions.sh +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env bash -# Check the synopsis and the summary of the nfpm package definitions of a repository. -# -# The first line of the description of a package is the synopsis of a deb (apt search, -# apt show), rpm.summary the one of an rpm. Both must be unique within the repository. -# Input (env): PATHS, the files to check; empty for every tracked YAML file. -set -euo pipefail - -command -v yq > /dev/null || { - echo "::error::yq is needed to read the package definitions" - exit 1 -} - -if [[ -n "${PATHS//[[:space:]]/}" ]]; then - # a list of paths, split on purpose - # shellcheck disable=SC2206 - FILES=($PATHS) -else - mapfile -t FILES < <(git ls-files '*.yaml' '*.yml') -fi - -# what the check reads of a definition, one value per line: its name, its synopsis, -# whether it sets an rpm summary, the first line of that summary, and a closing word that -# keeps the empty values before it. In yq a comma binds less than a pipe, hence the list. -# shellcheck disable=SC2016 -READ=' - select(tag == "!!map") | select(has("name") and has("arch") and has("version")) - | [ - (.name | tostring), - ((.description // "" | tostring | split("\n") | map(trim) | map(select(. != "")) | .[0]) // ""), - ((.rpm.summary // "" | tostring | length) > 0 | tostring), - ((.rpm.summary // "" | tostring | split("\n") | map(trim) | map(select(. != "")) | .[0]) // ""), - "end" - ] - | .[] -' - -ERRORS=0 -PACKAGES=0 -declare -A OWNERS_SYNOPSIS=() OWNERS_SUMMARY=() -declare -a SHARED_KEYS=() - -error() { - echo "::error file=$1::$2" - ERRORS=$((ERRORS + 1)) -} - -# records who uses a synopsis or a summary, and checks a debuginfo package names its package -record() { - local field=$1 path=$2 name=$3 value=$4 key base words - key="${field}"$'\t'"${value,,}" - if [[ "$field" == "synopsis" ]]; then - OWNERS_SYNOPSIS[$key]+="${path}"$'\t'"${name}"$'\n' - else - OWNERS_SUMMARY[$key]+="${path}"$'\t'"${name}"$'\n' - fi - SHARED_KEYS+=("$key") - if [[ "$name" == *-debuginfo ]]; then - base=${name%-debuginfo} - words=" ${value//,/ } " - words="${words%"${words##*[![:space:].]}"} " - [[ "$words" == *" ${base} "* ]] || error "$path" "${name}: the ${field} does not mention ${base}: '${value}'" - fi -} - -mapfile -t SORTED < <(printf '%s\n' "${FILES[@]}" | LC_ALL=C sort) -for path in "${SORTED[@]}"; do - [[ -n "$path" && "/${path%/*}/" == */packaging/* ]] || continue - # read apart from mapfile: a file yq cannot read fails the check - values=$(yq --unwrapScalar "$READ" "$path") || { - echo "::error file=${path}::this file cannot be read as YAML" - exit 1 - } - mapfile -t fields <<< "$values" - [[ ${#fields[@]} -eq 5 ]] || continue - PACKAGES=$((PACKAGES + 1)) - name=${fields[0]} - synopsis=${fields[1]} - if [[ "${fields[2]}" == "true" ]]; then - summary=${fields[3]:-} - else - # nfpm uses the first description line when rpm.summary is not set - summary=$synopsis - fi - - if [[ -z "$synopsis" ]]; then - error "$path" "${name}: the description is empty" - continue - fi - if [[ -z "$summary" ]]; then - error "$path" "${name}: the rpm summary is blank" - continue - fi - record "synopsis" "$path" "$name" "$synopsis" - record "rpm summary" "$path" "$name" "$summary" -done - -if ((PACKAGES == 0)); then - echo "::error::no nfpm package definition found" - exit 1 -fi - -# a synopsis or a summary used by several packages is an error for each of them -declare -A REPORTED=() -for key in "${SHARED_KEYS[@]}"; do - [[ -z "${REPORTED[$key]:-}" ]] || continue - REPORTED[$key]=1 - field=${key%%$'\t'*} - if [[ "$field" == "synopsis" ]]; then - owners=${OWNERS_SYNOPSIS[$key]} - else - owners=${OWNERS_SUMMARY[$key]} - fi - mapfile -t lines <<< "${owners%$'\n'}" - ((${#lines[@]} > 1)) || continue - names="" - for line in "${lines[@]}"; do - names+="${names:+, }${line#*$'\t'}" - done - for line in "${lines[@]}"; do - error "${line%%$'\t'*}" "${line#*$'\t'}: the ${field} is shared by several packages (${names})" - done -done - -echo "${PACKAGES} package definitions checked, ${ERRORS} error(s)" -((ERRORS == 0)) diff --git a/packaging/check-descriptions/check.sh b/packaging/check-descriptions/check.sh new file mode 100755 index 0000000..225111f --- /dev/null +++ b/packaging/check-descriptions/check.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Run check-descriptions.py, with PyYAML installed aside when the runner has none. +# Input (env): PATHS, the files to check; empty for every tracked YAML file. +set -euo pipefail + +PYYAML_VERSION="6.0.3" + +python="python3" +if ! python3 -c "import yaml" 2> /dev/null; then + environment=$(mktemp -d "${RUNNER_TEMP:-/tmp}/check-descriptions.XXXXXX") + if ! python3 -m venv "$environment" > /dev/null 2>&1 \ + || ! "${environment}/bin/pip" install --quiet --disable-pip-version-check "pyyaml==${PYYAML_VERSION}"; then + echo "::error::PyYAML is needed: install it (python3-yaml, or pip install pyyaml) before this step" + exit 1 + fi + echo "PyYAML ${PYYAML_VERSION} installed in a temporary environment" + python="${environment}/bin/python" +fi + +# a list of paths, split on purpose +# shellcheck disable=SC2086 +exec "$python" "$(dirname "$0")/check-descriptions.py" ${PATHS:-} diff --git a/packaging/tests/check-descriptions.bats b/packaging/tests/check-descriptions.bats index 5978584..8dcf66e 100644 --- a/packaging/tests/check-descriptions.bats +++ b/packaging/tests/check-descriptions.bats @@ -1,9 +1,9 @@ #!/usr/bin/env bats -# The check runs in a small git repository holding nfpm package definitions. +# check.sh runs in a small git repository holding nfpm package definitions. setup() { - CHECK="${BATS_TEST_DIRNAME}/../check-descriptions/check-descriptions.sh" + CHECK="${BATS_TEST_DIRNAME}/../check-descriptions/check.sh" REPO="${BATS_TEST_TMPDIR}/repository" mkdir -p "${REPO}/broker/packaging" "${REPO}/engine/packaging" git init --quiet "$REPO" @@ -119,30 +119,3 @@ check() { [ "$status" -ne 0 ] [[ "$output" == *"no nfpm package definition found"* ]] } - -@test "a definition that is not valid YAML fails, naming the file" { - printf 'name: "broken\narch: [\n' > "${REPO}/engine/packaging/broken.yaml" - check - [ "$status" -ne 0 ] - [[ "$output" == *"::error file=engine/packaging/broken.yaml::this file cannot be read as YAML"* ]] -} - -@test "a multi-line summary is read by its first line" { - printf 'name: "centreon-engine"\narch: all\nversion: "1"\ndescription: >\n Centreon Engine\n in two lines.\nrpm:\n summary: |\n\n Centreon Broker\n and more\n' > "${REPO}/engine/packaging/engine.yaml" - check - [ "$status" -ne 0 ] - [[ "$output" == *"centreon-engine: the rpm summary is shared by several packages (centreon-broker, centreon-engine)"* ]] - [[ "$output" != *"the synopsis is shared"* ]] -} - -@test "a runner without yq fails with its own message" { - mkdir "${BATS_TEST_TMPDIR}/bin" - for tool in bash git env sort; do - ln -s "$(command -v "$tool")" "${BATS_TEST_TMPDIR}/bin/${tool}" - done - git -C "$REPO" add -A - cd "$REPO" - run env -i PATH="${BATS_TEST_TMPDIR}/bin" "$CHECK" - [ "$status" -ne 0 ] - [[ "$output" == *"yq is needed"* ]] -} From eff8a67ac246ee862a05c8c9e48457e5eee34c0e Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 30 Nov 2026 09:39:12 +0100 Subject: [PATCH 6/6] test(packaging): cover invalid YAML and multi-line summaries in the description check --- packaging/tests/check-descriptions.bats | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packaging/tests/check-descriptions.bats b/packaging/tests/check-descriptions.bats index 8dcf66e..295b5b7 100644 --- a/packaging/tests/check-descriptions.bats +++ b/packaging/tests/check-descriptions.bats @@ -119,3 +119,18 @@ check() { [ "$status" -ne 0 ] [[ "$output" == *"no nfpm package definition found"* ]] } + +@test "a definition that is not valid YAML fails" { + printf 'name: "broken\narch: [\n' > "${REPO}/engine/packaging/broken.yaml" + check + [ "$status" -ne 0 ] + [[ "$output" != *"package definitions checked"* ]] +} + +@test "a multi-line summary is read by its first line" { + printf 'name: "centreon-engine"\narch: all\nversion: "1"\ndescription: >\n Centreon Engine\n in two lines.\nrpm:\n summary: |\n\n Centreon Broker\n and more\n' > "${REPO}/engine/packaging/engine.yaml" + check + [ "$status" -ne 0 ] + [[ "$output" == *"centreon-engine: the rpm summary is shared by several packages (centreon-broker, centreon-engine)"* ]] + [[ "$output" != *"the synopsis is shared"* ]] +}