Commit 5bb00aeddd

5bb00aeddd273e575fc148c564451a93ebb1cb6b

parent: 8097aa14ec

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-05-12 12:45 UTC

feat: More meaningful error messages on YAML parse errors

Layout: unified · split

lib/checks/check-additions.py +26 −1
@@ -17,6 +17,8 @@ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(_
17DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") 17DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
18DIFF_PATH = "/tmp/pr-diff.json" 18DIFF_PATH = "/tmp/pr-diff.json"
19FINDINGS_PATH = "/tmp/findings-data.json" 19FINDINGS_PATH = "/tmp/findings-data.json"
20SCHEMA_ERRORS_PATH = "/tmp/schema-errors.json"
21MAX_SCHEMA_ERRORS_SHOWN = 10
20 22
21REQUIRED_FIELDS = ("name", "description", "url", "icon") 23REQUIRED_FIELDS = ("name", "description", "url", "icon")
22 24
@@ -242,12 +244,35 @@ def check_opensource_github(diff):
242 return None 244 return None
243 245
244 246
247def load_schema_errors():
248 """Load detailed schema/YAML errors written by validate-awesome-privacy.py, if any."""
249 try:
250 with open(SCHEMA_ERRORS_PATH) as f:
251 data = json.load(f)
252 return [str(x) for x in data] if isinstance(data, list) else []
253 except (OSError, ValueError):
254 return []
255
256
257def schema_findings():
258 """Return one error-level finding per detailed schema error, or the generic fallback."""
259 errors = load_schema_errors()
260 if not errors:
261 return [{"msg": SCHEMA_MSG, "level": "error"}]
262 shown = errors[:MAX_SCHEMA_ERRORS_SHOWN]
263 out = [{"msg": e, "level": "error"} for e in shown]
264 extra = len(errors) - len(shown)
265 if extra > 0:
266 out.append({"msg": f"…and {extra} more schema error(s)", "level": "error"})
267 return out
268
269
245def main(): 270def main():
246 findings = [] 271 findings = []
247 critical = False 272 critical = False
248 try: 273 try:
249 if os.environ.get("SCHEMA_OUTCOME") == "failure": 274 if os.environ.get("SCHEMA_OUTCOME") == "failure":
250 findings.append({"msg": SCHEMA_MSG, "level": "error"}) 275 findings.extend(schema_findings())
251 276
252 diff = load_json(DIFF_PATH) 277 diff = load_json(DIFF_PATH)
253 head = load_yaml_data(DATA_PATH) 278 head = load_yaml_data(DATA_PATH)
lib/validate-awesome-privacy.py +96 −8
@@ -9,6 +9,7 @@ from jsonschema import Draft7Validator
9PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 9PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") 10DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
11SCHEMA_PATH = os.path.join(PROJECT_ROOT, "lib/schema.json") 11SCHEMA_PATH = os.path.join(PROJECT_ROOT, "lib/schema.json")
12ERRORS_OUTPUT_PATH = "/tmp/schema-errors.json"
12 13
13# Exit codes 14# Exit codes
14EXIT_VALID = 0 15EXIT_VALID = 0
@@ -25,6 +26,11 @@ yellow = (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) 26dim = (lambda s: f"\033[2m{s}\033[0m") if _use_color else (lambda s: s)
26 27
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
28def resolve_path(data, path_parts): 34def resolve_path(data, path_parts):
29 """Walk the data along path_parts, replacing indices with 'name' values.""" 35 """Walk the data along path_parts, replacing indices with 'name' values."""
30 segments = [] 36 segments = []
@@ -33,21 +39,99 @@ def resolve_path(data, path_parts):
33 if isinstance(current, dict) and part in current: 39 if isinstance(current, dict) and part in current:
34 current = current[part] 40 current = current[part]
35 if isinstance(current, dict) and "name" in current: 41 if isinstance(current, dict) and "name" in current:
36 segments.append(current["name"]) 42 segments.append(_clean(current["name"]))
37 elif not isinstance(part, int): 43 elif not isinstance(current, (dict, list)):
38 pass # skip dict keys like 'categories', 'sections', 'services' 44 segments.append(_clean(part))
39 elif isinstance(current, list) and isinstance(part, int) and part < len(current): 45 elif isinstance(current, list) and isinstance(part, int) and part < len(current):
40 current = current[part] 46 current = current[part]
41 if isinstance(current, dict) and "name" in current: 47 if isinstance(current, dict) and "name" in current:
42 segments.append(current["name"]) 48 segments.append(_clean(current["name"]))
43 else: 49 else:
44 segments.append(str(part)) 50 segments.append(_clean(part))
45 else: 51 else:
46 segments.append(str(part)) 52 segments.append(_clean(part))
47 break 53 break
48 return " > ".join(segments) if segments else "(root)" 54 return " > ".join(segments) if segments else "(root)"
49 55
50 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
51def load_yaml(path): 135def load_yaml(path):
52 try: 136 try:
53 with open(path, "r") as f: 137 with open(path, "r") as f:
@@ -56,7 +140,9 @@ def load_yaml(path):
56 print(red(f"File not found: {path}"), file=sys.stderr) 140 print(red(f"File not found: {path}"), file=sys.stderr)
57 sys.exit(EXIT_RUNTIME_ERROR) 141 sys.exit(EXIT_RUNTIME_ERROR)
58 except yaml.YAMLError as e: 142 except yaml.YAMLError as e:
59 print(red(f"Failed to parse YAML: {e}"), file=sys.stderr) 143 msg = format_yaml_error(e)
144 write_errors_file([msg])
145 print(red(f"Failed to parse YAML: {msg}"), file=sys.stderr)
60 sys.exit(EXIT_RUNTIME_ERROR) 146 sys.exit(EXIT_RUNTIME_ERROR)
61 147
62 148
@@ -78,7 +164,7 @@ def validate(data, schema):
78 formatted = [] 164 formatted = []
79 for error in errors: 165 for error in errors:
80 location = resolve_path(data, list(error.path)) 166 location = resolve_path(data, list(error.path))
81 formatted.append(f"{location}: {error.message}") 167 formatted.append(humanize_error(error, location))
82 return formatted 168 return formatted
83 169
84 170
@@ -88,6 +174,7 @@ def main():
88 errors = validate(data, schema) 174 errors = validate(data, schema)
89 175
90 if errors: 176 if errors:
177 write_errors_file(errors)
91 shown = errors[:MAX_ERRORS] 178 shown = errors[:MAX_ERRORS]
92 for msg in shown: 179 for msg in shown:
93 print(red("ERROR") + " " + msg, file=sys.stderr) 180 print(red("ERROR") + " " + msg, file=sys.stderr)
@@ -105,6 +192,7 @@ def main():
105 for c in categories 192 for c in categories
106 for s in c.get("sections", []) 193 for s in c.get("sections", [])
107 ) 194 )
195 clear_errors_file()
108 print(green(f"Valid! {num_categories} categories, {num_sections} sections, {num_services} services")) 196 print(green(f"Valid! {num_categories} categories, {num_sections} sections, {num_services} services"))
109 sys.exit(EXIT_VALID) 197 sys.exit(EXIT_VALID)
110 198