Skip to content

友链申请: 小辛的互联网作坊 #30

友链申请: 小辛的互联网作坊

友链申请: 小辛的互联网作坊 #30

name: Fetch Links Issues
on:
# 定时任务,每天 00:00 执行(北京时间)
schedule:
- cron: '0 16 * * *'
# 手动触发工作流
workflow_dispatch:
# 当有 issue 被关闭时触发
issues:
types: [closed]
jobs:
fetch-links:
# 新增的 if 判断:
# 1. 如果是定时任务(schedule)或手动触发(workflow_dispatch),则执行。
# 2. 如果是 issue 关闭事件,则检查 issue 是否包含 "Links" 标签,如果包含才执行。
if: >-
github.event_name == 'schedule' ||
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'issues' && contains(github.event.issue.labels.*.name, 'Links'))
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
fetch-depth: 1
token: ${{ secrets.PAT }}
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Fetch Links Issues and Generate JSON
env:
GITHUB_TOKEN: ${{ secrets.PAT }}
run: |
# 创建临时脚本文件
cat > fetch-links.mjs << 'EOF'
import { Octokit } from '@octokit/rest';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// 获取当前文件的目录
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function run() {
try {
// 初始化 GitHub API 客户端
const octokit = new Octokit({
auth: process.env.GITHUB_TOKEN,
});
const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/');
console.log(`仓库: ${owner}/${repo}`);
// 获取带有 "Links" 标签的 issues(包括已关闭的)
const { data: issues } = await octokit.issues.listForRepo({
owner,
repo,
state: 'all',
labels: 'Links',
per_page: 100,
});
console.log(`找到 ${issues.length} 个带有 Links 标签的 issues`);
// 处理每个 issue 的内容
const links = [];
for (const issue of issues) {
try {
// 提取 JSON 内容
const content = issue.body.trim();
// 尝试解析 JSON (移除可能存在的 markdown 分隔符)
const cleanContent = content.replace(/^```json\n|\n```$/g, '').split('---')[0].trim();
const linkData = JSON.parse(cleanContent);
// 确保数据有必要的字段
if (linkData.name && linkData.link) {
links.push(linkData);
console.log(`处理成功: ${linkData.name}`);
}
} catch (error) {
console.error(`处理 issue #${issue.number} 时出错:`, error.message);
}
}
// 按名称排序
links.sort((a, b) => a.name.localeCompare(b.name));
// 写入 Links.json 文件
const outputPath = path.join(process.cwd(), 'Links.json');
fs.writeFileSync(outputPath, JSON.stringify(links, null, 2));
console.log(`已生成 Links.json 文件,包含 ${links.length} 个链接`);
} catch (error) {
console.error('执行过程中出错:', error);
process.exit(1);
}
}
run();
EOF
# 安装依赖
npm install @octokit/rest
# 运行脚本
node fetch-links.mjs
- name: Commit and Push Changes
env:
GITHUB_TOKEN: ${{ secrets.PAT }}
run: |
git config --global user.name "GitHub Actions"
git config --global user.email "actions@github.com"
git add Links.json
# 检查是否有更改需要提交
if git diff --staged --quiet; then
echo "Links.json 没有变化,跳过提交"
exit 0
fi
git commit -m "更新 Links.json [skip ci]"
git push