Compare commits

...
Author SHA1 Message Date
William Grosset 4c5d06fc26 [eas-cli] Add --link-project-id flag to eas build 2026-08-04 13:46:36 -07:00
6 changed files with 469 additions and 6 deletions

No files matched your search

+2
View File
@@ -8,6 +8,8 @@ This is the log of notable changes to EAS CLI and related packages.
### 🎉 New features
- [eas-cli] Add `--link-project-id` flag to `eas build` to link the directory to an existing project before building, like `eas init --id`. ([#4138](https://github.com/expo/eas-cli/pull/4138) by [@williamgrosset](https://github.com/williamgrosset))
### 🐛 Bug fixes
- [build-tools] Revert "Pin the default `agent-device` version for remote sessions" now that `agent-device` 0.20.5 fixes the broken release. ([#4144](https://github.com/expo/eas-cli/pull/4144) by [@gwdp](https://github.com/gwdp))
+8 -4
View File
@@ -535,10 +535,10 @@ start a build
```
USAGE
$ eas build [-p android|ios|all] [-e PROFILE_NAME] [--local] [--output <value>] [--wait] [--clear-cache]
[-s | --auto-submit-with-profile PROFILE_NAME] [--what-to-test <value>] [-m <value>] [--build-logger-level
trace|debug|info|warn|error|fatal] [--freeze-credentials] [--refresh-ad-hoc-provisioning-profile] [--verbose-logs]
[--json] [--non-interactive]
$ eas build [-p android|ios|all] [-e PROFILE_NAME] [--force --link-project-id PROJECT_ID] [--local]
[--output <value>] [--wait] [--clear-cache] [-s | --auto-submit-with-profile PROFILE_NAME] [--what-to-test <value>]
[-m <value>] [--build-logger-level trace|debug|info|warn|error|fatal] [--freeze-credentials]
[--refresh-ad-hoc-provisioning-profile] [--verbose-logs] [--json] [--non-interactive]
FLAGS
-e, --profile=PROFILE_NAME Name of the build profile from eas.json. Defaults to "production" if
@@ -551,9 +551,13 @@ FLAGS
--build-logger-level=<option> The level of logs to output during the build process. Defaults to "info".
<options: trace|debug|info|warn|error|fatal>
--clear-cache Clear cache before the build
--force Used with --link-project-id: overwrite an existing different project
link, "owner", or "slug" in your app config without prompting
--freeze-credentials Prevent the build from updating credentials in non-interactive mode
--json Enable JSON output, non-JSON messages will be printed to stderr. Implies
--non-interactive.
--link-project-id=PROJECT_ID ID of an existing EAS project to link this directory to before building.
Writes "extra.eas.projectId" to your app config, like `eas init --id`.
--local Run build locally [experimental]
--non-interactive Run the command in non-interactive mode.
--output=<value> Output path for local build
@@ -0,0 +1,148 @@
import { getMockOclifConfig } from '../../../__tests__/commands/utils';
import { runBuildAndSubmitAsync } from '../../../build/runBuildAndSubmit';
import { linkExistingProjectByIdAsync } from '../../../project/projectInitialization';
import Build from '../index';
jest.mock('fs-extra', () => ({
pathExists: jest.fn().mockResolvedValue(false),
}));
jest.mock('../../../build/runBuildAndSubmit', () => ({
runBuildAndSubmitAsync: jest.fn(),
}));
jest.mock('../../../project/projectInitialization', () => ({
linkExistingProjectByIdAsync: jest.fn(),
}));
jest.mock('../../../utils/statuspageService', () => ({
maybeWarnAboutEasOutagesAsync: jest.fn(),
}));
jest.mock('../../../utils/json');
jest.mock('../../../log');
const VALID_UUID = '58b3e612-4d49-4de6-9dd4-0e5db1e0e6b4';
describe(Build, () => {
const mockConfig = getMockOclifConfig();
const graphqlClient = {};
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(runBuildAndSubmitAsync).mockResolvedValue({ buildIds: [], buildProfiles: [] });
jest.mocked(linkExistingProjectByIdAsync).mockResolvedValue({
projectId: VALID_UUID,
status: 'linked',
owner: 'jester',
slug: 'testing-123',
});
});
function createCommand(argv: string[]): Build {
const command = new Build(argv, mockConfig);
jest.spyOn(command as any, 'getContextAsync').mockResolvedValue({
loggedIn: {
actor: {},
graphqlClient,
},
getDynamicPrivateProjectConfigAsync: jest.fn(),
projectDir: '/project',
analytics: {},
vcsClient: {},
} as any);
return command;
}
it('links the project before starting the build when --link-project-id is passed', async () => {
await createCommand([
'--platform',
'ios',
'--non-interactive',
'--link-project-id',
VALID_UUID,
]).runAsync();
expect(linkExistingProjectByIdAsync).toHaveBeenCalledWith(graphqlClient, VALID_UUID, '/project', {
force: false,
nonInteractive: true,
});
const linkOrder = jest.mocked(linkExistingProjectByIdAsync).mock.invocationCallOrder[0];
const buildOrder = jest.mocked(runBuildAndSubmitAsync).mock.invocationCallOrder[0];
expect(linkOrder).toBeLessThan(buildOrder);
});
it('passes force: true when --force is set', async () => {
await createCommand([
'--platform',
'ios',
'--non-interactive',
'--link-project-id',
VALID_UUID,
'--force',
]).runAsync();
expect(linkExistingProjectByIdAsync).toHaveBeenCalledWith(graphqlClient, VALID_UUID, '/project', {
force: true,
nonInteractive: true,
});
});
it('does not link when the flag is not passed', async () => {
await createCommand(['--platform', 'ios', '--non-interactive']).runAsync();
expect(linkExistingProjectByIdAsync).not.toHaveBeenCalled();
expect(runBuildAndSubmitAsync).toHaveBeenCalled();
});
it('rejects --force without --link-project-id', async () => {
await expect(
createCommand(['--platform', 'ios', '--non-interactive', '--force']).runAsync()
).rejects.toThrow(/link-project-id/);
expect(runBuildAndSubmitAsync).not.toHaveBeenCalled();
});
it('rejects a --link-project-id value that is not a UUID', async () => {
await expect(
createCommand([
'--platform',
'ios',
'--non-interactive',
'--link-project-id',
'not-a-uuid',
]).runAsync()
).rejects.toThrow('must be a valid UUID');
expect(linkExistingProjectByIdAsync).not.toHaveBeenCalled();
expect(runBuildAndSubmitAsync).not.toHaveBeenCalled();
});
it('does not start a build when linking fails', async () => {
jest
.mocked(linkExistingProjectByIdAsync)
.mockRejectedValue(new Error('Failed to link project'));
await expect(
createCommand([
'--platform',
'ios',
'--non-interactive',
'--link-project-id',
VALID_UUID,
]).runAsync()
).rejects.toThrow('Failed to link project');
expect(runBuildAndSubmitAsync).not.toHaveBeenCalled();
});
it('works with --json', async () => {
await createCommand([
'--platform',
'ios',
'--non-interactive',
'--json',
'--link-project-id',
VALID_UUID,
]).runAsync();
expect(linkExistingProjectByIdAsync).toHaveBeenCalled();
expect(runBuildAndSubmitAsync).toHaveBeenCalled();
});
});
@@ -6,6 +6,7 @@ import chalk from 'chalk';
import figures from 'figures';
import fs from 'fs-extra';
import path from 'path';
import * as uuid from 'uuid';
import { LocalBuildMode } from '../../build/local';
import { BuildFlags, runBuildAndSubmitAsync } from '../../build/runBuildAndSubmit';
@@ -17,6 +18,7 @@ import {
import { StatuspageServiceName } from '../../graphql/generated';
import Log, { link } from '../../log';
import { RequestedPlatform, selectRequestedPlatformAsync } from '../../platform';
import { linkExistingProjectByIdAsync } from '../../project/projectInitialization';
import { selectAsync } from '../../prompts';
import uniq from '../../utils/expodash/uniq';
import { enableJsonOutput } from '../../utils/json';
@@ -28,6 +30,8 @@ interface RawBuildFlags {
'skip-credentials-check': boolean;
'skip-project-configuration': boolean;
profile?: string;
'link-project-id'?: string;
force?: boolean;
'non-interactive': boolean;
local: boolean;
output?: string;
@@ -67,6 +71,16 @@ export default class Build extends EasCommand {
'Name of the build profile from eas.json. Defaults to "production" if defined in eas.json.',
helpValue: 'PROFILE_NAME',
}),
'link-project-id': Flags.string({
description:
'ID of an existing EAS project to link this directory to before building. Writes "extra.eas.projectId" to your app config, like `eas init --id`.',
helpValue: 'PROJECT_ID',
}),
force: Flags.boolean({
dependsOn: ['link-project-id'],
description:
'Used with --link-project-id: overwrite an existing different project link, "owner", or "slug" in your app config without prompting',
}),
local: Flags.boolean({
default: false,
description: 'Run build locally [experimental]',
@@ -161,6 +175,13 @@ export default class Build extends EasCommand {
withServerSideEnvironment: null,
});
if (rawFlags['link-project-id']) {
await linkExistingProjectByIdAsync(graphqlClient, rawFlags['link-project-id'], projectDir, {
force: rawFlags.force ?? false,
nonInteractive: flags.nonInteractive,
});
}
await handleDeprecatedEasJsonAsync(projectDir, flags.nonInteractive);
if (!flags.localBuildOptions.localBuildMode) {
@@ -214,6 +235,12 @@ export default class Build extends EasCommand {
if (!flags.platform && nonInteractive) {
Errors.error('--platform is required when building in non-interactive mode', { exit: 1 });
}
if (flags['link-project-id'] && !uuid.validate(flags['link-project-id'])) {
Errors.error(
`--link-project-id must be a valid UUID. Received: ${flags['link-project-id']}`,
{ exit: 1 }
);
}
const autoSubmit = flags['auto-submit'] || flags['auto-submit-with-profile'] !== undefined;
if (flags['what-to-test'] && !autoSubmit) {
Errors.error(
@@ -0,0 +1,248 @@
import { instance, mock } from 'ts-mockito';
import { ExpoGraphqlClient } from '../../commandUtils/context/contextUtils/createGraphqlClient';
import { saveProjectIdToAppConfigAsync } from '../../commandUtils/context/contextUtils/getProjectIdAsync';
import { jester } from '../../credentials/__tests__/fixtures-constants';
import { AppFragment } from '../../graphql/generated';
import { AppQuery } from '../../graphql/queries/AppQuery';
import { confirmAsync } from '../../prompts';
import { createOrModifyExpoConfigAsync, getPrivateExpoConfigAsync } from '../expoConfig';
import {
ensureOwnerSlugConsistencyAsync,
linkExistingProjectByIdAsync,
} from '../projectInitialization';
jest.mock('../expoConfig');
jest.mock('../../commandUtils/context/contextUtils/getProjectIdAsync');
jest.mock('../../graphql/queries/AppQuery');
jest.mock('../../prompts');
jest.mock('../../ora', () => ({
ora: () => ({
start: () => ({ succeed: () => {}, fail: () => {} }),
}),
}));
const PROJECT_DIR = '/test-project';
const PROJECT_ID = '00000000-0000-0000-0000-000000000001';
const OTHER_PROJECT_ID = '00000000-0000-0000-0000-000000000002';
const app: AppFragment = {
id: PROJECT_ID,
name: 'testing-123',
slug: 'testing-123',
fullName: `@${jester.accounts[0].name}/testing-123`,
ownerAccount: jester.accounts[0],
};
const graphqlClient = instance(mock<ExpoGraphqlClient>());
function mockExpoConfig(exp: { projectId?: string; owner?: string; slug?: string }): void {
jest.mocked(getPrivateExpoConfigAsync).mockResolvedValue({
name: 'testing 123',
slug: exp.slug as string,
owner: exp.owner,
extra: exp.projectId ? { eas: { projectId: exp.projectId } } : {},
});
}
beforeEach(() => {
jest.resetAllMocks();
jest.mocked(AppQuery.byIdAsync).mockResolvedValue(app);
jest.mocked(createOrModifyExpoConfigAsync).mockResolvedValue({
type: 'success',
config: { name: 'testing 123', slug: 'testing-123' } as any,
});
});
describe(linkExistingProjectByIdAsync.name, () => {
const options = { force: false, nonInteractive: true };
it('rejects without writing anything when the project ID is unknown or inaccessible', async () => {
jest.mocked(AppQuery.byIdAsync).mockRejectedValue(new Error('Entity not authorized.'));
mockExpoConfig({ slug: 'testing-123' });
await expect(
linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, options)
).rejects.toThrow('No changes were made to your app config');
expect(saveProjectIdToAppConfigAsync).not.toHaveBeenCalled();
expect(createOrModifyExpoConfigAsync).not.toHaveBeenCalled();
});
it('links an unlinked project and queries the server exactly once', async () => {
mockExpoConfig({ owner: jester.accounts[0].name, slug: 'testing-123' });
const result = await linkExistingProjectByIdAsync(
graphqlClient,
PROJECT_ID,
PROJECT_DIR,
options
);
expect(result).toMatchObject({
projectId: PROJECT_ID,
status: 'linked',
owner: jester.accounts[0].name,
slug: 'testing-123',
});
expect(saveProjectIdToAppConfigAsync).toHaveBeenCalledWith(PROJECT_DIR, PROJECT_ID);
expect(AppQuery.byIdAsync).toHaveBeenCalledTimes(1);
});
it('is a no-op when already linked to the same project', async () => {
mockExpoConfig({
projectId: PROJECT_ID,
owner: jester.accounts[0].name,
slug: 'testing-123',
});
const result = await linkExistingProjectByIdAsync(
graphqlClient,
PROJECT_ID,
PROJECT_DIR,
options
);
expect(result.status).toBe('already-linked');
expect(saveProjectIdToAppConfigAsync).not.toHaveBeenCalled();
});
it('rejects in non-interactive mode when linked to a different project without --force', async () => {
mockExpoConfig({
projectId: OTHER_PROJECT_ID,
owner: jester.accounts[0].name,
slug: 'testing-123',
});
await expect(
linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, options)
).rejects.toThrow('Use --force flag to overwrite');
expect(saveProjectIdToAppConfigAsync).not.toHaveBeenCalled();
});
it('overwrites a different existing project link with force, without prompting', async () => {
mockExpoConfig({
projectId: OTHER_PROJECT_ID,
owner: jester.accounts[0].name,
slug: 'testing-123',
});
const result = await linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, {
force: true,
nonInteractive: true,
});
expect(result.status).toBe('linked');
expect(saveProjectIdToAppConfigAsync).toHaveBeenCalledWith(PROJECT_DIR, PROJECT_ID);
expect(confirmAsync).not.toHaveBeenCalled();
});
it('prompts to overwrite a different existing project link in interactive mode', async () => {
mockExpoConfig({
projectId: OTHER_PROJECT_ID,
owner: jester.accounts[0].name,
slug: 'testing-123',
});
jest.mocked(confirmAsync).mockResolvedValue(false);
await expect(
linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, {
force: false,
nonInteractive: false,
})
).rejects.toThrow('Aborting');
expect(saveProjectIdToAppConfigAsync).not.toHaveBeenCalled();
jest.mocked(confirmAsync).mockResolvedValue(true);
await linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, {
force: false,
nonInteractive: false,
});
expect(saveProjectIdToAppConfigAsync).toHaveBeenCalledWith(PROJECT_DIR, PROJECT_ID);
});
it('rejects on owner mismatch in non-interactive mode without --force', async () => {
mockExpoConfig({ projectId: PROJECT_ID, owner: 'someone-else', slug: 'testing-123' });
await expect(
linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, options)
).rejects.toThrow('Use --force flag to overwrite');
expect(createOrModifyExpoConfigAsync).not.toHaveBeenCalled();
});
it('rewrites a mismatched owner with force', async () => {
mockExpoConfig({ projectId: PROJECT_ID, owner: 'someone-else', slug: 'testing-123' });
await linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, {
force: true,
nonInteractive: true,
});
expect(createOrModifyExpoConfigAsync).toHaveBeenCalledWith(PROJECT_DIR, {
owner: jester.accounts[0].name,
});
expect(confirmAsync).not.toHaveBeenCalled();
});
it('fills in missing owner and slug without prompting', async () => {
mockExpoConfig({ projectId: PROJECT_ID });
await linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, options);
expect(createOrModifyExpoConfigAsync).toHaveBeenCalledWith(PROJECT_DIR, {
owner: jester.accounts[0].name,
});
expect(createOrModifyExpoConfigAsync).toHaveBeenCalledWith(PROJECT_DIR, {
slug: 'testing-123',
});
expect(confirmAsync).not.toHaveBeenCalled();
});
it('propagates dynamic config write failures', async () => {
mockExpoConfig({ owner: jester.accounts[0].name, slug: 'testing-123' });
jest
.mocked(saveProjectIdToAppConfigAsync)
.mockRejectedValue(new Error('Your project uses dynamic app configuration'));
await expect(
linkExistingProjectByIdAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, options)
).rejects.toThrow('dynamic app configuration');
});
});
describe(ensureOwnerSlugConsistencyAsync.name, () => {
it('queries the server itself when no prefetched app is provided', async () => {
jest.mocked(getPrivateExpoConfigAsync).mockResolvedValue({
name: 'testing 123',
slug: 'testing-123',
owner: jester.accounts[0].name,
});
const result = await ensureOwnerSlugConsistencyAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, {
force: false,
nonInteractive: true,
});
expect(result).toEqual({ owner: jester.accounts[0].name, slug: 'testing-123' });
expect(AppQuery.byIdAsync).toHaveBeenCalledTimes(1);
});
it('does not query the server when a prefetched app is provided', async () => {
jest.mocked(getPrivateExpoConfigAsync).mockResolvedValue({
name: 'testing 123',
slug: 'testing-123',
owner: jester.accounts[0].name,
});
const result = await ensureOwnerSlugConsistencyAsync(graphqlClient, PROJECT_ID, PROJECT_DIR, {
force: false,
nonInteractive: true,
prefetchedApp: app,
});
expect(result).toEqual({ owner: jester.accounts[0].name, slug: 'testing-123' });
expect(AppQuery.byIdAsync).not.toHaveBeenCalled();
});
});
@@ -12,6 +12,7 @@ import { getProjectDashboardUrl } from '../build/utils/url';
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
import { saveProjectIdToAppConfigAsync } from '../commandUtils/context/contextUtils/getProjectIdAsync';
import { validSlugName, validateFullNameAndSlug } from '../commandUtils/projectNameValidation';
import { AppFragment } from '../graphql/generated';
import { AppMutation } from '../graphql/mutations/AppMutation';
import { AppQuery } from '../graphql/queries/AppQuery';
import Log, { link } from '../log';
@@ -91,10 +92,14 @@ export async function ensureOwnerSlugConsistencyAsync(
graphqlClient: ExpoGraphqlClient,
projectId: string,
projectDir: string,
{ force, nonInteractive }: InitializeMethodOptions
{
force,
nonInteractive,
prefetchedApp,
}: InitializeMethodOptions & { prefetchedApp?: AppFragment }
): Promise<{ owner: string; slug: string }> {
const exp = await getPrivateExpoConfigAsync(projectDir);
const appForProjectId = await AppQuery.byIdAsync(graphqlClient, projectId);
const appForProjectId = prefetchedApp ?? (await AppQuery.byIdAsync(graphqlClient, projectId));
const correctOwner = appForProjectId.ownerAccount.name;
const correctSlug = appForProjectId.slug;
@@ -200,6 +205,35 @@ export async function initializeWithExplicitIDAsync(
});
}
export async function linkExistingProjectByIdAsync(
graphqlClient: ExpoGraphqlClient,
projectId: string,
projectDir: string,
{ force, nonInteractive }: InitializeMethodOptions
): Promise<{ projectId: string; status: ProjectInitStatus; owner: string; slug: string }> {
let app: AppFragment;
try {
app = await AppQuery.byIdAsync(graphqlClient, projectId);
} catch (error: any) {
throw new Error(
`Failed to link project with ID "${projectId}": ${
error?.message ?? error
}\nNo changes were made to your app config.`
);
}
const status = await initializeWithExplicitIDAsync(projectId, projectDir, {
force,
nonInteractive,
});
const { owner, slug } = await ensureOwnerSlugConsistencyAsync(
graphqlClient,
projectId,
projectDir,
{ force, nonInteractive, prefetchedApp: app }
);
return { projectId, status, owner, slug };
}
export async function initializeWithoutExplicitIDAsync(
graphqlClient: ExpoGraphqlClient,
actor: Actor,