Skip to content

Update setting.json #15

Update setting.json

Update setting.json #15

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 # 確保能獲取完整的 git 歷史
token: ${{ secrets.PAT_TOKEN }}
- name: Validate Merge and File Changes
run: |
echo "Checking if PR is merged..."
if [[ "${{ github.event.pull_request.merged }}" != "true" ]]; then
echo "PR is not merged. Skipping workflow."
exit 0
fi
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"
echo "Head SHA: $HEAD_SHA"
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
from datetime import datetime
from pytz import timezone
def get_repo_stats(owner, repo, info_name):
"""獲取指定 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
return {
"name": info_name, # 使用 infos/*.json 中的 name
"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)
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")
if os.path.exists("infos"):
for filename in os.listdir("infos"):
if filename.endswith(".json"):
with open(f"infos/{filename}", "r", encoding="utf-8") as f:
try:
data = json.load(f)
if "link" in data and "github.com" in data["link"] and "name" in data:
parts = data["link"].strip("/").split("/")
if len(parts) >= 2:
owner, repo = parts[-2], parts[-1]
print(f"處理倉庫: {owner}/{repo} ({data['name']})")
stats = get_repo_stats(owner, repo, data['name'])
if stats:
matched = False
for obj in repository_stats:
if obj["name"] == stats["name"]:
obj.update(stats)
obj["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"處理 {filename} 時發生錯誤: {str(e)}")
continue
with open(stats_file, "w", encoding="utf-8") as f:
json.dump(repository_stats, f, indent=2, ensure_ascii=False)
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)