Compare commits

...

9 Commits

2 changed files with 43 additions and 36 deletions
+6 -1
View File
@@ -1,4 +1,9 @@
FROM node:20 FROM alpine
RUN apk add --no-cache bash nodejs npm git \
&& node --version \
&& npm --version \
&& git --version
WORKDIR /action WORKDIR /action
+37 -35
View File
@@ -1,49 +1,51 @@
import { spawnSync } from 'child_process';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import axios from 'axios'; import { GITEA_SERVER_URL, GITEA_REPOSITORY, GITEA_TOKEN, PR_HEAD_BRANCH, FINDINGS_PATH } from './config.js';
import https from 'https';
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_HEAD_BRANCH, FINDINGS_PATH } from './config.js';
const httpsAgent = new https.Agent({ rejectUnauthorized: false }); function git(args, cwd) {
const headers = () => ({ Authorization: `token ${GITEA_TOKEN}`, 'Content-Type': 'application/json' }); const result = spawnSync('git', args, { cwd, encoding: 'utf8' });
const api = (p) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${p}`; 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) { export async function commitAndPush(workspace) {
try { const remoteUrl = GITEA_SERVER_URL.replace(/\/$/, '')
const fullPath = path.join(workspace, FINDINGS_PATH); .replace('https://', `https://${GITEA_TOKEN}@`)
const content = fs.readFileSync(fullPath, 'utf8'); .replace('http://', `http://${GITEA_TOKEN}@`) + `/${GITEA_REPOSITORY}.git`;
const encoded = Buffer.from(content).toString('base64');
const url = api(`/repos/${GITEA_REPOSITORY}/contents/${FINDINGS_PATH}`);
// 取得現有檔案 SHA(若存在) const repoDir = path.join(workspace, 'repo');
let sha;
try { try {
const res = await axios.get(`${url}?ref=${encodeURIComponent(PR_HEAD_BRANCH)}`, { headers: headers(), httpsAgent, timeout: 15000 }); if (!fs.existsSync(repoDir)) {
sha = res.data.sha; git(['clone', '--depth=1', '--branch', PR_HEAD_BRANCH, remoteUrl, repoDir], workspace);
} catch {
sha = undefined;
} }
const payload = JSON.stringify({ git(['config', 'user.email', 'ai-review[bot]@gitea'], repoDir);
message: 'chore: update ai-review findings [skip ci]', git(['config', 'user.name', 'AI Review Bot'], repoDir);
content: encoded, git(['fetch', 'origin', PR_HEAD_BRANCH], repoDir);
branch: PR_HEAD_BRANCH, git(['checkout', PR_HEAD_BRANCH], repoDir);
...(sha ? { sha } : {}),
});
const resp = await axios.request({ // 將 findings.json 從 workspace 複製到 clone 的 repo
method: sha ? 'put' : 'post', const srcFindings = path.join(workspace, FINDINGS_PATH);
url, const destFindings = path.join(repoDir, FINDINGS_PATH);
headers: { ...headers(), 'Content-Type': 'application/json' }, fs.mkdirSync(path.dirname(destFindings), { recursive: true });
httpsAgent, fs.copyFileSync(srcFindings, destFindings);
timeout: 30000,
data: payload,
});
const commitHash = resp.data.commit?.sha?.slice(0, 7) || 'unknown'; 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}`); console.log(` ✅ persisted findings commit=${commitHash} push=${PR_HEAD_BRANCH}`);
} catch (e) { } catch (e) {
const detail = e.response?.data ? JSON.stringify(e.response.data) : e.message; console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.message}`);
console.log(` ⚠️ Runner failed: commit/push 失敗: ${e.response?.status || ''} ${detail}`);
} }
} }