commit a05a0c567a6c86d6a245c9b870f104af051868ef
parent 2b18ab8bf03355f43ca4f362b626171dc3d040b7
Author: Amit Dutta <amitdutta4255@gmail.com>
Date: Thu, 28 May 2026 08:04:30 +0530
Update commit fetching method in update_commits.py
Refactor commit fetching to use Search API and improve deduplication logic.
Diffstat:
1 file changed, 65 insertions(+), 29 deletions(-)
diff --git a/.github/scripts/update_commits.py b/.github/scripts/update_commits.py
@@ -1,6 +1,7 @@
import urllib.request
import json
import re
+import os
from datetime import datetime
USERNAME = "notamitgamer"
@@ -8,48 +9,83 @@ USERNAME = "notamitgamer"
def fetch_recent_commits():
commits_data = []
try:
- # Events API captures activity across ALL repos, including orgs
- events_url = f"https://api.github.com/users/{USERNAME}/events/public?per_page=100"
- req = urllib.request.Request(events_url)
+ search_url = f"https://api.github.com/search/commits?q=author:{USERNAME}&sort=author-date&order=desc&per_page=15"
+ req = urllib.request.Request(search_url)
req.add_header('User-Agent', f'{USERNAME}-readme-updater')
+ req.add_header('Accept', 'application/vnd.github+json')
- with urllib.request.urlopen(req) as response:
- events = json.loads(response.read().decode())
+ # Use GITHUB_TOKEN if available to avoid rate limits
+ token = os.environ.get('GITHUB_TOKEN')
+ if token:
+ req.add_header('Authorization', f'token {token}')
- for event in events:
- # Only look at PushEvents (covers direct pushes + merged PRs)
- if event.get('type') != 'PushEvent':
- continue
+ with urllib.request.urlopen(req) as response:
+ data = json.loads(response.read().decode())
- repo_name = event['repo']['name'] # e.g. "is-a-dev/register"
- commits = event['payload'].get('commits', [])
+ items = data.get('items', [])
+ print(f"🔍 Search API returned {len(items)} commits.")
- for commit in commits:
- # Filter to only YOUR commits by email or name
- author = commit.get('author', {})
- if author.get('name', '').lower() != USERNAME.lower() and \
- USERNAME.lower() not in author.get('email', '').lower():
- continue
+ for item in items:
+ date_str = item['commit']['author']['date']
+ date_obj = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ")
- date_str = event['created_at']
- date_obj = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ")
+ msg = item['commit']['message'].split('\n')[0]
+ commit_url = item['html_url']
- msg = commit['message'].split('\n')[0]
- sha = commit['sha']
- commit_url = f"https://github.com/{repo_name}/commit/{sha}"
- repo_url = f"https://github.com/{repo_name}"
+ # Extract repo name from the commit URL
+ # e.g. https://github.com/owner/repo/commit/sha
+ parts = commit_url.split('/')
+ repo_name = f"{parts[3]}/{parts[4]}"
+ repo_url = f"https://github.com/{repo_name}"
- commits_data.append({
- 'date': date_obj,
- 'markdown': f"- [{msg}]({commit_url}) in [{repo_name}]({repo_url})"
- })
+ commits_data.append({
+ 'date': date_obj,
+ 'markdown': f"- [{msg}]({commit_url}) in [{repo_name}]({repo_url})"
+ })
+ # Sort by date descending
commits_data.sort(key=lambda x: x['date'], reverse=True)
- final_commits = [c['markdown'] for c in commits_data[:5]]
- print(f"Found {len(final_commits)} recent commits across all repositories.")
+ # Deduplicate (search can return same commit across multiple branches)
+ seen = set()
+ unique_commits = []
+ for c in commits_data:
+ if c['markdown'] not in seen:
+ seen.add(c['markdown'])
+ unique_commits.append(c)
+
+ final_commits = [c['markdown'] for c in unique_commits[:5]]
+ print(f"✅ Found {len(final_commits)} recent commits.")
return final_commits
except Exception as e:
print(f"Error fetching data: {e}")
return []
+
+
+def update_readme(commits):
+ if not commits:
+ print("No commits found to update.")
+ return
+
+ commit_list_md = "\n".join(commits)
+
+ with open('README.md', 'r', encoding='utf-8') as f:
+ readme = f.read()
+
+ updated_readme = re.sub(
+ r"<!-- START_RECENT_COMMITS -->.*?<!-- END_RECENT_COMMITS -->",
+ f"<!-- START_RECENT_COMMITS -->\n{commit_list_md}\n<!-- END_RECENT_COMMITS -->",
+ readme,
+ flags=re.DOTALL
+ )
+
+ with open('README.md', 'w', encoding='utf-8') as f:
+ f.write(updated_readme)
+
+ print("✅ README.md successfully updated!")
+
+
+if __name__ == "__main__":
+ recent_commits = fetch_recent_commits()
+ update_readme(recent_commits)