Skip to content

Commit 2088165

Browse files
committed
feat(automation): added github graph and automation
1 parent 48bd79d commit 2088165

5 files changed

Lines changed: 364 additions & 2 deletions

File tree

β€Ž.github/LOCAL_TEST.mdβ€Ž

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Test GitHub Stats Update Locally
2+
3+
This script allows you to test the stats update locally before pushing to GitHub.
4+
5+
## Prerequisites
6+
7+
Install required Python packages:
8+
9+
```bash
10+
pip install PyGithub requests
11+
```
12+
13+
## Generate a GitHub Personal Access Token
14+
15+
1. Go to https://github.com/settings/tokens
16+
2. Click "Generate new token (classic)"
17+
3. Give it a name like "README Stats"
18+
4. Select scopes: `public_repo` (or just `repo` if you want private repo stats too)
19+
5. Click "Generate token"
20+
6. Copy the token (you won't see it again!)
21+
22+
## Run the Test
23+
24+
### On Windows (PowerShell):
25+
26+
```powershell
27+
$env:GITHUB_TOKEN="your_token_here"
28+
$env:USERNAME="javaadde"
29+
python .github/scripts/update_stats.py
30+
```
31+
32+
### On Linux/Mac:
33+
34+
```bash
35+
export GITHUB_TOKEN="your_token_here"
36+
export USERNAME="javaadde"
37+
python .github/scripts/update_stats.py
38+
```
39+
40+
## What to Expect
41+
42+
The script will:
43+
1. Fetch your GitHub stats using the API
44+
2. Format them into a nice table
45+
3. Update the `### πŸ“Š GitHub Stats` section in README.md
46+
4. Print success messages
47+
48+
Check your README.md to see the updated stats!
49+
50+
## Note
51+
52+
⚠️ **Don't commit your personal access token!**
53+
54+
The token is only needed for local testing. When the workflow runs on GitHub Actions, it automatically uses the built-in `GITHUB_TOKEN` secret.

β€Ž.github/STATS_SETUP.mdβ€Ž

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# GitHub Stats Auto-Update Setup
2+
3+
This repository uses GitHub Actions to automatically update the README with fresh GitHub statistics daily.
4+
5+
## πŸš€ How It Works
6+
7+
1. **Daily Schedule**: The workflow runs every day at 00:00 UTC (5:30 AM IST)
8+
2. **Fetches Stats**: Uses GitHub API to get your latest stats (repos, stars, forks, followers, top languages)
9+
3. **Updates README**: Automatically updates the `### πŸ“Š GitHub Stats` section
10+
4. **Commits Changes**: Pushes the updated README back to the repository
11+
12+
## πŸ“ Files Created
13+
14+
- `.github/workflows/update-stats.yml` - GitHub Actions workflow configuration
15+
- `.github/scripts/update_stats.py` - Python script that fetches and formats stats
16+
17+
## βš™οΈ Setup Instructions
18+
19+
### 1. Push to GitHub
20+
21+
First, commit and push all the files to your GitHub repository:
22+
23+
```bash
24+
git add .
25+
git commit -m "Add GitHub stats auto-update workflow"
26+
git push origin main
27+
```
28+
29+
### 2. Enable GitHub Actions
30+
31+
1. Go to your repository on GitHub
32+
2. Click on the **Actions** tab
33+
3. If prompted, click **"I understand my workflows, go ahead and enable them"**
34+
35+
### 3. Manual Trigger (Optional)
36+
37+
To test the workflow immediately without waiting for the daily schedule:
38+
39+
1. Go to **Actions** tab in your repository
40+
2. Click on **"Update GitHub Stats"** workflow
41+
3. Click **"Run workflow"** button
42+
4. Select the branch (usually `main`)
43+
5. Click **"Run workflow"**
44+
45+
The workflow will run and update your README within a minute!
46+
47+
## πŸ”§ Customization
48+
49+
### Change Update Frequency
50+
51+
Edit `.github/workflows/update-stats.yml` and modify the cron schedule:
52+
53+
```yaml
54+
schedule:
55+
- cron: '0 0 * * *' # Daily at midnight UTC
56+
# Examples:
57+
# - cron: '0 */12 * * *' # Every 12 hours
58+
# - cron: '0 0 * * 1' # Every Monday
59+
```
60+
61+
### Modify Stats Display
62+
63+
Edit `.github/scripts/update_stats.py` to customize:
64+
- Which stats to display
65+
- Formatting and styling
66+
- Number of top languages shown (currently 5)
67+
68+
## 🎯 What Gets Updated
69+
70+
- πŸ“¦ Public Repositories count
71+
- ⭐ Total Stars Earned
72+
- 🍴 Total Forks
73+
- πŸ‘₯ Followers count
74+
- πŸ“ Public Gists count
75+
- πŸ”₯ Top 5 Programming Languages
76+
- πŸ• Last updated timestamp
77+
78+
## πŸ› Troubleshooting
79+
80+
### Workflow Not Running?
81+
82+
1. Check if GitHub Actions is enabled in your repository settings
83+
2. Verify the workflow file is in `.github/workflows/` directory
84+
3. Check the Actions tab for any error messages
85+
86+
### Stats Not Updating?
87+
88+
1. Go to Actions tab and check the latest workflow run
89+
2. Click on the failed run to see error logs
90+
3. Ensure the Python script has correct permissions
91+
92+
## πŸ“ Notes
93+
94+
- The workflow uses `GITHUB_TOKEN` which is automatically provided by GitHub Actions
95+
- No additional secrets or tokens need to be configured
96+
- The commit message includes `[skip ci]` to prevent infinite workflow loops
97+
- Stats are fetched only from public repositories
98+
99+
## πŸŽ‰ That's It!
100+
101+
Your GitHub stats will now update automatically every day! πŸš€
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import re
4+
import requests
5+
from datetime import datetime, timedelta
6+
7+
def get_github_data(username, token):
8+
"""Fetch GitHub data using both REST and GraphQL APIs"""
9+
headers = {"Authorization": f"token {token}"}
10+
11+
# 1. Fetch REST API data (Repos, Stars, Followers)
12+
rest_url = f"https://api.github.com/users/{username}"
13+
user_data = requests.get(rest_url, headers=headers).json()
14+
15+
# 2. Fetch GraphQL API data (Contribution Calendar)
16+
graphql_url = "https://api.github.com/graphql"
17+
query = """
18+
query($login: String!) {
19+
user(login: $login) {
20+
contributionsCollection {
21+
contributionCalendar {
22+
totalContributions
23+
weeks {
24+
contributionDays {
25+
contributionCount
26+
date
27+
}
28+
}
29+
}
30+
}
31+
repositories(first: 100, ownerAffiliations: OWNER) {
32+
nodes {
33+
stargazerCount
34+
languages(first: 5, orderBy: {field: SIZE, direction: DESC}) {
35+
edges {
36+
size
37+
node {
38+
name
39+
}
40+
}
41+
}
42+
}
43+
}
44+
}
45+
}
46+
"""
47+
variables = {"login": username}
48+
response = requests.post(graphql_url, json={"query": query, "variables": variables}, headers=headers)
49+
gql_data = response.json()
50+
51+
if 'errors' in gql_data:
52+
print(f"GraphQL Errors: {gql_data['errors']}")
53+
return None
54+
55+
user_gql = gql_data['data']['user']
56+
calendar = user_gql['contributionsCollection']['contributionCalendar']
57+
58+
# Calculate Streak
59+
all_days = []
60+
for week in calendar['weeks']:
61+
for day in week['contributionDays']:
62+
all_days.append(day)
63+
64+
all_days.sort(key=lambda x: x['date'], reverse=True)
65+
66+
current_streak = 0
67+
today = datetime.now().strftime('%Y-%m-%d')
68+
yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
69+
70+
# Start checking from today or yesterday
71+
start_index = 0
72+
if all_days[0]['date'] != today and all_days[0]['date'] != yesterday:
73+
current_streak = 0
74+
else:
75+
for day in all_days:
76+
if day['contributionCount'] > 0:
77+
current_streak += 1
78+
else:
79+
# If we hit a 0 and it's not today's pending count, we stop
80+
if day['date'] != today:
81+
break
82+
83+
# Calculate Total Stars
84+
total_stars = sum(repo['stargazerCount'] for repo in user_gql['repositories']['nodes'])
85+
86+
# Language Stats
87+
lang_stats = {}
88+
for repo in user_gql['repositories']['nodes']:
89+
for lang_edge in repo['languages']['edges']:
90+
name = lang_edge['node']['name']
91+
size = lang_edge['size']
92+
lang_stats[name] = lang_stats.get(name, 0) + size
93+
94+
top_languages = sorted(lang_stats.items(), key=lambda x: x[1], reverse=True)[:5]
95+
96+
return {
97+
'total_repos': user_data.get('public_repos', 0),
98+
'followers': user_data.get('followers', 0),
99+
'total_stars': total_stars,
100+
'total_contributions': calendar['totalContributions'],
101+
'current_streak': current_streak,
102+
'top_languages': [l[0] for l in top_languages],
103+
'last_updated': datetime.now().strftime('%B %d, %Y')
104+
}
105+
106+
def format_stats(stats):
107+
langs = " ".join([f"![{l}](https://img.shields.io/badge/-{l}-333?style=flat-square)" for l in stats['top_languages']])
108+
109+
return f"""### πŸ“Š My GitHub Real-time Stats
110+
111+
<div align="center">
112+
113+
| πŸ”₯ **Contribution Streak** | πŸ† **Total Contributions** | ⭐ **Total Stars** |
114+
|:---:|:---:|:---:|
115+
| **{stats['current_streak']} Days** | **{stats['total_contributions']}** | **{stats['total_stars']}** |
116+
117+
| πŸ“ˆ Metric | πŸ”’ Count |
118+
|:---|:---:|
119+
| πŸ“¦ **Public Repositories** | {stats['total_repos']} |
120+
| πŸ‘₯ **Followers** | {stats['followers']} |
121+
122+
#### πŸ› οΈ Top Technologies
123+
{langs}
124+
125+
<sub>Last automated update: {stats['last_updated']} β€’ Built with ⚑ by Javad</sub>
126+
</div>"""
127+
128+
def update_readme(stats_content):
129+
with open('README.md', 'r', encoding='utf-8') as f:
130+
content = f.read()
131+
132+
# Precise regex to replace the section
133+
pattern = r'### πŸ“Š GitHub Stats.*?(?=\n---|\Z)'
134+
new_content = re.sub(pattern, stats_content, content, flags=re.DOTALL)
135+
136+
with os.fdopen(os.open('README.md', os.O_WRONLY | os.O_TRUNC | os.O_CREAT, 0o644), 'w', encoding='utf-8') as f:
137+
f.write(new_content)
138+
139+
if __name__ == "__main__":
140+
TOKEN = os.environ.get('GITHUB_TOKEN')
141+
USER = os.environ.get('USERNAME', 'javaadde')
142+
143+
if TOKEN:
144+
data = get_github_data(USER, TOKEN)
145+
if data:
146+
update_readme(format_stats(data))
147+
print("πŸš€ Stats updated successfully!")
148+
else:
149+
print("❌ Failed to fetch data.")
150+
else:
151+
print("⚠️ No GITHUB_TOKEN found.")
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
name: Update GitHub Stats
2+
3+
on:
4+
schedule:
5+
# Runs every day at 00:00 UTC (5:30 AM IST)
6+
- cron: '0 0 * * *'
7+
workflow_dispatch: # Allows manual trigger
8+
9+
jobs:
10+
update-stats:
11+
runs-on: ubuntu-latest
12+
permissions:
13+
contents: write
14+
15+
steps:
16+
- name: Checkout repository
17+
uses: actions/checkout@v4
18+
with:
19+
token: ${{ secrets.GITHUB_TOKEN }}
20+
21+
- name: Set up Python
22+
uses: actions/setup-python@v5
23+
with:
24+
python-version: '3.11'
25+
26+
- name: Install dependencies
27+
run: |
28+
pip install requests PyGithub
29+
30+
- name: Update README with stats
31+
env:
32+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
33+
USERNAME: javaadde
34+
run: python .github/scripts/update_stats.py
35+
36+
- name: Commit and push if changed
37+
run: |
38+
git config --global user.name 'github-actions[bot]'
39+
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
40+
git add README.md
41+
git diff --quiet && git diff --staged --quiet || (git commit -m "πŸ€– Auto-update GitHub stats [skip ci]" && git push)

β€ŽREADME.mdβ€Ž

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,24 @@ const javad = {
5959

6060
---
6161

62-
### πŸ“Š Contribution Graph
62+
### πŸ“Š GitHub Stats
6363

64-
[![GitHub Streak](https://github-readme-streak-stats.herokuapp.com?user=javaadde&theme=react&hide_border=true&border_radius=&date_format=M%20j%5B%2C%20Y%5D)](https://git.io/streak-stats)
64+
<div align="center">
65+
66+
| πŸ”₯ **Contribution Streak** | πŸ† **Total Contributions** | ⭐ **Total Stars** |
67+
|:---:|:---:|:---:|
68+
| **Loading...** | **Loading...** | **Loading...** |
69+
70+
| πŸ“ˆ Metric | πŸ”’ Count |
71+
|:---|:---:|
72+
| πŸ“¦ **Public Repositories** | Loading... |
73+
| πŸ‘₯ **Followers** | Loading... |
74+
75+
#### πŸ› οΈ Top Technologies
76+
![Loading](https://img.shields.io/badge/-Loading-333?style=flat-square)
77+
78+
<sub>Next update: Midnight UTC β€’ Auto-updating via GitHub Actions</sub>
79+
</div>
6580

6681
---
6782

0 commit comments

Comments
Β (0)