Skip to content

Commit 3343abe

Browse files
authored
Merge pull request #15 from brown9804/update-traffic-api-14tohistorical
updating logic from 14 to historical
2 parents 2ee60f2 + d6e074c commit 3343abe

4 files changed

Lines changed: 116 additions & 23 deletions

File tree

.github/workflows/update-metrics.yml

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,23 @@ jobs:
2727
with:
2828
node-version: '20'
2929

30+
# You only need this if you want to isolate node_modules/npm install
31+
# Otherwise, just run the next step in the main directory
32+
- name: Run visitor counter logic in temp folder
33+
run: |
34+
mkdir temp-run
35+
cp update_repo_views_counter.js package.json package-lock.json temp-run/
36+
cd temp-run
37+
npm ci
38+
node update_repo_views_counter.js
39+
cd ..
40+
rm -rf temp-run
41+
env:
42+
TRAFFIC_TOKEN: ${{ secrets.TRAFFIC_TOKEN }}
43+
REPO: ${{ github.repository }}
44+
3045
- name: Install dependencies
31-
run: npm install
46+
run: npm ci
3247

3348
- name: Update visitor count
3449
run: node update_repo_views_counter.js
@@ -41,37 +56,38 @@ jobs:
4156
git config --global user.name "github-actions[bot]"
4257
git config --global user.email "github-actions[bot]@users.noreply.github.com"
4358
59+
# For PRs: update the PR branch
4460
- name: Commit and push to PR branch
4561
if: github.event_name == 'pull_request'
4662
env:
4763
TOKEN: ${{ secrets.GITHUB_TOKEN }}
4864
run: |
4965
git fetch origin
50-
git checkout -b ${{ github.event.pull_request.head.ref }} origin/${{ github.event.pull_request.head.ref }}
66+
git checkout ${{ github.event.pull_request.head.ref }}
5167
git add -A
5268
git commit -m "Update visitor count" || echo "No changes to commit"
5369
git remote set-url origin https://x-access-token:${TOKEN}@github.com/${{ github.repository }}
5470
git push origin HEAD:${{ github.event.pull_request.head.ref }}
5571
56-
- name: Commit and push to new branch (non-PR)
57-
if: github.event_name == 'pull_request'
72+
# For non-PRs (scheduled/manual): push to a dedicated temp branch and create a PR
73+
- name: Commit and push to temp branch
74+
if: github.event_name != 'pull_request'
5875
env:
5976
TOKEN: ${{ secrets.GITHUB_TOKEN }}
6077
run: |
61-
git fetch origin
62-
git checkout ${{ github.event.pull_request.head.ref }} || git checkout -b ${{ github.event.pull_request.head.ref }} origin/${{ github.event.pull_request.head.ref }}
78+
BRANCH="visitor-counter-update-${{ github.run_id }}"
79+
git checkout -b $BRANCH
6380
git add -A
6481
git commit -m "Update visitor count" || echo "No changes to commit"
6582
git remote set-url origin https://x-access-token:${TOKEN}@github.com/${{ github.repository }}
66-
git pull --rebase origin ${{ github.event.pull_request.head.ref }} || echo "No rebase needed"
67-
git push origin HEAD:${{ github.event.pull_request.head.ref }}
83+
git push origin HEAD:$BRANCH
6884
6985
- name: Create Pull Request (non-PR)
7086
if: github.event_name != 'pull_request'
7187
uses: peter-evans/create-pull-request@v6
7288
with:
7389
token: ${{ secrets.GITHUB_TOKEN }}
74-
branch: ${{ steps.push.outputs.branch }}
90+
branch: visitor-counter-update-${{ github.run_id }}
7591
title: "Update visitor count"
7692
body: "Automated update of visitor count"
7793
base: main

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ Last updated: 2025-07-10
151151

152152
<!-- START BADGE -->
153153
<div align="center">
154-
<img src="https://img.shields.io/badge/Total%20views-1022-limegreen" alt="Total views">
155-
<p>Refresh Date: 2025-07-11</p>
154+
<img src="https://img.shields.io/badge/Total%20views-1152-limegreen" alt="Total views">
155+
<p>Refresh Date: 2025-07-14</p>
156156
</div>
157157
<!-- END BADGE -->

metrics.json

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,32 @@
1-
{
2-
"total_views": 1022,
3-
"lastUpdated": "2025-07-11T20:07:49.421Z"
4-
}
1+
[
2+
{
3+
"date": "2025-07-07",
4+
"count": 330,
5+
"uniques": 20
6+
},
7+
{
8+
"date": "2025-07-08",
9+
"count": 159,
10+
"uniques": 6
11+
},
12+
{
13+
"date": "2025-07-10",
14+
"count": 482,
15+
"uniques": 1
16+
},
17+
{
18+
"date": "2025-07-11",
19+
"count": 170,
20+
"uniques": 4
21+
},
22+
{
23+
"date": "2025-07-12",
24+
"count": 7,
25+
"uniques": 1
26+
},
27+
{
28+
"date": "2025-07-14",
29+
"count": 4,
30+
"uniques": 1
31+
}
32+
]

update_repo_views_counter.js

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ if (!GITHUB_TOKEN || !REPO) {
1414

1515
const METRICS_FILE = 'metrics.json';
1616

17-
async function getVisitorCount() {
17+
// Fetch the last 14 days of traffic data (GitHub API returns up to 14 days)
18+
async function getLast14DaysTraffic() {
1819
const res = await fetch(`https://api.github.com/repos/${REPO}/traffic/views`, {
1920
headers: {
2021
'Accept': 'application/vnd.github+json',
@@ -29,20 +30,55 @@ async function getVisitorCount() {
2930
}
3031

3132
const data = await res.json();
32-
return data.count || 0;
33+
// Each entry contains: timestamp, count, uniques
34+
return data.views.map(item => ({
35+
date: item.timestamp.slice(0, 10), // Keep only YYYY-MM-DD
36+
count: item.count,
37+
uniques: item.uniques
38+
}));
3339
}
3440

35-
function updateMetricsFile(total_views) {
36-
const lastUpdated = new Date().toISOString();
37-
const metrics = { total_views, lastUpdated };
41+
// Read metrics.json as an array of daily entries (if exists)
42+
function readMetrics() {
43+
if (fs.existsSync(METRICS_FILE)) {
44+
const raw = fs.readFileSync(METRICS_FILE, 'utf-8');
45+
try {
46+
const arr = JSON.parse(raw);
47+
if (Array.isArray(arr)) return arr;
48+
} catch (e) {
49+
console.error('metrics.json is not valid JSON. Starting fresh.');
50+
}
51+
}
52+
return [];
53+
}
54+
55+
// Write the updated metrics array back to metrics.json
56+
function writeMetrics(metrics) {
3857
fs.writeFileSync(METRICS_FILE, JSON.stringify(metrics, null, 2));
39-
console.log(`metrics.json updated with ${total_views} views`);
58+
console.log(`metrics.json updated with ${metrics.length} days`);
4059
}
4160

61+
// Merge existing and new metrics, using the date as the unique key
62+
function mergeMetrics(existing, fetched) {
63+
// Use an object for fast deduplication by date
64+
const byDate = {};
65+
existing.forEach(entry => { byDate[entry.date] = entry; });
66+
fetched.forEach(entry => { byDate[entry.date] = entry; });
67+
// Convert back to array and sort by date ascending
68+
return Object.values(byDate).sort((a, b) => a.date.localeCompare(b.date));
69+
}
70+
71+
// Calculate the sum of all view counts (historical total)
72+
function calculateTotalViews(metrics) {
73+
return metrics.reduce((sum, entry) => sum + entry.count, 0);
74+
}
75+
76+
// Find and update the badge block in all Markdown files (recursive)
4277
function updateMarkdownBadges(total_views) {
4378
const refreshDate = new Date().toISOString().split('T')[0];
4479
const badgeRegex = /<!-- START BADGE -->[\s\S]*?<!-- END BADGE -->/g;
4580

81+
// This is your existing badge schema, preserved as requested
4682
const badgeBlock = `<!-- START BADGE -->
4783
<div align="center">
4884
<img src="https://img.shields.io/badge/Total%20views-${total_views}-limegreen" alt="Total views">
@@ -63,6 +99,7 @@ function updateMarkdownBadges(total_views) {
6399
});
64100
}
65101

102+
// Recursively find all Markdown files in a directory
66103
function findMarkdownFiles(dir) {
67104
let results = [];
68105
const list = fs.readdirSync(dir);
@@ -78,17 +115,29 @@ function findMarkdownFiles(dir) {
78115
return results;
79116
}
80117

118+
// Optionally delete node_modules after running
81119
function deleteNodeModules() {
82120
if (fs.existsSync('node_modules')) {
83121
execSync('rm -rf node_modules', { stdio: 'inherit' });
84122
console.log('node_modules folder deleted.');
85123
}
86124
}
87125

126+
// Main async function to orchestrate update
88127
(async () => {
89128
try {
90-
const total_views = await getVisitorCount();
91-
updateMetricsFile(total_views);
129+
// Fetch latest 14 days of traffic data
130+
const fetched = await getLast14DaysTraffic();
131+
// Load existing metrics.json (if present)
132+
const existing = readMetrics();
133+
// Merge and deduplicate daily metrics
134+
const merged = mergeMetrics(existing, fetched);
135+
// Save the updated metrics array
136+
writeMetrics(merged);
137+
138+
// Calculate historical total views for badge
139+
const total_views = calculateTotalViews(merged);
140+
// Update the badge in Markdown files
92141
updateMarkdownBadges(total_views);
93142
} catch (err) {
94143
console.error(err);

0 commit comments

Comments
 (0)