lib/checks/check-project.py

227 lines · 7089 bytes

  1"""Checks project health: URL reachability, GitHub repo stars, activity, and author match."""
  2
  3import json
  4import os
  5import sys
  6from datetime import datetime, timezone
  7
  8import requests
  9import yaml
 10
 11PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
 12DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
 13DIFF_PATH = "/tmp/pr-diff.json"
 14FINDINGS_PATH = "/tmp/findings-project.json"
 15
 16TIMEOUT = 10
 17USER_AGENT = "awesome-privacy-ci/1.0"
 18MIN_STARS = 100
 19INACTIVE_DAYS = 90
 20
 21LINK_MSG = (
 22    "Our automated checks were unable to verify the link(s) you included"
 23    " were reachable, so please double check this yourself"
 24)
 25AUTHOR_MSG = (
 26    "Looks like you are the author of this package. Please ensure that you"
 27    " have clearly disclosed this in your PR body for transparency"
 28)
 29STARS_MSG = (
 30    "It looks like your submission is adding a quite small project."
 31    " In some circumstances we may ask you to resubmit this once the project"
 32    " is more mature and has a proven track record of good practices and maintenance."
 33)
 34ACTIVITY_MSG = (
 35    "Please confirm that the project you are adding is actively maintained,"
 36    " as it looks to not have had any recent updates in the past 3 months."
 37)
 38
 39
 40def load_diff(path):
 41    """Load the diff JSON, returning None on any error."""
 42    try:
 43        with open(path) as f:
 44            return json.load(f)
 45    except Exception:
 46        return None
 47
 48
 49def check_url(url):
 50    """Return True if the URL is reachable, True on any error (no false positives)."""
 51    try:
 52        resp = requests.head(
 53            url, timeout=TIMEOUT, allow_redirects=True,
 54            headers={"User-Agent": USER_AGENT},
 55        )
 56        if resp.status_code >= 400:
 57            resp = requests.get(
 58                url, timeout=TIMEOUT, allow_redirects=True,
 59                headers={"User-Agent": USER_AGENT}, stream=True,
 60            )
 61            resp.close()
 62        return resp.status_code < 400
 63    except Exception:
 64        return True
 65
 66
 67def parse_github_field(value):
 68    """Parse a github field into (owner, repo), or (None, None) on failure."""
 69    if not value:
 70        return None, None
 71    if value.startswith("https://github.com/"):
 72        parts = value.removeprefix("https://github.com/").strip("/").split("/")
 73        if len(parts) >= 2:
 74            return parts[0], parts[1]
 75        return None, None
 76    if "/" in value:
 77        parts = value.split("/")
 78        if len(parts) == 2:
 79            return parts[0], parts[1]
 80    return None, None
 81
 82
 83def fetch_repo(owner, repo, token):
 84    """Fetch GitHub repo metadata, returning None on any error."""
 85    try:
 86        headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
 87        if token:
 88            headers["Authorization"] = f"token {token}"
 89        resp = requests.get(
 90            f"https://api.github.com/repos/{owner}/{repo}",
 91            headers=headers, timeout=TIMEOUT,
 92        )
 93        if resp.status_code == 200:
 94            return resp.json()
 95    except Exception:
 96        pass
 97    return None
 98
 99
100def load_yaml_data():
101    """Load the head YAML, returning None on any error."""
102    try:
103        with open(DATA_PATH) as f:
104            return yaml.safe_load(f)
105    except Exception:
106        return None
107
108
109def find_service_in_head(head, category, section, service_name):
110    """Look up a service in the head YAML by path."""
111    if not head:
112        return None
113    for cat in head.get("categories", []):
114        if cat.get("name") == category:
115            for sec in cat.get("sections", []):
116                if sec.get("name") == section:
117                    for svc in sec.get("services", []):
118                        if svc.get("name") == service_name:
119                            return svc
120    return None
121
122
123def get_services(diff, key):
124    """Safely extract a service list from the diff."""
125    return diff.get("services", {}).get(key, [])
126
127
128def check_links(diff, head):
129    """Return LINK_MSG if any service URL or icon URL is unreachable."""
130    for svc in get_services(diff, "added"):
131        fields = svc.get("fields", {})
132        url = fields.get("url")
133        if url and not check_url(url):
134            return LINK_MSG
135        icon = fields.get("icon")
136        if icon and not check_url(icon):
137            return LINK_MSG
138    for svc in get_services(diff, "modified"):
139        changed = svc.get("changed_fields", [])
140        if "url" not in changed and "icon" not in changed:
141            continue
142        head_svc = find_service_in_head(
143            head, svc["category"], svc["section"], svc["service"]
144        )
145        if head_svc:
146            if "url" in changed:
147                url = head_svc.get("url")
148                if url and not check_url(url):
149                    return LINK_MSG
150            if "icon" in changed:
151                icon = head_svc.get("icon")
152                if icon and not check_url(icon):
153                    return LINK_MSG
154    return None
155
156
157def check_repo_signals(diff, pr_user, token):
158    """Check GitHub repo author match, stars, and activity for added services."""
159    findings = []
160    if not token:
161        return findings
162    cache = {}
163    for svc in get_services(diff, "added"):
164        gh = svc.get("fields", {}).get("github")
165        owner, repo = parse_github_field(gh)
166        if not owner:
167            continue
168        cache_key = f"{owner}/{repo}"
169        if cache_key not in cache:
170            cache[cache_key] = fetch_repo(owner, repo, token)
171        data = cache[cache_key]
172        if not data:
173            continue
174
175        repo_owner = data.get("owner", {})
176        if (
177            pr_user
178            and repo_owner.get("type") == "User"
179            and repo_owner.get("login", "").lower() == pr_user.lower()
180            and AUTHOR_MSG not in findings
181        ):
182            findings.append(AUTHOR_MSG)
183
184        stars = data.get("stargazers_count", 0)
185        if stars < MIN_STARS and STARS_MSG not in findings:
186            findings.append(STARS_MSG)
187
188        pushed = data.get("pushed_at")
189        if pushed and ACTIVITY_MSG not in findings:
190            try:
191                pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00"))
192                now = datetime.now(timezone.utc)
193                if (now - pushed_dt).days > INACTIVE_DAYS:
194                    findings.append(ACTIVITY_MSG)
195            except Exception:
196                pass
197
198    return findings
199
200
201def main():
202    findings = []
203    try:
204        diff = load_diff(DIFF_PATH)
205        if not diff:
206            with open(FINDINGS_PATH, "w") as f:
207                json.dump(findings, f)
208            sys.exit(0)
209
210        head = load_yaml_data()
211        finding = check_links(diff, head)
212        if finding:
213            findings.append(finding)
214
215        pr_user = os.environ.get("PR_USER", "")
216        token = os.environ.get("GITHUB_TOKEN", "")
217        findings.extend(check_repo_signals(diff, pr_user, token))
218    except Exception:
219        pass
220
221    with open(FINDINGS_PATH, "w") as f:
222        json.dump(findings, f)
223    sys.exit(0)
224
225
226if __name__ == "__main__":
227    main()