name: Update README Table on: push: branches: - main paths: - '**/*.js' - '**/*.py' jobs: update-readme: runs-on: ubuntu-latest permissions: contents: write steps: - name: 检出代码 uses: actions/checkout@v4 with: fetch-depth: 2 - name: 配置 Python 环境 uses: actions/setup-python@v5 with: python-version: '3.x' - name: 运行更新脚本 env: TZ: Asia/Shanghai run: | cat << 'EOF' > update_readme.py import os import re import datetime import subprocess # 1. 获取更改的文件列表 try: diff_cmd = ['git', 'diff', '--name-only', 'HEAD~1', 'HEAD'] result = subprocess.run(diff_cmd, capture_output=True, text=True, check=True) changed_files = result.stdout.splitlines() except Exception: changed_files = [] target_files = [f for f in changed_files if (f.endswith('.js') or f.endswith('.py')) and os.path.exists(f)] if not target_files: exit(0) # 2. 提取 Env 名称 now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') updates = {} for f in target_files: with open(f, 'r', encoding='utf-8') as file: content = file.read() match = re.search(r'Env\s*\(\s*["\']([^"\']+)["\']\s*\)', content) if match: updates[match.group(1)] = now if not updates: exit(0) # 3. 智能修改内容 readme_path = 'README.md' with open(readme_path, 'r', encoding='utf-8') as f: full_text = f.read() # 设置正确的标记 start_tag = "" end_tag = "" if start_tag not in full_text or end_tag not in full_text: print("未发现表格锚点,请确保 README.md 中包含了 和 ") exit(1) # 找不到锚点直接报错退出,避免破坏文件 # 核心逻辑:拆分文件 -> 处理表格区 -> 重新拼接 pre_part, temp = full_text.split(start_tag) table_section, post_part = temp.split(end_tag) lines = table_section.strip().split('\n') new_table_lines = [] updated_names = set() for line in lines: # 过滤掉旧的表头,稍后统一添加 if line.strip().startswith('|') and '---' not in line and '脚本名称' not in line: parts = [p.strip() for p in line.split('|')] if len(parts) >= 4: name = parts[1] if name in updates: line = f"| {name} | {updates[name]} | ✅ |" updated_names.add(name) if line.strip(): new_table_lines.append(line) # 把剩余完全没在表格里出现过的新脚本加进去 for name, time in updates.items(): if name not in updated_names: new_table_lines.append(f"| {name} | {time} | ✅ |") # 补回表头(确保表头在最前面) table_header = [ "| 脚本名称 | 最后一次更新时间 | 当前状态 |", "| :--- | :----: | :----: |" ] new_table_lines = table_header + new_table_lines # 重新组装整个文件 final_table = "\n".join(new_table_lines) final_content = f"{pre_part}{start_tag}\n{final_table}\n{end_tag}{post_part}" with open(readme_path, 'w', encoding='utf-8') as f: f.write(final_content) EOF python update_readme.py - name: 提交并推送 run: | git config --local user.email "github-actions[bot]@users.noreply.github.com" git config --local user.name "github-actions[bot]" git add README.md if ! git diff --staged --quiet; then git commit -m "docs: 自动更新脚本状态 [skip ci]" git push else echo "没有变化需要提交" fi