fix: 改回 Gitea API commit,修正 URL encode 與 JSON.stringify

This commit is contained in:
2026-05-11 10:30:07 +00:00
parent af51ffacee
commit 2193bdd4d6
+37 -24
View File
@@ -1,36 +1,49 @@
import { spawnSync } from 'child_process'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { GITEA_SERVER_URL, GITEA_REPOSITORY, GITEA_TOKEN, PR_HEAD_BRANCH, FINDINGS_PATH } from './config.js'; import axios from 'axios';
import https from 'https';
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_HEAD_BRANCH, FINDINGS_PATH } from './config.js';
function git(args, cwd) { const httpsAgent = new https.Agent({ rejectUnauthorized: false });
const result = spawnSync('git', args, { cwd, encoding: 'utf8' }); const headers = () => ({ Authorization: `token ${GITEA_TOKEN}`, 'Content-Type': 'application/json' });
if (result.error) throw result.error; const api = (p) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${p}`;
if (result.status !== 0) throw new Error((result.stderr || result.stdout || '').trim());
return (result.stdout || '').trim();
}
export async function commitAndPush(workspace) { export async function commitAndPush(workspace) {
const repoDir = path.join(workspace, GITEA_REPOSITORY);
const remoteUrl = GITEA_SERVER_URL.replace(/\/$/, '').replace('https://', `https://${GITEA_TOKEN}@`).replace('http://', `http://${GITEA_TOKEN}@`) + `/${GITEA_REPOSITORY}.git`;
try { try {
git(['config', 'user.email', 'ai-review[bot]@gitea'], repoDir); const fullPath = path.join(workspace, GITEA_REPOSITORY, FINDINGS_PATH);
git(['config', 'user.name', 'AI Review Bot'], repoDir); const content = fs.readFileSync(fullPath, 'utf8');
git(['fetch', 'origin', PR_HEAD_BRANCH], repoDir); const encoded = Buffer.from(content).toString('base64');
git(['checkout', PR_HEAD_BRANCH], repoDir); const url = api(`/repos/${GITEA_REPOSITORY}/contents/${FINDINGS_PATH}`);
git(['add', FINDINGS_PATH], repoDir);
const status = git(['status', '--porcelain'], repoDir); // 取得現有檔案 SHA(若存在)
if (!status) { let sha;
console.log(' findings.json 無變更,跳過 commit'); try {
return; const res = await axios.get(`${url}?ref=${encodeURIComponent(PR_HEAD_BRANCH)}`, { headers: headers(), httpsAgent, timeout: 15000 });
sha = res.data.sha;
} catch {
sha = undefined;
} }
const out = git(['commit', '-m', 'chore: update ai-review findings [skip ci]'], repoDir); const payload = JSON.stringify({
const commitHash = out.match(/\[.+ ([a-f0-9]+)\]/)?.[1] || 'unknown'; message: 'chore: update ai-review findings [skip ci]',
git(['push', remoteUrl, PR_HEAD_BRANCH], repoDir); content: encoded,
branch: PR_HEAD_BRANCH,
...(sha ? { sha } : {}),
});
const resp = await axios.request({
method: sha ? 'put' : 'post',
url,
headers: { ...headers(), 'Content-Type': 'application/json' },
httpsAgent,
timeout: 30000,
data: payload,
});
const commitHash = resp.data.commit?.sha?.slice(0, 7) || 'unknown';
console.log(` ✅ persisted findings commit=${commitHash} push=${PR_HEAD_BRANCH}`); console.log(` ✅ persisted findings commit=${commitHash} push=${PR_HEAD_BRANCH}`);
} catch (e) { } catch (e) {
console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.message}`); const detail = e.response?.data ? JSON.stringify(e.response.data) : e.message;
console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.response?.status || ''} ${detail}`);
} }
} }