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