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:
4 pull_request: 4 pull_request:
5 branches: [main] 5 branches: [main]
6 types: [opened, edited, synchronize, reopened] 6 types: [opened, edited, synchronize, reopened]
7 paths:
8 - 'awesome-privacy.yml'
9 - '.github/README.md'
7 10
8permissions: 11permissions:
9 contents: read 12 contents: read
10 pull-requests: read 13 pull-requests: read
11 14
12jobs: 15jobs:
13 detect-changes: 16 pr-compliance:
14 name: Detect changes 17 name: PR Compliance
15 runs-on: ubuntu-latest 18 runs-on: ubuntu-latest
16 outputs:
17 yaml_changed: ${{ steps.changes.outputs.yaml_changed }}
18 non_yaml_changed: ${{ steps.changes.outputs.non_yaml_changed }}
19 steps: 19 steps:
20 - uses: actions/checkout@v4 20 - uses: actions/checkout@v4
21 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }} 21 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
22 - uses: actions/setup-python@v5 22 - uses: actions/setup-python@v5
23 with: 23 with:
24 python-version: "3.12" 24 python-version: "3.12"
25 - name: Detect changed files 25 - name: Check README edits
26 id: changes 26 id: readme
27 run: python lib/checks/detect-changes.py --base-ref ${{ github.event.pull_request.base.sha }} 27 continue-on-error: true
28 - name: Non-YAML changes warning 28 run: python lib/checks/check-readme-edits.py --base-ref ${{ github.event.pull_request.base.sha }}
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"
40 - name: Check PR metadata 29 - name: Check PR metadata
30 id: meta
41 env: 31 env:
42 PR_TITLE: ${{ github.event.pull_request.title }} 32 PR_TITLE: ${{ github.event.pull_request.title }}
43 PR_BODY: ${{ github.event.pull_request.body }} 33 PR_BODY: ${{ github.event.pull_request.body }}
44 PR_DRAFT: ${{ github.event.pull_request.draft }} 34 PR_DRAFT: ${{ github.event.pull_request.draft }}
35 README_FAILED: ${{ steps.readme.outcome == 'failure' && 'true' || 'false' }}
45 run: python lib/checks/check-pr-meta.py 36 run: python lib/checks/check-pr-meta.py
46 - name: Upload findings 37 - name: Upload findings
47 if: always() 38 if: always()
48 uses: actions/upload-artifact@v4 39 uses: actions/upload-artifact@v4
49 with: 40 with:
50 name: findings-meta 41 name: findings-compliance
51 path: /tmp/findings-meta.json 42 path: /tmp/findings-compliance.json
52 if-no-files-found: ignore 43 if-no-files-found: ignore
53 44 - name: Fail if critical
54 file-checks: 45 if: steps.readme.outcome == 'failure' || steps.meta.outcome == 'failure'
55 name: File checks 46 run: exit 1
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 }}
65 47
66 data-validation: 48 data-validation:
67 name: Data validation 49 name: Data Validation
68 needs: detect-changes
69 if: needs.detect-changes.outputs.yaml_changed == 'true'
70 runs-on: ubuntu-latest 50 runs-on: ubuntu-latest
51 outputs:
52 yaml_changed: ${{ steps.changes.outputs.yaml_changed }}
71 steps: 53 steps:
72 - uses: actions/checkout@v4 54 - uses: actions/checkout@v4
73 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }} 55 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
74 - uses: actions/setup-python@v5 56 - uses: actions/setup-python@v5
75 with: 57 with:
76 python-version: "3.12" 58 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
78 - name: Schema validation 65 - name: Schema validation
66 if: steps.changes.outputs.yaml_changed == 'true'
79 id: schema 67 id: schema
80 continue-on-error: true 68 continue-on-error: true
81 run: make validate 69 run: make validate
82 - name: YAML diff 70 - name: YAML diff
71 if: steps.changes.outputs.yaml_changed == 'true'
83 id: diff 72 id: diff
84 continue-on-error: true 73 continue-on-error: true
85 run: python lib/checks/check-yaml-diff.py --base-ref ${{ github.event.pull_request.base.sha }} 74 run: python lib/checks/check-yaml-diff.py --base-ref ${{ github.event.pull_request.base.sha }}
86 - name: Check additions 75 - name: Check additions
76 if: steps.changes.outputs.yaml_changed == 'true'
87 env: 77 env:
88 SCHEMA_OUTCOME: ${{ steps.schema.outcome }} 78 SCHEMA_OUTCOME: ${{ steps.schema.outcome }}
89 run: python lib/checks/check-additions.py 79 run: python lib/checks/check-additions.py
@@ -101,14 +91,14 @@ jobs:
101 name: findings-data 91 name: findings-data
102 path: /tmp/findings-data.json 92 path: /tmp/findings-data.json
103 if-no-files-found: ignore 93 if-no-files-found: ignore
104 - name: Fail if critical checks failed 94 - name: Fail if critical
105 if: steps.schema.outcome == 'failure' || steps.diff.outcome == 'failure' 95 if: steps.changes.outputs.yaml_changed == 'true' && (steps.schema.outcome == 'failure' || steps.diff.outcome == 'failure')
106 run: exit 1 96 run: exit 1
107 97
108 project-checks: 98 submission-eligibility:
109 name: Project checks 99 name: Submission Eligibility
110 needs: data-validation 100 needs: data-validation
111 if: "!cancelled() && needs.data-validation.result != 'skipped'" 101 if: "!cancelled() && needs.data-validation.outputs.yaml_changed == 'true'"
112 runs-on: ubuntu-latest 102 runs-on: ubuntu-latest
113 steps: 103 steps:
114 - uses: actions/checkout@v4 104 - uses: actions/checkout@v4
@@ -138,7 +128,7 @@ jobs:
138 summary: 128 summary:
139 name: Summary 129 name: Summary
140 if: always() 130 if: always()
141 needs: [detect-changes, pr-meta, file-checks, data-validation, project-checks] 131 needs: [pr-compliance, data-validation, submission-eligibility]
142 runs-on: ubuntu-latest 132 runs-on: ubuntu-latest
143 steps: 133 steps:
144 - uses: actions/checkout@v4 134 - uses: actions/checkout@v4
@@ -157,7 +147,6 @@ jobs:
157 PR_USER: ${{ github.event.pull_request.user.login }} 147 PR_USER: ${{ github.event.pull_request.user.login }}
158 PR_NUMBER: ${{ github.event.pull_request.number }} 148 PR_NUMBER: ${{ github.event.pull_request.number }}
159 RUN_ID: ${{ github.run_id }} 149 RUN_ID: ${{ github.run_id }}
160 README_FAILED: ${{ needs.file-checks.result == 'failure' && 'true' || 'false' }}
161 run: python lib/checks/format-comment.py 150 run: python lib/checks/format-comment.py
162 - name: Upload PR metadata 151 - name: Upload PR metadata
163 if: always() 152 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
5import re 5import re
6import sys 6import sys
7 7
8FINDINGS_PATH = "/tmp/findings-meta.json" 8FINDINGS_PATH = "/tmp/findings-compliance.json"
9 9
10BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"} 10BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"}
11 11
@@ -27,6 +27,11 @@ CHECKBOX_MSG = (
27 " to confirm that you've read the contributing guidelines, checked your submission," 27 " to confirm that you've read the contributing guidelines, checked your submission,"
28 " indicated your affiliation and agree to follow our CoC" 28 " indicated your affiliation and agree to follow our CoC"
29) 29)
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)
30 35
31 36
32def extract_section(body, header): 37def extract_section(body, header):
@@ -78,6 +83,13 @@ def check_checkboxes(body):
78 return None 83 return None
79 84
80 85
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
81def write_findings(findings): 93def write_findings(findings):
82 """Write the findings list to the output JSON file.""" 94 """Write the findings list to the output JSON file."""
83 with open(FINDINGS_PATH, "w") as f: 95 with open(FINDINGS_PATH, "w") as f:
@@ -91,6 +103,7 @@ def main():
91 title = os.environ.get("PR_TITLE", "") 103 title = os.environ.get("PR_TITLE", "")
92 body = os.environ.get("PR_BODY", "") 104 body = os.environ.get("PR_BODY", "")
93 draft = os.environ.get("PR_DRAFT", "false") 105 draft = os.environ.get("PR_DRAFT", "false")
106 readme_failed = os.environ.get("README_FAILED", "false")
94 107
95 finding = check_title(title) 108 finding = check_title(title)
96 if finding: 109 if finding:
@@ -111,6 +124,10 @@ def main():
111 finding = check_checkboxes(body) 124 finding = check_checkboxes(body)
112 if finding: 125 if finding:
113 findings.append(finding) 126 findings.append(finding)
127
128 finding = check_readme(readme_failed)
129 if finding:
130 findings.append(finding)
114 except Exception: 131 except Exception:
115 pass 132 pass
116 133
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""" 1"""Analyzes the diff between base and head versions of awesome-privacy.yml.
2Analyzes 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.
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.
5""" 3"""
6 4
7import argparse 5import argparse
@@ -12,22 +10,18 @@ import sys
12 10
13import yaml 11import yaml
14 12
15# Paths (relative to project root)
16PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 13PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
17DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") 14DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
18DIFF_OUTPUT_PATH = "/tmp/pr-diff.json" 15DIFF_OUTPUT_PATH = "/tmp/pr-diff.json"
19 16
20# Exit codes
21EXIT_PASS = 0 17EXIT_PASS = 0
22EXIT_RULE_VIOLATION = 1 18EXIT_RULE_VIOLATION = 1
23EXIT_RUNTIME_ERROR = 2 19EXIT_RUNTIME_ERROR = 2
24 20
25# ANSI color helpers
26_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR") 21_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
27red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) 22red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
28green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) 23green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
29yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s) 24yellow = (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)
31 25
32 26
33def load_base_yaml(base_ref): 27def load_base_yaml(base_ref):
@@ -35,13 +29,11 @@ def load_base_yaml(base_ref):
35 try: 29 try:
36 result = subprocess.run( 30 result = subprocess.run(
37 ["git", "show", f"{base_ref}:awesome-privacy.yml"], 31 ["git", "show", f"{base_ref}:awesome-privacy.yml"],
38 capture_output=True, text=True, check=True, 32 capture_output=True, text=True, check=True, cwd=PROJECT_ROOT,
39 cwd=PROJECT_ROOT,
40 ) 33 )
41 return yaml.safe_load(result.stdout) 34 return yaml.safe_load(result.stdout)
42 except subprocess.CalledProcessError: 35 except subprocess.CalledProcessError:
43 # File doesn't exist in base (completely new file) 36 print(yellow("awesome-privacy.yml not found in base ref, treating as empty"), file=sys.stderr)
44 print(yellow("Warning: awesome-privacy.yml not found in base ref, treating as empty"), file=sys.stderr)
45 return {"categories": []} 37 return {"categories": []}
46 except yaml.YAMLError as e: 38 except yaml.YAMLError as e:
47 print(red(f"Failed to parse base YAML: {e}"), file=sys.stderr) 39 print(red(f"Failed to parse base YAML: {e}"), file=sys.stderr)
@@ -51,165 +43,45 @@ def load_base_yaml(base_ref):
51def load_head_yaml(): 43def load_head_yaml():
52 """Load the YAML from the current working tree.""" 44 """Load the YAML from the current working tree."""
53 try: 45 try:
54 with open(DATA_PATH, "r") as f: 46 with open(DATA_PATH) as f:
55 return yaml.safe_load(f) 47 return yaml.safe_load(f)
56 except FileNotFoundError: 48 except (FileNotFoundError, yaml.YAMLError) as e:
57 print(red(f"File not found: {DATA_PATH}"), file=sys.stderr) 49 print(red(f"Failed to load head YAML: {e}"), 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)
61 sys.exit(EXIT_RUNTIME_ERROR) 50 sys.exit(EXIT_RUNTIME_ERROR)
62 51
63 52
64def build_service_index(data): 53def build_index(data, depth):
65 """Build a dict keyed by (category, section, service_name) -> service dict.""" 54 """Build a keyed index at the given depth (3=services, 2=sections, 1=categories)."""
66 index = {} 55 index = {}
67 for cat in data.get("categories", []): 56 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
69 for sec in cat.get("sections", []): 61 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
71 for svc in sec.get("services", []): 66 for svc in sec.get("services", []):
72 svc_name = svc.get("name", "") 67 index[(cn, sn, svc.get("name", ""))] = svc
73 key = (cat_name, sec_name, svc_name)
74 index[key] = svc
75 return index 68 return index
76 69
77 70
78def build_section_index(data): 71def diff_index(base_idx, head_idx):
79 """Build a dict keyed by (category, section) -> section metadata (excluding services).""" 72 """Return (added_keys, removed_keys, modified_keys_with_changed_fields)."""
80 index = {} 73 base_keys, head_keys = set(base_idx), set(head_idx)
81 for cat in data.get("categories", []): 74 added = sorted(head_keys - base_keys)
82 cat_name = cat.get("name", "") 75 removed = sorted(base_keys - head_keys)
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
126 modified = [] 76 modified = []
127 for key in sorted(base_keys & head_keys): 77 for key in sorted(base_keys & head_keys):
128 base_svc = base_idx[key] 78 if base_idx[key] != head_idx[key]:
129 head_svc = head_idx[key] 79 all_fields = set(base_idx[key]) | set(head_idx[key])
130 if base_svc != head_svc: 80 changed = sorted(f for f in all_fields if base_idx[key].get(f) != head_idx[key].get(f))
131 changed_fields = [] 81 modified.append((key, changed))
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
145 return added, removed, modified 82 return added, removed, modified
146 83
147 84
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
213def write_github_output(name, value): 85def write_github_output(name, value):
214 """Write a value to $GITHUB_OUTPUT.""" 86 """Write a value to $GITHUB_OUTPUT."""
215 output_file = os.environ.get("GITHUB_OUTPUT") 87 output_file = os.environ.get("GITHUB_OUTPUT")
@@ -218,123 +90,113 @@ def write_github_output(name, value):
218 f.write(f"{name}={value}\n") 90 f.write(f"{name}={value}\n")
219 91
220 92
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
221def write_step_summary(diff_result): 98def 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."""
223 summary_file = os.environ.get("GITHUB_STEP_SUMMARY") 100 summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
224 if not summary_file: 101 if not summary_file:
225 return 102 return
226 103
227 lines = ["## YAML Diff Analysis\n"] 104 lines = ["## YAML Diff Analysis\n"]
228 105 bullets = []
229 added = diff_result["services"]["added"] 106
230 removed = diff_result["services"]["removed"] 107 for svc in diff_result["services"]["added"]:
231 modified = diff_result["services"]["modified"] 108 bullets.append(f"- Added **{svc['service']}** in {svc['category']} → {svc['section']}")
232 section_changes = diff_result["sections"] 109 for svc in diff_result["services"]["removed"]:
233 category_changes = diff_result["categories"] 110 bullets.append(f"- Removed **{svc['service']}** from {svc['category']} → {svc['section']}")
234 111 for svc in diff_result["services"]["modified"]:
235 if not added and not removed and not modified and not section_changes and not category_changes: 112 fields = ", ".join(f"`{f}`" for f in svc["changed_fields"])
236 lines.append("No changes detected in `awesome-privacy.yml`.\n") 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)
237 else: 132 else:
238 lines.append("| Type | Category | Section | Service | Details |") 133 lines.append("No changes detected in `awesome-privacy.yml`.")
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("")
263 134
264 with open(summary_file, "a") as f: 135 with open(summary_file, "a") as f:
265 f.write("\n".join(lines) + "\n") 136 f.write("\n".join(lines) + "\n")
266 137
267 138
268def main(): 139def main():
269 parser = argparse.ArgumentParser(description="Analyze YAML diff for PR checks") 140 parser = argparse.ArgumentParser()
270 parser.add_argument("--base-ref", required=True, help="Base git ref (SHA or branch) to diff against") 141 parser.add_argument("--base-ref", required=True)
271 args = parser.parse_args() 142 args = parser.parse_args()
272 143
273 # Load both versions 144 base = load_base_yaml(args.base_ref)
274 base_data = load_base_yaml(args.base_ref) 145 head = load_head_yaml()
275 head_data = load_head_yaml() 146
276 147 svc_added, svc_removed, svc_modified = diff_index(
277 # Compute diffs 148 build_index(base, 3), build_index(head, 3),
278 added, removed, modified = diff_services(base_data, head_data) 149 )
279 section_changes = diff_sections(base_data, head_data) 150 sec_added, sec_removed, sec_modified = diff_index(
280 category_changes = diff_categories(base_data, head_data) 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"})
281 177
282 # Build result
283 diff_result = { 178 diff_result = {
284 "services": { 179 "services": {"added": added, "removed": removed, "modified": modified},
285 "added": added, 180 "sections": sections,
286 "removed": removed, 181 "categories": categories,
287 "modified": modified,
288 },
289 "sections": section_changes,
290 "categories": category_changes,
291 } 182 }
292 183
293 # Write diff JSON
294 with open(DIFF_OUTPUT_PATH, "w") as f: 184 with open(DIFF_OUTPUT_PATH, "w") as f:
295 json.dump(diff_result, f, indent=2) 185 json.dump(diff_result, f, indent=2)
296 print(f"Diff written to {DIFF_OUTPUT_PATH}")
297 186
298 # Determine if there are service-level changes 187 write_github_output("has_service_changes", str(bool(added or removed or modified)).lower())
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
303 write_step_summary(diff_result) 188 write_step_summary(diff_result)
304 189
305 # Enforce single-entry rule 190 svc_count = len(added) + len(removed) + len(modified)
306 service_change_count = len(added) + len(removed) + len(modified) 191 if svc_count > 1:
307 192 print(red(f"Single-entry rule violation: {svc_count} service changes found."), file=sys.stderr)
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)
318 sys.exit(EXIT_RULE_VIOLATION) 193 sys.exit(EXIT_RULE_VIOLATION)
319 194 if svc_count == 0 and len(sections) > 1:
320 # If no service changes, check section-level changes 195 print(red(f"Single-entry rule violation: {len(sections)} section changes found."), file=sys.stderr)
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)
329 sys.exit(EXIT_RULE_VIOLATION) 196 sys.exit(EXIT_RULE_VIOLATION)
330 197
331 # Summary 198 print(green(f"Single-entry rule passed. {svc_count} service, "
332 total = service_change_count + len(section_changes) + len(category_changes) 199 f"{len(sections)} section, {len(categories)} category change(s)."))
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)."))
338 sys.exit(EXIT_PASS) 200 sys.exit(EXIT_PASS)
339 201
340 202
lib/checks/detect-changes.py +2 −6
@@ -1,6 +1,6 @@
1""" 1"""
2Detects which files changed between the PR base and HEAD. 2Detects which files changed between the PR base and HEAD.
3Sets GitHub Actions outputs: yaml_changed, non_yaml_changed. 3Sets GitHub Actions output: yaml_changed.
4""" 4"""
5 5
6import argparse 6import argparse
@@ -38,12 +38,8 @@ def main():
38 print(f" {f}") 38 print(f" {f}")
39 39
40 yaml_changed = YAML_FILE in changed_files 40 yaml_changed = YAML_FILE in changed_files
41 non_yaml_changed = any(f != YAML_FILE for f in changed_files)
42
43 write_github_output("yaml_changed", str(yaml_changed).lower()) 41 write_github_output("yaml_changed", str(yaml_changed).lower())
44 write_github_output("non_yaml_changed", str(non_yaml_changed).lower()) 42 print(f"yaml_changed={yaml_changed}")
45
46 print(f"yaml_changed={yaml_changed}, non_yaml_changed={non_yaml_changed}")
47 43
48 44
49if __name__ == "__main__": 45if __name__ == "__main__":
lib/checks/format-comment.py +4 −13
@@ -7,12 +7,6 @@ import sys
7ARTIFACTS_DIR = "/tmp/artifacts" 7ARTIFACTS_DIR = "/tmp/artifacts"
8OUTPUT_DIR = "/tmp/pr-meta" 8OUTPUT_DIR = "/tmp/pr-meta"
9 9
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
16CONTRIBUTING = "https://github.com/Lissy93/awesome-privacy/blob/main/.github/CONTRIBUTING.md" 10CONTRIBUTING = "https://github.com/Lissy93/awesome-privacy/blob/main/.github/CONTRIBUTING.md"
17 11
18COMMENT_TEMPLATE = """<!-- pr-check-bot --> 12COMMENT_TEMPLATE = """<!-- pr-check-bot -->
@@ -38,12 +32,10 @@ def load_findings(filename):
38 return [] 32 return []
39 33
40 34
41def collect_findings(readme_failed): 35def collect_findings():
42 """Gather all findings in display order: meta, readme, data, project.""" 36 """Gather all findings in display order: compliance, data, project."""
43 all_findings = [] 37 all_findings = []
44 all_findings.extend(load_findings("findings-meta.json")) 38 all_findings.extend(load_findings("findings-compliance.json"))
45 if readme_failed:
46 all_findings.append(README_MSG)
47 all_findings.extend(load_findings("findings-data.json")) 39 all_findings.extend(load_findings("findings-data.json"))
48 all_findings.extend(load_findings("findings-project.json")) 40 all_findings.extend(load_findings("findings-project.json"))
49 return all_findings 41 return all_findings
@@ -78,7 +70,6 @@ def main():
78 user = os.environ.get("PR_USER", "contributor") 70 user = os.environ.get("PR_USER", "contributor")
79 pr_number = os.environ.get("PR_NUMBER", "") 71 pr_number = os.environ.get("PR_NUMBER", "")
80 run_id = os.environ.get("RUN_ID", "") 72 run_id = os.environ.get("RUN_ID", "")
81 readme_failed = os.environ.get("README_FAILED", "false") == "true"
82 73
83 os.makedirs(OUTPUT_DIR, exist_ok=True) 74 os.makedirs(OUTPUT_DIR, exist_ok=True)
84 75
@@ -89,7 +80,7 @@ def main():
89 with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f: 80 with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f:
90 f.write(run_id) 81 f.write(run_id)
91 82
92 findings = collect_findings(readme_failed) 83 findings = collect_findings()
93 write_step_summary(findings) 84 write_step_summary(findings)
94 85
95 if findings: 86 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()