lib/checks/check-additions.py

293 lines · 10025 bytes

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