Files
obfuscation_platform/project/compare_json_folders.py
T

163 lines
5.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""compare_json_folders.py ─ Version 3
Vergleicht alle .json‑Dateien in zwei Verzeichnissen rekursiv auf Inhaltsunterschiede
und gibt *sämtliche* Differenzen (alter ↔ neuer Wert) aus – **mit Ausnahme**
aller Felder, deren Schlüssel in ``IGNORE_KEYS`` steht (standardmäßig nur
``"image"``).
Aufruf:
python compare_json_folders.py <ORDNER_1> <ORDNER_2> [--ignore key1,key2,…]
Ausgabeformat:
<Dateiname>: <Anzahl> Unterschied(e)
• <JSON‑Pfad>: <Wert1> ≠ <Wert2>
• <JSON‑Pfad>: fehlt in Ordner 1 (Wert2=<Wert>)
• <JSON‑Pfad>: fehlt in Ordner 2 (Wert1=<Wert>)
Nur Standardbibliothek erforderlich.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any, List, Set
MAX_LEN = 80 # Werte in der Ausgabe ggf. kürzen
IGNORE_KEYS: Set[str] = {"image"} # Standard‑Ignoreliste
def fmt(value: Any) -> str:
"""Gibt eine kompakte Repräsentation eines JSON‑Wertes zurück."""
text = json.dumps(value, ensure_ascii=False) if not isinstance(value, str) else repr(value)
if len(text) > MAX_LEN:
return text[:MAX_LEN - 1] + "…"
return text
def load_json(path: Path) -> Any:
"""Liest eine JSON‑Datei ein."""
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def compare_json(a: Any, b: Any, path: str = "") -> List[str]:
"""Vergleicht zwei JSON‑Werte rekursiv und liefert *alle* Unterschiede als Textzeilen.
Pfade, die einen Schlüssel aus ``IGNORE_KEYS`` enthalten, werden übersprungen.
"""
diffs: List[str] = []
# Wenn der aktuelle Pfad bereits einen ignorierten Schlüssel enthält → keine Prüfung
if path and any(part in IGNORE_KEYS for part in path.split(".")):
return diffs # leer
# Typunterschied
if type(a) is not type(b):
diffs.append(f"{path or '<root>'}: Typ {type(a).__name__} ≠ {type(b).__name__}")
return diffs
# Dictionaries
if isinstance(a, dict):
keys_a = set(a)
keys_b = set(b)
for key in sorted(keys_a | keys_b):
if key in IGNORE_KEYS:
continue # Feld explizit ignorieren
sub_path = f"{path}.{key}" if path else key
if key not in a:
diffs.append(f"{sub_path}: fehlt in Ordner 1 (Wert2={fmt(b[key])})")
elif key not in b:
diffs.append(f"{sub_path}: fehlt in Ordner 2 (Wert1={fmt(a[key])})")
else:
diffs.extend(compare_json(a[key], b[key], sub_path))
return diffs
# Listen/Tuples
if isinstance(a, (list, tuple)):
len_max = max(len(a), len(b))
for idx in range(len_max):
sub_path = f"{path}[{idx}]"
diffs.extend(compare_json(a[idx] if idx < len(a) else None,
b[idx] if idx < len(b) else None,
sub_path)) if idx < len(a) and idx < len(b) else None
if idx >= len(a):
diffs.append(f"{sub_path}: fehlt in Ordner 1 (Wert2={fmt(b[idx])})")
elif idx >= len(b):
diffs.append(f"{sub_path}: fehlt in Ordner 2 (Wert1={fmt(a[idx])})")
return diffs
# Skalare Werte
if a != b:
diffs.append(f"{path or '<root>'}: {fmt(a)} ≠ {fmt(b)}")
return diffs
def compare_folders(dir1: Path, dir2: Path) -> None:
"""Vergleicht alle .json‑Dateien in dir1 und dir2 und zeigt sämtliche Unterschiede."""
files1 = {p.name for p in dir1.glob("*.json")}
files2 = {p.name for p in dir2.glob("*.json")}
all_files = sorted(files1 | files2)
if not all_files:
print("Keine .json‑Dateien gefunden.")
return
for filename in all_files:
p1 = dir1 / filename
p2 = dir2 / filename
if not p1.exists():
print(f"{filename}: fehlt in Ordner 1")
continue
if not p2.exists():
print(f"{filename}: fehlt in Ordner 2")
continue
try:
json1 = load_json(p1)
json2 = load_json(p2)
except Exception as exc:
print(f"{filename}: Fehler beim Einlesen — {exc}")
continue
diffs = compare_json(json1, json2)
if diffs:
print(f"{filename}: {len(diffs)} Unterschied(e)")
for d in diffs:
print(f" • {d}")
else:
pass
#print(f"{filename}: identisch")
def main() -> None:
parser = argparse.ArgumentParser(description="Vergleicht die Inhalte zweier Verzeichnisse mit JSON‑Dateien.")
parser.add_argument("dir1", type=Path, help="Erstes Verzeichnis")
parser.add_argument("dir2", type=Path, help="Zweites Verzeichnis")
parser.add_argument(
"--ignore",
metavar="KEYS",
help="Komma‑getrennte Liste von Schlüsseln, die ignoriert werden sollen (zusätzlich zu image)",
)
args = parser.parse_args()
global IGNORE_KEYS # pylint: disable=global‑statement
if args.ignore:
IGNORE_KEYS |= {k.strip() for k in args.ignore.split(",") if k.strip()}
if not args.dir1.is_dir() or not args.dir2.is_dir():
parser.error("Beide Pfade müssen existierende Verzeichnisse sein.")
compare_folders(args.dir1, args.dir2)
if __name__ == "__main__":
try:
main()
except BrokenPipeError:
sys.stderr.close()
sys.exit(0)