Commit 2476a57bac

2476a57bac22dd31a6ba7bd9f27ec0e4e38d86d8

parent: 66d9970144

Unsigned

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

Updates check workflow, to review pull requests

Layout: unified · split

.github/workflows/pr-check.yml +77 −109
@@ -18,13 +18,10 @@ jobs:
1818 non_yaml_changed: ${{ steps.changes.outputs.non_yaml_changed }}
1919 steps:
2020 - uses: actions/checkout@v4
21 with:
22 fetch-depth: 0
2321 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
2422 - uses: actions/setup-python@v5
2523 with:
2624 python-version: "3.12"
27 - run: pip install -q -r lib/requirements.txt
2825 - name: Detect changed files
2926 id: changes
3027 run: python lib/checks/detect-changes.py --base-ref ${{ github.event.pull_request.base.sha }}
@@ -32,54 +29,64 @@ jobs:
3229 if: steps.changes.outputs.non_yaml_changed == 'true'
3330 run: python lib/checks/warn-non-yaml.py --base-ref ${{ github.event.pull_request.base.sha }}
3431
35 readme:
36 name: README edits
32 pr-meta:
33 name: PR metadata
3734 runs-on: ubuntu-latest
3835 steps:
3936 - uses: actions/checkout@v4
40 with:
41 fetch-depth: 0
42 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
4337 - uses: actions/setup-python@v5
4438 with:
4539 python-version: "3.12"
46 - run: pip install -q -r lib/requirements.txt
47 - name: Check for direct README edits
48 run: python lib/checks/check-readme-edits.py --base-ref ${{ github.event.pull_request.base.sha }}
40 - name: Check PR metadata
41 env:
42 PR_TITLE: ${{ github.event.pull_request.title }}
43 PR_BODY: ${{ github.event.pull_request.body }}
44 PR_DRAFT: ${{ github.event.pull_request.draft }}
45 run: python lib/checks/check-pr-meta.py
46 - name: Upload findings
47 if: always()
48 uses: actions/upload-artifact@v4
49 with:
50 name: findings-meta
51 path: /tmp/findings-meta.json
52 if-no-files-found: ignore
4953
50 schema:
51 name: Schema validation
52 needs: detect-changes
53 if: needs.detect-changes.outputs.yaml_changed == 'true'
54 file-checks:
55 name: File checks
5456 runs-on: ubuntu-latest
5557 steps:
5658 - uses: actions/checkout@v4
59 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
5760 - uses: actions/setup-python@v5
5861 with:
5962 python-version: "3.12"
60 - run: pip install -q -r lib/requirements.txt
61 - name: Validate schema
62 run: make validate
63 - name: Check for direct README edits
64 run: python lib/checks/check-readme-edits.py --base-ref ${{ github.event.pull_request.base.sha }}
6365
64 diff:
65 name: Single-entry rule
66 data-validation:
67 name: Data validation
6668 needs: detect-changes
6769 if: needs.detect-changes.outputs.yaml_changed == 'true'
6870 runs-on: ubuntu-latest
69 outputs:
70 has_service_changes: ${{ steps.diff.outputs.has_service_changes }}
7171 steps:
7272 - uses: actions/checkout@v4
73 with:
74 fetch-depth: 0
7573 - run: git fetch --depth=1 origin ${{ github.event.pull_request.base.sha }}
7674 - uses: actions/setup-python@v5
7775 with:
7876 python-version: "3.12"
7977 - run: pip install -q -r lib/requirements.txt
80 - name: YAML diff analysis
78 - name: Schema validation
79 id: schema
80 continue-on-error: true
81 run: make validate
82 - name: YAML diff
8183 id: diff
84 continue-on-error: true
8285 run: python lib/checks/check-yaml-diff.py --base-ref ${{ github.event.pull_request.base.sha }}
86 - name: Check additions
87 env:
88 SCHEMA_OUTCOME: ${{ steps.schema.outcome }}
89 run: python lib/checks/check-additions.py
8390 - name: Upload diff data
8491 if: always()
8592 uses: actions/upload-artifact@v4
@@ -87,11 +94,21 @@ jobs:
8794 name: pr-diff
8895 path: /tmp/pr-diff.json
8996 if-no-files-found: ignore
90
91 links:
92 name: Link validation
93 needs: diff
94 if: needs.diff.result == 'success' && needs.diff.outputs.has_service_changes == 'true'
97 - name: Upload findings
98 if: always()
99 uses: actions/upload-artifact@v4
100 with:
101 name: findings-data
102 path: /tmp/findings-data.json
103 if-no-files-found: ignore
104 - name: Fail if critical checks failed
105 if: steps.schema.outcome == 'failure' || steps.diff.outcome == 'failure'
106 run: exit 1
107
108 project-checks:
109 name: Project checks
110 needs: data-validation
111 if: "!cancelled() && needs.data-validation.result != 'skipped'"
95112 runs-on: ubuntu-latest
96113 steps:
97114 - uses: actions/checkout@v4
@@ -104,93 +121,44 @@ jobs:
104121 with:
105122 name: pr-diff
106123 path: /tmp
107 - name: Validate links
108 run: python lib/checks/check-links.py --diff-json /tmp/pr-diff.json
124 continue-on-error: true
125 - name: Check project health
126 env:
127 PR_USER: ${{ github.event.pull_request.user.login }}
128 GITHUB_TOKEN: ${{ github.token }}
129 run: python lib/checks/check-project.py
130 - name: Upload findings
131 if: always()
132 uses: actions/upload-artifact@v4
133 with:
134 name: findings-project
135 path: /tmp/findings-project.json
136 if-no-files-found: ignore
109137
110 template:
111 name: PR template
138 summary:
139 name: Summary
140 if: always()
141 needs: [detect-changes, pr-meta, file-checks, data-validation, project-checks]
112142 runs-on: ubuntu-latest
113143 steps:
114144 - uses: actions/checkout@v4
115145 - uses: actions/setup-python@v5
116146 with:
117147 python-version: "3.12"
118 - run: pip install -q -r lib/requirements.txt
119 - name: PR template check
148 - name: Download all findings
149 uses: actions/download-artifact@v4
150 with:
151 pattern: findings-*
152 path: /tmp/artifacts
153 merge-multiple: true
154 continue-on-error: true
155 - name: Format comment
120156 env:
121 PR_BODY: ${{ github.event.pull_request.body }}
122 run: python lib/checks/check-template.py
123
124 comment:
125 name: Summary
126 if: always()
127 needs: [readme, schema, diff, links, template]
128 runs-on: ubuntu-latest
129 steps:
130 - name: Save PR metadata
131 run: |
132 mkdir -p /tmp/pr-meta
133 echo "${{ github.event.pull_request.number }}" > /tmp/pr-meta/number.txt
134 echo "${{ github.run_id }}" > /tmp/pr-meta/run-id.txt
135
136 - name: Build failure comment
137 if: contains(needs.*.result, 'failure')
138 run: |
139 cat > /tmp/pr-meta/comment.md << 'HEADER'
140 <!-- pr-check-bot -->
141 > [!CAUTION]
142 > ## PR check failed
143 HEADER
144
145 if [ "${{ needs.readme.result }}" = "failure" ]; then
146 cat >> /tmp/pr-meta/comment.md << 'EOF'
147
148 ### Direct README edits
149 The auto-generated section of the README must not be edited directly.
150 Please make your changes in `awesome-privacy.yml` instead — the README is regenerated from it.
151 EOF
152 fi
153
154 if [ "${{ needs.schema.result }}" = "failure" ]; then
155 cat >> /tmp/pr-meta/comment.md << 'EOF'
156
157 ### Schema validation failed
158 `awesome-privacy.yml` does not conform to the expected schema.
159 Please check your YAML against the structure defined in `lib/schema.json`.
160 EOF
161 fi
162
163 if [ "${{ needs.diff.result }}" = "failure" ]; then
164 cat >> /tmp/pr-meta/comment.md << 'EOF'
165
166 ### Single-entry rule
167 Each PR should add, modify, or remove only **one** service at a time.
168 If you need to change multiple services, please split them into separate PRs.
169 EOF
170 fi
171
172 if [ "${{ needs.links.result }}" = "failure" ]; then
173 cat >> /tmp/pr-meta/comment.md << 'EOF'
174
175 ### Link validation failed
176 One or more URLs in your entry could not be verified.
177 Please ensure all links are correct and accessible.
178 EOF
179 fi
180
181 if [ "${{ needs.template.result }}" = "failure" ]; then
182 cat >> /tmp/pr-meta/comment.md << 'EOF'
183
184 ### PR template incomplete
185 Your PR description is missing required sections.
186 Please fill out the **Type**, **Changes**, and **Checklist** sections of the PR template.
187 EOF
188 fi
189
190 printf '\n---\n*See the [workflow logs](%s/%s/actions/runs/%s) for full details.*\n' \
191 "${{ github.server_url }}" "${{ github.repository }}" "${{ github.run_id }}" \
192 >> /tmp/pr-meta/comment.md
193
157 PR_USER: ${{ github.event.pull_request.user.login }}
158 PR_NUMBER: ${{ github.event.pull_request.number }}
159 RUN_ID: ${{ github.run_id }}
160 README_FAILED: ${{ needs.file-checks.result == 'failure' && 'true' || 'false' }}
161 run: python lib/checks/format-comment.py
194162 - name: Upload PR metadata
195163 if: always()
196164 uses: actions/upload-artifact@v4
.github/workflows/pr-comment.yml +3 −8
@@ -33,7 +33,6 @@ jobs:
3333 script: |
3434 const fs = require('fs');
3535 const marker = '<!-- pr-check-bot -->';
36 const conclusion = context.payload.workflow_run.conclusion;
3736
3837 // Determine the PR number
3938 let prNumber;
@@ -73,12 +72,8 @@ jobs:
7372 });
7473 const existing = comments.find(c => c.body.includes(marker));
7574
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 }
75 const commentFile = 'pr-meta/comment.md';
76 if (fs.existsSync(commentFile)) {
8277 const body = fs.readFileSync(commentFile, 'utf8').trim();
8378 if (existing) {
8479 await github.rest.issues.updateComment({
@@ -96,7 +91,7 @@ jobs:
9691 });
9792 }
9893 } else if (existing) {
99 // Checks passed — remove stale failure comment
94 // No findings — remove stale comment
10095 await github.rest.issues.deleteComment({
10196 owner: context.repo.owner,
10297 repo: context.repo.repo,
lib/checks/check-additions.py added +173
@@ -0,0 +1,173 @@
1"""Validates data quality for added/modified services using the diff JSON."""
2
3import json
4import os
5import sys
6
7import yaml
8
9PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
10DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
11DIFF_PATH = "/tmp/pr-diff.json"
12FINDINGS_PATH = "/tmp/findings-data.json"
13
14REQUIRED_FIELDS = ("name", "description", "url", "icon")
15
16CONTRIBUTING = "https://github.com/Lissy93/awesome-privacy/blob/main/.github/CONTRIBUTING.md"
17
18SCHEMA_MSG = (
19 "Some of the schema checks have failed. Please check that your addition"
20 " contains all the required fields, with acceptable values, nothing"
21 " additional and that it is following valid YAML syntax"
22)
23MULTIPLE_MSG = "Please make just one addition per pull request"
24MISSING_TPL = (
25 "Did you include all required fields? Looks like {fields} is missing or"
26 f" invalid. Please see the [required fields]({CONTRIBUTING}#service-fields)"
27 " for available fields."
28)
29POSITION_MSG = (
30 "New entries must be added to the end of the section, unless otherwise requested"
31)
32OPENSOURCE_MSG = (
33 "You indicated this app/service is not open source. This will likely make"
34 " it ineligible for listing on Awesome Privacy in accordance with our"
35 f" [Requirements]({CONTRIBUTING}#requirements)."
36 " Please ensure that this is justified in your PR body."
37)
38
39
40def load_json(path):
41 """Load JSON from a file, returning None on any error."""
42 try:
43 with open(path) as f:
44 return json.load(f)
45 except Exception:
46 return None
47
48
49def load_yaml_data(path):
50 """Load YAML from a file, returning None on any error."""
51 try:
52 with open(path) as f:
53 return yaml.safe_load(f)
54 except Exception:
55 return None
56
57
58def find_section_services(head, category, section):
59 """Return the services list for a category/section pair, or None."""
60 for cat in head.get("categories", []):
61 if cat.get("name") == category:
62 for sec in cat.get("sections", []):
63 if sec.get("name") == section:
64 return sec.get("services", [])
65 return None
66
67
68def find_service_fields(head, category, section, service_name):
69 """Look up a service's fields in the head YAML."""
70 services = find_section_services(head, category, section)
71 if services:
72 for svc in services:
73 if svc.get("name") == service_name:
74 return svc
75 return None
76
77
78def check_required_fields(diff, head):
79 """Return a finding if any added/modified service is missing required fields."""
80 missing = set()
81 for svc in diff.get("services", {}).get("added", []):
82 fields = svc.get("fields", {})
83 for f in REQUIRED_FIELDS:
84 if not fields.get(f):
85 missing.add(f)
86 for svc in diff.get("services", {}).get("modified", []):
87 if not head:
88 continue
89 fields = find_service_fields(
90 head, svc["category"], svc["section"], svc["service"]
91 )
92 if fields:
93 for f in REQUIRED_FIELDS:
94 if not fields.get(f):
95 missing.add(f)
96 if missing:
97 names = ", ".join(f"`{f}`" for f in sorted(missing))
98 return MISSING_TPL.format(fields=names)
99 return None
100
101
102def check_position(diff, head):
103 """Return a finding if a newly added service is not at the end of its section."""
104 if not head:
105 return None
106 for svc in diff.get("services", {}).get("added", []):
107 services = find_section_services(head, svc["category"], svc["section"])
108 if services and services[-1].get("name") != svc["service"]:
109 return POSITION_MSG
110 return None
111
112
113def check_open_source(diff):
114 """Return a finding if an added service has openSource missing or not true."""
115 for svc in diff.get("services", {}).get("added", []):
116 fields = svc.get("fields", {})
117 if fields.get("openSource") is not True:
118 return OPENSOURCE_MSG
119 return None
120
121
122def check_single_entry(diff):
123 """Return a finding if the diff contains multiple service or section changes."""
124 services = diff.get("services", {})
125 svc_count = (
126 len(services.get("added", []))
127 + len(services.get("removed", []))
128 + len(services.get("modified", []))
129 )
130 if svc_count > 1:
131 return MULTIPLE_MSG
132 if svc_count == 0:
133 sec_count = len(diff.get("sections", []))
134 if sec_count > 1:
135 return MULTIPLE_MSG
136 return None
137
138
139def main():
140 findings = []
141 try:
142 if os.environ.get("SCHEMA_OUTCOME") == "failure":
143 findings.append(SCHEMA_MSG)
144
145 diff = load_json(DIFF_PATH)
146 head = load_yaml_data(DATA_PATH)
147
148 if diff:
149 finding = check_single_entry(diff)
150 if finding:
151 findings.append(finding)
152
153 finding = check_required_fields(diff, head)
154 if finding:
155 findings.append(finding)
156
157 finding = check_position(diff, head)
158 if finding:
159 findings.append(finding)
160
161 finding = check_open_source(diff)
162 if finding:
163 findings.append(finding)
164 except Exception:
165 pass
166
167 with open(FINDINGS_PATH, "w") as f:
168 json.dump(findings, f)
169 sys.exit(0)
170
171
172if __name__ == "__main__":
173 main()
lib/checks/check-pr-meta.py added +122
@@ -0,0 +1,122 @@
1"""Checks PR metadata: title format, draft status, template completeness, and checkboxes."""
2
3import json
4import os
5import re
6import sys
7
8FINDINGS_PATH = "/tmp/findings-meta.json"
9
10BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"}
11
12TITLE_MSG = (
13 "The pull request title does not follow the format defined in our guidelines."
14 " Please rename it to `[Add/Remove/Update] [software name] in [software section]`"
15)
16DRAFT_MSG = (
17 "Please avoid opening WIP pull requests."
18 " Your PR should be 100% ready and complete before submitting"
19)
20TEMPLATE_MSG = (
21 "Please fill in pull request template in full."
22 " You can find a copy of this"
23 " [here](https://github.com/Lissy93/awesome-privacy/blob/main/.github/PULL_REQUEST_TEMPLATE.md)"
24)
25CHECKBOX_MSG = (
26 "Ensure you have completed the checklist (put a tick the checkboxes with `[x]`),"
27 " to confirm that you've read the contributing guidelines, checked your submission,"
28 " indicated your affiliation and agree to follow our CoC"
29)
30
31
32def extract_section(body, header):
33 """Extract content between a ### header and the next delimiter."""
34 pattern = rf"###\s*{re.escape(header)}\s*\n(.*?)(?=\n---|\n###|\Z)"
35 match = re.search(pattern, body, re.DOTALL)
36 return match.group(1) if match else None
37
38
39def strip_html_comments(text):
40 """Remove HTML comments from text."""
41 return re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL).strip()
42
43
44def check_title(title):
45 """Return a finding if the PR title matches a known-bad pattern."""
46 if title and title.strip().lower() in BAD_TITLES:
47 return TITLE_MSG
48 return None
49
50
51def check_draft(draft_str):
52 """Return a finding if the PR is in draft state."""
53 if str(draft_str).lower() == "true":
54 return DRAFT_MSG
55 return None
56
57
58def check_template(body):
59 """Return a finding if required template sections are missing or empty."""
60 for header in ("Type", "Changes", "Checklist"):
61 content = extract_section(body, header)
62 if content is None or not strip_html_comments(content):
63 return TEMPLATE_MSG
64 return None
65
66
67def check_checkboxes(body):
68 """Return a finding if any checklist checkboxes are unchecked."""
69 section = extract_section(body, "Checklist")
70 if section is None:
71 return None
72 checked = re.findall(r"- \[x\]", section, re.IGNORECASE)
73 unchecked = re.findall(r"- \[ \]", section)
74 if not checked and not unchecked:
75 return None
76 if unchecked:
77 return CHECKBOX_MSG
78 return None
79
80
81def write_findings(findings):
82 """Write the findings list to the output JSON file."""
83 with open(FINDINGS_PATH, "w") as f:
84 json.dump(findings, f)
85
86
87def main():
88 findings = []
89 critical = False
90 try:
91 title = os.environ.get("PR_TITLE", "")
92 body = os.environ.get("PR_BODY", "")
93 draft = os.environ.get("PR_DRAFT", "false")
94
95 finding = check_title(title)
96 if finding:
97 findings.append(finding)
98
99 finding = check_draft(draft)
100 if finding:
101 findings.append(finding)
102
103 if not body or not body.strip():
104 findings.append(TEMPLATE_MSG)
105 critical = True
106 else:
107 finding = check_template(body)
108 if finding:
109 findings.append(finding)
110 critical = True
111 finding = check_checkboxes(body)
112 if finding:
113 findings.append(finding)
114 except Exception:
115 pass
116
117 write_findings(findings)
118 sys.exit(1 if critical else 0)
119
120
121if __name__ == "__main__":
122 main()
lib/checks/check-project.py added +217
@@ -0,0 +1,217 @@
1"""Checks project health: URL reachability, GitHub repo stars, activity, and author match."""
2
3import json
4import os
5import sys
6from datetime import datetime, timezone
7
8import requests
9import yaml
10
11PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
12DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
13DIFF_PATH = "/tmp/pr-diff.json"
14FINDINGS_PATH = "/tmp/findings-project.json"
15
16TIMEOUT = 10
17USER_AGENT = "awesome-privacy-ci/1.0"
18MIN_STARS = 100
19INACTIVE_DAYS = 90
20
21LINK_MSG = (
22 "Our automated checks were unable to verify the link(s) you included"
23 " were reachable, so please double check this yourself"
24)
25AUTHOR_MSG = (
26 "Looks like you are the author of this package. Please ensure that you"
27 " have clearly disclosed this in your PR body for transparency"
28)
29STARS_MSG = (
30 "It looks like your submission is adding a quite small project."
31 " In some circumstances we may ask you to resubmit this once the project"
32 " is more mature and has a proven track record of good practices and maintenance."
33)
34ACTIVITY_MSG = (
35 "Please confirm that the project you are adding is actively maintained,"
36 " as it looks to not have had any recent updates in the past 3 months."
37)
38
39
40def load_diff(path):
41 """Load the diff JSON, returning None on any error."""
42 try:
43 with open(path) as f:
44 return json.load(f)
45 except Exception:
46 return None
47
48
49def check_url(url):
50 """Return True if the URL is reachable, True on any error (no false positives)."""
51 try:
52 resp = requests.head(
53 url, timeout=TIMEOUT, allow_redirects=True,
54 headers={"User-Agent": USER_AGENT},
55 )
56 if resp.status_code >= 400:
57 resp = requests.get(
58 url, timeout=TIMEOUT, allow_redirects=True,
59 headers={"User-Agent": USER_AGENT}, stream=True,
60 )
61 resp.close()
62 return resp.status_code < 400
63 except Exception:
64 return True
65
66
67def parse_github_field(value):
68 """Parse a github field into (owner, repo), or (None, None) on failure."""
69 if not value:
70 return None, None
71 if value.startswith("https://github.com/"):
72 parts = value.removeprefix("https://github.com/").strip("/").split("/")
73 if len(parts) >= 2:
74 return parts[0], parts[1]
75 return None, None
76 if "/" in value:
77 parts = value.split("/")
78 if len(parts) == 2:
79 return parts[0], parts[1]
80 return None, None
81
82
83def fetch_repo(owner, repo, token):
84 """Fetch GitHub repo metadata, returning None on any error."""
85 try:
86 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
87 if token:
88 headers["Authorization"] = f"token {token}"
89 resp = requests.get(
90 f"https://api.github.com/repos/{owner}/{repo}",
91 headers=headers, timeout=TIMEOUT,
92 )
93 if resp.status_code == 200:
94 return resp.json()
95 except Exception:
96 pass
97 return None
98
99
100def load_yaml_data():
101 """Load the head YAML, returning None on any error."""
102 try:
103 with open(DATA_PATH) as f:
104 return yaml.safe_load(f)
105 except Exception:
106 return None
107
108
109def find_service_in_head(head, category, section, service_name):
110 """Look up a service in the head YAML by path."""
111 if not head:
112 return None
113 for cat in head.get("categories", []):
114 if cat.get("name") == category:
115 for sec in cat.get("sections", []):
116 if sec.get("name") == section:
117 for svc in sec.get("services", []):
118 if svc.get("name") == service_name:
119 return svc
120 return None
121
122
123def get_services(diff, key):
124 """Safely extract a service list from the diff."""
125 return diff.get("services", {}).get(key, [])
126
127
128def check_links(diff, head):
129 """Return LINK_MSG if any service URL is unreachable."""
130 for svc in get_services(diff, "added"):
131 url = svc.get("fields", {}).get("url")
132 if url and not check_url(url):
133 return LINK_MSG
134 for svc in get_services(diff, "modified"):
135 if "url" not in svc.get("changed_fields", []):
136 continue
137 head_svc = find_service_in_head(
138 head, svc["category"], svc["section"], svc["service"]
139 )
140 if head_svc:
141 url = head_svc.get("url")
142 if url and not check_url(url):
143 return LINK_MSG
144 return None
145
146
147def check_repo_signals(diff, pr_user, token):
148 """Check GitHub repo author match, stars, and activity for added services."""
149 findings = []
150 if not token:
151 return findings
152 cache = {}
153 for svc in get_services(diff, "added"):
154 gh = svc.get("fields", {}).get("github")
155 owner, repo = parse_github_field(gh)
156 if not owner:
157 continue
158 cache_key = f"{owner}/{repo}"
159 if cache_key not in cache:
160 cache[cache_key] = fetch_repo(owner, repo, token)
161 data = cache[cache_key]
162 if not data:
163 continue
164
165 repo_owner = data.get("owner", {})
166 if (
167 pr_user
168 and repo_owner.get("type") == "User"
169 and repo_owner.get("login", "").lower() == pr_user.lower()
170 and AUTHOR_MSG not in findings
171 ):
172 findings.append(AUTHOR_MSG)
173
174 stars = data.get("stargazers_count", 0)
175 if stars < MIN_STARS and STARS_MSG not in findings:
176 findings.append(STARS_MSG)
177
178 pushed = data.get("pushed_at")
179 if pushed and ACTIVITY_MSG not in findings:
180 try:
181 pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00"))
182 now = datetime.now(timezone.utc)
183 if (now - pushed_dt).days > INACTIVE_DAYS:
184 findings.append(ACTIVITY_MSG)
185 except Exception:
186 pass
187
188 return findings
189
190
191def main():
192 findings = []
193 try:
194 diff = load_diff(DIFF_PATH)
195 if not diff:
196 with open(FINDINGS_PATH, "w") as f:
197 json.dump(findings, f)
198 sys.exit(0)
199
200 head = load_yaml_data()
201 finding = check_links(diff, head)
202 if finding:
203 findings.append(finding)
204
205 pr_user = os.environ.get("PR_USER", "")
206 token = os.environ.get("GITHUB_TOKEN", "")
207 findings.extend(check_repo_signals(diff, pr_user, token))
208 except Exception:
209 pass
210
211 with open(FINDINGS_PATH, "w") as f:
212 json.dump(findings, f)
213 sys.exit(0)
214
215
216if __name__ == "__main__":
217 main()
lib/checks/format-comment.py added +106
@@ -0,0 +1,106 @@
1"""Aggregates findings from all check jobs into a formatted PR comment."""
2
3import json
4import os
5import sys
6
7ARTIFACTS_DIR = "/tmp/artifacts"
8OUTPUT_DIR = "/tmp/pr-meta"
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"
17
18COMMENT_TEMPLATE = """<!-- pr-check-bot -->
19Hello @{user}
20
21Thank you for contributing to Awesome Privacy! We will review your PR shortly. In the meantime, please ensure that your submission is inline with our guidelines in our [Contributing Requirements]({contributing}).
22
23Looks like there could be some issues in your PR. Please double check that:
24
25{findings}
26
27> [!NOTE]
28> I am a bot, and sometimes make mistakes in my suggestions. But a human will review your submission shortly!"""
29
30
31def load_findings(filename):
32 """Load a findings JSON array from the artifacts directory, or empty list on error."""
33 try:
34 with open(os.path.join(ARTIFACTS_DIR, filename)) as f:
35 data = json.load(f)
36 return data if isinstance(data, list) else []
37 except Exception:
38 return []
39
40
41def collect_findings(readme_failed):
42 """Gather all findings in display order: meta, readme, data, project."""
43 all_findings = []
44 all_findings.extend(load_findings("findings-meta.json"))
45 if readme_failed:
46 all_findings.append(README_MSG)
47 all_findings.extend(load_findings("findings-data.json"))
48 all_findings.extend(load_findings("findings-project.json"))
49 return all_findings
50
51
52def format_comment(findings, user):
53 """Build the markdown comment from findings."""
54 bullet_list = "\n".join(f"- {f}" for f in findings)
55 return COMMENT_TEMPLATE.format(
56 user=user, contributing=CONTRIBUTING, findings=bullet_list,
57 )
58
59
60def write_step_summary(findings):
61 """Write a summary to GITHUB_STEP_SUMMARY."""
62 summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
63 if not summary_file:
64 return
65 lines = ["## PR Check Summary\n"]
66 if findings:
67 lines.append(f"⚠️ Found {len(findings)} issue(s):\n")
68 for f in findings:
69 lines.append(f"- {f}")
70 else:
71 lines.append("✅ All checks passed.\n")
72 with open(summary_file, "a") as f:
73 f.write("\n".join(lines) + "\n")
74
75
76def main():
77 try:
78 user = os.environ.get("PR_USER", "contributor")
79 pr_number = os.environ.get("PR_NUMBER", "")
80 run_id = os.environ.get("RUN_ID", "")
81 readme_failed = os.environ.get("README_FAILED", "false") == "true"
82
83 os.makedirs(OUTPUT_DIR, exist_ok=True)
84
85 if pr_number:
86 with open(os.path.join(OUTPUT_DIR, "number.txt"), "w") as f:
87 f.write(pr_number)
88 if run_id:
89 with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f:
90 f.write(run_id)
91
92 findings = collect_findings(readme_failed)
93 write_step_summary(findings)
94
95 if findings:
96 comment = format_comment(findings, user)
97 with open(os.path.join(OUTPUT_DIR, "comment.md"), "w") as f:
98 f.write(comment)
99 except Exception:
100 pass
101
102 sys.exit(0)
103
104
105if __name__ == "__main__":
106 main()