Commit adc0df53a5
Unsigned
Layout: unified · split
.github/workflows/pr-check.yml added +125
| @@ -0,0 +1,125 @@ | ||
| 1 | name: PR Check | |
| 2 | ||
| 3 | on: | |
| 4 | pull_request: | |
| 5 | branches: [main] | |
| 6 | types: [opened, edited, synchronize, reopened] | |
| 7 | ||
| 8 | permissions: | |
| 9 | contents: read | |
| 10 | pull-requests: read | |
| 11 | ||
| 12 | jobs: | |
| 13 | check-pr: | |
| 14 | name: Check PR | |
| 15 | runs-on: ubuntu-latest | |
| 16 | ||
| 17 | steps: | |
| 18 | - uses: actions/checkout@v4 | |
| 19 | with: | |
| 20 | fetch-depth: 0 | |
| 21 | ||
| 22 | - name: Fetch base ref | |
| 23 | run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }} | |
| 24 | ||
| 25 | - uses: actions/setup-python@v5 | |
| 26 | with: | |
| 27 | python-version: "3.12" | |
| 28 | ||
| 29 | - run: pip install -q -r lib/requirements.txt | |
| 30 | ||
| 31 | - name: Detect changed files | |
| 32 | id: changes | |
| 33 | run: python lib/checks/detect-changes.py --base-ref ${{ github.event.pull_request.base.sha }} | |
| 34 | ||
| 35 | - name: Check for direct README edits | |
| 36 | id: readme | |
| 37 | run: python lib/checks/check-readme-edits.py --base-ref ${{ github.event.pull_request.base.sha }} | |
| 38 | ||
| 39 | - name: Schema validation | |
| 40 | id: schema | |
| 41 | if: steps.changes.outputs.yaml_changed == 'true' | |
| 42 | run: make validate | |
| 43 | ||
| 44 | - name: YAML diff analysis | |
| 45 | id: diff | |
| 46 | if: steps.changes.outputs.yaml_changed == 'true' | |
| 47 | run: python lib/checks/check-yaml-diff.py --base-ref ${{ github.event.pull_request.base.sha }} | |
| 48 | ||
| 49 | - name: Link validation | |
| 50 | if: steps.changes.outputs.yaml_changed == 'true' && steps.diff.outputs.has_service_changes == 'true' | |
| 51 | run: python lib/checks/check-links.py --diff-json /tmp/pr-diff.json | |
| 52 | ||
| 53 | - name: PR template check | |
| 54 | id: template | |
| 55 | env: | |
| 56 | PR_BODY: ${{ github.event.pull_request.body }} | |
| 57 | run: python lib/checks/check-template.py | |
| 58 | ||
| 59 | - name: Non-YAML changes warning | |
| 60 | if: steps.changes.outputs.non_yaml_changed == 'true' | |
| 61 | run: python lib/checks/warn-non-yaml.py --base-ref ${{ github.event.pull_request.base.sha }} | |
| 62 | ||
| 63 | - name: Save PR metadata | |
| 64 | if: always() | |
| 65 | run: | | |
| 66 | mkdir -p /tmp/pr-meta | |
| 67 | echo "${{ github.event.pull_request.number }}" > /tmp/pr-meta/number.txt | |
| 68 | echo "${{ github.run_id }}" > /tmp/pr-meta/run-id.txt | |
| 69 | ||
| 70 | - name: Build failure comment | |
| 71 | if: failure() | |
| 72 | run: | | |
| 73 | cat > /tmp/pr-meta/comment.md << 'HEADER' | |
| 74 | <!-- pr-check-bot --> | |
| 75 | > [!CAUTION] | |
| 76 | > ## PR check failed | |
| 77 | HEADER | |
| 78 | ||
| 79 | if [ "${{ steps.readme.outcome }}" = "failure" ]; then | |
| 80 | cat >> /tmp/pr-meta/comment.md << 'EOF' | |
| 81 | ||
| 82 | ### Direct README edits | |
| 83 | The auto-generated section of the README must not be edited directly. | |
| 84 | Please make your changes in `awesome-privacy.yml` instead — the README is regenerated from it. | |
| 85 | EOF | |
| 86 | fi | |
| 87 | ||
| 88 | if [ "${{ steps.schema.outcome }}" = "failure" ]; then | |
| 89 | cat >> /tmp/pr-meta/comment.md << 'EOF' | |
| 90 | ||
| 91 | ### Schema validation failed | |
| 92 | `awesome-privacy.yml` does not conform to the expected schema. | |
| 93 | Please check your YAML against the structure defined in `lib/schema.json`. | |
| 94 | EOF | |
| 95 | fi | |
| 96 | ||
| 97 | if [ "${{ steps.diff.outcome }}" = "failure" ]; then | |
| 98 | cat >> /tmp/pr-meta/comment.md << 'EOF' | |
| 99 | ||
| 100 | ### Single-entry rule | |
| 101 | Each PR should add, modify, or remove only **one** service at a time. | |
| 102 | If you need to change multiple services, please split them into separate PRs. | |
| 103 | EOF | |
| 104 | fi | |
| 105 | ||
| 106 | if [ "${{ steps.template.outcome }}" = "failure" ]; then | |
| 107 | cat >> /tmp/pr-meta/comment.md << 'EOF' | |
| 108 | ||
| 109 | ### PR template incomplete | |
| 110 | Your PR description is missing required sections. | |
| 111 | Please fill out the **Type**, **Changes**, and **Checklist** sections of the PR template. | |
| 112 | EOF | |
| 113 | fi | |
| 114 | ||
| 115 | # Footer with link to logs | |
| 116 | printf '\n---\n*See the [workflow logs](%s/%s/actions/runs/%s) for full details.*\n' \ | |
| 117 | "${{ github.server_url }}" "${{ github.repository }}" "${{ github.run_id }}" \ | |
| 118 | >> /tmp/pr-meta/comment.md | |
| 119 | ||
| 120 | - name: Upload PR metadata | |
| 121 | if: always() | |
| 122 | uses: actions/upload-artifact@v4 | |
| 123 | with: | |
| 124 | name: pr-meta | |
| 125 | path: /tmp/pr-meta/ | |
.github/workflows/pr-comment.yml added +105
| @@ -0,0 +1,105 @@ | ||
| 1 | name: PR Comment | |
| 2 | ||
| 3 | on: | |
| 4 | workflow_run: | |
| 5 | workflows: ["PR Check"] | |
| 6 | types: [completed] | |
| 7 | ||
| 8 | permissions: | |
| 9 | actions: read | |
| 10 | pull-requests: write | |
| 11 | ||
| 12 | jobs: | |
| 13 | comment: | |
| 14 | name: Post PR comment | |
| 15 | runs-on: ubuntu-latest | |
| 16 | if: github.event.workflow_run.event == 'pull_request' | |
| 17 | ||
| 18 | steps: | |
| 19 | - name: Download PR metadata | |
| 20 | id: download | |
| 21 | continue-on-error: true | |
| 22 | uses: actions/download-artifact@v4 | |
| 23 | with: | |
| 24 | name: pr-meta | |
| 25 | path: pr-meta | |
| 26 | run-id: ${{ github.event.workflow_run.id }} | |
| 27 | github-token: ${{ secrets.GITHUB_TOKEN }} | |
| 28 | ||
| 29 | - name: Post or update comment | |
| 30 | uses: actions/github-script@v7 | |
| 31 | with: | |
| 32 | github-token: ${{ secrets.BOT_TOKEN || secrets.GITHUB_TOKEN }} | |
| 33 | script: | | |
| 34 | const fs = require('fs'); | |
| 35 | const marker = '<!-- pr-check-bot -->'; | |
| 36 | const conclusion = context.payload.workflow_run.conclusion; | |
| 37 | ||
| 38 | // Determine the PR number | |
| 39 | let prNumber; | |
| 40 | const numberFile = 'pr-meta/number.txt'; | |
| 41 | if (fs.existsSync(numberFile)) { | |
| 42 | prNumber = parseInt(fs.readFileSync(numberFile, 'utf8').trim()); | |
| 43 | } else { | |
| 44 | // workflow_run.pull_requests is empty for fork PRs, so | |
| 45 | // fall back to searching by head SHA if needed | |
| 46 | const prs = context.payload.workflow_run.pull_requests; | |
| 47 | if (prs && prs.length > 0) { | |
| 48 | prNumber = prs[0].number; | |
| 49 | } else { | |
| 50 | const headSha = context.payload.workflow_run.head_sha; | |
| 51 | const { data: prList } = await github.rest.pulls.list({ | |
| 52 | owner: context.repo.owner, | |
| 53 | repo: context.repo.repo, | |
| 54 | state: 'open', | |
| 55 | sort: 'updated', | |
| 56 | direction: 'desc', | |
| 57 | per_page: 10, | |
| 58 | }); | |
| 59 | const match = prList.find(pr => pr.head.sha === headSha); | |
| 60 | if (!match) { | |
| 61 | console.log(`No open PR found for SHA ${headSha} — skipping comment.`); | |
| 62 | return; | |
| 63 | } | |
| 64 | prNumber = match.number; | |
| 65 | } | |
| 66 | } | |
| 67 | ||
| 68 | // Find existing bot comment | |
| 69 | const { data: comments } = await github.rest.issues.listComments({ | |
| 70 | owner: context.repo.owner, | |
| 71 | repo: context.repo.repo, | |
| 72 | issue_number: prNumber, | |
| 73 | }); | |
| 74 | const existing = comments.find(c => c.body.includes(marker)); | |
| 75 | ||
| 76 | if (conclusion === 'failure') { | |
| 77 | const commentFile = 'pr-meta/comment.md'; | |
| 78 | if (!fs.existsSync(commentFile)) { | |
| 79 | console.log('No comment.md found — skipping comment.'); | |
| 80 | return; | |
| 81 | } | |
| 82 | const body = fs.readFileSync(commentFile, 'utf8').trim(); | |
| 83 | if (existing) { | |
| 84 | await github.rest.issues.updateComment({ | |
| 85 | owner: context.repo.owner, | |
| 86 | repo: context.repo.repo, | |
| 87 | comment_id: existing.id, | |
| 88 | body, | |
| 89 | }); | |
| 90 | } else { | |
| 91 | await github.rest.issues.createComment({ | |
| 92 | owner: context.repo.owner, | |
| 93 | repo: context.repo.repo, | |
| 94 | issue_number: prNumber, | |
| 95 | body, | |
| 96 | }); | |
| 97 | } | |
| 98 | } else if (existing) { | |
| 99 | // Checks passed — remove stale failure comment | |
| 100 | await github.rest.issues.deleteComment({ | |
| 101 | owner: context.repo.owner, | |
| 102 | repo: context.repo.repo, | |
| 103 | comment_id: existing.id, | |
| 104 | }); | |
| 105 | } | |
lib/checks/__pycache__/check-links.cpython-310.pyc added
Binary file not shown.
lib/checks/__pycache__/check-readme-edits.cpython-310.pyc added
Binary file not shown.
lib/checks/__pycache__/check-template.cpython-310.pyc added
Binary file not shown.
lib/checks/__pycache__/check-yaml-diff.cpython-310.pyc added
Binary file not shown.
lib/checks/__pycache__/detect-changes.cpython-310.pyc added
Binary file not shown.
lib/checks/__pycache__/warn-non-yaml.cpython-310.pyc added
Binary file not shown.
lib/checks/check-links.py added +211
| @@ -0,0 +1,211 @@ | ||
| 1 | """ | |
| 2 | Validates URLs and metadata for added/modified services in a PR. | |
| 3 | Reads the diff JSON produced by check-yaml-diff.py. | |
| 4 | All checks are warnings only -- this script never fails (exit 0). | |
| 5 | """ | |
| 6 | ||
| 7 | import argparse | |
| 8 | import json | |
| 9 | import os | |
| 10 | import sys | |
| 11 | ||
| 12 | import requests | |
| 13 | import yaml | |
| 14 | ||
| 15 | # Paths (relative to project root) | |
| 16 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| 17 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | |
| 18 | ||
| 19 | # Exit codes | |
| 20 | EXIT_PASS = 0 | |
| 21 | EXIT_RUNTIME_ERROR = 2 | |
| 22 | ||
| 23 | # ANSI color helpers | |
| 24 | _use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | |
| 25 | red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) | |
| 26 | green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) | |
| 27 | yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s) | |
| 28 | ||
| 29 | TIMEOUT = 10 | |
| 30 | USER_AGENT = "awesome-privacy-ci/1.0" | |
| 31 | DESC_MIN_LEN = 50 | |
| 32 | DESC_MAX_LEN = 250 | |
| 33 | ||
| 34 | ||
| 35 | def 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 | ||
| 61 | def 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 | ||
| 111 | def 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 | ||
| 128 | def 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 | ||
| 155 | def 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 | ||
| 210 | if __name__ == "__main__": | |
| 211 | main() | |
lib/checks/check-readme-edits.py added +123
| @@ -0,0 +1,123 @@ | ||
| 1 | """ | |
| 2 | Fails if the PR directly edits the auto-generated section of the README. | |
| 3 | The generated section is between <!-- awesome-privacy-start --> and <!-- awesome-privacy-end -->. | |
| 4 | """ | |
| 5 | ||
| 6 | import argparse | |
| 7 | import os | |
| 8 | import re | |
| 9 | import subprocess | |
| 10 | import sys | |
| 11 | ||
| 12 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| 13 | README_PATH = ".github/README.md" | |
| 14 | README_ABS = os.path.join(PROJECT_ROOT, README_PATH) | |
| 15 | ||
| 16 | # Exit codes | |
| 17 | EXIT_PASS = 0 | |
| 18 | EXIT_FAIL = 1 | |
| 19 | EXIT_RUNTIME_ERROR = 2 | |
| 20 | ||
| 21 | # ANSI color helpers | |
| 22 | _use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | |
| 23 | red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) | |
| 24 | green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) | |
| 25 | ||
| 26 | ||
| 27 | def get_changed_files(base_ref): | |
| 28 | result = subprocess.run( | |
| 29 | ["git", "diff", "--name-only", f"{base_ref}..HEAD"], | |
| 30 | capture_output=True, text=True, check=True, | |
| 31 | cwd=PROJECT_ROOT, | |
| 32 | ) | |
| 33 | return result.stdout.strip().splitlines() | |
| 34 | ||
| 35 | ||
| 36 | def get_marker_lines(): | |
| 37 | """Find the line numbers of the start/end markers in the README.""" | |
| 38 | try: | |
| 39 | with open(README_ABS, "r") as f: | |
| 40 | lines = f.readlines() | |
| 41 | except FileNotFoundError: | |
| 42 | return None, None | |
| 43 | ||
| 44 | start_line = None | |
| 45 | end_line = None | |
| 46 | for i, line in enumerate(lines, start=1): | |
| 47 | if "<!-- awesome-privacy-start -->" in line: | |
| 48 | start_line = i | |
| 49 | if "<!-- awesome-privacy-end -->" in line: | |
| 50 | end_line = i | |
| 51 | ||
| 52 | return start_line, end_line | |
| 53 | ||
| 54 | ||
| 55 | def get_changed_line_numbers(base_ref): | |
| 56 | """Parse git diff hunk headers to find which lines were changed in the README.""" | |
| 57 | result = subprocess.run( | |
| 58 | ["git", "diff", "-U0", f"{base_ref}..HEAD", "--", README_PATH], | |
| 59 | capture_output=True, text=True, check=True, | |
| 60 | cwd=PROJECT_ROOT, | |
| 61 | ) | |
| 62 | ||
| 63 | changed_lines = [] | |
| 64 | for line in result.stdout.splitlines(): | |
| 65 | # Match hunk headers like @@ -10,5 +12,7 @@ | |
| 66 | match = re.match(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", line) | |
| 67 | if match: | |
| 68 | start = int(match.group(1)) | |
| 69 | count = int(match.group(2)) if match.group(2) else 1 | |
| 70 | for n in range(start, start + count): | |
| 71 | changed_lines.append(n) | |
| 72 | ||
| 73 | return changed_lines | |
| 74 | ||
| 75 | ||
| 76 | def write_step_summary(): | |
| 77 | summary_file = os.environ.get("GITHUB_STEP_SUMMARY") | |
| 78 | if not summary_file: | |
| 79 | return | |
| 80 | ||
| 81 | lines = [ | |
| 82 | "## Direct README Edit Detected\n", | |
| 83 | "This PR directly modifies the auto-generated section of `.github/README.md` " | |
| 84 | "(between `<!-- awesome-privacy-start -->` and `<!-- awesome-privacy-end -->`).\n", | |
| 85 | "**Please edit `awesome-privacy.yml` instead.** The README is regenerated automatically from that file.\n", | |
| 86 | ] | |
| 87 | ||
| 88 | with open(summary_file, "a") as f: | |
| 89 | f.write("\n".join(lines) + "\n") | |
| 90 | ||
| 91 | ||
| 92 | def main(): | |
| 93 | parser = argparse.ArgumentParser(description="Check for direct README edits to generated section") | |
| 94 | parser.add_argument("--base-ref", required=True, help="Base git ref to diff against") | |
| 95 | args = parser.parse_args() | |
| 96 | ||
| 97 | # Skip if README wasn't changed | |
| 98 | changed_files = get_changed_files(args.base_ref) | |
| 99 | if README_PATH not in changed_files: | |
| 100 | print(green("README not modified, skipping.")) | |
| 101 | sys.exit(EXIT_PASS) | |
| 102 | ||
| 103 | # Find marker lines | |
| 104 | start_line, end_line = get_marker_lines() | |
| 105 | if start_line is None or end_line is None: | |
| 106 | print("Could not find generated-section markers in README, skipping check.") | |
| 107 | sys.exit(EXIT_PASS) | |
| 108 | ||
| 109 | # Check if any changed lines fall within the generated section | |
| 110 | changed_lines = get_changed_line_numbers(args.base_ref) | |
| 111 | for line_num in changed_lines: | |
| 112 | if start_line <= line_num <= end_line: | |
| 113 | print(red("Direct edits to the generated section of the README are not allowed."), file=sys.stderr) | |
| 114 | print(red("Edit awesome-privacy.yml instead and the README will be regenerated."), file=sys.stderr) | |
| 115 | write_step_summary() | |
| 116 | sys.exit(EXIT_FAIL) | |
| 117 | ||
| 118 | print(green("README changes are outside the generated section, OK.")) | |
| 119 | sys.exit(EXIT_PASS) | |
| 120 | ||
| 121 | ||
| 122 | if __name__ == "__main__": | |
| 123 | main() | |
lib/checks/check-template.py added +206
| @@ -0,0 +1,206 @@ | ||
| 1 | """ | |
| 2 | Checks PR body against the pull request template. | |
| 3 | Reads the PR body from the PR_BODY environment variable (avoids shell injection). | |
| 4 | Exits with code 1 for severe violations (empty body, missing required sections). | |
| 5 | """ | |
| 6 | ||
| 7 | import os | |
| 8 | import re | |
| 9 | import sys | |
| 10 | ||
| 11 | # Exit codes | |
| 12 | EXIT_PASS = 0 | |
| 13 | EXIT_FAIL = 1 | |
| 14 | EXIT_RUNTIME_ERROR = 2 | |
| 15 | ||
| 16 | # Warnings that should cause a hard failure | |
| 17 | CRITICAL_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") | |
| 29 | red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) | |
| 30 | green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) | |
| 31 | yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s) | |
| 32 | ||
| 33 | # Valid PR types from the template | |
| 34 | VALID_TYPES = {"Addition", "Amendment", "Removal", "Spelling or Grammar", "Website Update", "Misc"} | |
| 35 | ||
| 36 | # Raw template text that indicates an unfilled section | |
| 37 | RAW_TYPE_LINE = "Addition / Amendment / Removal / Spelling or Grammar / Website Update / Misc" | |
| 38 | ||
| 39 | ||
| 40 | def strip_html_comments(text): | |
| 41 | """Remove <!-- ... --> comments from text.""" | |
| 42 | return re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL).strip() | |
| 43 | ||
| 44 | ||
| 45 | def 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 | ||
| 54 | def 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 | ||
| 84 | def 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 | ||
| 100 | def 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 | ||
| 123 | def 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 | ||
| 128 | def 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 | ||
| 155 | def 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 | ||
| 205 | if __name__ == "__main__": | |
| 206 | main() | |
lib/checks/check-yaml-diff.py added +342
| @@ -0,0 +1,342 @@ | ||
| 1 | """ | |
| 2 | Analyzes the diff between base and head versions of awesome-privacy.yml. | |
| 3 | Enforces the single-entry rule: only one service addition/amendment/removal per PR. | |
| 4 | Outputs a JSON diff to /tmp/pr-diff.json and writes a step summary. | |
| 5 | """ | |
| 6 | ||
| 7 | import argparse | |
| 8 | import json | |
| 9 | import os | |
| 10 | import subprocess | |
| 11 | import sys | |
| 12 | ||
| 13 | import yaml | |
| 14 | ||
| 15 | # Paths (relative to project root) | |
| 16 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| 17 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | |
| 18 | DIFF_OUTPUT_PATH = "/tmp/pr-diff.json" | |
| 19 | ||
| 20 | # Exit codes | |
| 21 | EXIT_PASS = 0 | |
| 22 | EXIT_RULE_VIOLATION = 1 | |
| 23 | EXIT_RUNTIME_ERROR = 2 | |
| 24 | ||
| 25 | # ANSI color helpers | |
| 26 | _use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | |
| 27 | red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) | |
| 28 | green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) | |
| 29 | yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s) | |
| 30 | dim = (lambda s: f"\033[2m{s}\033[0m") if _use_color else (lambda s: s) | |
| 31 | ||
| 32 | ||
| 33 | def load_base_yaml(base_ref): | |
| 34 | """Load the YAML from the base ref using git show.""" | |
| 35 | try: | |
| 36 | result = subprocess.run( | |
| 37 | ["git", "show", f"{base_ref}:awesome-privacy.yml"], | |
| 38 | capture_output=True, text=True, check=True, | |
| 39 | cwd=PROJECT_ROOT, | |
| 40 | ) | |
| 41 | return yaml.safe_load(result.stdout) | |
| 42 | 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) | |
| 45 | return {"categories": []} | |
| 46 | except yaml.YAMLError as e: | |
| 47 | print(red(f"Failed to parse base YAML: {e}"), file=sys.stderr) | |
| 48 | sys.exit(EXIT_RUNTIME_ERROR) | |
| 49 | ||
| 50 | ||
| 51 | def load_head_yaml(): | |
| 52 | """Load the YAML from the current working tree.""" | |
| 53 | try: | |
| 54 | with open(DATA_PATH, "r") as f: | |
| 55 | 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) | |
| 61 | sys.exit(EXIT_RUNTIME_ERROR) | |
| 62 | ||
| 63 | ||
| 64 | def build_service_index(data): | |
| 65 | """Build a dict keyed by (category, section, service_name) -> service dict.""" | |
| 66 | index = {} | |
| 67 | for cat in data.get("categories", []): | |
| 68 | cat_name = cat.get("name", "") | |
| 69 | for sec in cat.get("sections", []): | |
| 70 | sec_name = sec.get("name", "") | |
| 71 | for svc in sec.get("services", []): | |
| 72 | svc_name = svc.get("name", "") | |
| 73 | key = (cat_name, sec_name, svc_name) | |
| 74 | index[key] = svc | |
| 75 | return index | |
| 76 | ||
| 77 | ||
| 78 | def 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 | ||
| 91 | def 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 | ||
| 101 | def 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 = [] | |
| 127 | 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 | ||
| 145 | return added, removed, modified | |
| 146 | ||
| 147 | ||
| 148 | def 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 | ||
| 194 | def 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 | ||
| 213 | def write_github_output(name, value): | |
| 214 | """Write a value to $GITHUB_OUTPUT.""" | |
| 215 | output_file = os.environ.get("GITHUB_OUTPUT") | |
| 216 | if output_file: | |
| 217 | with open(output_file, "a") as f: | |
| 218 | f.write(f"{name}={value}\n") | |
| 219 | ||
| 220 | ||
| 221 | def write_step_summary(diff_result): | |
| 222 | """Write a Markdown summary to $GITHUB_STEP_SUMMARY.""" | |
| 223 | summary_file = os.environ.get("GITHUB_STEP_SUMMARY") | |
| 224 | if not summary_file: | |
| 225 | return | |
| 226 | ||
| 227 | 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") | |
| 237 | 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("") | |
| 263 | ||
| 264 | with open(summary_file, "a") as f: | |
| 265 | f.write("\n".join(lines) + "\n") | |
| 266 | ||
| 267 | ||
| 268 | def 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") | |
| 271 | args = parser.parse_args() | |
| 272 | ||
| 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) | |
| 281 | ||
| 282 | # Build result | |
| 283 | diff_result = { | |
| 284 | "services": { | |
| 285 | "added": added, | |
| 286 | "removed": removed, | |
| 287 | "modified": modified, | |
| 288 | }, | |
| 289 | "sections": section_changes, | |
| 290 | "categories": category_changes, | |
| 291 | } | |
| 292 | ||
| 293 | # Write diff JSON | |
| 294 | with open(DIFF_OUTPUT_PATH, "w") as f: | |
| 295 | json.dump(diff_result, f, indent=2) | |
| 296 | print(f"Diff written to {DIFF_OUTPUT_PATH}") | |
| 297 | ||
| 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 | |
| 303 | write_step_summary(diff_result) | |
| 304 | ||
| 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) | |
| 318 | 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) | |
| 329 | sys.exit(EXIT_RULE_VIOLATION) | |
| 330 | ||
| 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).")) | |
| 338 | sys.exit(EXIT_PASS) | |
| 339 | ||
| 340 | ||
| 341 | if __name__ == "__main__": | |
| 342 | main() | |
lib/checks/detect-changes.py added +50
| @@ -0,0 +1,50 @@ | ||
| 1 | """ | |
| 2 | Detects which files changed between the PR base and HEAD. | |
| 3 | Sets GitHub Actions outputs: yaml_changed, non_yaml_changed. | |
| 4 | """ | |
| 5 | ||
| 6 | import argparse | |
| 7 | import os | |
| 8 | import subprocess | |
| 9 | import sys | |
| 10 | ||
| 11 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| 12 | ||
| 13 | YAML_FILE = "awesome-privacy.yml" | |
| 14 | ||
| 15 | ||
| 16 | def write_github_output(name, value): | |
| 17 | output_file = os.environ.get("GITHUB_OUTPUT") | |
| 18 | if output_file: | |
| 19 | with open(output_file, "a") as f: | |
| 20 | f.write(f"{name}={value}\n") | |
| 21 | ||
| 22 | ||
| 23 | def main(): | |
| 24 | parser = argparse.ArgumentParser(description="Detect changed files in a PR") | |
| 25 | parser.add_argument("--base-ref", required=True, help="Base git ref to diff against") | |
| 26 | args = parser.parse_args() | |
| 27 | ||
| 28 | result = subprocess.run( | |
| 29 | ["git", "diff", "--name-only", f"{args.base_ref}..HEAD"], | |
| 30 | capture_output=True, text=True, check=True, | |
| 31 | cwd=PROJECT_ROOT, | |
| 32 | ) | |
| 33 | ||
| 34 | changed_files = [f for f in result.stdout.strip().splitlines() if f] | |
| 35 | ||
| 36 | print("Changed files:") | |
| 37 | for f in changed_files: | |
| 38 | print(f" {f}") | |
| 39 | ||
| 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()) | |
| 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}") | |
| 47 | ||
| 48 | ||
| 49 | if __name__ == "__main__": | |
| 50 | main() | |
lib/checks/warn-non-yaml.py added +58
| @@ -0,0 +1,58 @@ | ||
| 1 | """ | |
| 2 | Warns when a PR modifies files other than awesome-privacy.yml. | |
| 3 | This is expected for Website Update or Misc PRs, but may need extra review. | |
| 4 | """ | |
| 5 | ||
| 6 | import argparse | |
| 7 | import os | |
| 8 | import subprocess | |
| 9 | import sys | |
| 10 | ||
| 11 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| 12 | ||
| 13 | YAML_FILE = "awesome-privacy.yml" | |
| 14 | ||
| 15 | # ANSI color helpers | |
| 16 | _use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | |
| 17 | yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s) | |
| 18 | ||
| 19 | ||
| 20 | def 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 | ||
| 57 | if __name__ == "__main__": | |
| 58 | main() | |
lib/requirements.txt +1
| @@ -1,2 +1,3 @@ | ||
| 1 | 1 | PyYAML==6.0.1 |
| 2 | 2 | jsonschema==4.23.0 |
| 3 | requests==2.32.3 | |
lib/schema.json +48 −21
| @@ -7,38 +7,64 @@ | ||
| 7 | 7 | "items": { |
| 8 | 8 | "type": "object", |
| 9 | 9 | "properties": { |
| 10 | "name": { "type": "string" }, | |
| 10 | "name": { "type": "string", "minLength": 1, "maxLength": 50 }, | |
| 11 | 11 | "sections": { |
| 12 | 12 | "type": "array", |
| 13 | 13 | "items": { |
| 14 | 14 | "type": "object", |
| 15 | 15 | "properties": { |
| 16 | "name": { "type": "string" }, | |
| 16 | "name": { "type": "string", "minLength": 1, "maxLength": 100 }, | |
| 17 | 17 | "services": { |
| 18 | 18 | "type": "array", |
| 19 | 19 | "items": { |
| 20 | 20 | "type": "object", |
| 21 | 21 | "properties": { |
| 22 | "name": { "type": "string" }, | |
| 23 | "description": { "type": "string" }, | |
| 24 | "url": { "type": "string" }, | |
| 25 | "github": { "type": ["string", "null"] }, | |
| 26 | "icon": { "type": ["string", "null"] }, | |
| 27 | "followWith": { "type": ["string", "null"] }, | |
| 22 | "name": { "type": "string", "minLength": 1, "maxLength": 100 }, | |
| 23 | "description": { "type": "string", "minLength": 10, "maxLength": 1500 }, | |
| 24 | "url": { | |
| 25 | "type": "string", | |
| 26 | "anyOf": [ | |
| 27 | { "pattern": "^https?://" }, | |
| 28 | { "maxLength": 0 } | |
| 29 | ] | |
| 30 | }, | |
| 31 | "github": { | |
| 32 | "type": ["string", "null"], | |
| 33 | "pattern": "^([a-zA-Z0-9._-]+/[a-zA-Z0-9._-]+|https://github\\.com/.+)$" | |
| 34 | }, | |
| 35 | "icon": { | |
| 36 | "type": ["string", "null"], | |
| 37 | "pattern": "^https?://.+" | |
| 38 | }, | |
| 39 | "followWith": { "type": ["string", "null"], "minLength": 1, "maxLength": 100 }, | |
| 28 | 40 | "securityAudited": { "type": ["boolean", "null"] }, |
| 29 | 41 | "openSource": { "type": ["boolean", "null"] }, |
| 30 | 42 | "acceptsCrypto": { "type": ["boolean", "null"] }, |
| 31 | "tosdrId": { "type": ["number", "null"] }, | |
| 32 | "iosApp": { "type": ["string", "null"] }, | |
| 33 | "androidApp": { "type": ["string", "null"] }, | |
| 34 | "discordInvite": { "type": ["string", "null"] }, | |
| 35 | "subreddit": { "type": ["string", "null"] } | |
| 43 | "tosdrId": { "type": ["integer", "null"], "minimum": 1 }, | |
| 44 | "iosApp": { | |
| 45 | "type": ["string", "null"], | |
| 46 | "pattern": "^https://apps\\.apple\\.com/" | |
| 47 | }, | |
| 48 | "androidApp": { | |
| 49 | "type": ["string", "null"], | |
| 50 | "pattern": "^[a-zA-Z][a-zA-Z0-9_]*(\\.[a-zA-Z][a-zA-Z0-9_]*)+$" | |
| 51 | }, | |
| 52 | "discordInvite": { | |
| 53 | "type": ["string", "null"], | |
| 54 | "pattern": "^(https://discord\\.gg/[a-zA-Z0-9]+|[a-zA-Z0-9]+|)$" | |
| 55 | }, | |
| 56 | "subreddit": { | |
| 57 | "type": ["string", "null"], | |
| 58 | "pattern": "^[a-zA-Z0-9_]+$", | |
| 59 | "minLength": 1, | |
| 60 | "maxLength": 50 | |
| 61 | } | |
| 36 | 62 | }, |
| 37 | 63 | "required": ["name", "description", "url"], |
| 38 | 64 | "additionalProperties": false |
| 39 | 65 | } |
| 40 | 66 | }, |
| 41 | "intro": { "type": ["string", "null"] }, | |
| 67 | "intro": { "type": ["string", "null"], "minLength": 1 }, | |
| 42 | 68 | "notableMentions": { |
| 43 | 69 | "oneOf": [ |
| 44 | 70 | { |
| @@ -46,25 +72,26 @@ | ||
| 46 | 72 | "items": { |
| 47 | 73 | "type": "object", |
| 48 | 74 | "properties": { |
| 49 | "name": { "type": "string" }, | |
| 50 | "description": { "type": "string" }, | |
| 51 | "url": { "type": "string" } | |
| 75 | "name": { "type": "string", "minLength": 1, "maxLength": 100 }, | |
| 76 | "description": { "type": "string", "minLength": 1 }, | |
| 77 | "url": { "type": "string", "pattern": "^https?://" } | |
| 52 | 78 | }, |
| 53 | 79 | "required": ["name", "url"], |
| 54 | 80 | "additionalProperties": false |
| 55 | 81 | } |
| 56 | 82 | }, |
| 57 | { "type": "string" }, | |
| 83 | { "type": "string", "minLength": 1 }, | |
| 58 | 84 | { "type": "null" } |
| 59 | 85 | ] |
| 60 | 86 | }, |
| 61 | "furtherInfo": { "type": ["string", "null"] }, | |
| 62 | "wordOfWarning": { "type": ["string", "null"] }, | |
| 87 | "furtherInfo": { "type": ["string", "null"], "minLength": 1 }, | |
| 88 | "wordOfWarning": { "type": ["string", "null"], "minLength": 1 }, | |
| 63 | 89 | "alternativeTo": { |
| 64 | 90 | "oneOf": [ |
| 65 | 91 | { |
| 66 | 92 | "type": "array", |
| 67 | "items": { "type": "string" } | |
| 93 | "items": { "type": "string", "minLength": 1, "maxLength": 100 }, | |
| 94 | "minItems": 1 | |
| 68 | 95 | }, |
| 69 | 96 | { "type": "null" } |
| 70 | 97 | ] |