Bootstrap standalone PDF Presenter with CI, presentation core and artwork

This commit is contained in:
Dandaedre 2026-11-19 12:13:51 +01:00
commit 4fb3333cf5
27 changed files with 1120 additions and 0 deletions

2
.cargo/config.toml Normal file
View File

@ -0,0 +1,2 @@
[alias]
coverage = "llvm-cov --locked --workspace --json --summary-only --output-path coverage/summary.json"

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
/target/
/coverage/
/build/
/dist/
/downloads/
__pycache__/
*.py[cod]
.DS_Store
.env
*gitea-token*

57
AGENTS.md Normal file
View File

@ -0,0 +1,57 @@
# PDF Presenter
Standalone Rust application foundation for multiscreen PDF presentation. Read
`AGENT_DOCUMENTATION.md` and `docs/development/plan.md` before implementing behavior.
The current executable reports bootstrap status; do not describe it as a PDF viewer.
## Structure and intended architecture
- `crates/pdf-presenter/src/lib.rs`: tested, UI-independent presentation state.
- `src/main.rs` in that crate: executable entry point; future desktop host.
- `crates/pdf-presenter/tests/`: meaningful behavior tests, including boundary cases.
- `crates/pdf-presenter/assets/`: generated app artwork and provenance.
- `scripts/`, `tests/`, `Jenkinsfile`: standalone validation and badge publication.
- `docs/development/`: architecture decisions, implementation plan and CI setup.
- `docs/interfaces/`: persistent-format contracts when formats are introduced.
Keep a single-member workspace. Do not depend on sibling repositories. Rust/egui
is the starting desktop direction, following Canvas Pilot; validate multiwindow
behavior and renderer/platform support before choosing dependencies. Keep PDF
rendering, document state and display/window management separate without speculative
abstractions. Do not copy Pympress or PowerPoint code/assets without license review.
## Presentation safety
Open source PDFs read-only. Never rewrite a document as a side effect of presenting.
Failed loads retain the working document. Bound renderer memory/cache usage; handle
malformed, encrypted and large PDFs explicitly. Keep slow rendering off the UI thread.
Audience outputs must never show operator notes, dialogs, paths or controls. Require
explicit output activation, start blanked, and preserve blanking during navigation.
Display disconnects must not move operator content onto an audience output.
Never claim physical multiscreen acceptance from headless unit tests.
## Validation and publication
Run the commands in `docs/development/ci.md`: formatting, Clippy and rustdoc with
warnings denied, workspace tests, Python helper tests, and whole-application coverage
with a 75% floor. Include future GUI/renderer code; do not hide production files from
coverage. Exercise physical displays separately on each claimed platform.
CI uses `rust_no_docker`; it archives exactly three badge SVGs and only main/non-PR
builds publish to `/mnt/assets/coverage/idle-org/pdf-presenter/main/`. No automatic
releases, binaries or manual publication. Jenkins job creation is external setup.
Never modify another tool's badges or the shared manuals root.
Document each persistent representation under `docs/interfaces/` with versions,
fields, units, validation and round trips. Schema changes need matching examples,
tests and migrations or clear unsupported-version errors. There is no saved format yet.
## Working conventions
Inspect Git status first and preserve unrelated edits. Keep README concise; detailed
plans and acceptance records belong in docs. Update `docs/changelog.md` for each
subject and bump the workspace patch once per completed subject (initial bootstrap
is 0.1.0); keep Cargo.lock synchronized. Keep credentials, PDFs supplied for private
shows, generated binaries and caches out of Git. Every completed task changing files
ends with a descriptive commit; stage only task-owned changes. Report validation,
limitations and the commit hash. Push only when requested.

9
AGENT_DOCUMENTATION.md Normal file
View File

@ -0,0 +1,9 @@
# Agent documentation
- [Working rules](AGENTS.md)
- [Development](docs/development/README.md)
- [Implementation and acceptance plan](docs/development/plan.md)
- [CI and Jenkins setup](docs/development/ci.md)
- [Interface policy](docs/interfaces/README.md)
- [Artwork provenance](docs/development/icon-prompts.json)
- [Changelog](docs/changelog.md)

7
Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "pdf-presenter"
version = "0.1.0"

16
Cargo.toml Normal file
View File

@ -0,0 +1,16 @@
[workspace]
members = ["crates/pdf-presenter"]
default-members = ["crates/pdf-presenter"]
resolver = "3"
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter"
[profile.dev]
debug = 0
[profile.release]
strip = true

87
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,87 @@
// Multibranch Pipeline: BRANCH_NAME is required, never guessed from the worktree.
pipeline {
agent { label 'rust_no_docker' }
options {
skipDefaultCheckout(true)
disableConcurrentBuilds()
timeout(time: 45, unit: 'MINUTES')
}
environment {
PYTHONUNBUFFERED = '1'
PYTHONDONTWRITEBYTECODE = '1'
NO_COLOR = '1'
CARGO_TERM_COLOR = 'never'
BADGE_ROOT = '/mnt/assets/coverage'
}
stages {
stage('Checkout') {
steps {
deleteDir()
checkout scm
sh 'python3 scripts/ci.py init'
}
}
stage('Tools') {
steps {
sh '''
set -eu
python3 -c 'import sys; assert sys.version_info >= (3, 11), "Python 3.11+ required for CI"'
test -n "${BRANCH_NAME:?Configure this job as a Multibranch Pipeline}"
uname -sr
rustc --version
if ! cargo llvm-cov --version | grep -Fx 'cargo-llvm-cov 0.9.1'; then
cargo install cargo-llvm-cov --version 0.9.1 --locked
fi
rustup component add llvm-tools-preview clippy rustfmt
'''
}
}
stage('Format, lint and docs') {
steps {
sh '''
set -eu
cargo fmt --all --check
cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --locked --workspace --all-features --no-deps
'''
}
}
stage('Tests') {
steps {
// Keep failures visible while allowing independent coverage measurement.
catchError(buildResult: 'FAILURE', stageResult: 'FAILURE', catchInterruptions: false) {
sh '''
set -eu
python3 -m unittest discover -s tests -v
cargo test --locked --workspace --all-features
cargo build --locked --workspace --all-features
python3 scripts/ci.py tests-passed
'''
}
}
}
stage('Coverage') {
steps { sh 'python3 scripts/ci.py coverage' }
}
}
post {
cleanup {
script {
sh 'python3 scripts/ci.py finalize'
archiveArtifacts artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg',
fingerprint: true, allowEmptyArchive: false
if (env.BRANCH_NAME == 'main' && !env.CHANGE_ID) {
sh 'scripts/publish-badges.sh "$BADGE_ROOT" version test coverage'
}
echo "Tests, coverage diagnostics and badges finalized; result: ${currentBuild.currentResult}. No release created."
}
}
}
}

10
LICENSE Normal file
View File

@ -0,0 +1,10 @@
MIT License
Copyright (c) 2026 Beffroi
Copyright (c) 2026 idle-org
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

28
README.md Normal file
View File

@ -0,0 +1,28 @@
<h1 align="center">PDF Presenter</h1>
<p align="center"><img src="crates/pdf-presenter/assets/app-icon.png" width="160" height="160" alt="PDF Presenter icon"></p>
<p align="center">A standalone beffroi tool for multiscreen PDF presentations.</p>
<p align="center">
<img src="https://assets.dandaedre.com/coverage/idle-org/pdf-presenter/main/version.svg" alt="Current version">
<img src="https://assets.dandaedre.com/coverage/idle-org/pdf-presenter/main/test.svg" alt="Test status">
<img src="https://assets.dandaedre.com/coverage/idle-org/pdf-presenter/main/coverage.svg" alt="Line coverage">
</p>
**Repository foundation — not yet a usable PDF presenter.** The intended application
pairs an operator view with fullscreen audience outputs, inspired by Pympress and
PowerPoint workflows. It is independent of those projects.
The initial Rust core tests page navigation and audience blanking. PDF loading,
rendering, presenter UI and display selection are planned. Build status badges
become available after the first Jenkins publication.
```sh
cargo run --locked -p pdf-presenter
cargo test --locked --workspace
```
Builds independently; no sibling beffroi-tools or Canvas Pilot checkout is required.
[Development and CI](docs/development/README.md) · [Implementation plan](docs/development/plan.md) ·
[Agent guide](AGENTS.md) · [Changelog](docs/changelog.md) ·
[beffroi-tools](https://proxy.dandaedre.com/gitea/Beffroi/beffroi-tools)

4
coverage.toml Normal file
View File

@ -0,0 +1,4 @@
# Whole application; never exclude future GUI or renderer code to meet this floor.
line-floor = 75.0
tool = "cargo-llvm-cov"
tool-version = "0.9.1"

View File

@ -0,0 +1,7 @@
[package]
name = "pdf-presenter"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
description = "Foundation for a standalone multiscreen PDF presenter"

View File

@ -0,0 +1,6 @@
# Application artwork
`app-icon.png` is the generated master for the future desktop app and repository
avatar. The README consumes the same asset. Generate platform ICO/ICNS sizes during
packaging; no desktop bundle exists yet. Do not alter the master silently.
See [generation provenance](../../../docs/development/icon-prompts.json).

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

View File

@ -0,0 +1,58 @@
//! Presentation state shared by future operator and audience windows.
//!
//! This bootstrap does not load or render PDFs. Page indices are zero-based;
//! blanking hides audience content without losing the selected page.
use std::num::NonZeroUsize;
/// Navigation and audience-output state for one nonempty document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Presentation {
page_count: NonZeroUsize,
page: usize,
blanked: bool,
}
impl Presentation {
/// Start at the first page, with audience output initially blanked.
pub fn new(page_count: NonZeroUsize) -> Self {
Self {
page_count,
page: 0,
blanked: true,
}
}
/// Selected document page, regardless of output blanking.
pub fn page(&self) -> usize {
self.page
}
/// Page visible to the audience, or `None` while blanked.
pub fn audience_page(&self) -> Option<usize> {
(!self.blanked).then_some(self.page)
}
/// Show or hide audience content without changing navigation.
pub fn set_blanked(&mut self, blanked: bool) {
self.blanked = blanked;
}
/// Select a valid page. Invalid requests leave the state unchanged.
pub fn go_to(&mut self, page: usize) -> bool {
if page >= self.page_count.get() {
return false;
}
self.page = page;
true
}
/// Advance without wrapping at the end of the document.
pub fn advance(&mut self) {
self.page = (self.page + 1).min(self.page_count.get() - 1);
}
/// Go back without wrapping at the beginning of the document.
pub fn previous(&mut self) {
self.page = self.page.saturating_sub(1);
}
}

View File

@ -0,0 +1,8 @@
fn main() {
println!(
"PDF Presenter {} — repository foundation",
env!("CARGO_PKG_VERSION")
);
println!("PDF rendering and multiscreen windows are not implemented yet.");
println!("See docs/development/plan.md for implementation and acceptance work.");
}

View File

@ -0,0 +1,10 @@
#[test]
fn executable_identifies_its_actual_status() {
let output = std::process::Command::new(env!("CARGO_BIN_EXE_pdf-presenter"))
.output()
.unwrap();
assert!(output.status.success());
let text = String::from_utf8(output.stdout).unwrap();
assert!(text.contains(env!("CARGO_PKG_VERSION")));
assert!(text.contains("not implemented yet"));
}

View File

@ -0,0 +1,47 @@
use pdf_presenter::Presentation;
use std::num::NonZeroUsize;
#[test]
fn navigation_stops_at_document_boundaries() {
let mut show = Presentation::new(NonZeroUsize::new(3).unwrap());
show.previous();
assert_eq!(show.page(), 0);
show.advance();
assert_eq!(show.page(), 1);
show.advance();
show.advance();
assert_eq!(show.page(), 2);
show.previous();
assert_eq!(show.page(), 1);
let before = show.clone();
assert!(!show.go_to(3));
assert!(!show.go_to(usize::MAX));
assert_eq!(show, before);
assert!(show.go_to(0));
assert_eq!(show.page(), 0);
}
#[test]
fn blanking_preserves_navigation_and_starts_safe() {
let mut show = Presentation::new(NonZeroUsize::new(2).unwrap());
assert_eq!(show.audience_page(), None);
show.set_blanked(false);
assert_eq!(show.audience_page(), Some(0));
show.set_blanked(true);
show.advance();
assert_eq!(show.audience_page(), None);
show.set_blanked(false);
assert_eq!(show.audience_page(), Some(1));
}
#[test]
fn single_page_and_maximum_count_stay_in_bounds() {
let mut show = Presentation::new(NonZeroUsize::new(1).unwrap());
show.advance();
show.previous();
assert_eq!(show.page(), 0);
let mut largest = Presentation::new(NonZeroUsize::new(usize::MAX).unwrap());
assert!(largest.go_to(usize::MAX - 1));
largest.advance();
assert_eq!(largest.page(), usize::MAX - 1);
}

11
docs/changelog.md Normal file
View File

@ -0,0 +1,11 @@
# Changelog
## Unreleased
### 0.1.0
- Prepared the standalone PDF Presenter repository with a tested navigation/blanking
core, an explicit bootstrap executable, agent guidance and implementation plan.
- Added Jenkins validation, whole-workspace coverage and isolated three-badge
publication, plus generated application/repository artwork. PDF rendering and
multiscreen GUI are future work; no physical-output acceptance is claimed.

View File

@ -0,0 +1,14 @@
# Development
This is a standalone, single-member Rust workspace. Install Rust with rustfmt,
Clippy and llvm-tools-preview, plus Python 3.11+ for CI helpers. The foundation has
no third-party Rust dependencies. The desktop and PDF renderer dependencies remain
to be selected and validated.
- [Implementation and acceptance plan](plan.md)
- [Local checks and Jenkins](ci.md)
- [Persistent interfaces](../interfaces/README.md)
- [Changelog](../changelog.md)
Run `cargo run --locked -p pdf-presenter` for the bootstrap status executable.
No PDF opening, GUI, installation bundle or presentation output exists yet.

33
docs/development/ci.md Normal file
View File

@ -0,0 +1,33 @@
# CI and Jenkins setup
Create a Jenkins Multibranch Pipeline for `idle-org/pdf-presenter`, using the root
`Jenkinsfile`, SCM credentials and the existing `rust_no_docker` worker. Repository
upload does not create a Jenkins job. Configure branch discovery and a Gitea webhook
in Jenkins/Gitea when connecting the job.
The worker needs Rust, rustup, Python 3.11+, POSIX shell/awk/sed and a writable
`/mnt/assets/coverage`. The pipeline installs cargo-llvm-cov 0.9.1 and the rustfmt,
Clippy and llvm-tools-preview components. It builds and tests without a sibling
checkout, display server or PDF renderer.
```sh
python3 -m unittest discover -s tests -v
cargo fmt --all --check
cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
cargo test --locked --workspace --all-features
cargo build --locked --workspace --all-features
RUSTDOCFLAGS="-D warnings" cargo doc --locked --workspace --all-features --no-deps
python3 scripts/ci.py coverage
```
Coverage measures the entire Rust workspace with a 75% floor. Add all future
production GUI and renderer code to this same gate. Badge helpers are derived from
Canvas Pilot and have tests for invalid/stale reports and isolated publication.
Cleanup archives exactly `coverage/version.svg`, `coverage/test.svg` and
`coverage/coverage.svg`. Only main builds without CHANGE_ID publish badges under
`/mnt/assets/coverage/idle-org/pdf-presenter/main/`, including honest failed-test
or unavailable-coverage status. No shared asset root is synchronized or deleted.
There is no manual publisher, release job or binary upload in this pipeline.
The Jenkinsfile still requires a real Jenkins run; local tests cannot validate
worker configuration or prove the remote pipeline has run.

View File

@ -0,0 +1,12 @@
{
"tool": "built-in image_gen",
"use_case": "logo-brand",
"date": "2026-11-19",
"asset": "crates/pdf-presenter/assets/app-icon.png",
"prompt": "Use case: logo-brand\nAsset type: PDF Presenter desktop app icon and repository avatar, part of the beffroi-tools family.\nInput images: three reference icons showing the exact family style: dark charcoal rounded-square tile, softly beveled silver and bright turquoise objects, gentle 3D depth, subtle teal rim highlight. Use these as style references, not edit targets.\nPrimary request: Create a NEW matching family icon for a multiscreen PDF presenter. Inside the dark rounded-square tile, use a silver folded-corner document in front of a turquoise outlined presentation screen, and a simple bright turquoise play triangle on the document. Crisp bold uncluttered geometry, tactile satin metallic silver, very restrained dimensional shading. Distinct from the existing icons yet obviously in the same set.\nComposition: square, centered tile nearly fills frame, generous clear margins around the inner emblem, readable at 32px. Transparent exterior outside the tile, true alpha. No text, no letters, no watermark, no red, no blue, no photorealistic monitors, no elaborate background.",
"references": [
"beffroi-tools/crates/pptx-reporter/assets/app-icon.png",
"beffroi-tools/crates/rundown-converter/assets/app-icon.png",
"canvas-pilot/crates/canvas-pilot/assets/app-icon.png"
]
}

48
docs/development/plan.md Normal file
View File

@ -0,0 +1,48 @@
# Implementation and acceptance plan
## Completed foundation — 0.1.0
Independent workspace, source license, app/repository icon, agent instructions,
Jenkins pipeline, badge helpers and tests. The presentation core has bounded
zero-based navigation and audience blanking, with output initially blanked.
The executable only identifies the project's current status.
## Next implementation
1. Validate a PDF renderer and native multiwindow host in a small vertical slice.
Rust/egui is the initial direction for consistency with Canvas Pilot. Evaluate
PDF backend licensing, deployment, text/vector fidelity, page rotation,
password handling, cancellation and availability on Windows, Linux and macOS.
FreeBSD is the existing Jenkins worker, not a promised desktop platform.
2. Load a PDF read-only, render a page, and replace the current document only after
successful loading. Bound image dimensions, prefetch and cache memory. Add small,
synthetic PDF fixtures and real rendering tests.
3. Build an operator window with current/next previews, slide selection, elapsed
timer and keyboard controls. Keep presenter notes private; PDF notes layouts
require an explicit interpretation choice rather than guessing.
4. Add one audience window on an explicitly chosen display, aspect-preserving fit,
fullscreen and blank/unblank. Prove operator/audience isolation. Then extend to
multiple audience displays, initially showing the same slide.
5. Handle display hotplug, mixed DPI and orientation, failed renderer work, changing
documents and orderly shutdown. Persist display preferences only after their
contract and fallback rules are documented.
6. Package each validated platform with app icons and required renderer dependencies,
licenses and reproducible build instructions. Add a user manual when usable
workflows exist; reserve only the pdf-presenter book namespace.
## Decisions before extending scope
Independent content per display versus mirrored audience outputs, notes layout,
remote control, annotations, embedded media and transitions need separate scope.
PDF is the input target; native PowerPoint/PPTX playback is not implied. No external
network service or presentation-switcher integration is required for the first app.
## Acceptance still required
Unit tests verify navigation, invalid page rejection and blanking. They do not
verify rendered pixels or window placement. Before calling the app usable, run a
real PDF through the chosen backend and inspect rotated/cropped/mixed-size pages.
On every supported OS, exercise two and three displays, mixed DPI, fullscreen,
keyboard focus, output activation, blanking, monitor unplug/replug and load failure.
Record OS/backend versions and observed results. Confirm no operator content ever
appears on an audience output and no source PDF is modified.

10
docs/interfaces/README.md Normal file
View File

@ -0,0 +1,10 @@
# Persistent interfaces
The foundation writes no user settings, project files or exports. Presentation state
is in memory only: page indices are zero-based and blanking retains the selected
page. No file compatibility promise exists yet.
Before introducing persistence, document its location, version, fields, units,
precision, validation, omissions and round trips here. Add versioned examples and
meaningful tests, and provide migration or explicit unsupported-version handling.
Source PDFs always remain unchanged.

270
scripts/ci-coverage-badges.sh Executable file
View File

@ -0,0 +1,270 @@
#!/bin/sh
set -eu
usage() {
cat >&2 <<'EOF'
usage: $0 <version|test|coverage> [options]
Render one deterministic SVG badge. Defaults:
version --text version --value unknown --color #007ec6
test --text tests --value passing --color #4c1
coverage --text coverage --value - --color #9f9f9f --suffix %
Options:
--text TEXT left-hand label
--value VALUE right-hand value
--color COLOR value background (#RGB or #RRGGBB)
--size PX font size, from 6 through 24 (default: 11)
--height PX badge height, from 14 through 64 (default: 20)
--label-width PX fixed label width instead of automatic sizing
--value-width PX fixed value width instead of automatic sizing
--suffix TEXT text appended to the displayed value
--output PATH output file (default: coverage/<kind>.svg)
-h, --help show this help
Examples:
./ci-coverage-badges.sh version --value 1.2.3
./ci-coverage-badges.sh test --value failing
./ci-coverage-badges.sh coverage --value 87.4
./ci-coverage-badges.sh version --text release --value rc.12 --size 12 --color '#8a2be2'
EOF
exit "${1:-2}"
}
[ "$#" -ge 1 ] || usage
kind=$1
shift
case "$kind" in
version)
text=version
value=unknown
color='#007ec6'
suffix=
output=coverage/version.svg
;;
test)
text=tests
value=passing
color=
suffix=
output=coverage/test.svg
;;
coverage)
text=coverage
value=-
color=
suffix=%
output=coverage/coverage.svg
;;
-h|--help) usage 0 ;;
*)
echo "unsupported badge kind: $kind" >&2
usage
;;
esac
font_size=11
height=20
label_width=
value_width=
color_set=false
while [ "$#" -gt 0 ]; do
option=$1
case "$option" in
--text|--value|--color|--size|--height|--label-width|--value-width|--suffix|--output)
[ "$#" -ge 2 ] || {
echo "missing value for $option" >&2
exit 2
}
option_value=$2
shift 2
case "$option" in
--text) text=$option_value ;;
--value) value=$option_value ;;
--color) color=$option_value; color_set=true ;;
--size) font_size=$option_value ;;
--height) height=$option_value ;;
--label-width) label_width=$option_value ;;
--value-width) value_width=$option_value ;;
--suffix) suffix=$option_value ;;
--output) output=$option_value ;;
esac
;;
-h|--help) usage 0 ;;
*)
echo "unknown option: $option" >&2
usage
;;
esac
done
validate_text() {
field_name=$1
field_value=$2
if ! printf '%sX\n' "$field_value" | LC_ALL=C awk '
BEGIN { valid = 1 }
NR != 1 || $0 !~ /^[ -~]+X$/ || length($0) <= 1 { valid = 0 }
END { exit(valid == 0 ? 1 : 0) }
'; then
echo "$field_name must contain printable ASCII characters: $field_value" >&2
exit 2
fi
}
validate_integer() {
field_name=$1
field_value=$2
minimum=$3
maximum=$4
case "$field_value" in
''|*[!0-9]*)
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
;;
esac
if [ "$field_value" -lt "$minimum" ] || [ "$field_value" -gt "$maximum" ]; then
echo "$field_name must be an integer from $minimum through $maximum: $field_value" >&2
exit 2
fi
}
validate_text text "$text"
validate_text value "$value"
if [ -n "$suffix" ]; then
validate_text suffix "$suffix"
fi
validate_integer size "$font_size" 6 24
validate_integer height "$height" 14 64
if [ -n "$label_width" ]; then
validate_integer label-width "$label_width" 20 1000
fi
if [ -n "$value_width" ]; then
validate_integer value-width "$value_width" 20 1000
fi
case "$output" in
''|*/) echo "output must name an SVG file: $output" >&2; exit 2 ;;
esac
case "$kind" in
test)
if [ "$color_set" = false ]; then
case "$value" in
passing) color='#4c1' ;;
failing) color='#e05d44' ;;
*) color='#9f9f9f' ;;
esac
fi
;;
coverage)
if [ "$value" = '-' ]; then
[ "$color_set" = true ] || color='#9f9f9f'
else
if ! awk -v candidate="$value" 'BEGIN {
valid = candidate ~ /^[0-9]+([.][0-9]+)?$/ && candidate >= 0 && candidate <= 100
exit(valid ? 0 : 1)
}'; then
echo "coverage value must be - or a number from 0 through 100: $value" >&2
exit 2
fi
value=$(awk -v candidate="$value" 'BEGIN { printf "%.0f", candidate }')
if [ "$color_set" = false ]; then
if [ "$value" -ge 90 ]; then
color='#4c1'
elif [ "$value" -ge 70 ]; then
color='#dfb317'
else
color='#e05d44'
fi
fi
fi
;;
esac
case "$color" in
\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]|\#[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]) ;;
*) echo "color must be #RGB or #RRGGBB: $color" >&2; exit 2 ;;
esac
display_value=$value$suffix
if [ -z "$label_width" ]; then
label_width=$(printf '%s\\n' "$text" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
if [ -z "$value_width" ]; then
value_width=$(printf '%s\\n' "$display_value" | awk -v size="$font_size" '{
width = int(length($0) * size * 0.64 + 14)
print (width < 35 ? 35 : width)
}')
fi
badge_width=$((label_width + value_width))
label_center=$(awk -v width="$label_width" 'BEGIN { printf "%.1f", width / 2 }')
value_center=$(awk -v left="$label_width" -v width="$value_width" 'BEGIN {
printf "%.1f", left + width / 2
}')
vertical_center=$(awk -v badge_height="$height" 'BEGIN { printf "%.1f", badge_height / 2 }')
xml_escape() {
sed \
-e 's/&/\&amp;/g' \
-e 's/</\&lt;/g' \
-e 's/>/\&gt;/g' \
-e 's/"/\&quot;/g'
}
sed_replacement_escape() {
sed -e 's/[\\&|]/\\&/g'
}
escaped_text=$(printf '%s' "$text" | xml_escape | sed_replacement_escape)
escaped_value=$(printf '%s' "$display_value" | xml_escape | sed_replacement_escape)
escaped_title=$(printf '%s: %s' "$text" "$display_value" | xml_escape | sed_replacement_escape)
output_dir=${output%/*}
if [ "$output_dir" != "$output" ]; then
mkdir -p "$output_dir"
fi
temporary="${output}.tmp.$$"
trap 'rm -f "$temporary"' EXIT HUP INT TERM
sed \
-e "s/@BADGE_WIDTH@/$badge_width/g" \
-e "s/@HEIGHT@/$height/g" \
-e "s/@LABEL_WIDTH@/$label_width/g" \
-e "s/@VALUE_WIDTH@/$value_width/g" \
-e "s/@LABEL_CENTER@/$label_center/g" \
-e "s/@VALUE_CENTER@/$value_center/g" \
-e "s/@VERTICAL_CENTER@/$vertical_center/g" \
-e "s/@FONT_SIZE@/$font_size/g" \
-e "s/@COLOR@/$color/g" \
-e "s|@TITLE@|$escaped_title|g" \
-e "s|@TEXT@|$escaped_text|g" \
-e "s|@VALUE@|$escaped_value|g" \
>"$temporary" <<'EOF'
<svg xmlns="http://www.w3.org/2000/svg" width="@BADGE_WIDTH@" height="@HEIGHT@" role="img" aria-label="@TITLE@">
<title>@TITLE@</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
<stop offset=".9" stop-opacity=".3"/>
<stop offset="1" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r"><rect width="@BADGE_WIDTH@" height="@HEIGHT@" rx="3"/></clipPath>
<g clip-path="url(#r)">
<rect width="@LABEL_WIDTH@" height="@HEIGHT@" fill="#555"/>
<rect x="@LABEL_WIDTH@" width="@VALUE_WIDTH@" height="@HEIGHT@" fill="@COLOR@"/>
<rect width="@BADGE_WIDTH@" height="@HEIGHT@" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" dominant-baseline="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="@FONT_SIZE@">
<text x="@LABEL_CENTER@" y="@VERTICAL_CENTER@">@TEXT@</text>
<text x="@VALUE_CENTER@" y="@VERTICAL_CENTER@">@VALUE@</text>
</g>
</svg>
EOF
mv "$temporary" "$output"
trap - EXIT HUP INT TERM

130
scripts/ci.py Normal file
View File

@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Current-build coverage gate and badge lifecycle. Python 3.11+ on CI."""
import json
import math
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tomllib
ROOT = Path(__file__).resolve().parents[1]
def build_number():
number = os.environ.get("BUILD_NUMBER", "local")
if not number or not all(c.isalnum() or c in "-_" for c in number):
raise ValueError("Invalid BUILD_NUMBER")
return number
def render(kind, value):
subprocess.run([str(ROOT / "scripts/ci-coverage-badges.sh"), kind, "--value", str(value)], check=True)
def config():
return tomllib.loads((ROOT / "coverage.toml").read_text())
def measure(report, floor, tool_status):
"""Process an independently generated summary before deciding pass/fail."""
marker = Path(f"coverage/.coverage-ready-{build_number()}")
marker.unlink(missing_ok=True)
try:
data = json.loads(Path(report).read_text())
records = data["data"]
if len(records) != 1:
raise ValueError("expected one complete coverage record")
lines = records[0]["totals"]["lines"]
count, covered, percent = lines["count"], lines["covered"], lines["percent"]
if (type(count) is not int or type(covered) is not int or count <= 0
or not 0 <= covered <= count or not isinstance(percent, (float, int))
or not math.isfinite(percent) or not 0 <= percent <= 100
or abs(percent - 100 * covered / count) > .02):
raise ValueError("invalid line totals")
actual = 100 * covered / count
message = f"Line coverage: {actual:.2f}%; required minimum: {floor:.2f}%"
print(message, flush=True)
render("coverage", actual)
marker.touch()
Path("coverage/measurement.txt").write_text(f"{build_number()}\n{message}\n")
except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as error:
message = f"Line coverage: unavailable; required minimum: {floor:.2f}%; reason: {error}"
print(message, flush=True)
Path("coverage/measurement.txt").write_text(f"{build_number()}\n{message}\n")
print(f"Coverage gate: FAIL (measurement unavailable; tool exit status {tool_status})", flush=True)
return 1
if tool_status:
print(f"Coverage gate: FAIL (coverage tool/test exit status {tool_status})", flush=True)
return tool_status
if actual < floor:
print("Coverage gate: FAIL (below required minimum)", flush=True)
return 1
print("Coverage gate: PASS", flush=True)
return 0
def finalize():
Path("coverage").mkdir(exist_ok=True)
build = build_number()
passed = Path(f"coverage/.tests-passed-{build}")
ready = Path(f"coverage/.coverage-ready-{build}")
render("test", "passing" if passed.is_file() else "failing")
if not ready.is_file():
render("coverage", "-")
version = tomllib.loads((ROOT / "Cargo.toml").read_text())["workspace"]["package"]["version"]
render("version", version)
summary = Path("coverage/measurement.txt")
lines = summary.read_text().splitlines() if summary.is_file() else []
if lines and lines[0] == build:
print("\n".join(lines[1:]))
else:
print(f"Line coverage: unavailable; required minimum: {config()['line-floor']:.2f}%; reason: coverage stage did not complete")
for path in (passed, ready, Path("coverage/summary.json"), summary):
path.unlink(missing_ok=True)
for name in ("version", "test", "coverage"):
path = Path(f"coverage/{name}.svg")
if path.is_symlink() or not path.is_file() or not path.stat().st_size:
raise ValueError(f"Invalid badge: {path}")
if {p.name for p in Path("coverage").glob("*.svg")} != {"version.svg", "test.svg", "coverage.svg"}:
raise ValueError("Expected exactly three badge SVGs")
def main():
action = sys.argv[1]
if action == "init":
path = Path("coverage")
if path.is_symlink():
raise ValueError("Refusing coverage directory symlink")
if path.exists():
shutil.rmtree(path)
path.mkdir()
elif action == "tests-passed":
Path(f"coverage/.tests-passed-{build_number()}").touch()
elif action == "coverage":
directory = Path("coverage")
if directory.is_symlink():
raise ValueError("Refusing coverage directory symlink")
directory.mkdir(exist_ok=True)
summary = Path("coverage/summary.json")
summary.unlink(missing_ok=True)
status = 1
try:
status = subprocess.run(["cargo", "coverage"]).returncode
except OSError as error:
print(f"Coverage tool could not start: {error}", flush=True)
print(f"Coverage tool exit status: {status}", flush=True)
try:
return measure(summary, config()["line-floor"], status)
finally:
summary.unlink(missing_ok=True)
elif action == "finalize":
finalize()
else:
raise ValueError(f"Unknown action: {action}")
return 0
if __name__ == "__main__":
sys.exit(main())

44
scripts/publish-badges.sh Executable file
View File

@ -0,0 +1,44 @@
#!/bin/sh
# Publish validated badges; never sync the asset mount.
set -eu
[ "$#" -ge 2 ] || { echo "usage: $0 /absolute/publication/root coverage test version" >&2; exit 2; }
root=$1
shift
case "$root" in /*) ;; *) echo "Publication root must be absolute" >&2; exit 2;; esac
[ -d "$root" ] && [ -w "$root" ] && [ ! -L "$root" ] || { echo "Root must be an existing writable directory" >&2; exit 2; }
seen=" "
for name do
case "$name" in coverage|test|version) ;; *) echo "Invalid badge: $name" >&2; exit 2;; esac
case "$seen" in *" $name "*) echo "Duplicate badge: $name" >&2; exit 2;; esac
seen="$seen$name "
src="coverage/$name.svg"
[ -f "$src" ] && [ -s "$src" ] && [ ! -L "$src" ] || { echo "Invalid badge source: $src" >&2; exit 2; }
done
dest=$root
for component in idle-org pdf-presenter; do
dest="$dest/$component"
[ ! -L "$dest" ] || { echo "Refusing directory symlink: $dest" >&2; exit 2; }
if [ -e "$dest" ]; then
[ -d "$dest" ] || { echo "Not a directory: $dest" >&2; exit 2; }
else
mkdir -m 0755 "$dest"
fi
done
dest="$dest/main"
if [ -L "$dest" ]; then unlink "$dest"; fi
if [ -e "$dest" ]; then
[ -d "$dest" ] || { echo "Not a directory: $dest" >&2; exit 2; }
else
mkdir -m 0755 "$dest"
fi
temporary=
trap '[ -z "$temporary" ] || rm -f "$temporary"' EXIT HUP INT TERM
for name do
[ ! -L "$dest/$name.svg" ] && [ ! -d "$dest/$name.svg" ] || { echo "Invalid badge destination: $name" >&2; exit 2; }
temporary=$(mktemp "$dest/.badge.XXXXXXXX")
cp "coverage/$name.svg" "$temporary"
chmod 0644 "$temporary"
mv -f "$temporary" "$dest/$name.svg"
temporary=
done
trap - EXIT HUP INT TERM

182
tests/test_ci_badges.py Normal file
View File

@ -0,0 +1,182 @@
import contextlib
import importlib.util
import io
import json
import os
from pathlib import Path
import stat
import subprocess
import tempfile
import tomllib
import unittest
from unittest.mock import patch
from xml.etree import ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("badge_ci", ROOT / "scripts/ci.py")
ci = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ci)
class BadgeTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.cwd = Path.cwd()
os.chdir(self.root)
self.addCleanup(os.chdir, self.cwd)
Path("coverage").mkdir()
def render(self, kind, *args):
return subprocess.run([str(ROOT / "scripts/ci-coverage-badges.sh"), kind, *args],
capture_output=True, text=True)
def test_badge_values_colors_sizes_and_xml_escaping(self):
cases = [("version", "1.2.3", "#007ec6"), ("version", "1.2.3-very-long-preview.100", "#007ec6"),
("test", "passing", "#4c1"), ("test", "failing", "#e05d44"),
("test", "pending", "#9f9f9f"), ("coverage", "-", "#9f9f9f"),
("coverage", "30", "#e05d44"), ("coverage", "75.4", "#dfb317"),
("coverage", "99", "#4c1")]
for kind, value, color in cases:
with self.subTest(kind=kind, value=value):
self.assertEqual(self.render(kind, "--value", value).returncode, 0)
path = Path(f"coverage/{kind}.svg")
ET.parse(path)
self.assertIn(color, path.read_text())
result = self.render("version", "--value", 'a<&>"', "--text", "build & release",
"--size", "12", "--height", "30", "--label-width", "160",
"--value-width", "120", "--color", "#123abc", "--suffix", "!")
self.assertEqual(result.returncode, 0)
doc = ET.parse("coverage/version.svg").getroot()
self.assertEqual(doc.attrib["width"], "280")
self.assertIn('a<&>"!', "".join(doc.itertext()))
for kind in ("version", "test", "coverage"):
self.assertEqual(self.render(kind).returncode, 0)
ET.parse(f"coverage/{kind}.svg")
def test_invalid_renderer_input_preserves_output(self):
self.assertEqual(self.render("coverage", "--value", "80").returncode, 0)
before = Path("coverage/coverage.svg").read_bytes()
for args in [("--value", "101"), ("--value", "-1"), ("--value", "NaN"),
("--height", "2"), ("--size", "99"), ("--color", "red"),
("--text", "a\nb"), ("--label-width", "0"), ("--unknown", "x")]:
self.assertNotEqual(self.render("coverage", *args).returncode, 0)
self.assertEqual(Path("coverage/coverage.svg").read_bytes(), before)
self.assertNotEqual(self.render("nonsense").returncode, 0)
def report(self, covered):
path = Path("coverage/summary.json")
path.write_text(json.dumps({"data": [{"totals": {"lines": {
"count": 10000, "covered": covered, "percent": covered / 100}}}]}))
return path
def test_gate_threshold_tool_failure_and_cleanup_keep_measurement(self):
for covered, tool, expected in [(9000, 0, 0), (8000, 0, 0), (7999, 0, 1), (8500, 7, 7)]:
with self.subTest(covered=covered, tool=tool), patch.dict(os.environ, {"BUILD_NUMBER": "42"}):
output = io.StringIO()
with contextlib.redirect_stdout(output):
result = ci.measure(self.report(covered), 80, tool)
self.assertEqual(result, expected)
text = output.getvalue()
self.assertLess(text.index("Line coverage:"), text.index("Coverage gate:"))
self.assertIn("required minimum: 80.00%", text)
self.assertTrue(Path("coverage/.coverage-ready-42").is_file())
measured = Path("coverage/coverage.svg").read_bytes()
with contextlib.redirect_stdout(io.StringIO()):
ci.finalize()
self.assertEqual(Path("coverage/coverage.svg").read_bytes(), measured)
public = self.root / "public"
public.mkdir(exist_ok=True)
self.assertEqual(self.publish(public, "version", "test", "coverage").returncode, 0)
self.assertEqual((public / "idle-org/pdf-presenter/main/coverage.svg").read_bytes(), measured)
self.assertFalse(Path("coverage/.coverage-ready-42").exists())
self.assertIn("failing", Path("coverage/test.svg").read_text())
def test_coverage_from_fresh_checkout_reports_tool_failure_without_traceback(self):
Path("coverage").rmdir()
def unavailable(command):
self.assertTrue(Path("coverage").is_dir())
raise OSError("cargo unavailable")
with patch.object(ci.sys, "argv", ["ci.py", "coverage"]), \
patch.object(ci.subprocess, "run", side_effect=unavailable), \
contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(ci.main(), 1)
self.assertIn("unavailable", Path("coverage/measurement.txt").read_text())
self.assertFalse(Path("coverage/summary.json").exists())
def test_invalid_missing_and_stale_reports_are_neutral(self):
with patch.dict(os.environ, {"BUILD_NUMBER": "43"}):
for content in ("", "{}", '{"data":[]}', '{"data":[{"totals":{"lines":{"count":0,"covered":0,"percent":0}}}]}'):
path = Path("coverage/summary.json")
path.write_text(content)
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(ci.measure(path, 80, 0), 1)
ci.finalize()
self.assertIn("-%", Path("coverage/coverage.svg").read_text())
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(ci.measure(Path("missing.json"), 80, 1), 1)
Path("coverage/.coverage-ready-42").touch()
Path("coverage/.tests-passed-43").touch()
with contextlib.redirect_stdout(io.StringIO()):
ci.finalize()
self.assertIn("passing", Path("coverage/test.svg").read_text())
self.assertIn("-%", Path("coverage/coverage.svg").read_text())
def publish(self, root, *names):
return subprocess.run([str(ROOT / "scripts/publish-badges.sh"), str(root), *names],
capture_output=True, text=True, umask=0o077)
def test_publication_modes_atomic_replace_and_legacy_symlink(self):
for kind in ("version", "test", "coverage"):
self.assertEqual(self.render(kind).returncode, 0)
public = self.root / "public"
public.mkdir()
self.assertEqual(self.publish(public, "version", "test", "coverage").returncode, 0)
destination = public / "idle-org/pdf-presenter/main"
for directory in (public / "idle-org", destination.parent, destination):
self.assertEqual(stat.S_IMODE(directory.stat().st_mode), 0o755)
for path in destination.iterdir():
self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o644)
self.assertEqual(self.publish(public, "version", "test", "coverage").returncode, 0)
old = self.root / "old"
destination.rename(old)
destination.symlink_to(old, target_is_directory=True)
self.assertEqual(self.publish(public, "coverage").returncode, 0)
self.assertFalse(destination.is_symlink())
self.assertTrue((old / "coverage.svg").is_file())
for args in [("other",), ("test", "test")]:
self.assertNotEqual(self.publish(public, *args).returncode, 0)
self.assertNotEqual(self.publish("relative", "test").returncode, 0)
Path("coverage/test.svg").unlink()
Path("coverage/test.svg").symlink_to(old / "test.svg")
self.assertNotEqual(self.publish(public, "test").returncode, 0)
other = self.root / "other"
other.mkdir()
(other / "idle-org").symlink_to(public / "idle-org", target_is_directory=True)
self.assertNotEqual(self.publish(other, "coverage").returncode, 0)
def test_readme_urls_and_exact_archive_selection(self):
text = (ROOT / "README.md").read_text()
for kind in ("version", "test", "coverage"):
self.assertEqual(text.count(f"https://assets.dandaedre.com/coverage/idle-org/pdf-presenter/main/{kind}.svg"), 1)
self.assertIn("artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg'",
(ROOT / "Jenkinsfile").read_text())
def test_workspace_version_and_fresh_build_lifecycle(self):
with patch.dict(os.environ, {"BUILD_NUMBER": "44"}):
Path("coverage/stale.svg").write_text("old")
Path("coverage/.tests-passed-43").touch()
with patch("sys.argv", ["ci.py", "init"]):
ci.main()
self.assertEqual(list(Path("coverage").iterdir()), [])
with contextlib.redirect_stdout(io.StringIO()):
ci.finalize()
version = tomllib.loads((ROOT / "Cargo.toml").read_text())["workspace"]["package"]["version"]
self.assertIn(version, Path("coverage/version.svg").read_text())
self.assertIn("failing", Path("coverage/test.svg").read_text())
self.assertIn("-%", Path("coverage/coverage.svg").read_text())
self.assertEqual({p.name for p in Path("coverage").iterdir()},
{"version.svg", "test.svg", "coverage.svg"})