203 lines
7.6 KiB
Python
203 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Report which database-dump files changed relative to a git baseline.
|
|
|
|
The dump folder (schema.sql, data.sql, one CSV per table) is committed, so git
|
|
is the change detector: the baseline is `git show <base>:<path>` and the new
|
|
state is the working tree (staged, unstaged and untracked all count).
|
|
|
|
Exit status: 0 = no completeness problems, 1 = completeness warnings,
|
|
2 = could not run (not a git repo, bad ref, ...).
|
|
|
|
Usage: python3 tests/test_changed_files.py [--base REF] [--json]
|
|
Also collectable by pytest (test_* functions at the bottom).
|
|
"""
|
|
import argparse
|
|
import csv
|
|
import io
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
DB_DIR = Path(__file__).resolve().parent.parent
|
|
TESTS_DIR = Path(__file__).resolve().parent
|
|
SCHEMA = "schema.sql"
|
|
DATA = "data.sql"
|
|
|
|
STATUS_NAMES = {"A": "added", "M": "modified", "D": "deleted", "R": "renamed",
|
|
"C": "copied", "T": "type-changed", "U": "unmerged", "?": "untracked"}
|
|
|
|
|
|
class GitError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def git(*args, check=True):
|
|
p = subprocess.run(["git", *args], cwd=DB_DIR, capture_output=True)
|
|
if check and p.returncode != 0:
|
|
raise GitError(f"git {' '.join(args)}: {p.stderr.decode(errors='replace').strip()}")
|
|
return p.stdout
|
|
|
|
|
|
def git_text(*args):
|
|
return git(*args).decode("utf-8", errors="replace")
|
|
|
|
|
|
def under_tests(rel):
|
|
return (DB_DIR / rel).resolve().is_relative_to(TESTS_DIR)
|
|
|
|
|
|
def changed_files(base):
|
|
"""Return {path: {"status", "old_path"?, "stat"}} for files in this folder.
|
|
|
|
Paths are relative to the database folder. The tests/ folder is excluded.
|
|
"""
|
|
git("rev-parse", "--verify", "--quiet", f"{base}^{{commit}}")
|
|
out = git("diff", "--name-status", "-z", "-M", "--relative", base, "--", ".")
|
|
parts = out.decode("utf-8", errors="replace").split("\0")
|
|
files, i = {}, 0
|
|
while i < len(parts) and parts[i]:
|
|
code = parts[i][0]
|
|
if code in "RC":
|
|
old, new = parts[i + 1], parts[i + 2]
|
|
i += 3
|
|
files[new] = {"status": STATUS_NAMES[code], "old_path": old}
|
|
else:
|
|
files[parts[i + 1]] = {"status": STATUS_NAMES.get(code, code)}
|
|
i += 2
|
|
untracked = git("ls-files", "--others", "--exclude-standard", "-z", "--", ".")
|
|
for p in untracked.decode("utf-8", errors="replace").split("\0"):
|
|
if p:
|
|
files.setdefault(p, {"status": "untracked"})
|
|
files = {p: v for p, v in files.items() if not under_tests(p)}
|
|
|
|
# size of each change; binary/untracked files report no stat
|
|
stat = git_text("diff", "--numstat", "-M", "--relative", base, "--", ".")
|
|
for line in stat.splitlines():
|
|
add, dele, path = line.split("\t", 2)
|
|
if " => " in path or path not in files:
|
|
continue
|
|
files[path]["stat"] = {"added": add, "removed": dele}
|
|
return files
|
|
|
|
|
|
def tables_in_schema(text):
|
|
return set(re.findall(r"^CREATE TABLE public\.(\w+) \(", text, re.M))
|
|
|
|
|
|
def csv_header(text):
|
|
try:
|
|
return next(csv.reader(io.StringIO(text)))
|
|
except StopIteration:
|
|
return []
|
|
|
|
|
|
def base_text(base, path):
|
|
p = git("show", f"{base}:./{path}", check=False)
|
|
return p.decode("utf-8", errors="replace") if p else None
|
|
|
|
|
|
def analyze(base="HEAD"):
|
|
files = changed_files(base)
|
|
csv_files = {p: v for p, v in files.items() if p.endswith(".csv")}
|
|
other = {p: v for p, v in files.items() if not p.endswith(".csv")}
|
|
|
|
schema_tables = tables_in_schema((DB_DIR / SCHEMA).read_text(encoding="utf-8"))
|
|
csv_tables_now = {p.stem for p in DB_DIR.glob("*.csv")}
|
|
|
|
# CSV <-> table name for changed CSVs; header changes read from git + disk
|
|
header_changes = {}
|
|
for path, info in csv_files.items():
|
|
old_path = info.get("old_path", path)
|
|
old = base_text(base, old_path) if info["status"] not in ("added", "untracked") else None
|
|
new_file = DB_DIR / path
|
|
new = new_file.read_text(encoding="utf-8") if new_file.exists() else None
|
|
old_h = csv_header(old) if old is not None else None
|
|
new_h = csv_header(new) if new is not None else None
|
|
if old_h is not None and new_h is not None and old_h != new_h:
|
|
header_changes[path] = {"removed": [c for c in old_h if c not in new_h],
|
|
"added": [c for c in new_h if c not in old_h],
|
|
"reordered": sorted(old_h) == sorted(new_h)}
|
|
|
|
changed_csv_tables = {Path(p).stem for p in csv_files}
|
|
schema_changed = SCHEMA in other
|
|
data_changed = DATA in other
|
|
|
|
warnings = []
|
|
if changed_csv_tables and not data_changed:
|
|
warnings.append(f"CSV changed ({', '.join(sorted(changed_csv_tables))}) but {DATA} did not")
|
|
if data_changed and not changed_csv_tables:
|
|
warnings.append(f"{DATA} changed but no CSV did")
|
|
if header_changes and not schema_changed:
|
|
warnings.append(f"CSV header changed ({', '.join(sorted(header_changes))}) but {SCHEMA} did not")
|
|
if schema_changed and not (data_changed or changed_csv_tables):
|
|
warnings.append(f"{SCHEMA} changed but neither {DATA} nor any CSV did")
|
|
for t in sorted(schema_tables - csv_tables_now):
|
|
warnings.append(f"table '{t}' in {SCHEMA} has no {t}.csv")
|
|
for t in sorted(csv_tables_now - schema_tables):
|
|
warnings.append(f"{t}.csv has no table '{t}' in {SCHEMA}")
|
|
for p in sorted(other):
|
|
if p not in (SCHEMA, DATA):
|
|
warnings.append(f"unexpected changed file: {p}")
|
|
|
|
return {"base": base, "files": files, "header_changes": header_changes,
|
|
"changed_tables": sorted(changed_csv_tables), "warnings": warnings}
|
|
|
|
|
|
def render(report):
|
|
files = report["files"]
|
|
lines = [f"Baseline: {report['base']} (working tree vs baseline)", ""]
|
|
if not files:
|
|
lines.append("No changed files.")
|
|
for group, pick in (("schema", lambda p: p == SCHEMA), ("data", lambda p: p == DATA),
|
|
("csv", lambda p: p.endswith(".csv")),
|
|
("other", lambda p: p not in (SCHEMA, DATA) and not p.endswith(".csv"))):
|
|
rows = sorted(p for p in files if pick(p))
|
|
if not rows:
|
|
continue
|
|
lines.append(f"[{group}]")
|
|
for p in rows:
|
|
v = files[p]
|
|
size = f" +{v['stat']['added']} -{v['stat']['removed']}" if "stat" in v else ""
|
|
ren = f" (from {v['old_path']})" if "old_path" in v else ""
|
|
lines.append(f" {v['status']:<12} {p}{ren}{size}")
|
|
h = report["header_changes"].get(p)
|
|
if h:
|
|
if h["reordered"]:
|
|
lines.append(" header: columns reordered")
|
|
else:
|
|
lines.append(f" header: +{h['added']} -{h['removed']}")
|
|
lines.append("")
|
|
if report["warnings"]:
|
|
lines.append("Completeness warnings:")
|
|
lines += [f" ! {w}" for w in report["warnings"]]
|
|
else:
|
|
lines.append("Completeness: OK")
|
|
return "\n".join(lines)
|
|
|
|
|
|
# ---- pytest entry points -------------------------------------------------
|
|
|
|
def test_dump_files_are_consistent():
|
|
report = analyze()
|
|
assert not report["warnings"], "\n" + render(report)
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
ap.add_argument("--base", default="HEAD", help="git ref to compare against (default HEAD)")
|
|
ap.add_argument("--json", action="store_true", help="emit JSON instead of text")
|
|
args = ap.parse_args()
|
|
try:
|
|
report = analyze(args.base)
|
|
except GitError as e:
|
|
print(f"error: {e}", file=sys.stderr)
|
|
return 2
|
|
print(json.dumps(report, indent=2) if args.json else render(report))
|
|
return 1 if report["warnings"] else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|