Compare commits

...
10 changed files with 127 additions and 64 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
'@expo/build-tools': minor
---
Run the `after_checkout` workflow hook in build jobs that do not use custom steps.
@@ -91,7 +91,7 @@ describe(androidBuilder, () => {
);
});
it('passes the install_node_modules anchor and a hooks ref to setupAsync', async () => {
it('passes a hooks ref to setupAsync', async () => {
const ctx = new BuildContext(createTestAndroidJob(), {
workingdir: '/workingdir',
logBuffer: { getLogs: () => [], getPhaseLogs: () => [] },
@@ -105,7 +105,6 @@ describe(androidBuilder, () => {
expect(setupAsync).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
wrappedAnchors: ['install_node_modules'],
jobHooksRef: expect.objectContaining({ current: null }),
})
);
+1 -1
View File
@@ -72,7 +72,7 @@ async function buildInnerAsync(
ctx: BuildContext<Android.Job>,
jobHooksRef: JobHooksRef
): Promise<void> {
await setupAsync(ctx, { wrappedAnchors: ['install_node_modules'], jobHooksRef });
await setupAsync(ctx, { jobHooksRef });
const evictUsedBefore = new Date();
const workingDirectory = ctx.getReactNativeProjectDirectory();
const hasNativeCode = ctx.job.type === Workflow.GENERIC;
+1 -1
View File
@@ -76,7 +76,7 @@ async function buildInnerAsync(
ctx: BuildContext<Ios.Job>,
jobHooksRef: JobHooksRef
): Promise<void> {
await setupAsync(ctx, { wrappedAnchors: ['install_node_modules'], jobHooksRef });
await setupAsync(ctx, { jobHooksRef });
const hasNativeCode = ctx.job.type === Workflow.GENERIC;
const evictUsedBefore = new Date();
const credentialsManager = new CredentialsManager(ctx);
@@ -1,10 +1,10 @@
import { BuildPhase, BuildTrigger, Hooks, Ios } from '@expo/eas-build-job';
import { BuildPhase, BuildTrigger, HookKey, Hooks, Ios } from '@expo/eas-build-job';
import { bunyan } from '@expo/logger';
import { executeHookStepsAsync } from '@expo/steps';
import { createTestIosJob } from '../../__tests__/utils/job';
import { BuildContext } from '../../context';
import { runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { ParsedJobHooks, parseJobHooksAsync } from '../jobHooks';
// The primitive's step-execution rules (failure()/success(), no-if continuation,
@@ -16,7 +16,10 @@ jest.mock('@expo/steps', () => ({
}));
const executeHookStepsMock = jest.mocked(executeHookStepsAsync);
async function setup(hooks: Hooks | undefined): Promise<{
async function setup(
hooks: Hooks | undefined,
hookKeys: readonly HookKey[] = ['before_install_node_modules', 'after_install_node_modules']
): Promise<{
ctx: BuildContext<Ios.Job>;
hooks: ParsedJobHooks | null;
}> {
@@ -40,7 +43,7 @@ async function setup(hooks: Hooks | undefined): Promise<{
jest
.spyOn(ctx, 'runBuildPhase')
.mockImplementation((_phase: BuildPhase, fn: () => Promise<unknown>) => fn() as never);
return { ctx, hooks: await parseJobHooksAsync(ctx, ['install_node_modules']) };
return { ctx, hooks: await parseJobHooksAsync(ctx, hookKeys) };
}
const runArgs = <TJob extends Ios.Job>(
@@ -162,3 +165,23 @@ describe(runHookableBuildPhaseAsync, () => {
expect(writeBack).toHaveBeenCalled();
});
});
describe(runHookEntriesAsync, () => {
beforeEach(() => {
executeHookStepsMock.mockReset();
executeHookStepsMock.mockResolvedValue({ failedLocally: false, firstError: undefined });
});
it('runs the after_checkout entries that the parser built', async () => {
const { ctx, hooks } = await setup({ after_checkout: [{ run: 'echo after' }] }, [
'after_checkout',
]);
await runHookEntriesAsync({ ctx, hooks: hooks!, timing: 'after', anchor: 'checkout' });
expect(hooks!.hookEntriesByKey.after_checkout).toHaveLength(1);
expect(executeHookStepsMock).toHaveBeenCalledWith(
hooks!.globalContext,
hooks!.hookEntriesByKey.after_checkout,
{ anchor: 'checkout', timing: 'after', anchorResult: 'success' }
);
});
});
@@ -9,7 +9,7 @@ import { createTestIosJob } from '../../__tests__/utils/job';
import { BuildContext } from '../../context';
import { parseJobHooksAsync } from '../jobHooks';
const INSTALL: ['install_node_modules'] = ['install_node_modules'];
const INSTALL = ['before_install_node_modules', 'after_install_node_modules'] as const;
function createCtx(
hooks: Hooks | undefined,
@@ -4,7 +4,7 @@ import { createTestAndroidJob } from '../../__tests__/utils/job';
import { createMockLogger } from '../../__tests__/utils/logger';
import { BuildContext } from '../../context';
import { resolveEnvFromBuildProfileAsync, runEasBuildInternalAsync } from '../easBuildInternal';
import { runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from '../hookableBuildPhase';
import { JobHooksRef, setupAsync } from '../setup';
import { ParsedJobHooks, parseJobHooksAsync } from '../jobHooks';
import { prepareProjectSourcesAsync } from '../projectSources';
@@ -15,7 +15,10 @@ jest.mock('../easBuildInternal', () => ({
resolveEnvFromBuildProfileAsync: jest.fn(),
runEasBuildInternalAsync: jest.fn(),
}));
jest.mock('../hookableBuildPhase', () => ({ runHookableBuildPhaseAsync: jest.fn() }));
jest.mock('../hookableBuildPhase', () => ({
runHookEntriesAsync: jest.fn(),
runHookableBuildPhaseAsync: jest.fn(),
}));
jest.mock('../jobHooks', () => ({ parseJobHooksAsync: jest.fn() }));
jest.mock('../../utils/npmrc', () => ({ setUpNpmrcAsync: jest.fn() }));
jest.mock('../../utils/hooks', () => ({
@@ -79,6 +82,9 @@ describe(setupAsync, () => {
order.push('parse-hooks');
return PARSED;
});
jest.mocked(runHookEntriesAsync).mockImplementation(async () => {
order.push('after-checkout-hooks');
});
jest.mocked(runHookableBuildPhaseAsync).mockImplementation(async () => {
// Record the wrapper call; deliberately do NOT run its `fn` so the install
// internals stay out of the ordering test.
@@ -91,23 +97,50 @@ describe(setupAsync, () => {
}));
});
it('parses hooks after project prep + profile-env + pre-install hook, and before the install wrapper', async () => {
it('parses hooks after project prep + profile-env + pre-install hook, then runs the after_checkout hooks before the install wrapper', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
const parseAt = order.indexOf('parse-hooks');
expect(order.indexOf('prepare-project')).toBeLessThan(parseAt);
expect(order.indexOf('profile-env')).toBeLessThan(parseAt);
expect(order.indexOf('pre-install-hook')).toBeLessThan(parseAt);
expect(parseAt).toBeLessThan(order.indexOf('install-wrapper'));
expect(order).toEqual([
'prepare-project',
'profile-env',
'pre-install-hook',
'parse-hooks',
'after-checkout-hooks',
'install-wrapper',
]);
expect(parseJobHooksAsync).toHaveBeenCalledWith(expect.anything(), [
'after_checkout',
'before_install_node_modules',
'after_install_node_modules',
]);
expect(runHookEntriesAsync).toHaveBeenCalledWith(
expect.objectContaining({ hooks: PARSED, timing: 'after', anchor: 'checkout' })
);
});
it('publishes the parsed hooks to the ref before an after_checkout hook can fail', async () => {
jest.mocked(runHookEntriesAsync).mockRejectedValueOnce(new Error('hook boom'));
const jobHooksRef: JobHooksRef = { current: null };
await expect(
setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), { jobHooksRef })
).rejects.toThrow('hook boom');
expect(jobHooksRef.current).toBe(PARSED);
expect(runHookableBuildPhaseAsync).not.toHaveBeenCalled();
});
it('runs no after_checkout hooks when the job has no hooks', async () => {
jest.mocked(parseJobHooksAsync).mockResolvedValueOnce(null);
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
jobHooksRef: { current: null },
});
expect(runHookEntriesAsync).not.toHaveBeenCalled();
});
it('parses hooks unconditionally on a non-git-based build (never parked in the git-only branch)', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.EAS_CLI), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
expect(parseJobHooksAsync).toHaveBeenCalledTimes(1);
@@ -119,7 +152,6 @@ describe(setupAsync, () => {
it('publishes the parsed hooks to the ref before the install wrapper runs', async () => {
const jobHooksRef: JobHooksRef = { current: null };
await setupAsync(createCtx(BuildTrigger.GIT_BASED_INTEGRATION), {
wrappedAnchors: ['install_node_modules'],
jobHooksRef,
});
expect(jobHooksRef.current).toBe(PARSED);
@@ -57,7 +57,7 @@ export async function runHookableBuildPhaseAsync<TJob extends BuildJob, T>({
return result;
}
async function runHookEntriesAsync<TJob extends BuildJob>({
export async function runHookEntriesAsync<TJob extends BuildJob>({
ctx,
hooks,
timing,
+32 -36
View File
@@ -2,7 +2,6 @@ import {
BuildJob,
CompositeFunctionCatalog,
ErrorCode,
HookAnchorId,
HookKey,
UserError,
parseHookKey,
@@ -37,12 +36,12 @@ export interface ParsedJobHooks {
/**
* Parses the native job's `hooks` into engine-ready entries, once, at setup
* time. Shape-validates every registered key (reachable or not); constructs
* entries only for the anchors this build actually wraps. Returns null when the
* entries only for the hook keys this build runs. Returns null when the
* job declares no hooks.
*/
export async function parseJobHooksAsync<TJob extends BuildJob>(
ctx: BuildContext<TJob>,
wrappedAnchors: readonly HookAnchorId[]
hookKeys: readonly HookKey[]
): Promise<ParsedJobHooks | null> {
const hooks = ctx.job.hooks;
if (!hooks || Object.keys(hooks).length === 0) {
@@ -81,8 +80,8 @@ export async function parseJobHooksAsync<TJob extends BuildJob>(
}
}
// Construct entries for the wrapped anchors in EXECUTION order (per anchor,
// before_ then after_) so generated step ids and output references follow the
// Construct entries for the given hook keys in the order given, which is
// EXECUTION order, so generated step ids and output references follow the
// order steps actually run. All entries share one globalContext, so env and
// outputs accumulate across keys.
const hookEntriesByKey: Partial<Record<HookKey, HookEntry[]>> = {};
@@ -92,37 +91,34 @@ export async function parseJobHooksAsync<TJob extends BuildJob>(
ctx.getReactNativeProjectDirectory(),
{ logger: ctx.logger }
);
for (const anchor of wrappedAnchors) {
for (const side of ['before', 'after'] as const) {
const key: HookKey = `${side}_${anchor}`;
const steps = hooks[key];
if (!Array.isArray(steps) || steps.length === 0) {
continue;
}
let entries: HookEntry[];
try {
// Extended per key so a bad `uses:` path is attributed to that hook key.
await extendCompositeFunctionCatalogFromStepsAsync({
catalog: compositeFunctionCatalog,
rootSteps: steps,
loadCompositeFunction,
});
entries = await constructHookEntriesAsync(globalContext, steps, {
externalFunctions,
externalFunctionGroups,
compositeFunctionCatalog,
});
} catch (err) {
throw new UserError(
ErrorCode.HOOKS_ERROR,
`Failed to parse hooks.${key}: ${err instanceof Error ? err.message : String(err)}. Hooks use the same syntax as workflow steps.`,
{ cause: err }
);
}
hookEntriesByKey[key] = entries;
for (const entry of entries) {
orderedSteps.push(...entry.steps);
}
for (const key of hookKeys) {
const steps = hooks[key];
if (!Array.isArray(steps) || steps.length === 0) {
continue;
}
let entries: HookEntry[];
try {
// Extended per key so a bad `uses:` path is attributed to that hook key.
await extendCompositeFunctionCatalogFromStepsAsync({
catalog: compositeFunctionCatalog,
rootSteps: steps,
loadCompositeFunction,
});
entries = await constructHookEntriesAsync(globalContext, steps, {
externalFunctions,
externalFunctionGroups,
compositeFunctionCatalog,
});
} catch (err) {
throw new UserError(
ErrorCode.HOOKS_ERROR,
`Failed to parse hooks.${key}: ${err instanceof Error ? err.message : String(err)}. Hooks use the same syntax as workflow steps.`,
{ cause: err }
);
}
hookEntriesByKey[key] = entries;
for (const entry of entries) {
orderedSteps.push(...entry.steps);
}
}
+15 -7
View File
@@ -3,7 +3,6 @@ import {
BuildJob,
BuildPhase,
BuildTrigger,
HookAnchorId,
Ios,
Job,
Platform,
@@ -15,7 +14,7 @@ import nullthrows from 'nullthrows';
import path from 'path';
import { resolveEnvFromBuildProfileAsync, runEasBuildInternalAsync } from './easBuildInternal';
import { runHookableBuildPhaseAsync } from './hookableBuildPhase';
import { runHookEntriesAsync, runHookableBuildPhaseAsync } from './hookableBuildPhase';
import { installDependenciesAsync, resolvePackagerDir } from './installDependencies';
import { ParsedJobHooks, parseJobHooksAsync } from './jobHooks';
import { prepareProjectSourcesAsync } from './projectSources';
@@ -50,10 +49,7 @@ export interface JobHooksRef {
export async function setupAsync<TJob extends BuildJob>(
ctx: BuildContext<TJob>,
{
wrappedAnchors,
jobHooksRef,
}: { wrappedAnchors: readonly HookAnchorId[]; jobHooksRef: JobHooksRef }
{ jobHooksRef }: { jobHooksRef: JobHooksRef }
): Promise<void> {
await ctx.runBuildPhase(BuildPhase.PREPARE_PROJECT, async () => {
await retryAsync(
@@ -111,7 +107,19 @@ export async function setupAsync<TJob extends BuildJob>(
// Parse hooks unconditionally, after every pre-install env mutation
// (PREPARE_PROJECT, the git-based profile-env block, PRE_INSTALL_HOOK) and
// before the first wrapped phase.
jobHooksRef.current = await parseJobHooksAsync(ctx, wrappedAnchors);
jobHooksRef.current = await parseJobHooksAsync(ctx, [
'after_checkout',
'before_install_node_modules',
'after_install_node_modules',
]);
if (jobHooksRef.current) {
await runHookEntriesAsync({
ctx,
hooks: jobHooksRef.current,
timing: 'after',
anchor: 'checkout',
});
}
await runHookableBuildPhaseAsync({
ctx,