mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-25 00:15:45 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
64f42eea63 | ||
|
|
090727f822 | ||
|
|
22acd69b7b | ||
|
|
3e03342c49 | ||
|
|
245c16c834 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Report `EAS_INPUT_REQUIRED` in `error.errorCode` when a non-interactive fingerprint comparison needs a selection.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Report `EAS_PERMISSION_DENIED` in `error.errorCode` of JSON output when the API denies access.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Print a JSON error with a human-readable `message` on stdout when a command run with `--json` fails. The error can include a `requestId` and an `errorCode`, such as `EAS_PROJECT_NOT_CONFIGURED` or `EAS_LOGIN_REQUIRED`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Explain project creation permissions for unlinked projects and include `accountsWithProjectCreationPermission` and, when known, `accountName` in the JSON error.
|
||||
@@ -88,6 +88,17 @@ New to EAS? Follow [Create your first build](https://docs.expo.dev/build/setup/)
|
||||
- **[EAS Metadata](https://docs.expo.dev/eas/metadata/)** (`eas metadata:push`): maintain your app store presence from the command line (in preview).
|
||||
- **Project operations** (`eas env`, `eas credentials`, `eas device`, `eas channel`, …): manage environment variables, signing credentials, Apple devices, update channels, webhooks, and project settings.
|
||||
|
||||
## Handling JSON command failures
|
||||
|
||||
When an EAS command exits unsuccessfully with `--json`, read the optional `error.errorCode` from stdout to choose a recovery. Display the diagnostic for unknown codes or for older CLI versions that omit the code or JSON output.
|
||||
|
||||
| Code | Recovery |
|
||||
| --- | --- |
|
||||
| `EAS_PROJECT_NOT_CONFIGURED` | Link an existing project with `eas init --id`, or use `eas init --account` to create one. Check `accountName` and `accountsWithProjectCreationPermission` before choosing an account. |
|
||||
| `EAS_LOGIN_REQUIRED` | Sign in with `eas login` or provide an Expo access token in `EXPO_TOKEN`. |
|
||||
| `EAS_PERMISSION_DENIED` | Verify the account and token have access to the requested resource. Ask the project owner for the required permissions. |
|
||||
| `EAS_INPUT_REQUIRED` | For `fingerprint:compare`, provide a fingerprint hash, build ID, or individual update ID, or rerun interactively to choose. |
|
||||
|
||||
## Version policy
|
||||
|
||||
EAS CLI is designed to be installed globally or run with `npx`. Installing `eas-cli` into project dependencies is strongly discouraged because it can cause dependency conflicts that are difficult to debug.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
const nock = require('nock');
|
||||
|
||||
nock.disableNetConnect();
|
||||
|
||||
const api = nock('http://127.0.0.1:3000').persist();
|
||||
api
|
||||
.post('/graphql', body => body.query.includes('query CurrentUser'))
|
||||
.reply(200, {
|
||||
data: { meActor: { __typename: 'User', id: 'me', username: 'fixture', accounts: [] } },
|
||||
});
|
||||
api
|
||||
.post('/graphql', body => body.query.includes('query AppByIdQuery'))
|
||||
.reply(200, (_uri, body) => {
|
||||
if (process.env.EXPO_TOKEN === 'denied-token') {
|
||||
return {
|
||||
errors: [{ message: 'Fixture refusal', extensions: { errorCode: 'UNAUTHORIZED_ERROR' } }],
|
||||
};
|
||||
}
|
||||
return {
|
||||
data: {
|
||||
app: {
|
||||
byId: { id: body.variables.appId, slug: 'fixture', ownerAccount: { name: 'fixture' } },
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
api
|
||||
.post('/graphql', body => body.query.includes('query ViewUpdatesByGroup'))
|
||||
.reply(200, {
|
||||
data: { updatesByGroup: [{ id: 'ios-update' }, { id: 'android-update' }] },
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
const nock = require('nock');
|
||||
|
||||
nock.disableNetConnect();
|
||||
const accounts = ['creator', 'viewer'].map(name => ({
|
||||
id: name,
|
||||
name,
|
||||
viewerUserPermission2: {
|
||||
permissions: name === 'creator' ? ['PUBLISH'] : [],
|
||||
effectivePermissions: name === 'creator' ? ['PUBLISH'] : [],
|
||||
},
|
||||
}));
|
||||
nock('http://127.0.0.1:3000')
|
||||
.persist()
|
||||
.post('/graphql', body => body.query.includes('query CurrentUser'))
|
||||
.reply(200, {
|
||||
data: { meActor: { __typename: 'User', id: 'me', username: 'me', accounts } },
|
||||
});
|
||||
@@ -88,6 +88,17 @@ New to EAS? Follow [Create your first build](https://docs.expo.dev/build/setup/)
|
||||
- **[EAS Metadata](https://docs.expo.dev/eas/metadata/)** (`eas metadata:push`): maintain your app store presence from the command line (in preview).
|
||||
- **Project operations** (`eas env`, `eas credentials`, `eas device`, `eas channel`, …): manage environment variables, signing credentials, Apple devices, update channels, webhooks, and project settings.
|
||||
|
||||
## Handling JSON command failures
|
||||
|
||||
When an EAS command exits unsuccessfully with `--json`, read the optional `error.errorCode` from stdout to choose a recovery. Display the diagnostic for unknown codes or for older CLI versions that omit the code or JSON output.
|
||||
|
||||
| Code | Recovery |
|
||||
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `EAS_PROJECT_NOT_CONFIGURED` | Link an existing project with `eas init --id`, or use `eas init --account` to create one. Check `accountName` and `accountsWithProjectCreationPermission` before choosing an account. |
|
||||
| `EAS_LOGIN_REQUIRED` | Sign in with `eas login` or provide an Expo access token in `EXPO_TOKEN`. |
|
||||
| `EAS_PERMISSION_DENIED` | Verify the account and token have access to the requested resource. Ask the project owner for the required permissions. |
|
||||
| `EAS_INPUT_REQUIRED` | For `fingerprint:compare`, provide a fingerprint hash, build ID, or individual update ID, or rerun interactively to choose. |
|
||||
|
||||
## Version policy
|
||||
|
||||
EAS CLI is designed to be installed globally or run with `npx`. Installing `eas-cli` into project dependencies is strongly discouraged because it can cause dependency conflicts that are difficult to debug.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Command } from '@oclif/core';
|
||||
import { Command, Errors } from '@oclif/core';
|
||||
import { CombinedError } from '@urql/core';
|
||||
import chalk from 'chalk';
|
||||
import { GraphQLError } from 'graphql/error';
|
||||
@@ -32,6 +32,7 @@ import Log, { link } from '../log';
|
||||
import Sentry from '../sentry';
|
||||
import SessionManager from '../user/SessionManager';
|
||||
import { getActorDisplayName } from '../user/User';
|
||||
import { enableJsonOutput, printJsonErrorOutput } from '../utils/json';
|
||||
import { Client } from '../vcs/vcs';
|
||||
|
||||
export type ContextInput<
|
||||
@@ -239,6 +240,10 @@ export default abstract class EasCommand extends Command {
|
||||
|
||||
// eslint-disable-next-line async-protect/async-suffix
|
||||
async run(): Promise<any> {
|
||||
if (this.jsonOutputRequested()) {
|
||||
enableJsonOutput();
|
||||
}
|
||||
|
||||
// id is assigned by oclif in constructor based on the filepath:
|
||||
// commands/submit === submit, commands/build/list === build:list
|
||||
const command = `eas ${this.id}`;
|
||||
@@ -268,6 +273,16 @@ export default abstract class EasCommand extends Command {
|
||||
}
|
||||
}
|
||||
|
||||
/** Mirrors oclif's `jsonEnabled`, for commands that declare their own `json` flag. */
|
||||
private jsonOutputRequested(): boolean {
|
||||
if (!this.ctor.flags?.json) {
|
||||
return false;
|
||||
}
|
||||
const jsonIndex = this.argv.indexOf('--json');
|
||||
const passThroughIndex = this.argv.indexOf('--');
|
||||
return jsonIndex !== -1 && (passThroughIndex === -1 || jsonIndex < passThroughIndex);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line async-protect/async-suffix
|
||||
override async finally(err: Error): Promise<any> {
|
||||
await this.analytics.flushAsync();
|
||||
@@ -278,11 +293,27 @@ export default abstract class EasCommand extends Command {
|
||||
protected override catch(err: Error): Promise<any> {
|
||||
const commandId = this.id ?? 'unknown';
|
||||
let baseMessage = `${commandId} command failed.`;
|
||||
if (err instanceof EasCommandError) {
|
||||
if (!err.messageAlreadyPrinted) {
|
||||
let message = err.message;
|
||||
let code: string | undefined;
|
||||
let requestId: string | undefined;
|
||||
if (err instanceof Errors.ExitError) {
|
||||
// Errors.exit(1) carries no reason; the code that called it printed the reason already.
|
||||
Log.errorToStderr(err.message);
|
||||
message = baseMessage;
|
||||
} else if (err instanceof EasCommandError || err instanceof Errors.CLIError) {
|
||||
if (!(err instanceof EasCommandError && err.messageAlreadyPrinted)) {
|
||||
Log.errorToStderr(err.message);
|
||||
}
|
||||
// Only codes that eas-cli sets. GraphQL error codes belong to the server and stay out.
|
||||
code = err.code;
|
||||
} else if (err instanceof CombinedError && err?.graphQLErrors) {
|
||||
if (
|
||||
!err.networkError &&
|
||||
err.graphQLErrors.length > 0 &&
|
||||
err.graphQLErrors.every(error => error.extensions?.errorCode === 'UNAUTHORIZED_ERROR')
|
||||
) {
|
||||
code = 'EAS_PERMISSION_DENIED';
|
||||
}
|
||||
const cleanGQLErrorsMessage = err?.graphQLErrors
|
||||
.map((graphQLError: GraphQLError) => {
|
||||
const messageLine = graphQLError.message.replace('[GraphQL] ', '');
|
||||
@@ -331,9 +362,19 @@ export default abstract class EasCommand extends Command {
|
||||
: cleanGQLErrorsMessage;
|
||||
Log.errorToStderr(cleanMessage);
|
||||
baseMessage = BASE_GRAPHQL_ERROR_MESSAGE;
|
||||
message = cleanMessage;
|
||||
requestId = err.graphQLErrors[0]?.extensions?.requestId as string | undefined;
|
||||
} else {
|
||||
Log.errorToStderr(err.message);
|
||||
}
|
||||
if (this.jsonOutputRequested()) {
|
||||
printJsonErrorOutput({
|
||||
message,
|
||||
errorCode: code,
|
||||
requestId,
|
||||
...(err instanceof EasCommandError ? err.details : undefined),
|
||||
});
|
||||
}
|
||||
Log.debug(err);
|
||||
Sentry.withScope(scope => {
|
||||
scope.setTag('command', commandId);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Config } from '@oclif/core';
|
||||
import { Config, Errors, Flags } from '@oclif/core';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
import { AnalyticsWithOrchestration } from '../../analytics/AnalyticsManager';
|
||||
import { enableJsonOutput, printJsonErrorOutput } from '../../utils/json';
|
||||
|
||||
jest.mock('../../user/User');
|
||||
jest.mock('../../user/SessionManager');
|
||||
@@ -24,6 +25,7 @@ jest.mock('../../analytics/AnalyticsManager', () => {
|
||||
};
|
||||
});
|
||||
jest.mock('../../log');
|
||||
jest.mock('../../utils/json');
|
||||
|
||||
const mockRequestId = uuidv4();
|
||||
|
||||
@@ -64,7 +66,9 @@ beforeEach(() => {
|
||||
*/
|
||||
let lastCommandConfig: Config | undefined;
|
||||
|
||||
const createTestEasCommand = (): any => {
|
||||
const jsonFlags = { json: Flags.boolean() };
|
||||
|
||||
const createTestEasCommand = (flags = {}): any => {
|
||||
const { createAnalyticsAsync } = jest.requireMock('../../analytics/AnalyticsManager');
|
||||
createAnalyticsAsync.mockResolvedValue(analytics);
|
||||
const EasCommand = require('../EasCommand').default;
|
||||
@@ -75,6 +79,7 @@ const createTestEasCommand = (): any => {
|
||||
}
|
||||
}
|
||||
|
||||
TestEasCommand.flags = flags;
|
||||
TestEasCommand.id = 'testEasCommand'; // normally oclif will assign ids, but b/c this is located outside the commands folder it will not
|
||||
return TestEasCommand;
|
||||
};
|
||||
@@ -306,7 +311,7 @@ describe('EasCommand', () => {
|
||||
});
|
||||
|
||||
it('logs the cleaned message with request ID if present', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const TestEasCommand = createTestEasCommand(jsonFlags);
|
||||
const Log = jest.requireMock('../../log').default;
|
||||
const logErrorSpy = jest.spyOn(Log, 'errorToStderr');
|
||||
const logDebugSpy = jest.spyOn(Log, 'debug');
|
||||
@@ -330,9 +335,10 @@ describe('EasCommand', () => {
|
||||
runAsyncMock.mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
try {
|
||||
await TestEasCommand.run([], mockConfig);
|
||||
} catch {}
|
||||
await expect(TestEasCommand.run(['--json'], mockConfig)).rejects.toThrow();
|
||||
expect(printJsonErrorOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ requestId: mockRequestId, errorCode: undefined })
|
||||
);
|
||||
|
||||
expect(logErrorSpy).toBeCalledWith(
|
||||
`Unexpected GraphQL error message\nRequest ID: ${mockRequestId}`
|
||||
@@ -381,6 +387,66 @@ describe('EasCommand', () => {
|
||||
expect(logDebugSpy).toBeCalledWith(error);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ codes: ['UNAUTHORIZED_ERROR'], expected: 'EAS_PERMISSION_DENIED' },
|
||||
{ codes: ['UNAUTHORIZED_ERROR', 'OTHER_ERROR'], expected: undefined },
|
||||
{ codes: ['UNAUTHORIZED_ERROR'], networkError: new Error('offline'), expected: undefined },
|
||||
])(
|
||||
'classifies GraphQL failures with $codes and network error $networkError',
|
||||
async ({ codes, expected, networkError }) => {
|
||||
const TestEasCommand = createTestEasCommand(jsonFlags);
|
||||
const { CombinedError } = require('@urql/core');
|
||||
const graphQLErrors = codes.map(errorCode => ({
|
||||
message: 'Request failed',
|
||||
extensions: { errorCode },
|
||||
}));
|
||||
jest
|
||||
.spyOn(TestEasCommand.prototype, 'runAsync')
|
||||
.mockRejectedValue(new CombinedError({ graphQLErrors, networkError }));
|
||||
|
||||
await expect(TestEasCommand.run(['--json'], mockConfig)).rejects.toThrow();
|
||||
expect(printJsonErrorOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ errorCode: expected })
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it('enables JSON before authentication and reports login failures', async () => {
|
||||
const TestEasCommand = createTestEasCommand(jsonFlags);
|
||||
const SessionManager = jest.requireMock('../../user/SessionManager').default;
|
||||
SessionManager.prototype.getUserAsync.mockImplementationOnce(() => {
|
||||
expect(enableJsonOutput).toHaveBeenCalled();
|
||||
Errors.error('Log in first.', { code: 'EAS_LOGIN_REQUIRED' });
|
||||
});
|
||||
|
||||
await expect(TestEasCommand.run(['--json'], mockConfig)).rejects.toThrow();
|
||||
expect(printJsonErrorOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: 'Log in first.', errorCode: 'EAS_LOGIN_REQUIRED' })
|
||||
);
|
||||
});
|
||||
|
||||
it('reports the command name when it exits without a reason', async () => {
|
||||
const TestEasCommand = createTestEasCommand(jsonFlags);
|
||||
jest.spyOn(TestEasCommand.prototype, 'runAsync').mockImplementation(() => Errors.exit(1));
|
||||
|
||||
await expect(TestEasCommand.run(['--json'], mockConfig)).rejects.toThrow();
|
||||
expect(printJsonErrorOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: 'testEasCommand command failed.' })
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: 'forwarded', flags: jsonFlags, argv: ['--', '--json'] },
|
||||
{ name: 'unsupported', flags: {}, argv: ['--json'] },
|
||||
])('ignores --json when it is $name', async ({ flags, argv }) => {
|
||||
const TestEasCommand = createTestEasCommand(flags);
|
||||
jest.spyOn(TestEasCommand.prototype, 'runAsync').mockRejectedValue(new Error('failed'));
|
||||
|
||||
await expect(TestEasCommand.run(argv, mockConfig)).rejects.toThrow();
|
||||
expect(enableJsonOutput).not.toHaveBeenCalled();
|
||||
expect(printJsonErrorOutput).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-throws the error with default base message', async () => {
|
||||
const TestEasCommand = createTestEasCommand();
|
||||
const runAsyncMock = jest.spyOn(TestEasCommand.prototype, 'runAsync');
|
||||
|
||||
+10
@@ -513,6 +513,16 @@ describe(getProjectIdAsync, () => {
|
||||
expect(fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('gives the non-interactive error the EAS_PROJECT_NOT_CONFIGURED code', async () => {
|
||||
await expect(
|
||||
getProjectIdAsync(
|
||||
sessionManager,
|
||||
{ sdkVersion: '52.0.0', name: 'test', slug: 'test' },
|
||||
{ nonInteractive: true }
|
||||
)
|
||||
).rejects.toMatchObject({ code: 'EAS_PROJECT_NOT_CONFIGURED' });
|
||||
});
|
||||
|
||||
it('defers to the project fetch in non-interactive mode when the account is already known', async () => {
|
||||
const sessionManagerMock = mock<SessionManager>();
|
||||
when(sessionManagerMock.getGraphqlClient(anything())).thenReturn({} as ExpoGraphqlClient);
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
export interface EasCommandErrorDetails {
|
||||
accountName?: string;
|
||||
accountsWithProjectCreationPermission: string[];
|
||||
}
|
||||
|
||||
export class EasCommandError extends Error {
|
||||
/** True when the command already printed the message, so `EasCommand.catch` must not print it again. */
|
||||
public readonly messageAlreadyPrinted: boolean;
|
||||
/** A stable identifier, printed in the `--json` error output so programs need not match the message. */
|
||||
public readonly code?: string;
|
||||
|
||||
public readonly details?: EasCommandErrorDetails;
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
{ messageAlreadyPrinted = false }: { messageAlreadyPrinted?: boolean } = {}
|
||||
{
|
||||
messageAlreadyPrinted = false,
|
||||
code,
|
||||
details,
|
||||
}: { messageAlreadyPrinted?: boolean; code?: string; details?: EasCommandErrorDetails } = {}
|
||||
) {
|
||||
super(message);
|
||||
this.messageAlreadyPrinted = messageAlreadyPrinted;
|
||||
this.code = code;
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ export function isNonInteractiveByDefault(): boolean {
|
||||
export const EasNonInteractiveAndJsonFlags = {
|
||||
json: Flags.boolean({
|
||||
description:
|
||||
'Enable JSON output, non-JSON messages will be printed to stderr. Implies --non-interactive.',
|
||||
'Enable JSON output, non-JSON messages will be printed to stderr. On failure, prints {"error": {"message", "errorCode"?, "requestId"?}}. Implies --non-interactive.',
|
||||
}),
|
||||
'non-interactive': Flags.boolean({
|
||||
description: 'Run the command in non-interactive mode.',
|
||||
@@ -87,7 +87,8 @@ export const EASNonInteractiveFlag = {
|
||||
|
||||
export const EasJsonOnlyFlag = {
|
||||
json: Flags.boolean({
|
||||
description: 'Enable JSON output, non-JSON messages will be printed to stderr.',
|
||||
description:
|
||||
'Enable JSON output, non-JSON messages will be printed to stderr. On failure, prints {"error": {"message", "errorCode"?, "requestId"?}}.',
|
||||
}),
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { spawnSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
describe('build:list on an unlinked project', () => {
|
||||
it.each([true, false])('returns the project error with JSON mode %s', json => {
|
||||
const configLog = 'Loading the unlinked fixture project';
|
||||
const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eas-build-list-'));
|
||||
try {
|
||||
fs.writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify({ name: 'app' }));
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, 'app.config.js'),
|
||||
`console.log(${JSON.stringify(configLog)}); module.exports = { name: 'app', slug: 'app', sdkVersion: '56.0.0' };`
|
||||
);
|
||||
// A fresh update-check cache keeps oclif from spawning a registry request in the fixture.
|
||||
fs.writeFileSync(path.join(projectDir, 'version'), '{}');
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
'--require',
|
||||
require.resolve('../../../../jest/unlinkedProject.cjs'),
|
||||
path.resolve(__dirname, '../../../../bin/dev'),
|
||||
'build:list',
|
||||
'--non-interactive',
|
||||
...(json ? ['--json'] : []),
|
||||
],
|
||||
{
|
||||
cwd: projectDir,
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
HOME: projectDir,
|
||||
USERPROFILE: projectDir,
|
||||
EXPO_TOKEN: 'fixture-token',
|
||||
EAS_NO_VCS: '1',
|
||||
EAS_PROJECT_ROOT: projectDir,
|
||||
EAS_CACHE_DIR: projectDir,
|
||||
EXPO_LOCAL: '1',
|
||||
EXPO_NO_TELEMETRY: '1',
|
||||
CI: '1',
|
||||
NO_COLOR: '1',
|
||||
},
|
||||
timeout: 60000,
|
||||
encoding: 'utf8',
|
||||
}
|
||||
);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain('eas init --id');
|
||||
if (json) {
|
||||
expect(result.stderr).toContain(configLog);
|
||||
expect(JSON.parse(result.stdout)).toStrictEqual({
|
||||
error: {
|
||||
message: expect.stringContaining('eas init --id'),
|
||||
errorCode: 'EAS_PROJECT_NOT_CONFIGURED',
|
||||
accountsWithProjectCreationPermission: ['creator'],
|
||||
},
|
||||
});
|
||||
} else {
|
||||
expect(result.stdout).toContain(configLog);
|
||||
expect(result.stdout).not.toContain('EAS_PROJECT_NOT_CONFIGURED');
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(projectDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { spawnSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
describe('fingerprint:compare --json', () => {
|
||||
it.each([
|
||||
{ code: 'EAS_LOGIN_REQUIRED', token: undefined, args: ['--build-id', 'build-id'] },
|
||||
{ code: 'EAS_PERMISSION_DENIED', token: 'denied-token', args: ['--build-id', 'build-id'] },
|
||||
{ code: 'EAS_INPUT_REQUIRED', token: 'allowed-token', args: [] },
|
||||
{ code: 'EAS_INPUT_REQUIRED', token: 'allowed-token', args: ['--update-id', 'group-id'] },
|
||||
])('returns $code for $args', ({ code, token, args }) => {
|
||||
const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eas-fingerprint-'));
|
||||
try {
|
||||
fs.writeFileSync(path.join(projectDir, 'package.json'), '{"name":"fixture"}');
|
||||
fs.writeFileSync(
|
||||
path.join(projectDir, 'app.json'),
|
||||
JSON.stringify({
|
||||
expo: {
|
||||
name: 'fixture',
|
||||
slug: 'fixture',
|
||||
sdkVersion: '56.0.0',
|
||||
extra: { eas: { projectId: '00000000-0000-4000-8000-000000000001' } },
|
||||
},
|
||||
})
|
||||
);
|
||||
// The update check reads this cache before deciding whether to spawn a registry lookup.
|
||||
fs.writeFileSync(path.join(projectDir, 'version'), '{}');
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
'--require',
|
||||
require.resolve('../../../../jest/fingerprintProject.cjs'),
|
||||
path.resolve(__dirname, '../../../../bin/dev'),
|
||||
'fingerprint:compare',
|
||||
...args,
|
||||
'--json',
|
||||
],
|
||||
{
|
||||
cwd: projectDir,
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
HOME: projectDir,
|
||||
USERPROFILE: projectDir,
|
||||
EAS_CACHE_DIR: projectDir,
|
||||
EAS_PROJECT_ROOT: projectDir,
|
||||
EAS_NO_VCS: '1',
|
||||
EXPO_LOCAL: '1',
|
||||
EXPO_NO_TELEMETRY: '1',
|
||||
EXPO_TOKEN: token,
|
||||
CI: '1',
|
||||
NO_COLOR: '1',
|
||||
},
|
||||
timeout: 60000,
|
||||
encoding: 'utf8',
|
||||
}
|
||||
);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.status).toBe(1);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({
|
||||
error: { errorCode: code, message: expect.any(String) },
|
||||
});
|
||||
} finally {
|
||||
fs.rmSync(projectDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import EasCommand from '../../commandUtils/EasCommand';
|
||||
import { fetchBuildsAsync, formatBuild } from '../../commandUtils/builds';
|
||||
import { GetServerSideEnvironmentVariablesFn } from '../../commandUtils/context/ServerSideEnvironmentVariablesContextField';
|
||||
import { ExpoGraphqlClient } from '../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { EasCommandError } from '../../commandUtils/errors';
|
||||
import {
|
||||
EasEnvironmentFlagParameters,
|
||||
EasNonInteractiveAndJsonFlags,
|
||||
@@ -343,8 +344,9 @@ async function getFingerprintInfoAsync(
|
||||
}
|
||||
|
||||
if (nonInteractive) {
|
||||
throw new Error(
|
||||
'Insufficent arguments provided for fingerprint comparison in non-interactive mode'
|
||||
throw new EasCommandError(
|
||||
'Pass a fingerprint hash, --build-id, or --update-id to compare in non-interactive mode.',
|
||||
{ code: 'EAS_INPUT_REQUIRED' }
|
||||
);
|
||||
}
|
||||
return await getFingerprintInfoInteractiveAsync({
|
||||
@@ -572,8 +574,9 @@ async function getFingerprintInfoFromUpdateGroupIdOrUpdateIdAsync(
|
||||
const updateUrl =
|
||||
getExpoWebsiteBaseUrl() +
|
||||
`/accounts/${project.ownerAccount.name}/projects/${project.slug}/updates/${maybeUpdateGroupId}`;
|
||||
throw new Error(
|
||||
`Please pass in your update ID from ${updateUrl} or use interactive mode to select the update ID.`
|
||||
throw new EasCommandError(
|
||||
`Please pass in your update ID from ${updateUrl} or use interactive mode to select the update ID.`,
|
||||
{ code: 'EAS_INPUT_REQUIRED' }
|
||||
);
|
||||
}
|
||||
const update = await selectAsync<UpdateFragment>(
|
||||
|
||||
+32
-19
@@ -5,23 +5,36 @@ import { jester } from '../../credentials/__tests__/fixtures-constants';
|
||||
import { fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync } from '../fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync';
|
||||
|
||||
describe(fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync, () => {
|
||||
it('throws when non-interactive is specified but interaction is required', async () => {
|
||||
const graphqlClient = instance(mock<ExpoGraphqlClient>());
|
||||
await expect(
|
||||
fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync(
|
||||
graphqlClient,
|
||||
{ accountName: 'fake', projectName: 'fake' },
|
||||
{ nonInteractive: true },
|
||||
jester
|
||||
)
|
||||
).rejects.toThrow(
|
||||
`EAS project not configured. This command cannot configure it in non-interactive mode. ` +
|
||||
`Run one of the following, then re-run this command:\n\n` +
|
||||
`To link an existing project:\n\n` +
|
||||
` eas init --id <project-id> --non-interactive\n\n` +
|
||||
`To create a new project:\n\n` +
|
||||
` eas init --account fake --non-interactive\n\n` +
|
||||
`Accounts you can create projects in: jester`
|
||||
);
|
||||
});
|
||||
it.each([
|
||||
{
|
||||
accounts: jester.accounts,
|
||||
accountsWithProjectCreationPermission: ['jester'],
|
||||
permission:
|
||||
'Accounts you can create projects in: jester\nCreating a project in fake requires a credential with permission to create projects there.',
|
||||
},
|
||||
{
|
||||
accounts: [],
|
||||
accountsWithProjectCreationPermission: [],
|
||||
permission: 'Your current credential cannot create projects in any account.',
|
||||
},
|
||||
])(
|
||||
'shows both commands and explains create permissions: $accountsWithProjectCreationPermission',
|
||||
async ({ accounts, accountsWithProjectCreationPermission, permission }) => {
|
||||
const graphqlClient = instance(mock<ExpoGraphqlClient>());
|
||||
await expect(
|
||||
fetchOrCreateProjectIDForWriteToConfigWithConfirmationAsync(
|
||||
graphqlClient,
|
||||
{ accountName: 'fake', projectName: 'fake' },
|
||||
{ nonInteractive: true },
|
||||
{ ...jester, accounts }
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
details: { accountName: 'fake', accountsWithProjectCreationPermission },
|
||||
message:
|
||||
`EAS project not configured. This command cannot configure it in non-interactive mode. ` +
|
||||
`Run one of the following, then re-run this command:\n\nTo link an existing project:\n\n` +
|
||||
` eas init --id <project-id> --non-interactive\n\nTo create a new project:\n\n eas init --account fake --non-interactive\n\n${permission}`,
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EasCommandError } from '../commandUtils/errors';
|
||||
import { Actor, getCreatableAccountNames } from '../user/User';
|
||||
|
||||
/**
|
||||
@@ -20,15 +21,30 @@ export function getUnconfiguredProjectError({
|
||||
accountName?: string;
|
||||
reason?: string;
|
||||
additionalFix?: string;
|
||||
}): Error {
|
||||
return new Error(
|
||||
}): EasCommandError {
|
||||
const accountsWithProjectCreationPermission = getCreatableAccountNames(actor);
|
||||
const accountsMessage = accountsWithProjectCreationPermission.length
|
||||
? `Accounts you can create projects in: ${accountsWithProjectCreationPermission.join(', ')}`
|
||||
: 'Your current credential cannot create projects in any account.';
|
||||
const targetMessage =
|
||||
accountName &&
|
||||
accountsWithProjectCreationPermission.length &&
|
||||
!accountsWithProjectCreationPermission.includes(accountName)
|
||||
? `\nCreating a project in ${accountName} requires a credential with permission to create projects there.`
|
||||
: '';
|
||||
return new EasCommandError(
|
||||
`EAS project not configured. ${reason} ` +
|
||||
`Run one of the following, then re-run this command:\n\n` +
|
||||
`To link an existing project:\n\n` +
|
||||
` eas init --id <project-id> --non-interactive\n\n` +
|
||||
`To create a new project:\n\n` +
|
||||
` eas init --account ${accountName ?? '<account-name>'} --non-interactive\n\n` +
|
||||
`Accounts you can create projects in: ${getCreatableAccountNames(actor).join(', ')}` +
|
||||
(additionalFix ? `\n\n${additionalFix}` : '')
|
||||
accountsMessage +
|
||||
targetMessage +
|
||||
(additionalFix ? `\n\n${additionalFix}` : ''),
|
||||
{
|
||||
code: 'EAS_PROJECT_NOT_CONFIGURED',
|
||||
details: { accountName, accountsWithProjectCreationPermission },
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -185,7 +185,8 @@ export default class SessionManager {
|
||||
)} environment variable if you're using EAS CLI on CI (${learnMore(
|
||||
'https://docs.expo.dev/accounts/programmatic-access/',
|
||||
{ dim: false }
|
||||
)})`
|
||||
)})`,
|
||||
{ code: 'EAS_LOGIN_REQUIRED' }
|
||||
);
|
||||
}
|
||||
if (printNewLine) {
|
||||
|
||||
@@ -313,6 +313,15 @@ describe(SessionManager, () => {
|
||||
});
|
||||
|
||||
describe('showLoginPromptAsync', () => {
|
||||
it('fails with the EAS_LOGIN_REQUIRED code in non-interactive mode', async () => {
|
||||
const sessionManager = new SessionManager(analytics);
|
||||
|
||||
await expect(
|
||||
sessionManager.showLoginPromptAsync({ nonInteractive: true })
|
||||
).rejects.toMatchObject({ code: 'EAS_LOGIN_REQUIRED' });
|
||||
expect(promptAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prompts for OTP when 2FA is enabled', async () => {
|
||||
jest
|
||||
.mocked(promptAsync)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
describe('printJsonErrorOutput', () => {
|
||||
const originalStdoutWrite = process.stdout.write;
|
||||
const originalStderrWrite = process.stderr.write;
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
process.stderr.write = originalStderrWrite;
|
||||
});
|
||||
|
||||
it('prints one error object on stdout, without ANSI codes, once per process', () => {
|
||||
const stdout = jest.fn(() => true);
|
||||
const stderr = jest.fn(() => true);
|
||||
process.stdout.write = stdout as any;
|
||||
process.stderr.write = stderr as any;
|
||||
// Jest's console does not write through process.stdout, so record which stream was live.
|
||||
const printed: { text: string; toStdout: boolean }[] = [];
|
||||
jest.spyOn(console, 'log').mockImplementation((text: string) => {
|
||||
printed.push({ text, toStdout: process.stdout.write === stdout });
|
||||
});
|
||||
|
||||
jest.isolateModules(() => {
|
||||
const { printJsonErrorOutput } = require('../json');
|
||||
printJsonErrorOutput({
|
||||
errorCode: 'EAS_PROJECT_NOT_CONFIGURED',
|
||||
message: '\u001b[31mEAS project not configured.\u001b[39m',
|
||||
});
|
||||
printJsonErrorOutput({ message: 'update:republish command failed.' });
|
||||
});
|
||||
|
||||
expect(printed).toHaveLength(1);
|
||||
expect(printed[0].toStdout).toBe(true);
|
||||
expect(JSON.parse(printed[0].text)).toEqual({
|
||||
error: { message: 'EAS project not configured.', errorCode: 'EAS_PROJECT_NOT_CONFIGURED' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import assert from 'assert';
|
||||
import { stripVTControlCharacters } from 'util';
|
||||
|
||||
import type { EasCommandErrorDetails } from '../commandUtils/errors';
|
||||
import Log from '../log';
|
||||
|
||||
let stdoutWrite: NodeJS.WriteStream['write'] | undefined;
|
||||
@@ -22,6 +24,30 @@ export function printJsonOnlyOutput(value: object): void {
|
||||
}
|
||||
}
|
||||
|
||||
export interface JsonErrorOutput extends Partial<EasCommandErrorDetails> {
|
||||
message: string;
|
||||
errorCode?: string;
|
||||
requestId?: string;
|
||||
}
|
||||
|
||||
let jsonErrorPrinted = false;
|
||||
|
||||
/**
|
||||
* Print `{ "error": { message, errorCode?, requestId? } }` on stdout for a command that failed with --json.
|
||||
*
|
||||
* Once per process: `update:rollback` runs other commands in-process, and the innermost error is the one
|
||||
* that says what went wrong.
|
||||
*/
|
||||
export function printJsonErrorOutput(error: JsonErrorOutput): void {
|
||||
if (jsonErrorPrinted) {
|
||||
return;
|
||||
}
|
||||
jsonErrorPrinted = true;
|
||||
// The command may have failed before it could enable JSON output.
|
||||
enableJsonOutput();
|
||||
printJsonOnlyOutput({ error: { ...error, message: stripVTControlCharacters(error.message) } });
|
||||
}
|
||||
|
||||
function sanitizeValue(value: any): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(val => sanitizeValue(val));
|
||||
|
||||
Reference in new issue
Block a user