Files
to-my-gitea-cron/src/routes/sync.ts
2026-03-18 01:29:09 +08:00

68 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}