lib/checks/check-additions.py

348 lines · 12904 bytes

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