mirror of
https://github.com/go-gitea/gitea.git
synced 2026-06-02 21:08:57 +02:00
## Summary This PR improves reusable workflow support for Gitea Actions. The parsing of the called workflow now happens on Gitea side, not on the runner. When the caller becomes ready, Gitea fetches the called workflow source, parses it, and inserts each child job into the database as a `ActionRunJob` linked to the caller via `ParentCallJobID`. As a result, every callee job is dispatched as its own task and its logs surface as an independent job entry in the UI, rather than being inlined into the caller's "Set up job" step. This PR supports two kinds of `uses` : - same-repo call: `uses: ./.gitea/workflows/foo.yaml` - cross-repo call: `uses: OWNER/REPO/.gitea/workflows/foo.yaml@REF` ## **⚠️ BREAKING ⚠️** External reusable workflows (`uses: https://other-gitea-instance/OWNER/REPO/.gitea/workflows/test.yaml@REF`) are no longer supported. To keep using them, clone the repositories to the local instance. ## Main changes ### Execution model - Each caller job carries `IsReusableCaller=true` and won't be fetched by runners. - `ParentCallJobID` can link a called job to its caller. - Caller status is derived from its direct children. ### Workflow syntax - `jobparser` now supports parsing `on: workflow_call` trigger with `inputs:`, `outputs:`, and `secrets:` declarations. - **Max nesting depth**: capped at `MaxReusableCallLevels = 9`, which means a top-level caller may have at most 9 nested callers below it. - **Cycle prevention**: at expansion time, `checkCallerChain` walks the caller's ancestor chain via `ParentCallJobID` and rejects if the same `uses:` string appears anywhere upstream (`reusable workflow call cycle detected`). This catches both direct (`A -> A`) and indirect (`A -> B -> A`) cycles. ### Cross-repo access - To share reusable workflows from private repos, use `Collaborative Owners` introduced by #32562 ### Rerun semantics - `expandRerunJobIDs` partitions the latest attempt's jobs into: - a **rerun set**: jobs being rerun + downstream siblings within the same scope. - an **ancestor set**: reusable callers whose only *some* descendants are being rerun (the caller itself is not). - Cloning behavior for callers in `execRerunPlan`: - **Caller is fully rerun** (caller's `AttemptJobID` in `rerunSet`): none of its descendants are cloned. The caller is cloned with `IsCallerExpanded=false`, and re-expansion (which reinserts the children fresh) happens later when the resolver brings the caller to `Waiting` again. - **Caller is in ancestor set** (only some descendants rerun): the caller is pass-through (`Status` will be updated by its fresh children). Its non-rerun descendants are also pass-through clones (point `SourceTaskID` at the original task). Their `ParentCallJobID` is remapped to the new attempt's caller row. ### UI - Job list in `RepoActionView.vue` is now tree-shaped: callers indent their children. Callers default to collapsed. - New caller detail page using `WorkflowGraph` to show direct children only; the run summary's `WorkflowGraph` shows top-level callers and their immediate descendants. ### Known trade-offs - **Caller expansion runs inside the enclosing write transaction.** `expandReusableWorkflowCaller` performs a git read of the called workflow while holding the row locks that update the caller and insert its children. This is intentional: the caller-row update and child-row inserts must commit atomically. None of the call sites is hot (each caller is expanded once per attempt), so the trade-off is acceptable. - **A malformed `if:` expression on a job leaves it `Blocked` silently.** `evaluateJobIf` now runs server-side as part of resolver passes; deterministic expression errors (typos, undefined context fields) are logged but do not surface in the UI. This is the same behavior the resolver already had for concurrency-expression errors. Distinguishing transient DB errors from user-authored expression errors and writing the latter back as `StatusFailure` is a follow-up. #### Screenshots <img width="1600" alt="image" src="https://github.com/user-attachments/assets/bfaa9b7a-07e9-4127-8de9-a81f86e82828" /> <img width="1600" alt="image" src="https://github.com/user-attachments/assets/8af109b3-ef28-4b53-aaad-d4632b923224" /> ## References - https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows - https://docs.github.com/en/actions/reference/workflows-and-actions/reusing-workflow-configurations --- Replace #36388 --------- Signed-off-by: Zettat123 <zettat123@gmail.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: Claude (Opus 4.7) <noreply@anthropic.com>
207 lines
6.9 KiB
TypeScript
207 lines
6.9 KiB
TypeScript
import {createElementFromAttrs} from '../utils/dom.ts';
|
|
import {renderAnsi} from '../render/ansi.ts';
|
|
import {reactive} from 'vue';
|
|
import type {ActionsArtifact, ActionsJob, ActionsRun, ActionsStatus} from '../modules/gitea-actions.ts';
|
|
import type {IntervalId} from '../types.ts';
|
|
import {POST} from '../modules/fetch.ts';
|
|
|
|
// How GitHub Actions logs work:
|
|
// * Workflow command outputs log commands like "::group::the-title", "::add-matcher::...."
|
|
// * Workflow runner parses and processes the commands to "##[group]", apply "matchers", hide secrets, etc.
|
|
// * The reported logs are the processed logs.
|
|
// HOWEVER: Gitea runner does not completely process those commands. Many works are done by the frontend at the moment.
|
|
const LogLinePrefixCommandMap: Record<string, LogLineCommandName> = {
|
|
'::group::': 'group',
|
|
'##[group]': 'group',
|
|
'::endgroup::': 'endgroup',
|
|
'##[endgroup]': 'endgroup',
|
|
|
|
'##[error]': 'error',
|
|
'##[warning]': 'warning',
|
|
'##[notice]': 'notice',
|
|
'##[debug]': 'debug',
|
|
'##[command]': 'command',
|
|
'[command]': 'command',
|
|
|
|
// https://github.com/actions/toolkit/blob/master/docs/commands.md
|
|
// https://github.com/actions/runner/blob/main/docs/adrs/0276-problem-matchers.md#registration
|
|
'::add-matcher::': 'hidden',
|
|
'##[add-matcher]': 'hidden',
|
|
'::remove-matcher': 'hidden', // it has arguments
|
|
};
|
|
|
|
// Pattern for ::cmd:: and ::cmd args:: format (args are stripped for display)
|
|
const LogLineCmdPattern = /^::(error|warning|notice|debug)(?:\s[^:]*)?::/;
|
|
|
|
export type LogLine = {
|
|
index: number;
|
|
timestamp: number;
|
|
message: string;
|
|
};
|
|
|
|
export type LogLineCommandName = 'group' | 'endgroup' | 'command' | 'error' | 'warning' | 'notice' | 'debug' | 'hidden';
|
|
export type LogLineCommand = {
|
|
name: LogLineCommandName,
|
|
prefix: string,
|
|
};
|
|
|
|
export function parseLogLineCommand(line: LogLine): LogLineCommand | null {
|
|
// TODO: in the future it can be refactored to be a general parser that can parse arguments, drop the "prefix match"
|
|
for (const prefix of Object.keys(LogLinePrefixCommandMap)) {
|
|
if (line.message.startsWith(prefix)) {
|
|
return {name: LogLinePrefixCommandMap[prefix], prefix};
|
|
}
|
|
}
|
|
// Handle ::cmd:: and ::cmd args:: format (runner may pass these through raw)
|
|
const match = LogLineCmdPattern.exec(line.message);
|
|
if (match) {
|
|
return {name: match[1] as LogLineCommandName, prefix: match[0]};
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const LogLineLabelMap: Partial<Record<LogLineCommandName, string>> = {
|
|
'error': 'Error',
|
|
'warning': 'Warning',
|
|
'notice': 'Notice',
|
|
'debug': 'Debug',
|
|
};
|
|
|
|
export function createLogLineMessage(line: LogLine, cmd: LogLineCommand | null) {
|
|
const logMsgAttrs = {class: 'log-msg'};
|
|
if (cmd?.name) logMsgAttrs.class += ` log-cmd-${cmd.name}`; // make it easier to add styles to some commands like "error"
|
|
|
|
// TODO: for some commands (::group::), the "prefix removal" works well, for some commands with "arguments" (::remove-matcher ...::),
|
|
// it needs to do further processing in the future (fortunately, at the moment we don't need to handle these commands)
|
|
const msgContent = cmd ? line.message.substring(cmd.prefix.length) : line.message;
|
|
|
|
const logMsg = createElementFromAttrs('span', logMsgAttrs);
|
|
const label = cmd ? LogLineLabelMap[cmd.name] : null;
|
|
if (label) {
|
|
logMsg.append(createElementFromAttrs('span', {class: 'log-msg-label'}, `${label}:`));
|
|
const msgSpan = document.createElement('span');
|
|
msgSpan.innerHTML = ` ${renderAnsi(msgContent.trimStart())}`;
|
|
logMsg.append(msgSpan);
|
|
} else {
|
|
logMsg.innerHTML = renderAnsi(msgContent);
|
|
}
|
|
return logMsg;
|
|
}
|
|
|
|
// buildJobsByParentJobID groups jobs by their parentJobID (0 = top level).
|
|
// Useful for rendering the reusable-workflow caller/child tree in the sidebar.
|
|
export function buildJobsByParentJobID(jobs: ActionsJob[]): Map<number, ActionsJob[]> {
|
|
const childrenByParent = new Map<number, ActionsJob[]>();
|
|
for (const job of jobs) {
|
|
const parentID = job.parentJobID || 0;
|
|
const existing = childrenByParent.get(parentID);
|
|
if (existing) {
|
|
existing.push(job);
|
|
} else {
|
|
childrenByParent.set(parentID, [job]);
|
|
}
|
|
}
|
|
return childrenByParent;
|
|
}
|
|
|
|
// collectCallerChildJobs returns the direct children of a caller job.
|
|
export function collectCallerChildJobs(jobs: ActionsJob[], callerJobID: number): ActionsJob[] {
|
|
if (!callerJobID) return [];
|
|
return buildJobsByParentJobID(jobs).get(callerJobID) || [];
|
|
}
|
|
|
|
export function createEmptyActionsRun(): ActionsRun {
|
|
return {
|
|
repoId: 0,
|
|
link: '',
|
|
viewLink: '',
|
|
title: '',
|
|
titleHTML: '',
|
|
status: '' as ActionsStatus, // do not show the status before initialized, otherwise it would show an incorrect "error" icon
|
|
canCancel: false,
|
|
canApprove: false,
|
|
canRerun: false,
|
|
canRerunFailed: false,
|
|
canDeleteArtifact: false,
|
|
done: false,
|
|
workflowID: '',
|
|
workflowLink: '',
|
|
isSchedule: false,
|
|
runAttempt: 0,
|
|
attempts: [],
|
|
duration: '',
|
|
triggeredAt: 0,
|
|
triggerEvent: '',
|
|
jobs: [] as Array<ActionsJob>,
|
|
commit: {
|
|
localeCommit: '',
|
|
localePushedBy: '',
|
|
shortSHA: '',
|
|
link: '',
|
|
pusher: {
|
|
displayName: '',
|
|
link: '',
|
|
},
|
|
branch: {
|
|
name: '',
|
|
link: '',
|
|
isDeleted: false,
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
export function createActionRunViewStore(viewUrl: string) {
|
|
let loadingAbortController: AbortController | null = null;
|
|
let intervalID: IntervalId | null = null;
|
|
const viewData = reactive({
|
|
currentRun: createEmptyActionsRun(),
|
|
runArtifacts: [] as Array<ActionsArtifact>,
|
|
});
|
|
const loadCurrentRun = async () => {
|
|
if (loadingAbortController) return;
|
|
const abortController = new AbortController();
|
|
loadingAbortController = abortController;
|
|
try {
|
|
const resp = await POST(viewUrl, {signal: abortController.signal, data: {}});
|
|
const runResp = await resp.json();
|
|
if (loadingAbortController !== abortController) return;
|
|
|
|
viewData.runArtifacts = runResp.artifacts || [];
|
|
viewData.currentRun = runResp.state.run;
|
|
// clear the interval timer if the job is done
|
|
if (viewData.currentRun.done && intervalID) {
|
|
clearInterval(intervalID);
|
|
intervalID = null;
|
|
}
|
|
} catch (e) {
|
|
// avoid network error while unloading page, and ignore "abort" error
|
|
if (e instanceof TypeError || abortController.signal.aborted) return;
|
|
throw e;
|
|
} finally {
|
|
if (loadingAbortController === abortController) loadingAbortController = null;
|
|
}
|
|
};
|
|
|
|
return {
|
|
viewData,
|
|
|
|
async startPollingCurrentRun() {
|
|
await loadCurrentRun();
|
|
intervalID = setInterval(() => loadCurrentRun(), 1000);
|
|
},
|
|
async forceReloadCurrentRun() {
|
|
loadingAbortController?.abort();
|
|
loadingAbortController = null;
|
|
await loadCurrentRun();
|
|
},
|
|
stopPollingCurrentRun() {
|
|
if (!intervalID) return;
|
|
clearInterval(intervalID);
|
|
intervalID = null;
|
|
},
|
|
};
|
|
}
|
|
|
|
export type ActionRunViewStore = ReturnType<typeof createActionRunViewStore>;
|