Skip to content

Update language.json #34

Update language.json

Update language.json #34

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
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)