z43-hooks
Repo-standard C++/Python checks and the change gate used by
SuperMash/git_hooks/.pre-commit-config.yaml (hosted repo, pinned by tag).
One checker dispatches by file suffix; one [tool.z43] table in a repo's
pyproject.toml is the only place rules are activated, tightened, or
excluded; one report/exit-code contract runs through every entry point.
z43-checks- rules ruff cannot express, over any mix of paths..pyfiles get the stdlib-AST Python rules (missingFinal, singleton naming, assert/# nosecplacement, single-use TypeVar, unguarded module-scope work, advisory NamedTuple/module-length); C/C++ files (.cpp .cxx .cc .h .hpp .hxx .inl) route to the C++ rule registry: house rules (include guards, redundantvirtual, file-scopeusing namespace, wide-string concat, base-alias visibility) and pyd binding-tree rules (throws, binding docstrings,.deflambdas,.export_values()).--fixapplies the mechanical fixes,--unsafe-fixesadds the rename tier,--dry-runpreviews the--fixcounts without writing.--select/--ignorechoose codes or category stems for one run;--list-codesprints the rule map. The path-levelpath-spacecheck judges every path it is given, whatever the file type - directory arguments see only the checkable suffixes, so the pre-commit hook (which passes every staged file individually) is the complete sweep. Exit: 0 clean, 1 findings, 2 the run was degraded (a file could not be seen at all) - never a silent zero.z43-change-gate- runs ruff + bandit + the checks above and reports only findings on lines added by the staged diff (advisoryinfofindings join the report only with--include-info). One policy inversion:nosec-redundantnever blocks a commit - dead-# noseccleanup is driven by whole-filez43-checks --fix, so a per-commit diff gate must not wait on it. Path-level codes (path-space) bypass the added-line filter: a staged path is being committed now, whether or not its content changed. Exit: 0 clean, 1 findings on added lines, 2 a tool or the staged diff could not run.z43-cpp-include- the deterministic include normalizer (see below). Check-by-default;--fixis the only writer.z43-audit- the deep audit the incremental gate cannot be: whole-tree pybind sweeps (docstring layout, Raises: attribution, entity guards, weak types) and, underz43-audit stubs MODULE, the generated.pyiside.--ignore CATEGORYreports a category but never gates on it; exit: 0 clean, 1 findings, 2 degraded.
z43_hooks/autofix.py remains an importable module (its main() still
runs the same fix pipeline); its old standalone console script is gone with
no alias - use z43-checks --fix.
z43_hooks/audit.py keeps its own category vocabulary (the codes above are
the per-line gate rules; the audit's heuristics - weak-type,
legacy-enum, export-values, unchecked-entity-deref,
missing-raises-section, split-docstring-literal, bad-none-default,
cpp-name-in-docstring, ... - are whole-tree findings) with severities
defect (gates) / review / artifact / defer / info (advisory,
--include-info). --ignore <category> reports the category in full but
never gates on it, so a verification pass can measure a grandfathered family
without failing on it: export-values is measured every run and its site
count is printed even when the category is ignored. The same marker dialect
applies: // z43: ignore[code] on the flagged line or inside the owning
.def(...) downgrades a defect to info ([suppressed]).
Rule map
Every shipped rule is a declaration in the registry z43_hooks.core.RULES
(code, level, scope, fix tier). Discover it from the tool: z43-checks --list-codes --format json.
| Code | Level | Scope | Fix tier | Fires on |
|---|---|---|---|---|
final-missing |
error | all | safe | a module-level binding never rebound and never mutated after the bind, not Final (except-handler, __main__-guard binds and implicit type aliases exempt) |
final-maybe-missing |
error | all | unsafe | a never-rebound binding whose object is mutated after the bind (attr/subscript store, or a container mutator on a container-literal bind) - Final is advisory there, implicit type aliases exempt |
naming-module |
error | all | unsafe | an UPPER_CASE name bound to a singleton instance |
nosec-missing |
error | all | safe | an assert in non-test code with no # nosec |
nosec-redundant |
error | all | safe | a # nosec in a test file (bandit skips tests) |
typevar-single-use |
error | all | report-only | a TypeVar used once in a signature |
script-main-guard |
info | all | report-only | module-scope code that runs at import outside any if __name__ == "__main__": guard (a guard excuses only its own block; packages/setup.py/tests/__main__ exempt) |
tuple-namedtuple |
info | all | report-only | a multi-field tuple[...] return, advisory |
module-length |
info | all | report-only | a module past the soft line limit, advisory |
suppression-unused |
error | all | safe | a # z43: ignore marker that covers nothing |
path-space |
error | all | report-only | a staged path with a space in the file or folder name (any file type; unwaivable by marker - no line owns a path) |
virtual-redundant |
error | all | safe | a C++ member declared virtual with override/final |
ns-using |
error | all | report-only | a file-scope using namespace in a C++ header |
boost-deprecated |
error | all | report-only | a banned boost API on a line of code (the std:: equivalent is the house shape; comment text and NOLINT lines never fire) |
tr-wide-split |
error | all | safe | a split tr()/QT_TR_NOOP() string whose continuation segment carries an encoding prefix |
guard-missing |
error | all | safe | a C++ header with neither #pragma once nor a classic #ifndef X/#define X guard |
|
| guard-mixed | error | all | report-only | a C++ header carrying both #pragma once and a classic guard |
| super-alias-visibility | error | all | unsafe | a configured base alias ([tool.z43.checks.super-alias-visibility] names; dormant when empty) that is public/protected instead of private, or targets a non-direct base (that second shape is report-only: retargeting changes name lookup) |
| throw-type | error | pyd-only | unsafe | a bare std::runtime_error whose message complains about input (the rewrite to XCORE_VALIDATE_NOT changes the Python-visible type) |
| throw-macro-spelling | info | pyd-only | safe | a correct-type throw spelled raw instead of XCORE_RAISE_IF/XCORE_VALIDATE_NOT |
| throw-macro | info | all | safe | a call site of an ad-hoc throw macro the shared <XCore/CommonMacros.h> replaces |
| throw-macro-broken | error | all | report-only | a #define throwing std::runtime_error(os) with no os (instantiation cannot compile), and its call sites |
| enum-export-values | error | pyd-only | unsafe (diff-gated) | a .export_values() call — measured whole-file, gated on added lines |
| doc-split | error | pyd-only | safe | a binding docstring split across adjacent string literals |
| doc-multiline | error | pyd-only | safe | a \n-escaped prose docstring literal (safe only when delimiter-safe) |
| doc-long | info | pyd-only | report-only | a binding docstring past 4000 characters, advisory |
| lambda-long | info | pyd-only | report-only | a .def lambda past the [tool.z43.checks.lambda-long] line limit, advisory |
| lambda-passthrough | info | pyd-only | report-only | a single-call-body .def lambda (excepting py::init and cls-absorbing static-property getters) |
Level: error fails a run, info is advisory and never does (pass
--include-info to see it). Scope: all checks every file of the language;
a pyd-only scope fires only under a pyd directory segment. Fix tier:
safe runs under --fix, unsafe needs --unsafe-fixes, report-only
(None) never rewrites. diff-gated codes are reported and counted by
whole-file z43-checks without failing it (legacy sites stay visible, they
do not block), while z43-change-gate fires them on lines a commit adds.
Activation model
[tool.z43.checks] in the nearest repo pyproject.toml that carries a
[tool.z43] table (walked up from each target path - nested per-package
pyprojects without a table are stepped over, ruff's rule for [tool.ruff],
so a monorepo's build files never shadow the repo's activation) is the single
source of what is enforced. The pre-commit hook passes no selection args, so
the hook, an editor, a CLI run, and CI never disagree:
[tool.z43]
# Only build/ and .mypy_cache/ ship built-in; every vendored tree is named
# here (fragments match any single path segment, case-insensitively).
exclude = ["build", ".mypy_cache", "vendor_dir", "gen-py"]
extend-exclude = ["generated"] # APPENDS instead of replacing (ruff semantics)
[tool.z43.checks]
select = ["final-missing", "throw-type"] # explicit activation (see below)
ignore = ["naming-module"] # opt codes/stems out repo-wide
strict = ["B024", "F822"] # replaces the gate's ruff zero-tolerance set
strict-cpp = ["boost-deprecated", "virtual-redundant"] # replaces the C++ zero-tolerance set
select is the activation list: with it, only the listed codes/stems run;
without it, every registered rule stays active. A new built-in rule does not
go live in a configured repo until the repo adds it, exactly like
[tool.ruff.lint] select. ignore still overrides select (ruff's order).
CLI --select/--ignore override the table for one run only. Matching is
at hyphen boundaries: --ignore nosec covers nosec-missing and
nosec-redundant; --select final covers final-missing and
final-maybe-missing, a bare fin matches nothing. Exclusions are forced
everywhere, the fix pipeline
included: neither z43-checks --fix nor the autofix module writes into an
excluded tree (a stderr note, not a silent skip), and an explicitly passed
vendored path is still skipped from checks. Any directory below the config
root that ships its own .clang-format auto-skips as vendored.
The include normalizer (z43-cpp-include)
Three stages share one tool: normalize (fix the include string:
case-correctness against headers on disk, main-header quoting, clear
quoting violations), group (bucket partition, blank-line structure)
and order (sort WITHIN buckets). --stage accepts normalize
(default), group, order and all; all runs normalize THEN group
THEN order in memory and writes the combined result once (for
already-normalized modules - the safe rollout path stays one stage per
commit). Normalize is line-local and never relocates an include; group
relocates lines but never rewrites a string; order permutes includes in
place within each bucket's written lines (structure untouched).
- check mode is the default and writes nothing: exit 1 on any
would-change (a string rewrite for normalize, a line that moves for
group), exit 0 with visible warnings otherwise, exit 2 for a degraded
run (unreadable file, bad
--roots).--fixis the only writer and exits by leftovers (0 all applied, 1 could-not-apply or leftover, 2 degraded).--dry-runprints per-category/per-module counts;--format jsonrenders per-file changes{line, category, from, to}and moves{line, from_bucket, to_bucket}plus the counts. - case: an include matching an on-disk header only case-insensitively is rewritten to the disk casing (Linux builds break on the wrong case), for angle and quoted forms and module-qualified paths alike.
- quoting: the TU's own header (
Foo.cpp->Foo.h; the*_pyd.hmodule header inpyddirs) must be a quoted local include, and a quoted include that resolves under an index root becomes the angle form. A relative"../Foo.h"stays quoted - nothing is guessed. - unresolved: an include resolving nowhere and not a known system / third-party / order-sensitive (ACIS-family) spelling is warned with a per-module count, never rewritten - and warnings alone never fail a run.
- group buckets, in emitted order: (0) the TU's pinned main header,
(1) repo-local - resolves under the edited file's own repo root, or a
relative
"../Foo.h"that stays inside it, (2) second-party - resolves under a different--rootsroot (the repo split derives from the file's path, never from config), (3) third-party - a configuredthirdparty_groupsprefix or order-sensitive (ACIS) spelling, and (4) system/STL. An include that resolves nowhere lands in bucket 3: the conservative bucket, because an unresolvable target looks like a library header. No line is ever dropped. - blank-line structure is exact: one blank line between non-empty
buckets, none inside one; trailing
//comments ride with their include; everything outside an include region is untouched. - hard boundaries the tool never crosses: conditional-inclusion arms
(each
#if/#else/#elifarm groups independently inside the arm),extern "C"blocks, pragmas, comment lines, and real code. - pch: a precompiled-header include at position 0 of the include
block (any spelling whose basename is a known PCH, including a
relative
"../PreCompiled.h") is canonical bucket-0 content: never a would-change, never relocated, never judged - the delete-vs-keep decision is a human audit. A PCH-named include anywhere ELSE is an ordinary include: bucketed like any header, NOT moved to position 0. - Group operates on canonical strings (run normalize first, or
--stage all); run standalone on mis-cased includes it still groups correctly - classification is case-folded - and the would-change list just carries the moves. - order sorts WITHIN each bucket (after grouping; it never moves an
include across a bucket or a hard boundary, and the position-0 PCH pin
stays put). Repo-local and second-party includes are ranked by COARSE
naming-convention tiers from
[tool.z43.includes] tier_order(an ordered glob list likeXCore*,xcoremath,*), alphabetical within a tier; a NEW module matching an existing tier glob lands in that tier automatically, and an unmatched module sorts after every named tier (never dropped - the property that keeps the tier list maintenance- free). The third-party bucket is sorted in configured per-library sub-blocks (thirdparty_groupsorder: boost, Eigen, VTK, pybind, ACIS, ...) alphabetical within, unmatched third-party after the configured groups; the system bucket is alphabetical. Every sort is case-insensitive with the written position as a stable tiebreak, so output is deterministic across platforms. - order-sensitive carve-out: an include matching an
[tool.z43.includes] order_sensitivepattern (the ACIS api/error family:<api.err>,*.hxx,Windows.h) is FIXED in its written line - excluded from any sort, so its relative order with the rest of the family survives normalize+group+order unchanged (the macro-ordering contract). Adding a pattern toorder_sensitivein a repo's table protects a new family the same way. The ACIS undefinition header (UndefACIS.h) is pinned last within the third-party bucket (it redefines the error macros, so it must follow every header consuming them). - Index roots = the nearest
pyproject.tomldir plus--rootsrepeats; the shared exclude/auto-skip layer applies and excluded trees are never even indexed (a vendored path passed explicitly stays skipped, exit unchanged).
The report categories (case, quoting, pch, unresolved, moves,
reorders, kept) are REPORT CATEGORIES with counts - not rule codes:
no registry entry, no per-line z43: ignore suppression, and the code
table above is unchanged. [tool.z43.includes] (tier_order /
thirdparty_groups / order_sensitive) replaces the shipped defaults
wholesale; the defaults live in z43_hooks/cpp_include_data.py, measured
off the real trees. Output is idempotent (stage(stage(x)) == stage(x)
for each stage and
for all) and clang-format idempotent under the consumer .clang-format
files (include
sorting stays off there - the two tools never fight).
Fix safety
Like ruff, fixes are tiered (the tiers live in the same rule registry):
| Tier | Codes | Contract |
|---|---|---|
safe (--fix) |
final-missing, nosec-missing, nosec-redundant, suppression-unused, virtual-redundant, tr-wide-split, guard-missing, throw-macro-spelling, throw-macro, doc-split, doc-multiline |
only adds/removes what the checker prescribes; semantics cannot change |
unsafe (--unsafe-fixes) |
naming-module, final-maybe-missing, throw-type, enum-export-values, super-alias-visibility |
renames the singleton and same-file usages / annotates Final on a binding whose object is mutated / changes the Python-visible exception type / deletes public enum names / moves a base alias to a private section - review the diff |
| report-only | typevar-single-use, script-main-guard, tuple-namedtuple, module-length, path-space, ns-using, boost-deprecated, guard-mixed, throw-macro-broken, doc-long, lambda-long, lambda-passthrough |
needs judgement |
Every Python edit must keep the file compile()-able, and every C++ edit
must re-parse with no new grammar error nodes, or it is skipped and counted.
After fixing, the fix pipeline best-effort sorts imports via
ruff check --fix --select I when ruff is on PATH.
The C++ front end (tree-sitter, a hard dependency) counts grammar error nodes per run and surfaces them in the report footer only - macro-heavy headers never flood the report or fail a run.
The gate's tool invocations live in z43_hooks/tools.py (one seam for
ruff/bandit/git, unpinned - bump by rebuilding the hook env). A pip-installing
consumer pulls the same unpinned ruff/bandit pair with the gate extra
(z43-hooks[gate]); the z43-change-gate hook lists them as
additional_dependencies instead, since pre-commit cannot request extras.
When a tool cannot run, the gate says so on stderr and exits 2 instead of
passing the commit on silence.
Suppressing a finding
mypy-style, on the offending line (comment position only - prose about the syntax is not a marker):
MAX = 3 # z43: ignore[final-missing] one code
X = f() # z43: ignore[final-missing, naming-module]
Y = g() # z43: ignore every z43 code on this line
C++ uses the same dialect in // comments (scanned inside comment spans
only, so a marker inside a string or raw-string body is never a marker):
virtual Foo() override; // z43: ignore[virtual-redundant]
For the binding-tree (pyd) codes, a marker anywhere inside the owning
.def(...) call covers every finding in that call - one ignore comment
tames a whole lambda body instead of one line:
m.def("go", [](int n) {
// z43: ignore[throw-type]
if (n < 0) throw std::runtime_error("n must be >= 0");
return n;
}, "Go.");
A marker whose listed code covers nothing is reported as
suppression-unused (ruff's RUF100 analogue) - and --fix prunes it, so
stale ignores cannot accumulate.
Path-level codes are the dialect's limit made explicit: a finding with no
source line (path-space) can carry no marker, so the footer offers no
waiver hint for it. ignore in [tool.z43.checks] (or --ignore) opts it
out - the config layer, not a line comment.
path-space is adapted from check-spaces-in-paths
(MIT, Bryn Lloyd) - rewritten for this rule registry, not copied.
Develop:
python -m pip install pre-commit && pre-commit install
pre-commit run --all-files # or: python -m pytest -q, ruff check .
.pre-commit-config.yaml is this repo's own standard ruff-based config.
Release: bump version in pyproject.toml, then tag vX.Y.Z matching it
and push the tag. The CI (.gitlab-ci.yml) runs the tests and publishes the
wheel to this project's PyPI package registry. Bump the rev: in the
consumer config afterwards.
Install a published version (replace <PROJECT_ID> with this project's
numeric id, shown on the project overview page). Add [gate] to also pull
the change gate's ruff/bandit:
pip install "z43-hooks[gate]" \
--index-url https://git.speag.com/api/v4/projects/<PROJECT_ID>/packages/pypi/simple
Metadata
Release files for z43-hooks 0.1.8
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| z43_hooks-0.1.8.tar.gz | 246.9 kB | Without provenance | Details for z43_hooks-0.1.8.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| z43_hooks-0.1.8-py3-none-any.whl | Python 3 | none | any | Details for z43_hooks-0.1.8-py3-none-any.whl |
Total release size: 399.6 kB
Release files / z43_hooks-0.1.8.tar.gz
| Download URL | z43_hooks-0.1.8.tar.gz |
|---|---|
| Size | 246.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
06047fe3668e1f3c0d95cbf704d4021424ef5a520552a467dd6698a89b04f3ff
|
|
BLAKE2b-256 checksum How to use checksums |
0a9477392f04c9f8e51b72f7e89297535d52772f7539e4e516f732df82c4e6a7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.18
|
Release files / z43_hooks-0.1.8-py3-none-any.whl
| Download URL | z43_hooks-0.1.8-py3-none-any.whl |
|---|---|
| Size | 152.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a1c1c37c8ba7373eeabeee3672288171f2e094fbc5e979fe4798497250ae1b23
|
|
BLAKE2b-256 checksum How to use checksums |
0fffc0762e6baa50351242d4e26ef605374520793da20ce33b2a28416fbc37eb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.18
|
Security for z43-hooks 0.1.8
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.