52 lines
1.6 KiB
JavaScript
52 lines
1.6 KiB
JavaScript
import axios from 'axios';
|
|
import https from 'https';
|
|
import { GITEA_TOKEN, GITEA_SERVER_URL, GITEA_REPOSITORY, PR_NUMBER, PR_HEAD_BRANCH } from './config.js';
|
|
|
|
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
|
|
const headers = () => ({ Authorization: `token ${GITEA_TOKEN}`, 'Content-Type': 'application/json' });
|
|
const api = (path) => `${GITEA_SERVER_URL.replace(/\/$/, '')}/api/v1${path}`;
|
|
|
|
export async function getPRDiff() {
|
|
const resp = await axios.get(api(`/repos/${GITEA_REPOSITORY}/pulls/${PR_NUMBER}.diff`), { headers: headers(), timeout: 60000, httpsAgent });
|
|
return resp.data;
|
|
}
|
|
|
|
export async function postComment(body) {
|
|
const resp = await axios.post(api(`/repos/${GITEA_REPOSITORY}/issues/${PR_NUMBER}/comments`), { body }, { headers: headers(), timeout: 30000, httpsAgent });
|
|
return resp.data;
|
|
}
|
|
|
|
/**
|
|
* 透過 Gitea API 建立或更新檔案(不需要 git binary)
|
|
*/
|
|
export async function commitFile(filePath, content, message) {
|
|
const encoded = Buffer.from(content).toString('base64');
|
|
const url = api(`/repos/${GITEA_REPOSITORY}/contents/${filePath}`);
|
|
|
|
// 先嘗試取得現有檔案的 SHA
|
|
let sha;
|
|
try {
|
|
const existing = await axios.get(`${url}?ref=${PR_HEAD_BRANCH}`, { headers: headers(), httpsAgent, timeout: 15000 });
|
|
sha = existing.data.sha;
|
|
} catch {
|
|
sha = undefined;
|
|
}
|
|
|
|
const payload = {
|
|
message,
|
|
content: encoded,
|
|
branch: PR_HEAD_BRANCH,
|
|
...(sha ? { sha } : {}),
|
|
};
|
|
|
|
const resp = await axios.request({
|
|
method: sha ? 'put' : 'post',
|
|
url,
|
|
headers: headers(),
|
|
httpsAgent,
|
|
timeout: 30000,
|
|
data: payload,
|
|
});
|
|
return resp.data;
|
|
}
|