lib/checks/check-additions.py

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