This commit is contained in:
2026-03-18 01:25:49 +08:00
committed by cnb
parent 819cbcebac
commit 83ac00588e
6 changed files with 118 additions and 10 deletions

68
src/routes/sync.ts Normal file
View File

@@ -0,0 +1,68 @@
import { app, gitea, rootPath } from '../app'
import { Repo } from './cnb';
import { execSync } from 'node:child_process';
import path from 'node:path';
import fs from 'fs';
import { useKey } from '@kevisual/context';
app.route({
path: 'repo',
key: 'sync',
description: '同步仓库数据',
}).define(async (ctx) => {
const res = await app.run({ path: 'cnb', key: 'list-today' });
if (res.code === 200) {
const list: Repo[] = res.data.list || [];
let syncList: Repo[] = [];
for (const item of list) {
try {
const [owner, repo] = item.path.split('/');
const giteaRepo = await gitea.repo.getRepo(owner, repo);
const giteaUsername = 'oauth2';
const giteaPassword = useKey('GITEA_TOKEN');
item.giteaUrl = `https://${giteaUsername}:${giteaPassword}@git.xiongxiao.me/${owner}/${repo}.git`;
if (giteaRepo.code === 200) {
// 已经存在了
} else {
await gitea.repo.createRepo({
name: owner + '/' + repo,
description: item.description,
});
}
syncList.push(item);
} catch (err) {
console.error(`处理 ${item.path} 失败`, item);
}
// 开始同步
for (const repo of syncList) {
try {
await sync(repo);
} catch (err) {
console.error(`同步 ${repo.path} 失败`, repo);
}
}
}
}
}).addTo(app)
const sync = async (repo: Repo) => {
const cwd = path.join(rootPath, repo.name);
if (!fs.existsSync(cwd)) {
execSync(`git clone ${repo.web_url} ${cwd}`);
}
// 添加一个remote 叫做gitea的远程仓库指向gitea的地址
const remoteUrl = repo.giteaUrl!;
try {
execSync(`git remote add gitea ${remoteUrl}`, { cwd });
} catch (err) {
// 已经添加过了
}
try {
// 拉取最新的代码
execSync(`git pull origin main`, { cwd });
// 推送到gitea
execSync(`git push gitea main`, { cwd });
} catch (err) {
console.error(`同步推送 ${repo.path} 失败`, repo);
}
}