Day 5: Packaging and Quality – checkcert as a Package
Goal: turn
checkcertfrom Day 4 into a versioned, checked package that can be installed viauv tool install· Duration: approx. 90 min · Prerequisite: Day 4
Briefing
pyproject.tomlis the single source for name, version, dependencies and tool configuration.- Quality runs automatically: ruff (lint, format, security rules),
mypy
--strict, pytest with a coverage threshold. - pre-commit blocks faulty commits before they reach the repo.
uv buildproduces a wheel and an sdist,uv tool installturns it into a command in your PATH – isolated in a venv of its own.
src/ + pyproject.toml --uv build--> dist/checkcert-0.2.0-py3-none-any.whl
| |
pre-commit: ruff, mypy uv tool install --> ~/.local/bin/checkcert
Drill 1: Copy of Day 4 with its own Git repo
cd ~/py-lab
rsync -a --exclude .venv --exclude .git --exclude __pycache__ \
--exclude '.*_cache' tag04-checkcert/ tag05-checkcert/
cd tag05-checkcert && git init -q
cat > .gitignore <<'EOF'
.venv/
__pycache__/
.*_cache/
.coverage
dist/
EOF
uv run pytest -q | tail -1Expected:
21 passed, 1 skipped in 0.64s
Why? Day 4 stays untouched as a reference. We need a Git repo of its
own for pre-commit and release tags; .venv is not copied
but recreated by uv run.
Save your progress? Sign up for free
Drill 2: Metadata and tool configuration
We write pyproject.toml once, complete and tidy:
cat > pyproject.toml <<'EOF'
[project]
name = "checkcert"
version = "0.1.0"
description = "TLS-Zertifikate prüfen: Restlaufzeit in Tagen, Exit-Code nach Nagios"
readme = "README.md"
license = "MIT"
authors = [{ name = "Thomas Zachmann", email = "[email protected]" }]
keywords = ["tls", "x509", "certificate", "monitoring", "nagios"]
classifiers = [
"Environment :: Console",
"Programming Language :: Python :: 3.14",
"Topic :: System :: Monitoring",
]
requires-python = ">=3.14"
dependencies = ["typer>=0.27.3"]
[project.scripts]
checkcert = "checkcert:main"
[build-system]
requires = ["uv_build>=0.9.26,<0.10.0"]
build-backend = "uv_build"
[dependency-groups]
dev = [
"pytest>=9.1.1",
"pytest-cov>=7.1.0",
"ruff>=0.17.0",
]
[tool.ruff.lint]
extend-select = ["E501", "B", "UP", "SIM", "I", "S"]
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S101"] # assert ist in pytest erwünscht
[tool.mypy]
strict = true
files = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov=checkcert --cov-fail-under=85"
EOF
uv add -q --dev mypy
cat > README.md <<'EOF'
# checkcert
Prüft die Restlaufzeit von TLS-Zertifikaten und endet mit einem Exit-Code
nach Nagios-Konvention (0 OK, 1 WARN, 2 CRIT, 3 ERROR).
checkcert github.com example.com:443 --warn 30 --crit 7
checkcert -f hosts.txt
EOFWhy? license = "MIT" is an SPDX expression (PEP 639),
classifiers and keywords make the package discoverable. With
uv init, authors comes from your git
configuration – check it. The README ends up in the package as its
description. New are the rules I (import sorting) and
S (security, Bandit rules), mypy in strict mode, and
addopts: every pytest run now measures coverage and fails
below 85 %.
Save your progress? Sign up for free
Drill 3: One source for the version
The version lives only in pyproject.toml; at runtime,
importlib.metadata reads it from the installed package.
cat > src/checkcert/__init__.py <<'EOF'
"""checkcert – TLS-Zertifikate prüfen."""
from importlib.metadata import version
from checkcert.cli import app
__version__ = version("checkcert") # einzige Quelle: pyproject.toml
def main() -> None:
app()
EOFsrc/checkcert/cli.py gets a callback function
show_version and a last parameter _version;
the rest is unchanged from Day 4:
cat > src/checkcert/cli.py <<'EOF'
"""checkcert – Restlaufzeit von TLS-Zertifikaten prüfen (Exit-Code nach Nagios)."""
import logging
from importlib.metadata import version
from pathlib import Path
from typing import Annotated
import typer
from checkcert.core import Result, Status, check
app = typer.Typer(help=__doc__, add_completion=False)
def parse_target(target: str) -> tuple[str, int]:
"""'host' oder 'host:port' -> (host, port)."""
host, sep, port = target.rpartition(":")
if not sep:
return target, 443
if not port.isdigit():
raise typer.BadParameter(f"ungültiger Port in {target!r}")
return host, int(port)
def read_targets(path: Path) -> list[str]:
"""Eine Adresse pro Zeile; Leerzeilen und #-Kommentare werden ignoriert."""
lines = path.read_text(encoding="utf-8").splitlines()
return [s for line in lines if (s := line.split("#", 1)[0].strip())]
def render(r: Result) -> str:
days = "-" if r.days is None else str(r.days)
expires = f"{r.expires:%Y-%m-%d}" if r.expires else "-"
line = f"{r.status.name:<6} {days:>5} {expires:<10} {r.host}:{r.port}"
return f"{line} ({r.error})" if r.error else line
def show_version(value: bool) -> None:
if value:
typer.echo(f"checkcert {version('checkcert')}")
raise typer.Exit()
@app.command()
def main(
targets: Annotated[list[str] | None, typer.Argument(help="host[:port]")] = None,
file: Annotated[
Path | None, typer.Option("--file", "-f", exists=True, help="Hostliste")
] = None,
warn: Annotated[int, typer.Option(help="WARN unter so vielen Tagen")] = 30,
crit: Annotated[int, typer.Option(help="CRIT unter so vielen Tagen")] = 7,
timeout: Annotated[float, typer.Option(help="Sekunden pro Host")] = 5.0,
verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
_version: Annotated[
bool, typer.Option("--version", callback=show_version, is_eager=True)
] = False,
) -> None:
"""Prüft alle Ziele und endet mit dem schlechtesten Status als Exit-Code."""
logging.basicConfig(
level=logging.DEBUG if verbose else logging.ERROR,
format="%(levelname)s %(name)s: %(message)s",
)
all_targets = (targets or []) + (read_targets(file) if file else [])
if not all_targets:
raise typer.BadParameter("mindestens ein Host oder --file angeben")
pairs = [parse_target(t) for t in all_targets] # Fehler vor dem ersten Check
typer.echo(f"{'STATUS':<6} {'TAGE':>5} {'ABLAUF':<10} HOST")
worst = Status.OK
for host, port in pairs:
result = check(host, port, warn=warn, crit=crit, timeout=timeout)
typer.echo(render(result))
worst = max(worst, result.status)
raise typer.Exit(code=int(worst))
EOFAppend a test to tests/test_cli.py:
cat >> tests/test_cli.py <<'EOF'
def test_version_flag() -> None:
result = CliRunner().invoke(cli.app, ["--version"])
assert result.exit_code == 0
assert result.stdout.startswith("checkcert 0.")
EOF
uv run checkcert --version
uv run python -m checkcert --versionExpected:
checkcert 0.1.0
checkcert 0.1.0
Why? is_eager=True evaluates --version
before all other arguments – otherwise typer would first complain
“mindestens ein Host” (at least one host). A second, hand-maintained
version number in the code is guaranteed to go stale at some point.
Save your progress? Sign up for free
Drill 4: Lint, format, types, tests
uv run ruff check . && uv run ruff format --check .
uv run mypy
uv run pytest -q | tail -2Expected (shortened):
All checks passed!
8 files already formatted
Success: no issues found in 4 source files
Required test coverage of 85% reached. Total coverage: 91.92%
22 passed, 1 skipped in 0.11s
Why? mypy reads files and strict from
pyproject.toml, so uv run mypy is enough. As a
dev dependency, its version is pinned in uv.lock – locally,
in CI and in the hook, the same mypy version checks. The S
rules find, for example, subprocess with
shell=True, hard-coded passwords or assert in
production code.
Save your progress? Sign up for free
Drill 5: pre-commit as the bouncer
Local hooks call the tools via uv run, i.e. exactly the
versions from uv.lock:
cat > .pre-commit-config.yaml <<'EOF'
# Local hooks: use the versions from uv.lock, no second tool pinning
repos:
- repo: local
hooks:
- id: ruff-check
name: ruff check
entry: uv run ruff check --fix
language: system
types: [python]
- id: ruff-format
name: ruff format
entry: uv run ruff format
language: system
types: [python]
- id: mypy
name: mypy
entry: uv run mypy
language: system
types: [python]
pass_filenames: false
EOF
uvx pre-commit install
git add -A && uvx pre-commit run --all-files
git commit -qm "checkcert 0.1.0 als Paket" && git log --onelineExpected (hash differs):
pre-commit installed at .git/hooks/pre-commit
ruff check...............................................................Passed
ruff format..............................................................Passed
mypy.....................................................................Passed
ruff check...............................................................Passed
ruff format..............................................................Passed
mypy.....................................................................Passed
41f7af0 checkcert 0.1.0 als Paket
The hooks run twice: once via run --all-files (checks
all files Git knows about – hence the git add beforehand),
once automatically on commit. Now a type error – days can
be None:
cat >> src/checkcert/core.py <<'EOF'
def days_left(r: Result) -> int:
return r.days
EOF
git add -A && git commit -qm "days_left"; echo "exit=$?"
git restore --staged --worktree src/checkcert/core.pyExpected (shortened):
mypy.....................................................................Failed
- hook id: mypy
- exit code: 1
src/checkcert/core.py:95: error: Incompatible return value type (got "int | None...
exit=1
The commit did not happen. uvx runs pre-commit from the
uv cache – no global installation.
Tip: In an emergency,
git commit --no-verifybypasses the hooks. That is why CI has to run the same checks again (Day 14).
Save your progress? Sign up for free
Drill 6: Versioning
Semantic versioning: MAJOR.MINOR.PATCH. A new feature
(--version) without a breaking change means a minor
release.
uv version
uv version --bump minor --dry-run
uv version --bump minor
git commit -qam "Release 0.2.0" && git tag v0.2.0
uv run checkcert --versionExpected (shortened):
checkcert 0.1.0
checkcert 0.1.0 => 0.2.0
checkcert 0.1.0 => 0.2.0
ruff check...........................................(no files to check)Skipped
ruff format..........................................(no files to check)Skipped
mypy.................................................(no files to check)Skipped
checkcert 0.2.0
Why? uv version --bump changes
pyproject.toml, updates uv.lock and reinstalls
the project – that is why --version reports 0.2.0 right
away. The Git tag marks the state the release is built from. The hooks
skip themselves because no Python file was changed.
Save your progress? Sign up for free
Drill 7: Build and look inside
uv build
unzip -l dist/checkcert-0.2.0-py3-none-any.whl | awk 'NR>3 {print $4}' | grep .
unzip -p dist/checkcert-0.2.0-py3-none-any.whl \
checkcert-0.2.0.dist-info/entry_points.txtExpected (shortened):
Successfully built dist/checkcert-0.2.0.tar.gz
Successfully built dist/checkcert-0.2.0-py3-none-any.whl
checkcert/
checkcert/__init__.py
checkcert/__main__.py
checkcert/cli.py
checkcert/core.py
checkcert-0.2.0.dist-info/
checkcert-0.2.0.dist-info/WHEEL
checkcert-0.2.0.dist-info/entry_points.txt
checkcert-0.2.0.dist-info/METADATA
checkcert-0.2.0.dist-info/RECORD
[console_scripts]
checkcert = checkcert:main
Why? The wheel is a ZIP with exactly the package and metadata – no
tests, no lab/, no venv. py3-none-any means:
pure Python, runs on any platform. The sdist (.tar.gz)
contains the sources for environments that want to build themselves. On
installation, entry_points.txt becomes the executable
checkcert.
Save your progress? Sign up for free
Drill 8: The tool is done
uv tool install dist/checkcert-0.2.0-py3-none-any.whl
uv tool list
cd / && command -v checkcert && checkcert --version
checkcert github.com expired.badssl.com --timeout 3; echo "exit=$?"
cd ~/py-lab/tag05-checkcertExpected (path and days differ):
Installed 1 executable: checkcert
checkcert v0.2.0
- checkcert
/Users/<du>/.local/bin/checkcert
checkcert 0.2.0
STATUS TAGE ABLAUF HOST
OK 50 2026-11-29 github.com:443
ERROR - - expired.badssl.com:443 (certificate has expired)
exit=3
checkcert now runs from any directory, in a venv of its
own under ~/.local/share/uv/tools/ – without touching the
system Python or other tools. For an update: build a new version, then
uv tool install --force dist/<neues-wheel>. During
development, uv tool install --editable . is handy: code
changes take effect immediately.
Save your progress? Sign up for free
Checkpoint
#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
cd ~/py-lab/tag05-checkcert
check "Tests grün, Coverage >= 85 %" "uv run pytest -q"
check "ruff sauber" "uv run ruff check . && uv run ruff format --check ."
check "mypy strict" "uv run mypy"
check "pre-commit-Hook aktiv" "test -x .git/hooks/pre-commit"
check "Release getaggt" "git tag | grep -qx v0.2.0"
check "Wheel ohne Tests" \
"! unzip -l dist/checkcert-0.2.0-py3-none-any.whl | grep -q tests/"
check "checkcert 0.2.0 im PATH" "checkcert --version | grep -qx 'checkcert 0.2.0'"Expected:
✔ Tests grün, Coverage >= 85 %
✔ ruff sauber
✔ mypy strict
✔ pre-commit-Hook aktiv
✔ Release getaggt
✔ Wheel ohne Tests
✔ checkcert 0.2.0 im PATH
Challenge
The tests take fractions of a second, but once the suite grows they
shouldn’t slow down every commit. Make pytest run only before
git push.
Hint: pre-commit knows
stages: [pre-push]; the matching Git hook is installed by
--hook-type pre-push.
Solution
Append to .pre-commit-config.yaml (indented like the
other hooks):
- id: pytest
name: pytest
entry: uv run pytest -q
language: system
pass_filenames: false
always_run: true
stages: [pre-push]uvx pre-commit install --hook-type pre-push
uvx pre-commit run --hook-stage pre-push --all-files
ls .git/hooks | grep -v sampleExpected:
pre-commit installed at .git/hooks/pre-push
ruff check...............................................................Passed
ruff format..............................................................Passed
mypy.....................................................................Passed
pytest...................................................................Passed
pre-commit
pre-push
Hooks without stages run in every stage;
always_run: true starts pytest even if no Python file is
part of the push.
Save your progress? Sign up for free
Enterprise Note
- Upload internal packages to a registry of your own (Artifactory,
Nexus, GitLab Package Registry) with
uv publish --publish-url ...; install via--index– never use package names that also exist on PyPI (dependency confusion). - Build releases only in CI, not on a laptop: clean checkout, tag as the trigger, sign the wheel (Sigstore) and generate an SBOM.
- Air gap:
uv tool installfrom a wheelhouse (--find-links ./wheels --offline), collect the dependencies beforehand withuv exportandpip download. - Take the license seriously: don’t accidentally publish company code
with
license = "MIT"; check the licenses of your dependencies, e.g.uv run --with pip-licenses pip-licenses. --no-verifyis allowed, so mandatory checks also belong in the merge request as a required check.