lib/validate-awesome-privacy.py

113 lines · 3849 bytes

  1import json
  2import os
  3import sys
  4
  5import yaml
  6from jsonschema import Draft7Validator
  7
  8# Paths (relative to project root)
  9PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 10DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
 11SCHEMA_PATH = os.path.join(PROJECT_ROOT, "lib/schema.json")
 12
 13# Exit codes
 14EXIT_VALID = 0
 15EXIT_VALIDATION_ERRORS = 1
 16EXIT_RUNTIME_ERROR = 2
 17
 18MAX_ERRORS = 20
 19
 20# ANSI color helpers (disabled when NO_COLOR is set or stderr is not a TTY)
 21_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
 22red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
 23green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
 24yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
 25dim = (lambda s: f"\033[2m{s}\033[0m") if _use_color else (lambda s: s)
 26
 27
 28def resolve_path(data, path_parts):
 29    """Walk the data along path_parts, replacing indices with 'name' values."""
 30    segments = []
 31    current = data
 32    for part in path_parts:
 33        if isinstance(current, dict) and part in current:
 34            current = current[part]
 35            if isinstance(current, dict) and "name" in current:
 36                segments.append(current["name"])
 37            elif not isinstance(part, int):
 38                pass  # skip dict keys like 'categories', 'sections', 'services'
 39        elif isinstance(current, list) and isinstance(part, int) and part < len(current):
 40            current = current[part]
 41            if isinstance(current, dict) and "name" in current:
 42                segments.append(current["name"])
 43            else:
 44                segments.append(str(part))
 45        else:
 46            segments.append(str(part))
 47            break
 48    return " > ".join(segments) if segments else "(root)"
 49
 50
 51def load_yaml(path):
 52    try:
 53        with open(path, "r") as f:
 54            return yaml.safe_load(f)
 55    except FileNotFoundError:
 56        print(red(f"File not found: {path}"), file=sys.stderr)
 57        sys.exit(EXIT_RUNTIME_ERROR)
 58    except yaml.YAMLError as e:
 59        print(red(f"Failed to parse YAML: {e}"), file=sys.stderr)
 60        sys.exit(EXIT_RUNTIME_ERROR)
 61
 62
 63def load_schema(path):
 64    try:
 65        with open(path, "r") as f:
 66            return json.load(f)
 67    except FileNotFoundError:
 68        print(red(f"File not found: {path}"), file=sys.stderr)
 69        sys.exit(EXIT_RUNTIME_ERROR)
 70    except json.JSONDecodeError as e:
 71        print(red(f"Failed to parse JSON schema: {e}"), file=sys.stderr)
 72        sys.exit(EXIT_RUNTIME_ERROR)
 73
 74
 75def validate(data, schema):
 76    validator = Draft7Validator(schema)
 77    errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
 78    formatted = []
 79    for error in errors:
 80        location = resolve_path(data, list(error.path))
 81        formatted.append(f"{location}: {error.message}")
 82    return formatted
 83
 84
 85def main():
 86    data = load_yaml(DATA_PATH)
 87    schema = load_schema(SCHEMA_PATH)
 88    errors = validate(data, schema)
 89
 90    if errors:
 91        shown = errors[:MAX_ERRORS]
 92        for msg in shown:
 93            print(red("ERROR") + " " + msg, file=sys.stderr)
 94        if len(errors) > MAX_ERRORS:
 95            print(dim(f"...and {len(errors) - MAX_ERRORS} more"), file=sys.stderr)
 96        print(red(f"Validation failed: {len(errors)} error(s)"), file=sys.stderr)
 97        sys.exit(EXIT_VALIDATION_ERRORS)
 98
 99    # Gather stats
100    categories = data.get("categories", [])
101    num_categories = len(categories)
102    num_sections = sum(len(c.get("sections", [])) for c in categories)
103    num_services = sum(
104        len(s.get("services", []))
105        for c in categories
106        for s in c.get("sections", [])
107    )
108    print(green(f"Valid! {num_categories} categories, {num_sections} sections, {num_services} services"))
109    sys.exit(EXIT_VALID)
110
111
112if __name__ == "__main__":
113    main()