lib/validate-awesome-privacy.py
201 lines · 7282 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")
12ERRORS_OUTPUT_PATH = "/tmp/schema-errors.json"
13
14# Exit codes
15EXIT_VALID = 0
16EXIT_VALIDATION_ERRORS = 1
17EXIT_RUNTIME_ERROR = 2
18
19MAX_ERRORS = 20
20
21# ANSI color helpers (disabled when NO_COLOR is set or stderr is not a TTY)
22_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
23red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
24green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
25yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
26dim = (lambda s: f"\033[2m{s}\033[0m") if _use_color else (lambda s: s)
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` or a full https://github.com/... URL",
61 "iosApp": "must be a full https://apps.apple.com/... URL",
62 "androidApp": "must be a package name like `com.example.app`",
63 "discordInvite": "must be a discord invite code or https://discord.gg/... URL",
64 "subreddit": "must be an alphanumeric subreddit name (no `/r/` prefix)",
65}
66
67
68def _q(v):
69 """As _clean but truncates long values for use inside inline `…` displays."""
70 s = _clean(v)
71 return s if len(s) <= 80 else s[:77] + "..."
72
73
74def _quoted(s):
75 """Extract all 'single-quoted' tokens from a string."""
76 parts = s.split("'")
77 return parts[1::2]
78
79
80def format_yaml_error(exc):
81 """Build a human-readable YAML error message, including line/column when available."""
82 mark = getattr(exc, "problem_mark", None) or getattr(exc, "context_mark", None)
83 problem = (getattr(exc, "problem", None) or "").strip()
84 where = f" at line {mark.line + 1}, column {mark.column + 1}" if mark else ""
85 return f"YAML syntax error{where}: {problem}" if problem else f"YAML syntax error{where}"
86
87
88def humanize_error(error, location):
89 """Render a jsonschema ValidationError as a single short, human-readable line."""
90 v = error.validator
91 raw = error.message
92 field = error.path[-1] if error.path and isinstance(error.path[-1], str) else None
93
94 if v == "required":
95 missing = (_quoted(raw) or ["?"])[0]
96 return f"{location}: missing required field `{missing}`"
97 if v == "additionalProperties":
98 extras = _quoted(raw) or ["?"]
99 joined = ", ".join(f"`{e}`" for e in extras)
100 return f"{location}: unknown field(s) {joined}"
101 if v == "type":
102 types = error.validator_value
103 types_s = " or ".join(types) if isinstance(types, list) else str(types)
104 return f"{location}: expected {types_s} (got `{_q(error.instance)}`)"
105 if v == "minLength":
106 return f"{location}: too short ({len(error.instance)} chars, minimum {error.validator_value})"
107 if v == "maxLength":
108 return f"{location}: too long ({len(error.instance)} chars, maximum {error.validator_value})"
109 if v == "minimum":
110 return f"{location}: value `{_q(error.instance)}` is below minimum {error.validator_value}"
111 if v in ("pattern", "anyOf", "oneOf"):
112 hint = FIELD_HINTS.get(field) if field else None
113 suffix = f" — {hint}" if hint else ""
114 return f"{location}: invalid value `{_q(error.instance)}`{suffix}"
115 return f"{location}: {raw}"
116
117
118def write_errors_file(messages):
119 """Persist error messages to a known location so downstream tools can surface them."""
120 try:
121 with open(ERRORS_OUTPUT_PATH, "w") as f:
122 json.dump(list(messages), f)
123 except OSError:
124 pass
125
126
127def clear_errors_file():
128 """Remove any stale errors file from a previous run."""
129 try:
130 os.remove(ERRORS_OUTPUT_PATH)
131 except OSError:
132 pass
133
134
135def load_yaml(path):
136 try:
137 with open(path, "r") as f:
138 return yaml.safe_load(f)
139 except FileNotFoundError:
140 print(red(f"File not found: {path}"), file=sys.stderr)
141 sys.exit(EXIT_RUNTIME_ERROR)
142 except yaml.YAMLError as e:
143 msg = format_yaml_error(e)
144 write_errors_file([msg])
145 print(red(f"Failed to parse YAML: {msg}"), file=sys.stderr)
146 sys.exit(EXIT_RUNTIME_ERROR)
147
148
149def load_schema(path):
150 try:
151 with open(path, "r") as f:
152 return json.load(f)
153 except FileNotFoundError:
154 print(red(f"File not found: {path}"), file=sys.stderr)
155 sys.exit(EXIT_RUNTIME_ERROR)
156 except json.JSONDecodeError as e:
157 print(red(f"Failed to parse JSON schema: {e}"), file=sys.stderr)
158 sys.exit(EXIT_RUNTIME_ERROR)
159
160
161def validate(data, schema):
162 validator = Draft7Validator(schema)
163 errors = sorted(validator.iter_errors(data), key=lambda e: list(e.path))
164 formatted = []
165 for error in errors:
166 location = resolve_path(data, list(error.path))
167 formatted.append(humanize_error(error, location))
168 return formatted
169
170
171def main():
172 data = load_yaml(DATA_PATH)
173 schema = load_schema(SCHEMA_PATH)
174 errors = validate(data, schema)
175
176 if errors:
177 write_errors_file(errors)
178 shown = errors[:MAX_ERRORS]
179 for msg in shown:
180 print(red("ERROR") + " " + msg, file=sys.stderr)
181 if len(errors) > MAX_ERRORS:
182 print(dim(f"...and {len(errors) - MAX_ERRORS} more"), file=sys.stderr)
183 print(red(f"Validation failed: {len(errors)} error(s)"), file=sys.stderr)
184 sys.exit(EXIT_VALIDATION_ERRORS)
185
186 # Gather stats
187 categories = data.get("categories", [])
188 num_categories = len(categories)
189 num_sections = sum(len(c.get("sections", [])) for c in categories)
190 num_services = sum(
191 len(s.get("services", []))
192 for c in categories
193 for s in c.get("sections", [])
194 )
195 clear_errors_file()
196 print(green(f"Valid! {num_categories} categories, {num_sections} sections, {num_services} services"))
197 sys.exit(EXIT_VALID)
198
199
200if __name__ == "__main__":
201 main()