import { readFileSync } from 'node:fs'; // Gitea exposes its event payload through the GitHub-compatible runner variables. export function readCiContext() { const env = process.env; const eventName = env.GITHUB_EVENT_NAME; if (!['push', 'pull_request', 'workflow_dispatch'].includes(eventName)) { throw new Error('Only push, pull_request and workflow_dispatch events are supported.'); } const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8')); const commit = env.GITHUB_SHA; if (!/^[a-f0-9]{40}$/.test(commit ?? '')) throw new Error('A commit SHA is required.'); const pullRequest = eventName === 'pull_request' ? event.pull_request : undefined; if (eventName === 'pull_request' && pullRequest?.head?.sha !== commit) { throw new Error('CI must validate the pull request head commit.'); } const tag = env.GITHUB_REF?.startsWith('refs/tags/') ? env.GITHUB_REF.slice(10) : ''; const branch = pullRequest ? pullRequest.head.ref : env.GITHUB_REF?.startsWith('refs/heads/') ? env.GITHUB_REF.slice(11) : ''; if (!tag && !branch) throw new Error('A branch or tag ref is required.'); const slug = branch .toLowerCase() .replace(/[^a-z0-9]/g, '-') .slice(0, 63) .replace(/^-+|-+$/g, ''); const publish = eventName === 'push' || (eventName === 'pull_request' && Boolean(env.GITHUB_REPOSITORY) && pullRequest.head.repo?.full_name === env.GITHUB_REPOSITORY); return { commit, tag, branch, slug, publish, pullRequest, before: event.before }; }