Commit 512299c71d

512299c71db3edc0f25c6e75b8ce9c390fd5cb75

parent: 2476a57bac

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-02-23 20:28 UTC

Updates PR check step concurency

Layout: unified · split

.github/workflows/pr-check.yml +34 −45
@@ -4,86 +4,76 @@ on:
44 pull_request:
55 branches: [main]
66 types: [opened, edited, synchronize, reopened]
7 paths:
8 - 'awesome-privacy.yml'
9 - '.github/README.md'
710
811permissions:
912 contents: read
1013 pull-requests: read
1114
1215jobs:
13 detect-changes:
14 name: Detect changes
16 pr-compliance:
17 name: PR Compliance
1518 runs-on: ubuntu-latest
16 outputs:
17 yaml_changed: ${{ steps.changes.outputs.yaml_changed }}
18 non_yaml_changed: ${{ steps.changes.outputs.non_yaml_changed }}
1919 steps:
2020 - uses: actions/checkout@v4
2121 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
2222 - uses: actions/setup-python@v5
2323 with:
2424 python-version: "3.12"
25 - name: Detect changed files
26 id: changes
27 run: python lib/checks/detect-changes.py --base-ref ${{ github.event.pull_request.base.sha }}
28 - name: Non-YAML changes warning
29 if: steps.changes.outputs.non_yaml_changed == 'true'
30 run: python lib/checks/warn-non-yaml.py --base-ref ${{ github.event.pull_request.base.sha }}
31
32 pr-meta:
33 name: PR metadata
34 runs-on: ubuntu-latest
35 steps:
36 - uses: actions/checkout@v4
37 - uses: actions/setup-python@v5
38 with:
39 python-version: "3.12"
25 - name: Check README edits
26 id: readme
27 continue-on-error: true
28 run: python lib/checks/check-readme-edits.py --base-ref ${{ github.event.pull_request.base.sha }}
4029 - name: Check PR metadata
30 id: meta
4131 env:
4232 PR_TITLE: ${{ github.event.pull_request.title }}
4333 PR_BODY: ${{ github.event.pull_request.body }}
4434 PR_DRAFT: ${{ github.event.pull_request.draft }}
35 README_FAILED: ${{ steps.readme.outcome == 'failure' && 'true' || 'false' }}
4536 run: python lib/checks/check-pr-meta.py
4637 - name: Upload findings
4738 if: always()
4839 uses: actions/upload-artifact@v4
4940 with:
50 name: findings-meta
51 path: /tmp/findings-meta.json
41 name: findings-compliance
42 path: /tmp/findings-compliance.json
5243 if-no-files-found: ignore
53
54 file-checks:
55 name: File checks
56 runs-on: ubuntu-latest
57 steps:
58 - uses: actions/checkout@v4
59 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
60 - uses: actions/setup-python@v5
61 with:
62 python-version: "3.12"
63 - name: Check for direct README edits
64 run: python lib/checks/check-readme-edits.py --base-ref ${{ github.event.pull_request.base.sha }}
44 - name: Fail if critical
45 if: steps.readme.outcome == 'failure' || steps.meta.outcome == 'failure'
46 run: exit 1
6547
6648 data-validation:
67 name: Data validation
68 needs: detect-changes
69 if: needs.detect-changes.outputs.yaml_changed == 'true'
49 name: Data Validation
7050 runs-on: ubuntu-latest
51 outputs:
52 yaml_changed: ${{ steps.changes.outputs.yaml_changed }}
7153 steps:
7254 - uses: actions/checkout@v4
7355 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
7456 - uses: actions/setup-python@v5
7557 with:
7658 python-version: "3.12"
77 - run: pip install -q -r lib/requirements.txt
59 - name: Detect changes
60 id: changes
61 run: python lib/checks/detect-changes.py --base-ref ${{ github.event.pull_request.base.sha }}
62 - name: Install dependencies
63 if: steps.changes.outputs.yaml_changed == 'true'
64 run: pip install -q -r lib/requirements.txt
7865 - name: Schema validation
66 if: steps.changes.outputs.yaml_changed == 'true'
7967 id: schema
8068 continue-on-error: true
8169 run: make validate
8270 - name: YAML diff
71 if: steps.changes.outputs.yaml_changed == 'true'
8372 id: diff
8473 continue-on-error: true
8574 run: python lib/checks/check-yaml-diff.py --base-ref ${{ github.event.pull_request.base.sha }}
8675 - name: Check additions
76 if: steps.changes.outputs.yaml_changed == 'true'
8777 env:
8878 SCHEMA_OUTCOME: ${{ steps.schema.outcome }}
8979 run: python lib/checks/check-additions.py
@@ -101,14 +91,14 @@ jobs:
10191 name: findings-data
10292 path: /tmp/findings-data.json
10393 if-no-files-found: ignore
104 - name: Fail if critical checks failed
105 if: steps.schema.outcome == 'failure' || steps.diff.outcome == 'failure'
94 - name: Fail if critical
95 if: steps.changes.outputs.yaml_changed == 'true' && (steps.schema.outcome == 'failure' || steps.diff.outcome == 'failure')
10696 run: exit 1
10797
108 project-checks:
109 name: Project checks
98 submission-eligibility:
99 name: Submission Eligibility
110100 needs: data-validation
111 if: "!cancelled() && needs.data-validation.result != 'skipped'"
101 if: "!cancelled() && needs.data-validation.outputs.yaml_changed == 'true'"
112102 runs-on: ubuntu-latest
113103 steps:
114104 - uses: actions/checkout@v4
@@ -138,7 +128,7 @@ jobs:
138128 summary:
139129 name: Summary
140130 if: always()
141 needs: [detect-changes, pr-meta, file-checks, data-validation, project-checks]
131 needs: [pr-compliance, data-validation, submission-eligibility]
142132 runs-on: ubuntu-latest
143133 steps:
144134 - uses: actions/checkout@v4
@@ -157,7 +147,6 @@ jobs:
157147 PR_USER: ${{ github.event.pull_request.user.login }}
158148 PR_NUMBER: ${{ github.event.pull_request.number }}
159149 RUN_ID: ${{ github.run_id }}
160 README_FAILED: ${{ needs.file-checks.result == 'failure' && 'true' || 'false' }}
161150 run: python lib/checks/format-comment.py
162151 - name: Upload PR metadata
163152 if: always()
lib/checks/check-links.py deleted −211
@@ -1,211 +0,0 @@
1"""
2Validates URLs and metadata for added/modified services in a PR.
3Reads the diff JSON produced by check-yaml-diff.py.
4All checks are warnings only -- this script never fails (exit 0).
5"""
6
7import argparse
8import json
9import os
10import sys
11
12import requests
13import yaml
14
15# Paths (relative to project root)
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")
18
19# Exit codes
20EXIT_PASS = 0
21EXIT_RUNTIME_ERROR = 2
22
23# ANSI color helpers
24_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
25red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
26green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
27yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
28
29TIMEOUT = 10
30USER_AGENT = "awesome-privacy-ci/1.0"
31DESC_MIN_LEN = 50
32DESC_MAX_LEN = 250
33
34
35def check_url(url, label):
36 """Check if a URL is reachable. Returns (ok, message)."""
37 try:
38 resp = requests.head(
39 url,
40 timeout=TIMEOUT,
41 allow_redirects=True,
42 headers={"User-Agent": USER_AGENT},
43 )
44 if resp.status_code >= 400:
45 # Retry with GET -- some servers reject HEAD
46 resp = requests.get(
47 url,
48 timeout=TIMEOUT,
49 allow_redirects=True,
50 headers={"User-Agent": USER_AGENT},
51 stream=True,
52 )
53 resp.close()
54 if resp.status_code >= 400:
55 return False, f"{label}: HTTP {resp.status_code} for {url}"
56 return True, None
57 except requests.RequestException as e:
58 return False, f"{label}: Connection error for {url} ({type(e).__name__})"
59
60
61def check_service(service_data, service_name, category, section):
62 """Run all checks on a single service. Returns list of warning strings."""
63 warnings = []
64 name_prefix = f"{category} > {section} > {service_name}"
65
66 # Check url
67 url = service_data.get("url")
68 if url:
69 ok, msg = check_url(url, "url")
70 if not ok:
71 warnings.append(f"{name_prefix}: {msg}")
72 else:
73 warnings.append(f"{name_prefix}: missing required field 'url'")
74
75 # Check icon
76 icon = service_data.get("icon")
77 if icon:
78 ok, msg = check_url(icon, "icon")
79 if not ok:
80 warnings.append(f"{name_prefix}: {msg}")
81 else:
82 warnings.append(f"{name_prefix}: missing 'icon' field (recommended by contributing guide)")
83
84 # Check iosApp
85 ios_app = service_data.get("iosApp")
86 if ios_app:
87 ok, msg = check_url(ios_app, "iosApp")
88 if not ok:
89 warnings.append(f"{name_prefix}: {msg}")
90
91 # Check github
92 github = service_data.get("github")
93 if github:
94 github_url = f"https://github.com/{github}"
95 ok, msg = check_url(github_url, "github")
96 if not ok:
97 warnings.append(f"{name_prefix}: {msg}")
98
99 # Check description length
100 desc = service_data.get("description", "")
101 desc_stripped = desc.strip()
102 desc_len = len(desc_stripped)
103 if desc_len < DESC_MIN_LEN:
104 warnings.append(f"{name_prefix}: description too short ({desc_len} chars, minimum {DESC_MIN_LEN})")
105 elif desc_len > DESC_MAX_LEN:
106 warnings.append(f"{name_prefix}: description too long ({desc_len} chars, maximum {DESC_MAX_LEN})")
107
108 return warnings
109
110
111def find_service_in_head(category, section, service_name):
112 """Look up a service in the head YAML by category/section/service name."""
113 try:
114 with open(DATA_PATH, "r") as f:
115 data = yaml.safe_load(f)
116 for cat in data.get("categories", []):
117 if cat.get("name") == category:
118 for sec in cat.get("sections", []):
119 if sec.get("name") == section:
120 for svc in sec.get("services", []):
121 if svc.get("name") == service_name:
122 return svc
123 except Exception:
124 pass
125 return None
126
127
128def write_step_summary(all_warnings, services_checked):
129 """Write a Markdown summary to $GITHUB_STEP_SUMMARY."""
130 summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
131 if not summary_file:
132 return
133
134 lines = ["## Link Validation\n"]
135
136 if not services_checked:
137 lines.append("No services to check.\n")
138 elif not all_warnings:
139 lines.append(f"All checks passed for {services_checked} service(s).\n")
140 else:
141 lines.append(f"Checked {services_checked} service(s), found {len(all_warnings)} warning(s):\n")
142 lines.append("| Warning |")
143 lines.append("|---------|")
144 for w in all_warnings:
145 escaped = w.replace("|", "\\|")
146 lines.append(f"| {escaped} |")
147 lines.append("")
148 lines.append("> **Note:** Link warnings are informational only and do not fail the check. "
149 "URLs may be temporarily down or block automated requests.\n")
150
151 with open(summary_file, "a") as f:
152 f.write("\n".join(lines) + "\n")
153
154
155def main():
156 parser = argparse.ArgumentParser(description="Validate links for added/modified services")
157 parser.add_argument("--diff-json", required=True, help="Path to the diff JSON file")
158 args = parser.parse_args()
159
160 # Load diff
161 try:
162 with open(args.diff_json, "r") as f:
163 diff = json.load(f)
164 except (FileNotFoundError, json.JSONDecodeError) as e:
165 print(red(f"Failed to load diff JSON: {e}"), file=sys.stderr)
166 sys.exit(EXIT_RUNTIME_ERROR)
167
168 all_warnings = []
169 services_checked = 0
170
171 # Check added services
172 for svc in diff.get("services", {}).get("added", []):
173 services_checked += 1
174 warnings = check_service(
175 svc.get("fields", {}),
176 svc["service"],
177 svc["category"],
178 svc["section"],
179 )
180 all_warnings.extend(warnings)
181
182 # Check modified services -- only if they have URL-related field changes
183 for svc in diff.get("services", {}).get("modified", []):
184 url_fields = {"url", "icon", "iosApp", "github", "description"}
185 changed = set(svc.get("changed_fields", []))
186 if changed & url_fields:
187 services_checked += 1
188 head_svc = find_service_in_head(svc["category"], svc["section"], svc["service"])
189 if head_svc:
190 warnings = check_service(
191 head_svc,
192 svc["service"],
193 svc["category"],
194 svc["section"],
195 )
196 all_warnings.extend(warnings)
197
198 # Print results
199 if all_warnings:
200 print(yellow(f"Link validation: {len(all_warnings)} warning(s)"), file=sys.stderr)
201 for w in all_warnings:
202 print(f" {yellow('WARNING')} {w}", file=sys.stderr)
203 else:
204 print(green(f"Link validation passed. {services_checked} service(s) checked."))
205
206 write_step_summary(all_warnings, services_checked)
207 sys.exit(EXIT_PASS)
208
209
210if __name__ == "__main__":
211 main()
lib/checks/check-pr-meta.py +18 −1
@@ -5,7 +5,7 @@ import os
55import re
66import sys
77
8FINDINGS_PATH = "/tmp/findings-meta.json"
8FINDINGS_PATH = "/tmp/findings-compliance.json"
99
1010BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"}
1111
@@ -27,6 +27,11 @@ CHECKBOX_MSG = (
2727 " to confirm that you've read the contributing guidelines, checked your submission,"
2828 " indicated your affiliation and agree to follow our CoC"
2929)
30README_MSG = (
31 "Do not edit the README directly. This file is auto-generated from the"
32 " content in `awesome-privacy.yml`, and so your changes will be overridden!"
33 " Instead, only modify the YAML file, and be sure to follow our Contributing Guidelines."
34)
3035
3136
3237def extract_section(body, header):
@@ -78,6 +83,13 @@ def check_checkboxes(body):
7883 return None
7984
8085
86def check_readme(readme_failed):
87 """Return a finding if the README check reported a failure."""
88 if readme_failed == "true":
89 return README_MSG
90 return None
91
92
8193def write_findings(findings):
8294 """Write the findings list to the output JSON file."""
8395 with open(FINDINGS_PATH, "w") as f:
@@ -91,6 +103,7 @@ def main():
91103 title = os.environ.get("PR_TITLE", "")
92104 body = os.environ.get("PR_BODY", "")
93105 draft = os.environ.get("PR_DRAFT", "false")
106 readme_failed = os.environ.get("README_FAILED", "false")
94107
95108 finding = check_title(title)
96109 if finding:
@@ -111,6 +124,10 @@ def main():
111124 finding = check_checkboxes(body)
112125 if finding:
113126 findings.append(finding)
127
128 finding = check_readme(readme_failed)
129 if finding:
130 findings.append(finding)
114131 except Exception:
115132 pass
116133
lib/checks/check-template.py deleted −206
@@ -1,206 +0,0 @@
1"""
2Checks PR body against the pull request template.
3Reads the PR body from the PR_BODY environment variable (avoids shell injection).
4Exits with code 1 for severe violations (empty body, missing required sections).
5"""
6
7import os
8import re
9import sys
10
11# Exit codes
12EXIT_PASS = 0
13EXIT_FAIL = 1
14EXIT_RUNTIME_ERROR = 2
15
16# Warnings that should cause a hard failure
17CRITICAL_WARNINGS = {
18 "PR body is empty or not provided",
19 "Type section is missing",
20 "Type section is empty",
21 "Changes section is missing",
22 "Changes section is empty",
23 "Checklist section is missing",
24 "Checklist section does not contain any checkbox items",
25}
26
27# ANSI color helpers
28_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
29red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
30green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
31yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
32
33# Valid PR types from the template
34VALID_TYPES = {"Addition", "Amendment", "Removal", "Spelling or Grammar", "Website Update", "Misc"}
35
36# Raw template text that indicates an unfilled section
37RAW_TYPE_LINE = "Addition / Amendment / Removal / Spelling or Grammar / Website Update / Misc"
38
39
40def strip_html_comments(text):
41 """Remove <!-- ... --> comments from text."""
42 return re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL).strip()
43
44
45def extract_section(body, header):
46 """Extract content between a ### header and the next --- or ### header."""
47 pattern = rf"###\s*{re.escape(header)}\s*\n(.*?)(?=\n---|\n###|\Z)"
48 match = re.search(pattern, body, re.DOTALL)
49 if match:
50 return match.group(1)
51 return None
52
53
54def check_type_section(content):
55 """Check the Type section. Returns list of warning strings."""
56 warnings = []
57
58 if content is None:
59 warnings.append("Type section is missing")
60 return warnings
61
62 cleaned = strip_html_comments(content).strip()
63
64 if not cleaned:
65 warnings.append("Type section is empty")
66 return warnings
67
68 # Check for raw template text (unchanged)
69 if RAW_TYPE_LINE in cleaned:
70 warnings.append("Type section appears unchanged from the template -- please select one type")
71 return warnings
72
73 # Check how many valid types are present
74 found_types = [t for t in VALID_TYPES if t in cleaned]
75
76 if len(found_types) == 0:
77 warnings.append(f"Type section does not contain a recognized type. Expected one of: {', '.join(sorted(VALID_TYPES))}")
78 elif len(found_types) > 1:
79 warnings.append(f"Type section contains multiple types ({', '.join(found_types)}) -- please select only one")
80
81 return warnings
82
83
84def check_text_section(content, section_name):
85 """Check a text section (Changes, Supporting Material, Affiliation). Returns list of warnings."""
86 warnings = []
87
88 if content is None:
89 warnings.append(f"{section_name} section is missing")
90 return warnings
91
92 cleaned = strip_html_comments(content).strip()
93
94 if not cleaned:
95 warnings.append(f"{section_name} section is empty")
96
97 return warnings
98
99
100def check_checklist(content):
101 """Check the Checklist section. Returns list of warnings."""
102 warnings = []
103
104 if content is None:
105 warnings.append("Checklist section is missing")
106 return warnings
107
108 checked = re.findall(r"- \[x\]", content, re.IGNORECASE)
109 unchecked = re.findall(r"- \[ \]", content)
110
111 total = len(checked) + len(unchecked)
112
113 if total == 0:
114 warnings.append("Checklist section does not contain any checkbox items")
115 return warnings
116
117 if unchecked:
118 warnings.append(f"Checklist has {len(unchecked)} unchecked item(s) out of {total}")
119
120 return warnings
121
122
123def has_critical_warnings(warnings):
124 """Return True if any warning is a critical (hard-fail) violation."""
125 return any(w in CRITICAL_WARNINGS for w in warnings)
126
127
128def write_step_summary(all_warnings):
129 """Write a Markdown summary to $GITHUB_STEP_SUMMARY."""
130 summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
131 if not summary_file:
132 return
133
134 lines = ["## PR Template Check\n"]
135
136 if not all_warnings:
137 lines.append("All template checks passed.\n")
138 else:
139 critical = has_critical_warnings(all_warnings)
140 lines.append(f"Found {len(all_warnings)} warning(s):\n")
141 for w in all_warnings:
142 lines.append(f"- {w}")
143 lines.append("")
144 if critical:
145 lines.append("> **Error:** One or more required sections are missing or empty. "
146 "Please fill out the PR template before this check can pass.\n")
147 else:
148 lines.append("> **Note:** Template warnings are informational and do not fail the check. "
149 "Reviewers will verify compliance.\n")
150
151 with open(summary_file, "a") as f:
152 f.write("\n".join(lines) + "\n")
153
154
155def main():
156 pr_body = os.environ.get("PR_BODY")
157
158 if pr_body is None or pr_body.strip() == "":
159 all_warnings = [
160 "PR body is empty or not provided",
161 "Type section is missing",
162 "Changes section is missing",
163 "Supporting Material section is missing",
164 "Affiliation section is missing",
165 "Checklist section is missing",
166 ]
167 print(yellow(f"PR template check: {len(all_warnings)} warning(s)"), file=sys.stderr)
168 for w in all_warnings:
169 print(f" {yellow('WARNING')} {w}", file=sys.stderr)
170 write_step_summary(all_warnings)
171 sys.exit(EXIT_FAIL)
172
173 all_warnings = []
174
175 # Check each section
176 type_content = extract_section(pr_body, "Type")
177 all_warnings.extend(check_type_section(type_content))
178
179 changes_content = extract_section(pr_body, "Changes")
180 all_warnings.extend(check_text_section(changes_content, "Changes"))
181
182 supporting_content = extract_section(pr_body, "Supporting Material")
183 all_warnings.extend(check_text_section(supporting_content, "Supporting Material"))
184
185 affiliation_content = extract_section(pr_body, "Affiliation")
186 all_warnings.extend(check_text_section(affiliation_content, "Affiliation"))
187
188 checklist_content = extract_section(pr_body, "Checklist")
189 all_warnings.extend(check_checklist(checklist_content))
190
191 # Print results
192 if all_warnings:
193 print(yellow(f"PR template check: {len(all_warnings)} warning(s)"), file=sys.stderr)
194 for w in all_warnings:
195 print(f" {yellow('WARNING')} {w}", file=sys.stderr)
196 else:
197 print(green("PR template check passed."))
198
199 write_step_summary(all_warnings)
200 if has_critical_warnings(all_warnings):
201 sys.exit(EXIT_FAIL)
202 sys.exit(EXIT_PASS)
203
204
205if __name__ == "__main__":
206 main()
lib/checks/check-yaml-diff.py +107 −245
@@ -1,7 +1,5 @@
1"""
2Analyzes the diff between base and head versions of awesome-privacy.yml.
3Enforces the single-entry rule: only one service addition/amendment/removal per PR.
4Outputs a JSON diff to /tmp/pr-diff.json and writes a step summary.
1"""Analyzes the diff between base and head versions of awesome-privacy.yml.
2Enforces the single-entry rule and outputs a JSON diff to /tmp/pr-diff.json.
53"""
64
75import argparse
@@ -12,22 +10,18 @@ import sys
1210
1311import yaml
1412
15# Paths (relative to project root)
1613PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1714DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
1815DIFF_OUTPUT_PATH = "/tmp/pr-diff.json"
1916
20# Exit codes
2117EXIT_PASS = 0
2218EXIT_RULE_VIOLATION = 1
2319EXIT_RUNTIME_ERROR = 2
2420
25# ANSI color helpers
2621_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
2722red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
2823green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
2924yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
30dim = (lambda s: f"\033[2m{s}\033[0m") if _use_color else (lambda s: s)
3125
3226
3327def load_base_yaml(base_ref):
@@ -35,13 +29,11 @@ def load_base_yaml(base_ref):
3529 try:
3630 result = subprocess.run(
3731 ["git", "show", f"{base_ref}:awesome-privacy.yml"],
38 capture_output=True, text=True, check=True,
39 cwd=PROJECT_ROOT,
32 capture_output=True, text=True, check=True, cwd=PROJECT_ROOT,
4033 )
4134 return yaml.safe_load(result.stdout)
4235 except subprocess.CalledProcessError:
43 # File doesn't exist in base (completely new file)
44 print(yellow("Warning: awesome-privacy.yml not found in base ref, treating as empty"), file=sys.stderr)
36 print(yellow("awesome-privacy.yml not found in base ref, treating as empty"), file=sys.stderr)
4537 return {"categories": []}
4638 except yaml.YAMLError as e:
4739 print(red(f"Failed to parse base YAML: {e}"), file=sys.stderr)
@@ -51,165 +43,45 @@ def load_base_yaml(base_ref):
5143def load_head_yaml():
5244 """Load the YAML from the current working tree."""
5345 try:
54 with open(DATA_PATH, "r") as f:
46 with open(DATA_PATH) as f:
5547 return yaml.safe_load(f)
56 except FileNotFoundError:
57 print(red(f"File not found: {DATA_PATH}"), file=sys.stderr)
58 sys.exit(EXIT_RUNTIME_ERROR)
59 except yaml.YAMLError as e:
60 print(red(f"Failed to parse head YAML: {e}"), file=sys.stderr)
48 except (FileNotFoundError, yaml.YAMLError) as e:
49 print(red(f"Failed to load head YAML: {e}"), file=sys.stderr)
6150 sys.exit(EXIT_RUNTIME_ERROR)
6251
6352
64def build_service_index(data):
65 """Build a dict keyed by (category, section, service_name) -> service dict."""
53def build_index(data, depth):
54 """Build a keyed index at the given depth (3=services, 2=sections, 1=categories)."""
6655 index = {}
6756 for cat in data.get("categories", []):
68 cat_name = cat.get("name", "")
57 cn = cat.get("name", "")
58 if depth == 1:
59 index[cn] = {k: v for k, v in cat.items() if k != "sections"}
60 continue
6961 for sec in cat.get("sections", []):
70 sec_name = sec.get("name", "")
62 sn = sec.get("name", "")
63 if depth == 2:
64 index[(cn, sn)] = {k: v for k, v in sec.items() if k != "services"}
65 continue
7166 for svc in sec.get("services", []):
72 svc_name = svc.get("name", "")
73 key = (cat_name, sec_name, svc_name)
74 index[key] = svc
67 index[(cn, sn, svc.get("name", ""))] = svc
7568 return index
7669
7770
78def build_section_index(data):
79 """Build a dict keyed by (category, section) -> section metadata (excluding services)."""
80 index = {}
81 for cat in data.get("categories", []):
82 cat_name = cat.get("name", "")
83 for sec in cat.get("sections", []):
84 sec_name = sec.get("name", "")
85 key = (cat_name, sec_name)
86 meta = {k: v for k, v in sec.items() if k != "services"}
87 index[key] = meta
88 return index
89
90
91def build_category_index(data):
92 """Build a dict keyed by category_name -> category metadata (excluding sections)."""
93 index = {}
94 for cat in data.get("categories", []):
95 cat_name = cat.get("name", "")
96 meta = {k: v for k, v in cat.items() if k != "sections"}
97 index[cat_name] = meta
98 return index
99
100
101def diff_services(base_data, head_data):
102 """Find added, removed, and modified services."""
103 base_idx = build_service_index(base_data)
104 head_idx = build_service_index(head_data)
105
106 base_keys = set(base_idx.keys())
107 head_keys = set(head_idx.keys())
108
109 added = []
110 for key in sorted(head_keys - base_keys):
111 added.append({
112 "category": key[0],
113 "section": key[1],
114 "service": key[2],
115 "fields": head_idx[key],
116 })
117
118 removed = []
119 for key in sorted(base_keys - head_keys):
120 removed.append({
121 "category": key[0],
122 "section": key[1],
123 "service": key[2],
124 })
125
71def diff_index(base_idx, head_idx):
72 """Return (added_keys, removed_keys, modified_keys_with_changed_fields)."""
73 base_keys, head_keys = set(base_idx), set(head_idx)
74 added = sorted(head_keys - base_keys)
75 removed = sorted(base_keys - head_keys)
12676 modified = []
12777 for key in sorted(base_keys & head_keys):
128 base_svc = base_idx[key]
129 head_svc = head_idx[key]
130 if base_svc != head_svc:
131 changed_fields = []
132 all_fields = set(base_svc.keys()) | set(head_svc.keys())
133 for field in sorted(all_fields):
134 old_val = base_svc.get(field)
135 new_val = head_svc.get(field)
136 if old_val != new_val:
137 changed_fields.append(field)
138 modified.append({
139 "category": key[0],
140 "section": key[1],
141 "service": key[2],
142 "changed_fields": changed_fields,
143 })
144
78 if base_idx[key] != head_idx[key]:
79 all_fields = set(base_idx[key]) | set(head_idx[key])
80 changed = sorted(f for f in all_fields if base_idx[key].get(f) != head_idx[key].get(f))
81 modified.append((key, changed))
14582 return added, removed, modified
14683
14784
148def diff_sections(base_data, head_data):
149 """Find section-level metadata changes (intro, wordOfWarning, etc.)."""
150 base_idx = build_section_index(base_data)
151 head_idx = build_section_index(head_data)
152
153 base_keys = set(base_idx.keys())
154 head_keys = set(head_idx.keys())
155
156 changes = []
157
158 # New sections
159 for key in sorted(head_keys - base_keys):
160 changes.append({
161 "category": key[0],
162 "section": key[1],
163 "change_type": "added_section",
164 })
165
166 # Removed sections
167 for key in sorted(base_keys - head_keys):
168 changes.append({
169 "category": key[0],
170 "section": key[1],
171 "change_type": "removed_section",
172 })
173
174 # Modified section metadata
175 for key in sorted(base_keys & head_keys):
176 base_meta = base_idx[key]
177 head_meta = head_idx[key]
178 if base_meta != head_meta:
179 changed_fields = []
180 all_fields = set(base_meta.keys()) | set(head_meta.keys())
181 for field in sorted(all_fields):
182 if base_meta.get(field) != head_meta.get(field):
183 changed_fields.append(field)
184 changes.append({
185 "category": key[0],
186 "section": key[1],
187 "change_type": "modified_section_metadata",
188 "changed_fields": changed_fields,
189 })
190
191 return changes
192
193
194def diff_categories(base_data, head_data):
195 """Find structural category changes."""
196 base_idx = build_category_index(base_data)
197 head_idx = build_category_index(head_data)
198
199 base_keys = set(base_idx.keys())
200 head_keys = set(head_idx.keys())
201
202 changes = []
203
204 for name in sorted(head_keys - base_keys):
205 changes.append({"category": name, "change_type": "added_category"})
206
207 for name in sorted(base_keys - head_keys):
208 changes.append({"category": name, "change_type": "removed_category"})
209
210 return changes
211
212
21385def write_github_output(name, value):
21486 """Write a value to $GITHUB_OUTPUT."""
21587 output_file = os.environ.get("GITHUB_OUTPUT")
@@ -218,123 +90,113 @@ def write_github_output(name, value):
21890 f.write(f"{name}={value}\n")
21991
22092
93def fmt_path(key):
94 """Format a tuple key as a readable path."""
95 return " → ".join(key) if isinstance(key, tuple) else key
96
97
22198def write_step_summary(diff_result):
222 """Write a Markdown summary to $GITHUB_STEP_SUMMARY."""
99 """Write a bullet-point Markdown summary to $GITHUB_STEP_SUMMARY."""
223100 summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
224101 if not summary_file:
225102 return
226103
227104 lines = ["## YAML Diff Analysis\n"]
228
229 added = diff_result["services"]["added"]
230 removed = diff_result["services"]["removed"]
231 modified = diff_result["services"]["modified"]
232 section_changes = diff_result["sections"]
233 category_changes = diff_result["categories"]
234
235 if not added and not removed and not modified and not section_changes and not category_changes:
236 lines.append("No changes detected in `awesome-privacy.yml`.\n")
105 bullets = []
106
107 for svc in diff_result["services"]["added"]:
108 bullets.append(f"- Added **{svc['service']}** in {svc['category']} → {svc['section']}")
109 for svc in diff_result["services"]["removed"]:
110 bullets.append(f"- Removed **{svc['service']}** from {svc['category']} → {svc['section']}")
111 for svc in diff_result["services"]["modified"]:
112 fields = ", ".join(f"`{f}`" for f in svc["changed_fields"])
113 bullets.append(f"- Modified {fields} in {svc['category']} → {svc['section']} → {svc['service']}")
114 for change in diff_result["sections"]:
115 ct = change["change_type"]
116 path = f"{change['category']} → {change['section']}"
117 if ct == "added_section":
118 bullets.append(f"- Added section **{change['section']}** in {change['category']}")
119 elif ct == "removed_section":
120 bullets.append(f"- Removed section **{change['section']}** from {change['category']}")
121 else:
122 fields = ", ".join(f"`{f}`" for f in change.get("changed_fields", []))
123 bullets.append(f"- Modified section metadata ({fields}) in {path}")
124 for change in diff_result["categories"]:
125 if change["change_type"] == "added_category":
126 bullets.append(f"- Added category **{change['category']}**")
127 else:
128 bullets.append(f"- Removed category **{change['category']}**")
129
130 if bullets:
131 lines.extend(bullets)
237132 else:
238 lines.append("| Type | Category | Section | Service | Details |")
239 lines.append("|------|----------|---------|---------|---------|")
240
241 for svc in added:
242 lines.append(f"| Added | {svc['category']} | {svc['section']} | {svc['service']} | New service |")
243
244 for svc in removed:
245 lines.append(f"| Removed | {svc['category']} | {svc['section']} | {svc['service']} | Service removed |")
246
247 for svc in modified:
248 fields = ", ".join(svc["changed_fields"])
249 lines.append(f"| Modified | {svc['category']} | {svc['section']} | {svc['service']} | Changed: {fields} |")
250
251 for change in section_changes:
252 detail = change["change_type"].replace("_", " ").title()
253 fields = ", ".join(change.get("changed_fields", []))
254 if fields:
255 detail += f" ({fields})"
256 lines.append(f"| Section | {change['category']} | {change['section']} | - | {detail} |")
257
258 for change in category_changes:
259 detail = change["change_type"].replace("_", " ").title()
260 lines.append(f"| Category | {change['category']} | - | - | {detail} |")
261
262 lines.append("")
133 lines.append("No changes detected in `awesome-privacy.yml`.")
263134
264135 with open(summary_file, "a") as f:
265136 f.write("\n".join(lines) + "\n")
266137
267138
268139def main():
269 parser = argparse.ArgumentParser(description="Analyze YAML diff for PR checks")
270 parser.add_argument("--base-ref", required=True, help="Base git ref (SHA or branch) to diff against")
140 parser = argparse.ArgumentParser()
141 parser.add_argument("--base-ref", required=True)
271142 args = parser.parse_args()
272143
273 # Load both versions
274 base_data = load_base_yaml(args.base_ref)
275 head_data = load_head_yaml()
276
277 # Compute diffs
278 added, removed, modified = diff_services(base_data, head_data)
279 section_changes = diff_sections(base_data, head_data)
280 category_changes = diff_categories(base_data, head_data)
144 base = load_base_yaml(args.base_ref)
145 head = load_head_yaml()
146
147 svc_added, svc_removed, svc_modified = diff_index(
148 build_index(base, 3), build_index(head, 3),
149 )
150 sec_added, sec_removed, sec_modified = diff_index(
151 build_index(base, 2), build_index(head, 2),
152 )
153 cat_added, cat_removed, _ = diff_index(
154 build_index(base, 1), build_index(head, 1),
155 )
156
157 added = [{"category": k[0], "section": k[1], "service": k[2],
158 "fields": build_index(head, 3)[k]} for k in svc_added]
159 removed = [{"category": k[0], "section": k[1], "service": k[2]} for k in svc_removed]
160 modified = [{"category": k[0], "section": k[1], "service": k[2],
161 "changed_fields": cf} for k, cf in svc_modified]
162
163 sections = []
164 for k in sec_added:
165 sections.append({"category": k[0], "section": k[1], "change_type": "added_section"})
166 for k in sec_removed:
167 sections.append({"category": k[0], "section": k[1], "change_type": "removed_section"})
168 for k, cf in sec_modified:
169 sections.append({"category": k[0], "section": k[1],
170 "change_type": "modified_section_metadata", "changed_fields": cf})
171
172 categories = []
173 for k in cat_added:
174 categories.append({"category": k, "change_type": "added_category"})
175 for k in cat_removed:
176 categories.append({"category": k, "change_type": "removed_category"})
281177
282 # Build result
283178 diff_result = {
284 "services": {
285 "added": added,
286 "removed": removed,
287 "modified": modified,
288 },
289 "sections": section_changes,
290 "categories": category_changes,
179 "services": {"added": added, "removed": removed, "modified": modified},
180 "sections": sections,
181 "categories": categories,
291182 }
292183
293 # Write diff JSON
294184 with open(DIFF_OUTPUT_PATH, "w") as f:
295185 json.dump(diff_result, f, indent=2)
296 print(f"Diff written to {DIFF_OUTPUT_PATH}")
297186
298 # Determine if there are service-level changes
299 has_service_changes = bool(added or removed or modified)
300 write_github_output("has_service_changes", str(has_service_changes).lower())
301
302 # Write step summary
187 write_github_output("has_service_changes", str(bool(added or removed or modified)).lower())
303188 write_step_summary(diff_result)
304189
305 # Enforce single-entry rule
306 service_change_count = len(added) + len(removed) + len(modified)
307
308 if service_change_count > 1:
309 print(red("Single-entry rule violation: PRs must contain only one service change."), file=sys.stderr)
310 print(red(f"Found {service_change_count} service-level changes:"), file=sys.stderr)
311 for svc in added:
312 print(f" + Added: {svc['category']} > {svc['section']} > {svc['service']}", file=sys.stderr)
313 for svc in removed:
314 print(f" - Removed: {svc['category']} > {svc['section']} > {svc['service']}", file=sys.stderr)
315 for svc in modified:
316 fields = ", ".join(svc["changed_fields"])
317 print(f" ~ Modified: {svc['category']} > {svc['section']} > {svc['service']} ({fields})", file=sys.stderr)
190 svc_count = len(added) + len(removed) + len(modified)
191 if svc_count > 1:
192 print(red(f"Single-entry rule violation: {svc_count} service changes found."), file=sys.stderr)
318193 sys.exit(EXIT_RULE_VIOLATION)
319
320 # If no service changes, check section-level changes
321 if service_change_count == 0 and len(section_changes) > 1:
322 print(red("Single-entry rule violation: PRs must contain only one section-level change."), file=sys.stderr)
323 print(red(f"Found {len(section_changes)} section-level changes:"), file=sys.stderr)
324 for change in section_changes:
325 detail = change["change_type"].replace("_", " ")
326 fields = change.get("changed_fields", [])
327 extra = f" ({', '.join(fields)})" if fields else ""
328 print(f" ~ {change['category']} > {change['section']}: {detail}{extra}", file=sys.stderr)
194 if svc_count == 0 and len(sections) > 1:
195 print(red(f"Single-entry rule violation: {len(sections)} section changes found."), file=sys.stderr)
329196 sys.exit(EXIT_RULE_VIOLATION)
330197
331 # Summary
332 total = service_change_count + len(section_changes) + len(category_changes)
333 if total == 0:
334 print(green("No changes detected in awesome-privacy.yml"))
335 else:
336 print(green(f"Single-entry rule passed. {service_change_count} service change(s), "
337 f"{len(section_changes)} section change(s), {len(category_changes)} category change(s)."))
198 print(green(f"Single-entry rule passed. {svc_count} service, "
199 f"{len(sections)} section, {len(categories)} category change(s)."))
338200 sys.exit(EXIT_PASS)
339201
340202
lib/checks/detect-changes.py +2 −6
@@ -1,6 +1,6 @@
11"""
22Detects which files changed between the PR base and HEAD.
3Sets GitHub Actions outputs: yaml_changed, non_yaml_changed.
3Sets GitHub Actions output: yaml_changed.
44"""
55
66import argparse
@@ -38,12 +38,8 @@ def main():
3838 print(f" {f}")
3939
4040 yaml_changed = YAML_FILE in changed_files
41 non_yaml_changed = any(f != YAML_FILE for f in changed_files)
42
4341 write_github_output("yaml_changed", str(yaml_changed).lower())
44 write_github_output("non_yaml_changed", str(non_yaml_changed).lower())
45
46 print(f"yaml_changed={yaml_changed}, non_yaml_changed={non_yaml_changed}")
42 print(f"yaml_changed={yaml_changed}")
4743
4844
4945if __name__ == "__main__":
lib/checks/format-comment.py +4 −13
@@ -7,12 +7,6 @@ import sys
77ARTIFACTS_DIR = "/tmp/artifacts"
88OUTPUT_DIR = "/tmp/pr-meta"
99
10README_MSG = (
11 "Do not edit the README directly. This file is auto-generated from the"
12 " content in `awesome-privacy.yml`, and so your changes will be overridden!"
13 " Instead, only modify the YAML file, and be sure to follow our Contributing Guidelines."
14)
15
1610CONTRIBUTING = "https://github.com/Lissy93/awesome-privacy/blob/main/.github/CONTRIBUTING.md"
1711
1812COMMENT_TEMPLATE = """<!-- pr-check-bot -->
@@ -38,12 +32,10 @@ def load_findings(filename):
3832 return []
3933
4034
41def collect_findings(readme_failed):
42 """Gather all findings in display order: meta, readme, data, project."""
35def collect_findings():
36 """Gather all findings in display order: compliance, data, project."""
4337 all_findings = []
44 all_findings.extend(load_findings("findings-meta.json"))
45 if readme_failed:
46 all_findings.append(README_MSG)
38 all_findings.extend(load_findings("findings-compliance.json"))
4739 all_findings.extend(load_findings("findings-data.json"))
4840 all_findings.extend(load_findings("findings-project.json"))
4941 return all_findings
@@ -78,7 +70,6 @@ def main():
7870 user = os.environ.get("PR_USER", "contributor")
7971 pr_number = os.environ.get("PR_NUMBER", "")
8072 run_id = os.environ.get("RUN_ID", "")
81 readme_failed = os.environ.get("README_FAILED", "false") == "true"
8273
8374 os.makedirs(OUTPUT_DIR, exist_ok=True)
8475
@@ -89,7 +80,7 @@ def main():
8980 with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f:
9081 f.write(run_id)
9182
92 findings = collect_findings(readme_failed)
83 findings = collect_findings()
9384 write_step_summary(findings)
9485
9586 if findings:
lib/checks/warn-non-yaml.py deleted −58
@@ -1,58 +0,0 @@
1"""
2Warns when a PR modifies files other than awesome-privacy.yml.
3This is expected for Website Update or Misc PRs, but may need extra review.
4"""
5
6import argparse
7import os
8import subprocess
9import sys
10
11PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
12
13YAML_FILE = "awesome-privacy.yml"
14
15# ANSI color helpers
16_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
17yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
18
19
20def main():
21 parser = argparse.ArgumentParser(description="Warn about non-YAML file changes")
22 parser.add_argument("--base-ref", required=True, help="Base git ref to diff against")
23 args = parser.parse_args()
24
25 result = subprocess.run(
26 ["git", "diff", "--name-only", f"{args.base_ref}..HEAD"],
27 capture_output=True, text=True, check=True,
28 cwd=PROJECT_ROOT,
29 )
30
31 changed_files = [f for f in result.stdout.strip().splitlines() if f]
32 non_yaml = [f for f in changed_files if f != YAML_FILE]
33
34 if not non_yaml:
35 return
36
37 print(yellow("This PR modifies files other than awesome-privacy.yml:"), file=sys.stderr)
38 for f in non_yaml:
39 print(f" {f}", file=sys.stderr)
40
41 # Write step summary
42 summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
43 if summary_file:
44 lines = [
45 "## Non-YAML Changes Warning\n",
46 "This PR modifies files other than `awesome-privacy.yml`:\n",
47 ]
48 for f in non_yaml:
49 lines.append(f"- `{f}`")
50 lines.append("")
51 lines.append("> **Note:** Most PRs should only modify `awesome-privacy.yml`. "
52 "Non-YAML changes may require additional review.\n")
53 with open(summary_file, "a") as f:
54 f.write("\n".join(lines) + "\n")
55
56
57if __name__ == "__main__":
58 main()