feat(actions)!: improve support for reusable workflows (#37478)

## 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>
This commit is contained in:
Zettat123
2026-05-30 00:31:14 -06:00
committed by GitHub
parent 2960d6889c
commit 0359746abe
41 changed files with 4692 additions and 363 deletions
+64 -9
View File
@@ -1,7 +1,8 @@
<script setup lang="ts">
import {nextTick, onBeforeUnmount, onMounted, ref, toRefs, watch} from 'vue';
import {computed, nextTick, onBeforeUnmount, onMounted, ref, toRefs, watch} from 'vue';
import {SvgIcon} from '../svg.ts';
import ActionStatusIcon from './ActionStatusIcon.vue';
import WorkflowGraph from './WorkflowGraph.vue';
import {addDelegatedEventListener, createElementFromAttrs, toggleElem} from '../utils/dom.ts';
import {formatDatetime, formatDatetimeISO} from '../utils/time.ts';
import {POST} from '../modules/fetch.ts';
@@ -9,13 +10,14 @@ import {copyToClipboardWithFeedback} from '../modules/clipboard.ts';
import type {IntervalId} from '../types.ts';
import {toggleFullScreen} from '../utils.ts';
import {localUserSettings} from '../modules/user-settings.ts';
import type {ActionsArtifact, ActionsRun, ActionsStatus} from '../modules/gitea-actions.ts';
import type {ActionsArtifact, ActionsJob, ActionsRun, ActionsStatus} from '../modules/gitea-actions.ts';
import {
type ActionRunViewStore,
collectCallerChildJobs,
createLogLineMessage,
type LogLine,
type LogLineCommand,
parseLogLineCommand
parseLogLineCommand,
} from './ActionRunView.ts';
function isLogElementInViewport(el: Element, {extraViewPortHeight}={extraViewPortHeight: 0}): boolean {
@@ -116,6 +118,15 @@ const currentJob = ref<CurrentJob>({
const stepsContainer = ref<HTMLElement | null>(null);
const jobStepLogs = ref<Array<StepContainerElement | undefined>>([]);
// Reusable workflow caller view: when the selected job is a caller node, the right pane
// shows the children list rather than step logs (callers don't run on a runner).
const selectedJob = computed<ActionsJob | undefined>(() => (run.value.jobs || []).find((it) => it.id === props.jobId));
const isCallerJob = computed(() => Boolean(selectedJob.value?.isReusableCaller));
const callerChildJobs = computed<ActionsJob[]>(() => {
if (!isCallerJob.value) return [];
return collectCallerChildJobs(run.value.jobs || [], props.jobId);
});
watch(optionAlwaysAutoScroll, () => {
saveLocaleStorageOptions();
});
@@ -417,11 +428,17 @@ async function hashChangeListener() {
<template>
<div class="job-info-header">
<div class="job-info-header-left gt-ellipsis">
<h3 class="job-info-header-title gt-ellipsis">
{{ currentJob.title }}
</h3>
<div class="job-info-header-title-row">
<h3 class="job-info-header-title gt-ellipsis">
{{ isCallerJob ? selectedJob?.name : currentJob.title }}
</h3>
<span v-if="isCallerJob && selectedJob?.callUses" class="ui label job-info-header-uses">
<span>uses:</span>
<span class="gt-ellipsis">{{ selectedJob.callUses }}</span>
</span>
</div>
<p class="job-info-header-detail">
{{ currentJob.detail }}
{{ isCallerJob && selectedJob ? locale.status[selectedJob.status] : currentJob.detail }}
</p>
</div>
<div class="job-info-header-right">
@@ -460,8 +477,22 @@ async function hashChangeListener() {
</div>
</div>
</div>
<!-- Caller (reusable workflow) view: render the direct children's dependency graph,
mirroring the run summary's WorkflowGraph but scoped to this caller's subtree.
The caller's name + uses path + status all live in job-info-header above. -->
<div class="caller-children-container" v-if="isCallerJob">
<WorkflowGraph
v-if="callerChildJobs.length > 0"
:store="store"
:jobs="callerChildJobs"
:run-link="run.link"
:workflow-id="`${run.workflowID}#caller-${props.jobId}`"
:locale="locale"
/>
</div>
<!-- always create the node because we have our own event listeners on it, don't use "v-if" -->
<div class="job-step-container" ref="stepsContainer" v-show="currentJob.steps.length">
<div class="job-step-container" ref="stepsContainer" v-show="!isCallerJob && currentJob.steps.length">
<div class="job-step-section" v-for="(jobStep, stepIdx) in currentJob.steps" :key="stepIdx">
<div
class="job-step-summary"
@@ -547,7 +578,8 @@ async function hashChangeListener() {
border-radius: 3px;
}
.job-info-header:has(+ .job-step-container) {
.job-info-header:has(+ .job-step-container),
.job-info-header:has(+ .caller-children-container) {
border-radius: var(--border-radius) var(--border-radius) 0 0;
}
@@ -564,6 +596,29 @@ async function hashChangeListener() {
.job-info-header-left {
flex: 1;
min-width: 0;
}
.job-info-header-title-row {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.job-info-header-uses {
display: inline-flex !important;
align-items: baseline;
gap: 4px;
min-width: 0;
}
.caller-children-container {
flex: 1;
display: flex;
flex-direction: column;
border-top: 1px solid var(--color-console-border);
color: var(--color-console-fg);
}
.job-step-container {
@@ -18,6 +18,10 @@ const {currentRun: run} = toRefs(props.store.viewData);
const isRerun = computed(() => run.value.runAttempt > 1);
// The summary's dependency graph is the workflow's top-level shape: a reusable caller
// renders as a single node, its expanded children belong to the caller's own detail page.
const topLevelJobs = computed(() => (run.value.jobs || []).filter((j) => !j.parentJobID));
const triggerUser = computed(() => {
const currentAttempt = run.value.attempts.find((attempt) => attempt.current);
if (currentAttempt) {
@@ -54,9 +58,9 @@ onBeforeUnmount(() => {
</div>
</div>
<WorkflowGraph
v-if="run.jobs.length > 0"
v-if="topLevelJobs.length > 0"
:store="store"
:jobs="run.jobs"
:jobs="topLevelJobs"
:run-link="run.link"
:workflow-id="run.workflowID"
:locale="locale"
+24 -2
View File
@@ -88,6 +88,28 @@ export function createLogLineMessage(line: LogLine, cmd: LogLineCommand | null)
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,
@@ -161,7 +183,7 @@ export function createActionRunViewStore(viewUrl: string) {
}
};
return reactive({
return {
viewData,
async startPollingCurrentRun() {
@@ -178,7 +200,7 @@ export function createActionRunViewStore(viewUrl: string) {
clearInterval(intervalID);
intervalID = null;
},
});
};
}
export type ActionRunViewStore = ReturnType<typeof createActionRunViewStore>;
+114 -12
View File
@@ -1,12 +1,12 @@
<script setup lang="ts">
import {SvgIcon} from '../svg.ts';
import ActionStatusIcon from './ActionStatusIcon.vue';
import {toRefs} from 'vue';
import {computed, ref, toRefs} from 'vue';
import {POST, DELETE} from '../modules/fetch.ts';
import ActionRunSummaryView from './ActionRunSummaryView.vue';
import ActionRunJobView from './ActionRunJobView.vue';
import type {ActionsRunAttempt} from '../modules/gitea-actions.ts';
import {createActionRunViewStore} from './ActionRunView.ts';
import type {ActionsJob, ActionsRunAttempt} from '../modules/gitea-actions.ts';
import {buildJobsByParentJobID, createActionRunViewStore} from './ActionRunView.ts';
import {buildArtifactTooltipHtml} from './ActionRunArtifacts.ts';
defineOptions({
@@ -23,6 +23,62 @@ const locale = props.locale;
const store = createActionRunViewStore(props.actionsViewUrl);
const {currentRun: run, runArtifacts: artifacts} = toRefs(store.viewData);
type JobListItem = {
job: ActionsJob;
depth: number;
hasChildren: boolean;
};
// Caller jobs default to collapsed. Membership in this set means "user has manually expanded this caller"
const expandedJobIDs = ref(new Set<number>());
function toggleExpandedJob(jobID: number) {
const next = new Set(expandedJobIDs.value);
if (next.has(jobID)) {
next.delete(jobID);
} else {
next.add(jobID);
}
expandedJobIDs.value = next;
}
// When a child job is currently selected, force-expand the chain of caller ancestors
const forcedExpandedJobIDs = computed(() => {
const expanded = new Set<number>();
if (!props.jobId) return expanded;
const jobsByID = new Map((run.value.jobs || []).map((job) => [job.id, job]));
let cur = jobsByID.get(props.jobId);
while (cur?.parentJobID) {
expanded.add(cur.parentJobID);
cur = jobsByID.get(cur.parentJobID);
}
return expanded;
});
function isJobCollapsed(jobID: number) {
return !expandedJobIDs.value.has(jobID) && !forcedExpandedJobIDs.value.has(jobID);
}
const visibleJobListItems = computed<JobListItem[]>(() => {
const jobs = [...(run.value.jobs || [])].sort((a, b) => a.id - b.id);
const childrenByParent = buildJobsByParentJobID(jobs);
const result: JobListItem[] = [];
const stack: Array<{job: ActionsJob; depth: number}> = [];
const top = childrenByParent.get(0) || [];
for (let i = top.length - 1; i >= 0; i--) stack.push({job: top[i], depth: 0});
while (stack.length > 0) {
const {job, depth} = stack.pop()!;
const children = childrenByParent.get(job.id) || [];
const hasChildren = children.length > 0;
result.push({job, depth, hasChildren});
if (hasChildren && isJobCollapsed(job.id)) continue;
for (let i = children.length - 1; i >= 0; i--) stack.push({job: children[i], depth: depth + 1});
}
return result;
});
function formatAttemptTitle(attempt: ActionsRunAttempt) {
return attempt.latest ? `${locale.latestAttempt} #${attempt.attempt}` : `${locale.attempt} #${attempt.attempt}`;
}
@@ -153,13 +209,31 @@ async function deleteArtifact(name: string) {
<div class="ui divider"/>
<div class="left-list-header">{{ locale.allJobs }}</div>
<div class="flex-items-block action-view-sidebar-list">
<div class="item" v-for="job in run.jobs" :key="job.id" :class="props.jobId === job.id ? 'selected' : ''">
<a class="flex-text-block tw-flex-1 silenced" :href="job.link">
<ActionStatusIcon :locale-status="locale.status[job.status]" :status="job.status" icon-variant="circle-fill"/>
<span class="tw-flex-1 gt-ellipsis">{{ job.name }}</span>
<SvgIcon name="octicon-sync" role="button" :data-tooltip-content="locale.rerun" class="job-rerun-button tw-cursor-pointer link-action interact-fg" :data-url="`${run.link}/jobs/${job.id}/rerun`" v-if="job.canRerun"/>
<span class="job-duration">{{ job.duration }}</span>
<div
class="item job-brief-item"
:class="{'selected': props.jobId === item.job.id}"
:style="{paddingLeft: `${10 + item.depth * 16}px`}"
v-for="item in visibleJobListItems"
:key="item.job.id"
>
<a class="tw-contents silenced" :href="item.job.link">
<ActionStatusIcon :locale-status="locale.status[item.job.status]" :status="item.job.status" icon-variant="circle-fill"/>
<span class="tw-min-w-0 gt-ellipsis">{{ item.job.name }}</span>
<SvgIcon name="octicon-sync" role="button" :data-tooltip-content="locale.rerun" class="job-rerun-button tw-cursor-pointer link-action interact-fg" :data-url="`${run.link}/jobs/${item.job.id}/rerun`" v-if="item.job.canRerun"/>
<span class="job-duration">{{ item.job.duration }}</span>
</a>
<button
v-if="item.hasChildren"
type="button"
class="job-brief-toggle"
:class="{'collapsed': isJobCollapsed(item.job.id)}"
@click="toggleExpandedJob(item.job.id)"
:title="isJobCollapsed(item.job.id) ? locale.expandCallerJobs : locale.collapseCallerJobs"
:aria-label="isJobCollapsed(item.job.id) ? locale.expandCallerJobs : locale.collapseCallerJobs"
:aria-expanded="!isJobCollapsed(item.job.id)"
>
<SvgIcon name="octicon-chevron-down" :size="14"/>
</button>
</div>
</div>
@@ -332,19 +406,47 @@ async function deleteArtifact(name: string) {
background-color: var(--color-active);
}
/* the re-run button replaces the duration on hover/focus */
.job-brief-toggle {
border: none;
padding: 0;
background: transparent;
cursor: pointer;
color: inherit;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
/* the icon is always chevron-down; flip to chevron-up when expanded */
transition: transform 0.15s ease;
/* sit right after the job name; rerun/duration float to the right via auto-margin */
order: 1;
}
.job-brief-toggle:not(.collapsed) {
transform: rotate(180deg);
}
/* push rerun/duration to the right edge; only one is visible at a time (hover swap),
the visible one absorbs the free space via auto-margin */
.action-view-sidebar-list > .item .job-rerun-button,
.action-view-sidebar-list > .item .job-duration {
order: 2;
margin-left: auto;
}
/* the re-run button replaces the duration on hover or job-link focus */
.action-view-sidebar-list > .item .job-rerun-button {
display: none;
}
.action-view-sidebar-list > .item:hover .job-rerun-button,
.action-view-sidebar-list > .item:focus-within .job-rerun-button {
.action-view-sidebar-list > .item:has(a:focus) .job-rerun-button {
display: inline-flex;
}
/* only swap out the duration when a re-run button exists to take its place */
.action-view-sidebar-list > .item:hover .job-rerun-button ~ .job-duration,
.action-view-sidebar-list > .item:focus-within .job-rerun-button ~ .job-duration {
.action-view-sidebar-list > .item:has(a:focus) .job-rerun-button ~ .job-duration {
display: none;
}
+65 -52
View File
@@ -115,7 +115,8 @@ const jobsWithLayout = computed<JobNode[]>(() => {
let maxJobsPerLevel = 0;
props.jobs.forEach(job => {
const level = levels.get(job.name) || levels.get(job.jobId) || 0;
// `?? 0`, not `|| 0`: a root job's level is 0, which `||` would wrongly discard.
const level = levels.get(scopedKey(job)) ?? 0;
if (!jobsByLevel[level]) {
jobsByLevel[level] = [];
@@ -164,75 +165,87 @@ const jobsWithLayout = computed<JobNode[]>(() => {
}
});
// scopedKey identifies a job within its reusable-workflow call scope so that the same
// JobID in different reusable calls does not collide.
function scopedKey(job: {parentJobID: number; jobId: string}): string {
return `${job.parentJobID || 0}:${job.jobId}`;
}
function buildDirectNeedsMap(jobs: ActionsJob[]): Map<string, string[]> {
const directNeedsByJobId = new Map<string, string[]>();
const dependentsByJobId = new Map<string, Set<string>>();
// The map keys/values are scoped keys, not bare jobIds, so we keep edge construction
// accurate when reusable workflows reuse common job names like "build" / "test".
const directNeedsByScopedKey = new Map<string, string[]>();
const dependentsByScopedKey = new Map<string, Set<string>>();
for (const job of jobs) {
const needs = job.needs || [];
directNeedsByJobId.set(job.jobId, needs);
const fromKey = scopedKey(job);
const needKeys = (job.needs || []).map((n) => `${job.parentJobID || 0}:${n}`);
directNeedsByScopedKey.set(fromKey, needKeys);
for (const need of needs) {
if (!dependentsByJobId.has(need)) {
dependentsByJobId.set(need, new Set());
for (const needKey of needKeys) {
if (!dependentsByScopedKey.has(needKey)) {
dependentsByScopedKey.set(needKey, new Set());
}
dependentsByJobId.get(need)!.add(job.jobId);
dependentsByScopedKey.get(needKey)!.add(fromKey);
}
}
const reachabilityCache = new Map<string, boolean>();
function canReach(fromJobId: string, toJobId: string): boolean {
const cacheKey = `${fromJobId}->${toJobId}`;
function canReach(fromKey: string, toKey: string): boolean {
const cacheKey = `${fromKey}->${toKey}`;
if (reachabilityCache.has(cacheKey)) {
return reachabilityCache.get(cacheKey)!;
}
const visited = new Set<string>();
const stack = [...(dependentsByJobId.get(fromJobId) || [])];
const stack = [...(dependentsByScopedKey.get(fromKey) || [])];
while (stack.length > 0) {
const current = stack.pop()!;
if (current === toJobId) {
if (current === toKey) {
reachabilityCache.set(cacheKey, true);
return true;
}
if (visited.has(current)) continue;
visited.add(current);
stack.push(...(dependentsByJobId.get(current) || []));
stack.push(...(dependentsByScopedKey.get(current) || []));
}
reachabilityCache.set(cacheKey, false);
return false;
}
const reducedNeedsByJobId = new Map<string, string[]>();
for (const [jobId, needs] of directNeedsByJobId.entries()) {
reducedNeedsByJobId.set(jobId, needs.filter((need) => {
const reducedNeedsByScopedKey = new Map<string, string[]>();
for (const [fromKey, needs] of directNeedsByScopedKey.entries()) {
reducedNeedsByScopedKey.set(fromKey, needs.filter((need) => {
return !needs.some((otherNeed) => otherNeed !== need && canReach(need, otherNeed));
}));
}
return reducedNeedsByJobId;
return reducedNeedsByScopedKey;
}
const directNeedsByJobId = computed(() => buildDirectNeedsMap(props.jobs));
const directNeedsByScopedKey = computed(() => buildDirectNeedsMap(props.jobs));
const edges = computed<Edge[]>(() => {
const edgesList: Edge[] = [];
const jobsByJobId = new Map<string, ActionsJob[]>();
// Store every job per scoped key, not just one: matrix-expanded jobs share same jobId
const jobsByScopedKey = new Map<string, ActionsJob[]>();
for (const job of props.jobs) {
if (!jobsByJobId.has(job.jobId)) {
jobsByJobId.set(job.jobId, []);
const key = scopedKey(job);
const existing = jobsByScopedKey.get(key);
if (existing) {
existing.push(job);
} else {
jobsByScopedKey.set(key, [job]);
}
jobsByJobId.get(job.jobId)!.push(job);
}
for (const job of props.jobs) {
for (const need of directNeedsByJobId.value.get(job.jobId) || []) {
const upstreamJobs = jobsByJobId.get(need) || [];
for (const upstreamJob of upstreamJobs) {
for (const needKey of directNeedsByScopedKey.value.get(scopedKey(job)) || []) {
for (const upstreamJob of jobsByScopedKey.get(needKey) || []) {
edgesList.push({
fromId: upstreamJob.id,
toId: job.id,
@@ -469,10 +482,11 @@ const nodesWithOutgoingEdge = computed(() => {
function computeJobLevels(jobs: ActionsJob[]): Map<string, number> {
const jobMap = new Map<string, ActionsJob>()
// Scope-aware: each job is keyed by `${parentJobID}:${jobId}` so the same JobID
// in different reusable workflow calls does not cross-link in the level graph.
const jobMap = new Map<string, ActionsJob>();
jobs.forEach(job => {
jobMap.set(job.name, job);
if (job.jobId) jobMap.set(job.jobId, job);
jobMap.set(scopedKey(job), job);
});
const levels = new Map<string, number>();
@@ -480,60 +494,59 @@ function computeJobLevels(jobs: ActionsJob[]): Map<string, number> {
const recursionStack = new Set<string>();
const MAX_DEPTH = 100;
function dfs(jobNameOrId: string, depth: number = 0): number {
function dfs(scoped: string, depth: number = 0): number {
if (depth > MAX_DEPTH) {
console.error(`Max recursion depth (${MAX_DEPTH}) reached for: ${jobNameOrId}`);
console.error(`Max recursion depth (${MAX_DEPTH}) reached for: ${scoped}`);
return 0;
}
if (recursionStack.has(jobNameOrId)) {
console.error(`Cycle detected involving: ${jobNameOrId}`);
if (recursionStack.has(scoped)) {
console.error(`Cycle detected involving: ${scoped}`);
return 0;
}
if (visited.has(jobNameOrId)) {
return levels.get(jobNameOrId) || 0;
if (visited.has(scoped)) {
return levels.get(scoped) || 0;
}
recursionStack.add(jobNameOrId);
visited.add(jobNameOrId);
recursionStack.add(scoped);
visited.add(scoped);
const job = jobMap.get(jobNameOrId);
const job = jobMap.get(scoped);
if (!job) {
recursionStack.delete(jobNameOrId);
recursionStack.delete(scoped);
return 0;
}
if (!job.needs?.length) {
levels.set(job.jobId, 0);
recursionStack.delete(jobNameOrId);
levels.set(scoped, 0);
recursionStack.delete(scoped);
return 0;
}
let maxLevel = -1;
for (const need of job.needs) {
const needJob = jobMap.get(need);
const needScoped = `${job.parentJobID || 0}:${need}`;
const needJob = jobMap.get(needScoped);
if (!needJob) continue;
const needLevel = dfs(need, depth + 1);
const needLevel = dfs(needScoped, depth + 1);
maxLevel = Math.max(maxLevel, needLevel);
}
const level = maxLevel + 1
levels.set(job.name, level);
if (job.jobId && job.jobId !== job.name) {
levels.set(job.jobId, level);
}
const level = maxLevel + 1;
levels.set(scoped, level);
recursionStack.delete(jobNameOrId);
recursionStack.delete(scoped);
return level;
}
jobs.forEach(job => {
if (!visited.has(job.name) && !visited.has(job.jobId)) {
dfs(job.name);
const sk = scopedKey(job);
if (!visited.has(sk)) {
dfs(sk);
}
})
});
return levels;
}
+2
View File
@@ -27,6 +27,8 @@ export function initRepositoryActionView() {
pushedBy: el.getAttribute('data-locale-runs-pushed-by'),
summary: el.getAttribute('data-locale-summary'),
allJobs: el.getAttribute('data-locale-all-jobs'),
expandCallerJobs: el.getAttribute('data-locale-expand-caller-jobs'),
collapseCallerJobs: el.getAttribute('data-locale-collapse-caller-jobs'),
triggeredVia: el.getAttribute('data-locale-triggered-via'),
totalDuration: el.getAttribute('data-locale-total-duration'),
artifactsTitle: el.getAttribute('data-locale-artifacts-title'),
+4
View File
@@ -62,6 +62,10 @@ export type ActionsJob = {
canRerun: boolean;
needs?: string[];
duration: string;
isReusableCaller: boolean;
parentJobID: number; // 0 for top-level jobs.
callUses?: string;
};
export type ActionsArtifact = {