Files
Bookshelf/umbra-bookshelf/tests/verify_structure.py
bdm dec732931c Consolidate three plugins into Umbra Bookshelf
Merge BD Bookshelf (0.1.0), BD BookShelfHelper (2.0.0) and BD SimpleEmail
(2.0.0) into a single plugin released as Umbra Bookshelf 1.0.0, with the
BD Bookshelf theme left as a separate, unrenamed artifact.

Modules
  includes/books/    catalogue, ISBN/ASIN, series, retail, ratings, shortcodes,
                     SEO, GDPR, scrapers, admin, CSV/post import
  includes/library/  book post type + series taxonomy, pen names, data entry,
                     shortlinks, reviews, migrate
  includes/email/    subscribers, newsletters, composition, sending

Renamed: plugin headers, text domains (all three -> umbra-bookshelf), classes
(BD_*/BDM_* -> Umbra_*), constants (-> UMBRA_BOOKSHELF_*), asset handles, JS
globals and admin slugs.

Deliberately not renamed -- persisted contract with live installs and with
published post content: table names, option keys, post meta keys, transients,
nonce actions, cron hooks, AJAX actions, shortcodes ([bd-book], [bd-books],
[bdm_signup]), post type `book`, taxonomy `series`, cookies and CSS classes.
BD_BookShelfHelper survives only as a class_alias for the unmodified theme.

Collisions resolved
  * class-umbra-theme-compatibility.php declared BD_BookShelfHelper, the same
    name as the library module's helper. Latent while the plugins were
    separate (only fired when both were active), but an unconditional fatal
    once merged. Renamed to Umbra_Theme_Compatibility with a class_alias.
  * All three modules called add_menu_page. One top-level menu is now
    registered by the bootstrap at admin_menu priority 9.
  * BD Bookshelf and BookShelfHelper both claimed bd-bookshelf-settings, leaving
    one Settings screen unreachable -> umbra-bookshelf-settings and
    umbra-bookshelf-library-settings.
  * Catalogue and library both enqueued bd-bookshelf-admin; the second enqueue
    was silently discarded -> unique handles per module.
  * Umbra_Admin and Umbra_Migration both registered bd_bookshelf_import_csv, so
    one handler silently replaced the other. The import page now lives only in
    Umbra_Admin (the variant wired to the admin JS); Umbra_Migration keeps only
    the preview/run endpoints it uniquely provides.
  * Modules were constructed from an init callback, so their own init
    registrations raced the hook being dispatched. Now constructed on
    plugins_loaded behind a re-entrancy guard.

Also
  * Missing assets created: assets/images/default-cover.png (referenced but
    never committed, so every cover-less book 404'd) and email/assets/js/
    admin.js (enqueued on every email admin page but never committed).
  * Library module's strpos($hook, 'bd-bookshelf') asset check matched every
    catalogue and email screen once slugs shared the umbra-bookshelf- prefix;
    now matched against its own slug list.
  * Consolidated uninstall deduplicates the double drop of bd_books/bd_series.
  * Specs aligned to the new name; pre-merge specs retained under
    spec/archive/ with provenance notes.
  * Tests added: tests/verify_structure.py (static) and tests/smoke_runtime.php
    (WordPress-stub runtime boot, front-end and admin contexts).

Deferred and recorded in docs/KNOWN-ISSUES.md: the catalogue and library
modules still create bd_books and bd_series with two incompatible schemas
(pre-existing, now unconditional), and Goodreads/Amazon scraping is still
implemented twice on shared cron hooks.
2026-10-18 19:55:36 -07:00

181 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""Static verification for the merged umbra-bookshelf plugin.
Checks:
1. PHP syntax of every file
2. No class declared twice (fatal error in PHP)
3. Every class referenced by new X / X:: actually exists
4. Every require_once path resolves on disk
5. Every wp_enqueue_* asset path resolves on disk (no 404s)
6. No leftover pre-rename identifiers
7. Preserved storage/API contracts still present
"""
import io
import os
import re
import subprocess
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
failures = []
notes = []
def rel(p):
return os.path.relpath(p, ROOT)
def walk(exts):
for dirpath, _, files in os.walk(ROOT):
for f in files:
if f.endswith(exts):
yield os.path.join(dirpath, f)
# ---------------------------------------------------------------- 1. php -l
php = [f for f in walk('.php')]
for f in php:
r = subprocess.run(['php', '-l', f], capture_output=True, text=True)
if 'No syntax errors' not in r.stdout:
failures.append('PHP SYNTAX: %s\n%s' % (rel(f), r.stdout + r.stderr))
print('1. php -l: %d files checked' % len(php))
# ------------------------------------------------- 2. duplicate class decls
decls = {}
for f in php:
src = io.open(f, encoding='utf-8', errors='replace').read()
for m in re.finditer(r'^\s*(?:final\s+|abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)',
src, re.M):
decls.setdefault(m.group(1), []).append(rel(f))
dupes = {c: fs for c, fs in decls.items() if len(fs) > 1}
for c, fs in sorted(dupes.items()):
failures.append('DUPLICATE CLASS: %s declared in %s' % (c, ', '.join(fs)))
print('2. class declarations: %d unique, %d duplicated'
% (len(decls), len(dupes)))
# --------------------------------------------- 3. referenced classes exist
refs = set()
for f in php:
src = io.open(f, encoding='utf-8', errors='replace').read()
for m in re.finditer(r'\bnew\s+([A-Z][A-Za-z0-9_]*)\s*\(', src):
refs.add(m.group(1))
for m in re.finditer(r"\b([A-Z][A-Za-z0-9_]*)::", src):
refs.add(m.group(1))
# names defined by this plugin, or provided by WordPress
wp_provided = {'BD_BookShelfHelper', # created via class_alias()
'WP_Error', 'WP_Query', 'WP_Post', 'WP_REST_Response',
'WP_REST_Request', 'WP_REST_Server', 'WP_Term', 'wpdb',
'ReflectionClass', 'DateTime', 'Exception', 'ArrayObject'}
known_external = {'GeminiClient',
# browser JS globals, matched by the `new X(` heuristic
# when scanning inline <script> blocks inside PHP files
'FormData', 'URL', 'Image', 'Audio'}
missing = sorted(r for r in refs
if r not in decls
and r not in wp_provided
and r not in known_external)
for r in missing:
failures.append('UNDEFINED CLASS REFERENCED: %s' % r)
print('3. class references: %d referenced, %d undefined' % (len(refs), len(missing)))
# --------------------------------------------------- 4. require_once paths
for f in php:
src = io.open(f, encoding='utf-8', errors='replace').read()
for m in re.finditer(r"require(?:_once)?\s+([^;]+);", src):
expr = m.group(1)
pm = re.search(r"UMBRA_BOOKSHELF_DIR\s*\.\s*'([^']+)'", expr)
if pm:
target = os.path.join(ROOT, pm.group(1).lstrip('/'))
if not os.path.isfile(target):
failures.append('MISSING REQUIRE: %s -> %s' % (rel(f), pm.group(1)))
elif "__DIR__" in expr:
pm = re.search(r"__DIR__\s*\.\s*'([^']+)'", expr)
if pm:
target = os.path.join(os.path.dirname(f), pm.group(1).lstrip('/'))
if not os.path.isfile(target):
failures.append('MISSING REQUIRE: %s -> %s'
% (rel(f), pm.group(1)))
print('4. require_once targets verified')
# ------------------------------------------------------- 5. asset 404 check
assets = 0
for f in list(walk('.php')):
src = io.open(f, encoding='utf-8', errors='replace').read()
for m in re.finditer(
r"UMBRA_BOOKSHELF_URL\s*\.\s*'([^']+\.(?:css|js|png|jpg|svg))'",
src):
target = os.path.join(ROOT, m.group(1))
assets += 1
if not os.path.isfile(target):
failures.append('ASSET 404: %s -> %s' % (rel(f), m.group(1)))
print('5. enqueued assets: %d references, all resolved' % assets)
# -------------------------------------------- 6. leftover pre-rename tokens
stale_pat = re.compile(r'\b(?:BD_[A-Z][A-Za-z0-9_]*|BDM_[A-Za-z0-9_]*)\b')
stale = []
# Scan shipped plugin source only. Excluded on purpose:
# spec/archive/ -- historical pre-merge specs, must keep the old names
# tests/ -- asserts that the old names are GONE, so it mentions them
SCAN_DIRS = ('includes', 'admin', 'public', 'library', 'email')
scan_files = []
for d in SCAN_DIRS:
for dirpath, _, files in os.walk(os.path.join(ROOT, d)):
for f in files:
if f.endswith(('.php', '.js', '.css')):
scan_files.append(os.path.join(dirpath, f))
for f in ['umbra-bookshelf.php', 'uninstall.php']:
scan_files.append(os.path.join(ROOT, f))
scan_files = [f for f in scan_files if os.path.isfile(f)]
for f in scan_files:
src = io.open(f, encoding='utf-8', errors='replace').read()
for i, line in enumerate(src.splitlines(), 1):
for m in stale_pat.finditer(line):
# BD_BookShelfHelper is intentionally kept as the legacy theme alias
if m.group(0) == 'BD_BookShelfHelper':
notes.append('%s:%d keeps legacy alias %s'
% (rel(f), i, m.group(0)))
continue
stale.append('%s:%d %s' % (rel(f), i, m.group(0)))
for s in sorted(set(stale)):
failures.append('STALE IDENTIFIER: %s' % s)
print('6. stale identifiers: %d (excluding documented legacy alias)'
% len(set(stale)))
# ------------------------------------- 7. preserved contracts still present
contracts = [
('bd_books', 'table name'),
('bd_series', 'table name'),
('bd_bookshelf_db_version', 'option key'),
('bd_bookshelf_activation_time', 'option key'),
('_bd_bookshelf_book_id', 'post meta key'),
('bd_bookshelf_import_posts', 'nonce action'),
('bd_bookshelf_import_csv', 'nonce/ajax action'),
('bd_bookshelf_sync_ratings', 'cron hook'),
('bd_bookshelf_goodreads_refresh', 'cron hook'),
('bd_bookshelf_amazon_scrape', 'cron hook'),
('bdm_update_links', 'ajax action'),
('bdm_autosave', 'ajax action'),
('bdm_ajax_signup', 'ajax action'),
('bd_bookshelf_consent', 'cookie name'),
]
blob = ''
for f in walk(('.php', '.js')):
blob += io.open(f, encoding='utf-8', errors='replace').read()
for tok, kind in contracts:
if tok not in blob:
failures.append('LOST CONTRACT (%s): %s' % (kind, tok))
print('7. preserved contracts: %d checked' % len(contracts))
# ------------------------------------------------------------------- report
print()
for n in sorted(set(notes)):
print('note: %s' % n)
print()
if failures:
print('FAIL (%d)' % len(failures))
for f in failures:
print(' - %s' % f)
sys.exit(1)
print('PASS - all static checks clean')