lib/checks/check-additions.py
328 lines · 11909 bytes
1"""Validates data quality for added/modified services using the diff JSON."""
2
3import json
4import logging
5import os
6import sys
7
8import yaml
9
10sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11import utils
12
13utils.setup_logging()
14logger = logging.getLogger(__name__)
15
16PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
17DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
18DIFF_PATH = "/tmp/pr-diff.json"
19FINDINGS_PATH = "/tmp/findings-data.json"
20SCHEMA_ERRORS_PATH = "/tmp/schema-errors.json"
21MAX_SCHEMA_ERRORS_SHOWN = 10
22
23REQUIRED_FIELDS = ("name", "description", "url", "icon")
24REPO_FIELDS = ("github", "codeberg", "git")
25
26CONTRIBUTING = "https://github.com/Lissy93/awesome-privacy/blob/main/.github/CONTRIBUTING.md"
27
28SCHEMA_MSG = (
29 "Some of the schema checks have failed. Please check that your addition"
30 " contains all the required fields, with acceptable values, nothing"
31 " additional and that it is following valid YAML syntax"
32)
33MULTIPLE_MSG = "Please make just one addition per pull request"
34MISSING_TPL = (
35 "Did you include all required fields? Looks like {fields} is missing or"
36 f" invalid. Please see the [required fields]({CONTRIBUTING}#service-fields)"
37 " for available fields."
38)
39POSITION_MSG = (
40 "New entries must be added to the end of the section, unless otherwise requested"
41)
42OPENSOURCE_MSG = (
43 "You indicated this app/service is not open source. This will likely make"
44 " it ineligible for listing on Awesome Privacy in accordance with our"
45 f" [Requirements]({CONTRIBUTING}#requirements)."
46 " Please ensure that this is justified in your PR body."
47)
48DUPLICATE_NAME_MSG = (
49 "A service named `{name}` already exists (in {location})."
50 " If this is a different service, please clarify in your PR description"
51)
52DUPLICATE_URL_MSG = (
53 "The URL `{url}` is already associated with `{existing}`."
54 " Please check this isn't a duplicate submission"
55)
56DESC_LENGTH_MSG = (
57 "Description length ({length} chars) is outside the recommended 50\u2013250"
58 f" character range. Please see our [Contributing Guidelines]({CONTRIBUTING}#description)"
59)
60OPENSOURCE_GITHUB_MSG = (
61 "You marked this service as open source but didn't include a repository link."
62 " Please add a `github`, `codeberg` or `git` field"
63)
64
65
66def _has_repo(fields):
67 """Return True if a service has any source-repository field set."""
68 return any(fields.get(f) for f in REPO_FIELDS)
69
70
71def load_json(path):
72 """Load JSON from a file, returning None on any error."""
73 try:
74 with open(path) as f:
75 return json.load(f)
76 except Exception:
77 return None
78
79
80def load_yaml_data(path):
81 """Load YAML from a file, returning None on any error."""
82 try:
83 with open(path) as f:
84 return yaml.safe_load(f)
85 except Exception:
86 return None
87
88
89def find_section_services(head, category, section):
90 """Return the services list for a category/section pair, or None."""
91 for cat in head.get("categories", []):
92 if cat.get("name") == category:
93 for sec in cat.get("sections", []):
94 if sec.get("name") == section:
95 return sec.get("services", [])
96 return None
97
98
99def find_service_fields(head, category, section, service_name):
100 """Look up a service's fields in the head YAML."""
101 services = find_section_services(head, category, section)
102 if services:
103 for svc in services:
104 if svc.get("name") == service_name:
105 return svc
106 return None
107
108
109def check_required_fields(diff, head):
110 """Return a finding if any added/modified service is missing required fields."""
111 missing = set()
112 for svc in diff.get("services", {}).get("added", []):
113 fields = svc.get("fields", {})
114 for f in REQUIRED_FIELDS:
115 if fields.get(f) is None:
116 missing.add(f)
117 for svc in diff.get("services", {}).get("modified", []):
118 if not head:
119 continue
120 changed = svc.get("changed_fields", [])
121 fields = find_service_fields(
122 head, svc["category"], svc["section"], svc["service"]
123 )
124 if fields:
125 for f in REQUIRED_FIELDS:
126 if f in changed and fields.get(f) is None:
127 missing.add(f)
128 if missing:
129 names = ", ".join(f"`{f}`" for f in sorted(missing))
130 return MISSING_TPL.format(fields=names)
131 return None
132
133
134def check_position(diff, head):
135 """Return a finding if a newly added service is not at the end of its section."""
136 if not head:
137 return None
138 for svc in diff.get("services", {}).get("added", []):
139 services = find_section_services(head, svc["category"], svc["section"])
140 if services and services[-1].get("name") != svc["service"]:
141 return POSITION_MSG
142 return None
143
144
145def check_open_source(diff):
146 """Return a finding if an added service has openSource missing or not true."""
147 for svc in diff.get("services", {}).get("added", []):
148 fields = svc.get("fields", {})
149 if fields.get("openSource") is not True and not _has_repo(fields):
150 return OPENSOURCE_MSG
151 return None
152
153
154def check_single_entry(diff):
155 """Return a finding if the diff adds multiple new services or sections."""
156 services = diff.get("services", {})
157 added_count = len(services.get("added", []))
158 if added_count > 1:
159 return MULTIPLE_MSG
160 if added_count == 0:
161 added_sections = [s for s in diff.get("sections", [])
162 if s.get("change_type") == "added_section"]
163 if len(added_sections) > 1:
164 return MULTIPLE_MSG
165 return None
166
167
168def _added_keys(diff):
169 """Build a set of (category, section, lowercase_name) for added services."""
170 keys = set()
171 for svc in diff.get("services", {}).get("added", []):
172 name = svc.get("fields", {}).get("name", "").lower().strip()
173 keys.add((svc.get("category", ""), svc.get("section", ""), name))
174 return keys
175
176
177def build_name_index(head, diff):
178 """Build {lowercase_name: "category > section"} from all services, excluding additions."""
179 index = {}
180 if not head:
181 return index
182 exclude = _added_keys(diff)
183 for cat in head.get("categories", []):
184 cn = cat.get("name", "")
185 for sec in cat.get("sections", []):
186 sn = sec.get("name", "")
187 for svc in sec.get("services", []):
188 name = svc.get("name", "").lower().strip()
189 if name and (cn, sn, name) not in exclude:
190 index[name] = f"{cn} > {sn}"
191 return index
192
193
194def build_url_index(head, diff):
195 """Build {url: service_name} from all services, excluding additions."""
196 index = {}
197 if not head:
198 return index
199 exclude = _added_keys(diff)
200 for cat in head.get("categories", []):
201 cn = cat.get("name", "")
202 for sec in cat.get("sections", []):
203 sn = sec.get("name", "")
204 for svc in sec.get("services", []):
205 name = svc.get("name", "").lower().strip()
206 if (cn, sn, name) in exclude:
207 continue
208 url = svc.get("url", "")
209 if url:
210 index[url] = svc.get("name", "")
211 return index
212
213
214def check_duplicate_name(diff, name_index):
215 """Return a finding if an added service name already exists in the YAML."""
216 for svc in diff.get("services", {}).get("added", []):
217 name = svc.get("fields", {}).get("name", "").lower().strip()
218 if name and name in name_index:
219 return DUPLICATE_NAME_MSG.format(
220 name=svc["fields"]["name"], location=name_index[name],
221 )
222 return None
223
224
225def check_duplicate_url(diff, url_index):
226 """Return a finding if an added service URL already exists in the YAML."""
227 for svc in diff.get("services", {}).get("added", []):
228 url = svc.get("fields", {}).get("url", "")
229 if url and url in url_index:
230 return DUPLICATE_URL_MSG.format(url=url, existing=url_index[url])
231 return None
232
233
234def check_description_length(diff):
235 """Return a finding if an added service description is outside 50-250 chars."""
236 for svc in diff.get("services", {}).get("added", []):
237 desc = svc.get("fields", {}).get("description", "")
238 length = len(desc)
239 if length < 50 or length > 280:
240 return DESC_LENGTH_MSG.format(length=length)
241 return None
242
243
244def check_opensource_github(diff):
245 """Return a finding if an added service is open source but has no github field."""
246 for svc in diff.get("services", {}).get("added", []):
247 fields = svc.get("fields", {})
248 if fields.get("openSource") is True and not _has_repo(fields):
249 return OPENSOURCE_GITHUB_MSG
250 return None
251
252
253def load_schema_errors():
254 """Load detailed schema/YAML errors written by validate-awesome-privacy.py, if any."""
255 try:
256 with open(SCHEMA_ERRORS_PATH) as f:
257 data = json.load(f)
258 return [str(x) for x in data] if isinstance(data, list) else []
259 except (OSError, ValueError):
260 return []
261
262
263def schema_findings():
264 """Return one error-level finding per detailed schema error, or the generic fallback."""
265 errors = load_schema_errors()
266 if not errors:
267 return [{"msg": SCHEMA_MSG, "level": "error"}]
268 shown = errors[:MAX_SCHEMA_ERRORS_SHOWN]
269 out = [{"msg": e, "level": "error"} for e in shown]
270 extra = len(errors) - len(shown)
271 if extra > 0:
272 out.append({"msg": f"…and {extra} more schema error(s)", "level": "error"})
273 return out
274
275
276def main():
277 findings = []
278 critical = False
279 try:
280 if os.environ.get("SCHEMA_OUTCOME") == "failure":
281 logger.warning("Schema validation failed upstream, surfacing schema errors")
282 findings.extend(schema_findings())
283
284 diff = load_json(DIFF_PATH)
285 head = load_yaml_data(DATA_PATH)
286
287 if not diff:
288 logger.info("No diff at %s, nothing to validate", DIFF_PATH)
289 else:
290 added = diff.get("services", {}).get("added", [])
291 modified = diff.get("services", {}).get("modified", [])
292 logger.info("Validating additions: %d added, %d modified service(s)",
293 len(added), len(modified))
294
295 name_index = build_name_index(head, diff)
296 url_index = build_url_index(head, diff)
297
298 checks = [
299 ("single-entry", check_single_entry(diff), False),
300 ("required-fields", check_required_fields(diff, head), True),
301 ("position", check_position(diff, head), False),
302 ("open-source", check_open_source(diff), False),
303 ("duplicate-name", check_duplicate_name(diff, name_index), False),
304 ("duplicate-url", check_duplicate_url(diff, url_index), False),
305 ("description-length", check_description_length(diff), False),
306 ("opensource-repo", check_opensource_github(diff), False),
307 ]
308 for name, finding, is_error in checks:
309 if not finding:
310 continue
311 logger.info("flagged: %s", name)
312 if is_error:
313 findings.append({"msg": finding, "level": "error"})
314 critical = True
315 else:
316 findings.append(finding)
317 except Exception as exc:
318 logger.error("Unhandled error in main: %s", exc, exc_info=True)
319
320 logger.info("Additions check: %d finding(s)%s, writing to %s",
321 len(findings), " (critical)" if critical else "", FINDINGS_PATH)
322 with open(FINDINGS_PATH, "w") as f:
323 json.dump(findings, f)
324 sys.exit(1 if critical else 0)
325
326
327if __name__ == "__main__":
328 main()