52 lines
2.0 KiB
JavaScript
52 lines
2.0 KiB
JavaScript
import { spawnSync } from 'child_process';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { GITEA_SERVER_URL, GITEA_REPOSITORY, GITEA_TOKEN, PR_HEAD_BRANCH, FINDINGS_PATH } from './config.js';
|
|
|
|
function git(args, cwd) {
|
|
const result = spawnSync('git', args, { cwd, encoding: 'utf8' });
|
|
if (result.error) throw result.error;
|
|
if (result.status !== 0) throw new Error((result.stderr || result.stdout || '').trim());
|
|
return (result.stdout || '').trim();
|
|
}
|
|
|
|
export async function commitAndPush(workspace) {
|
|
const remoteUrl = GITEA_SERVER_URL.replace(/\/$/, '')
|
|
.replace('https://', `https://${GITEA_TOKEN}@`)
|
|
.replace('http://', `http://${GITEA_TOKEN}@`) + `/${GITEA_REPOSITORY}.git`;
|
|
|
|
const repoDir = path.join(workspace, 'repo');
|
|
|
|
try {
|
|
if (!fs.existsSync(repoDir)) {
|
|
git(['clone', '--depth=1', '--branch', PR_HEAD_BRANCH, remoteUrl, repoDir], workspace);
|
|
}
|
|
|
|
git(['config', 'user.email', 'ai-review[bot]@gitea'], repoDir);
|
|
git(['config', 'user.name', 'AI Review Bot'], repoDir);
|
|
git(['fetch', 'origin', PR_HEAD_BRANCH], repoDir);
|
|
git(['checkout', PR_HEAD_BRANCH], repoDir);
|
|
|
|
// 將 findings.json 從 workspace 複製到 clone 的 repo
|
|
const srcFindings = path.join(workspace, FINDINGS_PATH);
|
|
const destFindings = path.join(repoDir, FINDINGS_PATH);
|
|
fs.mkdirSync(path.dirname(destFindings), { recursive: true });
|
|
fs.copyFileSync(srcFindings, destFindings);
|
|
|
|
git(['add', FINDINGS_PATH], repoDir);
|
|
|
|
const status = git(['status', '--porcelain'], repoDir);
|
|
if (!status) {
|
|
console.log(' findings.json 無變更,跳過 commit');
|
|
return;
|
|
}
|
|
|
|
const out = git(['commit', '-m', 'chore: update ai-review findings [skip ci]'], repoDir);
|
|
const commitHash = out.match(/\[.+ ([a-f0-9]+)\]/)?.[1] || 'unknown';
|
|
git(['push', remoteUrl, PR_HEAD_BRANCH], repoDir);
|
|
console.log(` ✅ persisted findings commit=${commitHash} push=${PR_HEAD_BRANCH}`);
|
|
} catch (e) {
|
|
console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.message}`);
|
|
}
|
|
}
|