lib/validate-awesome-privacy.py

205 lines · 7036 bytes

  1import json
  2import logging
  3import os
  4import sys
  5
  6import yaml
  7from jsonschema import Draft7Validator
  8
  9sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
 10import utils
 11
 12utils.setup_logging()
 13logger = logging.getLogger(__name__)
 14
 15# Paths (relative to project root)
 16PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 17DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
 18SCHEMA_PATH = os.path.join(PROJECT_ROOT, "lib/schema.json")
 19ERRORS_OUTPUT_PATH = "/tmp/schema-errors.json"
 20
 21# Exit codes
 22EXIT_VALID = 0
 23EXIT_VALIDATION_ERRORS = 1
 24EXIT_RUNTIME_ERROR = 2
 25
 26MAX_ERRORS = 20
 27
 28
 29def _clean(v):
 30    """Stringify a value for inline display: neutralise backticks, collapse newlines."""
 31    return str(v).replace("`", "'").replace("\n", " ").replace("\r", " ").strip()
 32
 33
 34def resolve_path(data, path_parts):
 35    """Walk the data along path_parts, replacing indices with 'name' values."""
 36    segments = []
 37    current = data
 38    for part in path_parts:
 39        if isinstance(current, dict) and part in current:
 40            current = current[part]
 41            if isinstance(current, dict) and "name" in current:
 42                segments.append(_clean(current["name"]))
 43            elif not isinstance(current, (dict, list)):
 44                segments.append(_clean(part))
 45        elif isinstance(current, list) and isinstance(part, int) and part < len(current):
 46            current = current[part]
 47            if isinstance(current, dict) and "name" in current:
 48                segments.append(_clean(current["name"]))
 49            else:
 50                segments.append(_clean(part))
 51        else:
 52            segments.append(_clean(part))
 53            break
 54    return " > ".join(segments) if segments else "(root)"
 55
 56
 57FIELD_HINTS = {
 58    "url": "must start with http:// or https://",
 59    "icon": "must start with http:// or https://",
 60    "github": "must be `user/repo`",
 61    "codeberg": "must be `user/repo`",
 62    "git": "must be a full http(s):// URL to the source repository",
 63    "iosApp": "must be a full https://apps.apple.com/... URL",
 64    "androidApp": "must be a package name like `com.example.app`",
 65    "discordInvite": "must be a discord invite code or https://discord.gg/... URL",
 66    "subreddit": "must be an alphanumeric subreddit name (no `/r/` prefix)",
 67}
 68
 69
 70def _q(v):
 71    """As _clean but truncates long values for use inside inline `…` displays."""
 72    s = _clean(v)
 73    return s if len(s) <= 80 else s[:77] + "..."
 74
 75
 76def _quoted(s):
 77    """Extract all 'single-quoted' tokens from a string."""
 78    parts = s.split("'")
 79    return parts[1::2]
 80
 81
 82def format_yaml_error(exc):
 83    """Build a human-readable YAML error message, including line/column when available."""
 84    mark = getattr(exc, "problem_mark", None) or getattr(exc, "context_mark", None)
 85    problem = (getattr(exc, "problem", None) or "").strip()
 86    where = f" at line {mark.line + 1}, column {mark.column + 1}" if mark else ""
 87    return f"YAML syntax error{where}: {problem}" if problem else f"YAML syntax error{where}"
 88
 89
 90def humanize_error(error, location):
 91    """Render a jsonschema ValidationError as a single short, human-readable line."""
 92    v = error.validator
 93    raw = error.message
 94    field = error.path[-1] if error.path and isinstance(error.path[-1], str) else None
 95
 96    if v == "required":
 97        missing = (_quoted(raw) or ["?"])[0]
 98        return f"{location}: missing required field `{missing}`"
 99    if v == "additionalProperties":
100        extras = _quoted(raw) or ["?"]
101        joined = ", ".join(f"`{e}`" for e in extras)
102        return f"{location}: unknown field(s) {joined}"
103    if v == "type":
104        types = error.validator_value
105        types_s = " or ".join(types) if isinstance(types, list) else str(types)
106        return f"{location}: expected {types_s} (got `{_q(error.instance)}`)"
107    if v == "minLength":
108        return f"{location}: too short ({len(error.instance)} chars, minimum {error.validator_value})"
109    if v == "maxLength":
110        return f"{location}: too long ({len(error.instance)} chars, maximum {error.validator_value})"
111    if v == "minimum":
112        return f"{location}: value `{_q(error.instance)}` is below minimum {error.validator_value}"
113    if v in ("pattern", "anyOf", "oneOf"):
114        hint = FIELD_HINTS.get(field) if field else None
115        suffix = f" — {hint}" if hint else ""
116        return f"{location}: invalid value `{_q(error.instance)}`{suffix}"
117    return f"{location}: {raw}"
118
119
120def write_errors_file(messages):
121    """Persist error messages to a known location so downstream tools can surface them."""
122    try:
123        with open(ERRORS_OUTPUT_PATH, "w") as f:
124            json.dump(list(messages), f)
125    except OSError:
126        pass
127
128
129def clear_errors_file():
130    """Remove any stale errors file from a previous run."""
131    try:
132        os.remove(ERRORS_OUTPUT_PATH)
133    except OSError:
134        pass
135
136
137def load_yaml(path):
138    try:
139        with open(path, "r") as f:
140            return yaml.safe_load(f)
141    except FileNotFoundError:
142        logger.error("File not found: %s", path)
143        sys.exit(EXIT_RUNTIME_ERROR)
144    except yaml.YAMLError as e:
145        msg = format_yaml_error(e)
146        write_errors_file([msg])
147        logger.error("Failed to parse YAML: %s", msg)
148        sys.exit(EXIT_RUNTIME_ERROR)
149
150
151def load_schema(path):
152    try:
153        with open(path, "r") as f:
154            return json.load(f)
155    except FileNotFoundError:
156        logger.error("File not found: %s", path)
157        sys.exit(EXIT_RUNTIME_ERROR)
158    except json.JSONDecodeError as e:
159        logger.error("Failed to parse JSON schema: %s", e)
160        sys.exit(EXIT_RUNTIME_ERROR)
161
162
163def validate(data, schema):
164    validator = Draft7Validator(schema)
165    errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
166    formatted = []
167    for error in errors:
168        location = resolve_path(data, list(error.path))
169        formatted.append(humanize_error(error, location))
170    return formatted
171
172
173def main():
174    logger.info("Validating awesome-privacy.yml against schema")
175    data = load_yaml(DATA_PATH)
176    schema = load_schema(SCHEMA_PATH)
177    errors = validate(data, schema)
178
179    if errors:
180        write_errors_file(errors)
181        shown = errors[:MAX_ERRORS]
182        for msg in shown:
183            logger.error(msg)
184        if len(errors) > MAX_ERRORS:
185            logger.warning("...and %d more", len(errors) - MAX_ERRORS)
186        logger.error("Validation failed: %d error(s)", len(errors))
187        sys.exit(EXIT_VALIDATION_ERRORS)
188
189    # Gather stats
190    categories = data.get("categories", [])
191    num_categories = len(categories)
192    num_sections = sum(len(c.get("sections", [])) for c in categories)
193    num_services = sum(
194        len(s.get("services", []))
195        for c in categories
196        for s in c.get("sections", [])
197    )
198    clear_errors_file()
199    logger.info("Valid! %d categories, %d sections, %d services",
200                num_categories, num_sections, num_services)
201    sys.exit(EXIT_VALID)
202
203
204if __name__ == "__main__":
205    main()