generated from ExpTechTW/Example
-
Notifications
You must be signed in to change notification settings - Fork 2
205 lines (169 loc) · 8.29 KB
/
track.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
name: Track Repository Stats
on:
pull_request:
types:
- closed
jobs:
track-stats:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.PAT_TOKEN }}
- name: Get changed files
id: changed-files
run: |
echo "Getting changed files..."
BASE_SHA=${{ github.event.pull_request.base.sha }}
HEAD_SHA=${{ github.event.pull_request.head.sha }}
echo "base_sha=$BASE_SHA" >> $GITHUB_ENV
echo "head_sha=$HEAD_SHA" >> $GITHUB_ENV
CHANGED_FILES=$(git diff --name-only $BASE_SHA $HEAD_SHA)
echo "Changed files: $CHANGED_FILES"
if ! echo "$CHANGED_FILES" | grep -q "^infos/"; then
echo "No changes in infos/ directory. Skipping workflow."
exit 0
fi
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install requests python-dateutil pytz
- name: Fetch repository stats
env:
GITHUB_TOKEN: ${{ secrets.PAT_TOKEN }}
run: |
python - <<EOF
import json
import os
import requests
import subprocess
from datetime import datetime
from pytz import timezone
from operator import itemgetter
def get_changed_files():
base_sha = "${{ github.event.pull_request.base.sha }}"
head_sha = "${{ github.event.pull_request.head.sha }}"
cmd = f"git diff --name-only {base_sha} {head_sha}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return [f for f in result.stdout.strip().split('\n') if f.startswith('infos/') and f.endswith('.json')]
def get_repo_stats(owner, repo, plugin_info):
headers = {
"Authorization": f"token {os.environ.get('GITHUB_TOKEN')}",
"Accept": "application/vnd.github.v3+json"
}
base_url = f"https://api.github.com/repos/{owner}/{repo}"
repo_response = requests.get(base_url, headers=headers)
if repo_response.status_code != 200:
print(f"Failed to get repo info: {repo_response.status_code}")
return None
repo_data = repo_response.json()
releases_response = requests.get(f"{base_url}/releases", headers=headers)
releases = releases_response.json() if releases_response.status_code == 200 else []
total_downloads = 0
release_stats = []
for release in releases:
release_downloads = sum(asset["download_count"] for asset in release["assets"])
release_stats.append({
"tag_name": release["tag_name"],
"name": release["name"],
"downloads": release_downloads,
"published_at": release["published_at"]
})
total_downloads += release_downloads
return {
"name": plugin_info["name"],
"version": plugin_info["version"],
"description": plugin_info["description"],
"author": plugin_info["author"],
"dependencies": plugin_info.get("dependencies", {}),
"resources": plugin_info.get("resources", []),
"link": plugin_info["link"],
"repository": {
"full_name": repo_data["full_name"],
"releases": {
"total_count": len(releases),
"total_downloads": total_downloads,
"releases": release_stats
}
}
}
def process_plugin_files(repository_stats, changed_info_files):
now = datetime.now(timezone("Asia/Taipei")).strftime("%Y-%m-%d %H:%M:%S")
oldest_index = None
oldest_time = None
for i, obj in enumerate(repository_stats):
current_time = obj.get("updated_at", "")
if oldest_time is None or current_time < oldest_time:
oldest_time = current_time
oldest_index = i
for file_path in changed_info_files:
try:
with open(file_path, "r", encoding="utf-8") as f:
plugin_info = json.load(f)
if "link" in plugin_info and "github.com" in plugin_info["link"] and "name" in plugin_info:
parts = plugin_info["link"].strip("/").split("/")
if len(parts) >= 2:
owner, repo = parts[-2], parts[-1]
print(f"處理倉庫: {owner}/{repo} ({plugin_info['name']})")
stats = get_repo_stats(owner, repo, plugin_info)
if stats:
stats["updated_at"] = now
for i, obj in enumerate(repository_stats):
if obj["name"] == stats["name"]:
repository_stats[i] = stats
print(f"更新倉庫數據: {stats['name']}")
break
else:
repository_stats.append(stats)
print(f"新增倉庫數據: {stats['name']}")
except Exception as e:
print(f"處理 {file_path} 時發生錯誤: {str(e)}")
continue
if oldest_index is not None:
oldest_record = repository_stats[oldest_index]
if "link" in oldest_record and "github.com" in oldest_record["link"]:
parts = oldest_record["link"].strip("/").split("/")
if len(parts) >= 2:
owner, repo = parts[-2], parts[-1]
stats = get_repo_stats(owner, repo, oldest_record)
if stats:
oldest_record["repository"] = stats["repository"]
oldest_record["updated_at"] = now
print(f"更新最舊的倉庫狀態: {oldest_record['name']}")
return repository_stats
try:
print("初始化資料...")
os.makedirs("data", exist_ok=True)
changed_info_files = get_changed_files()
if not changed_info_files:
print("No plugin info files were changed in this PR")
exit(0)
stats_file = "data/repository_stats.json"
repository_stats = []
if os.path.exists(stats_file):
with open(stats_file, "r", encoding="utf-8") as f:
repository_stats = json.load(f)
repository_stats = process_plugin_files(repository_stats, changed_info_files)
repository_stats.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
with open(stats_file, "w", encoding="utf-8") as f:
json.dump(repository_stats, f, ensure_ascii=False, separators=(',', ':'))
print("數據更新完成!")
except Exception as e:
print(f"發生錯誤: {str(e)}")
raise
EOF
- name: Commit and push changes
run: |
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git add data/repository_stats.json
git diff --quiet && git diff --staged --quiet || (git commit -m "Update repository statistics [skip ci]" && git push)