Skip to content

Update language.json #22

Update language.json

Update language.json #22

Workflow file for this run

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
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):
"""獲取指定 GitHub 倉庫的統計數據並整合插件信息"""
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
def get_status(version):
if "-pre" in version:
return "pre"
elif "-rc" in version:
return "rc"
return "stable"
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"],
"status": get_status(plugin_info["version"]),
"repository": {
"full_name": repo_data["full_name"],
"releases": {
"total_count": len(releases),
"total_downloads": total_downloads,
"releases": release_stats
}
}
}
try:
print("初始化資料...")
os.makedirs("data", exist_ok=True)
# 獲取 PR 中修改的文件
changed_info_files = get_changed_files()
if not changed_info_files:
print("No plugin info files were changed in this PR")
exit(0)
# 讀取現有的 stats 文件
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)
now = datetime.now(timezone("Asia/Taipei")).strftime("%Y-%m-%d %H:%M:%S")
# 只處理 PR 中修改的插件文件
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:
matched = False
for i, obj in enumerate(repository_stats):
if obj["name"] == stats["name"]:
repository_stats[i] = stats
repository_stats[i]["updated_at"] = now
matched = True
print(f"更新倉庫數據: {stats['name']}")
break
if not matched:
stats["updated_at"] = now
repository_stats.append(stats)
print(f"新增倉庫數據: {stats['name']}")
except Exception as e:
print(f"處理 {file_path} 時發生錯誤: {str(e)}")
continue
# 壓縮成一行輸出
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)