Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions .talismanrc
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,45 @@ fileignoreconfig:
- filename: test/integration/harness/launch-api.ts
checksum: a4549b87c896744422e71ab5395a1d6d2dfa372678d2488aecc4247ee9738f87
- filename: test/integration/harness/session.ts
checksum: 74dc637304710b1df882bea6a1c52b8779f1bd416dbeeab93a9026c68edb3f9e
checksum: 49000399e4150155dbdccccc8a97e2cda429035062c41e69c30a5f904e5a361c
- filename: test/integration/specs/launch-github.test.ts
checksum: 4ea1ae16627383530d7590374ba2b37fde87b5c111cc6c38c5125456aa9b51c8
- filename: test/integration/harness/fixtures.ts
checksum: b3133a65f3f4b3f3a32caf0cc0bf65b0c71187f96e044a3331ddcce3adea88c1
checksum: e22bc8ab6f0c266b1f53700bd3611a934f7469b1995bf451cad2115f86ca4b3e
- filename: src/base-command.ts
checksum: db8bc45f6d8aa3daebae621920c8618b6e23d1a20984dee0749d91bfa5c1530c
checksum: 3f7bcb2dff516aa166c7e721d3d60bf1b14db4bb1fc22a339ed21afba4d86a13
- filename: test/unit/base-command.test.ts
checksum: 4612c2a41c9d5a7af887f77842feee0a6f6a28ba95a094282b5e9aa20dba6c8c
- filename: src/graphql/queries.ts
checksum: 6877ec55200ec4913b3c2bde7cc45e16b50e8e7a4a2cfc26529ded6d9fe27718
- filename: test/integration/specs/secrets-list.test.ts
checksum: d4cdd09fe16a876f7457bdf9bbaa83511624c12a0c7a967abc5f26a678696629
- filename: src/commands/launch/secrets/list.ts
checksum: da14a738f37a9610ab9dec7978de81cbb778ed0da9e73c4df4806c6e3c4c00cf
- filename: src/commands/launch/secrets/list.test.ts
checksum: af09c894e3c21b061078a614f599e642b3db11e6f2145cb588e14e2476ff612a
- filename: src/graphql/mutation.ts
checksum: c420996deea097d6125ccd9648d0b87806bf7edeb4eda5604a068eee3e669542
- filename: src/util/secrets.ts
checksum: 9ccc5fdb18cb3c4ea637d6834c5b91e860c374abd01d808d002b3862d2f0c67a
- filename: src/commands/launch/secrets/set.ts
checksum: 80b805d6f746b6cfbef06690f4219fe7b810d58755dcc4fd3042092922b497b6
- filename: src/util/secrets.test.ts
checksum: acadbf4e3b1a62d2ebd81f203bdb673c314d1534a7598d95d675a27905c7c8cb
- filename: test/integration/specs/secrets-set.test.ts
checksum: 0975c0277d2643273d61d2f194ff7e1599f79f21fe4372367746f0fbd5b14d4b
- filename: src/commands/launch/secrets/set.test.ts
checksum: 2953250cb9353eaa298a30e480badf5b12a6e8a9851355e3a9055e7a1bbaa98f
- filename: src/commands/launch/secrets/unset.ts
checksum: 3c7d81a01ccfbd32fd2060ed88ef14fba525fded736604b4302c68ca9bc2d966
- filename: src/commands/launch/secrets/unset.test.ts
checksum: 89449d31e20184f2f32619f75bca546c088f8f75e3a0e9e7c1735fc4cec1882f
- filename: test/integration/specs/secrets-unset.test.ts
checksum: 363d8fbfb996395eb89c355b623a337143d5049f99bf20bf45c8c076eeefe06e
- filename: src/graphql/secrets-mutations.test.ts
checksum: e812adf5638b6f55bd4986abc7cedd6707895191dc409e8cfe5de3dc87e5b338
- filename: src/base-secrets-command.ts
checksum: 21b5c6d1d69c1dc72979b53fa706eda50874536b32c1549879ea83b38f54d375
- filename: src/base-secrets-command.test.ts
checksum: 71613e5e8abe20656130e85de53539ebbaa16c23cd050c4b1fac5fda676c8dd1
version: "1.0"
15 changes: 12 additions & 3 deletions src/base-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
* @return {*} {Promise<void>}
* @memberof BaseCommand
*/
async getConfig(): Promise<void> {
async getConfig(options: { interactive?: boolean } = {}): Promise<void> {
if (this.sharedConfig.config && existsSync(this.sharedConfig.config)) {
const config: Record<string, any> = JSON.parse(readFileSync(this.sharedConfig.config, 'utf-8'));
const configKeys = keys(config);
Expand All @@ -160,7 +160,7 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
if (this.flags.branch && includes(configKeys, this.flags.branch)) {
this.sharedConfig.currentConfig = config[this.flags.branch];
} else if (configKeys?.length > 1) {
await this.handleBranchSelection(config, configKeys);
await this.handleBranchSelection(config, configKeys, options.interactive !== false);
} else {
// By default there is only one configuration ("project"), set it as the default
this.sharedConfig.currentConfig = config[configKeys[0]];
Expand All @@ -172,11 +172,20 @@ export abstract class BaseCommand<T extends typeof Command> extends Command {
}
}

private async handleBranchSelection(config: Record<string, any>, configKeys: string[]): Promise<void> {
private async handleBranchSelection(
config: Record<string, any>,
configKeys: string[],
interactive = true,
): Promise<void> {
// Filter out the "project" key from the branch choices
const branchChoices = configKeys.filter((key) => key !== 'project');

// If there are multiple keys (branches), excluding "project", prompt user to choose
if (branchChoices.length > 1 && !interactive) {
this.log('Multiple branches are configured; pass --branch to choose one.', 'error');
process.exit(1);
}

if (branchChoices.length > 1) {
this.sharedConfig.currentConfig = await ux
.inquire({
Expand Down
284 changes: 284 additions & 0 deletions src/base-secrets-command.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
import { tmpdir } from 'os';
import { join } from 'path';
import { Readable } from 'stream';
import { randomUUID } from 'crypto';
import { cliux } from '@contentstack/cli-utilities';
import { mkdtempSync, writeFileSync } from 'fs';

import { selectOrg, selectProject, getOrganizations } from './util';

import { SecretsBaseCommand } from './base-secrets-command';
import ListSecrets from './commands/launch/secrets/list';
import SetSecret from './commands/launch/secrets/set';
import UnsetSecret from './commands/launch/secrets/unset';

jest.mock('./util', () => {
const actual = jest.requireActual('./util');
return {
...actual,
Logger: jest.fn().mockImplementation(() => ({ log: jest.fn() })),
selectOrg: jest.fn(),
selectProject: jest.fn(),
getOrganizations: jest.fn(),
};
});

jest.mock('@contentstack/cli-utilities', () => {
const { launchCommand } = jest.requireActual('./test/mocks/cli-utilities');
return launchCommand;
});

class Probe extends SecretsBaseCommand<typeof Probe> {
async run(): Promise<void> {}
}

class UnexpectedArgsError extends Error {
parse = {};
}

class NonExistentFlagsError extends Error {
parse = {};
}

class FailedFlagValidationError extends Error {
parse = {};
}

const originalStdin = Object.getOwnPropertyDescriptor(process, 'stdin') as PropertyDescriptor;

const stubStdin = (isTTY: boolean) => {
const stream: any = Readable.from([]);
stream.isTTY = isTTY;
Object.defineProperty(process, 'stdin', { value: stream, configurable: true });
};

const projectsResponse = (uids: string[]) => ({
data: {
projects: { edges: uids.map((uid) => ({ node: { uid, name: `name-${uid}` } })) },
},
});

const writeConfig = (content: Record<string, any>) => {
const path = join(mkdtempSync(join(tmpdir(), 'secrets-base-')), '.cs-launch.json');
writeFileSync(path, JSON.stringify(content));
return path;
};

const buildProbe = (flags: Record<string, any> = {}, currentConfig: Record<string, any> = {}, extra: any = {}) => {
const cmd = new Probe([], {} as any);
const query = jest.fn().mockResolvedValue(projectsResponse(['P1', 'P2']));
(cmd as any).flags = flags;
(cmd as any).log = jest.fn();
(cmd as any).sharedConfig = { currentConfig: { ...currentConfig }, ...extra };
(cmd as any).apolloClient = { query };
(cmd as any).managementSdk = {};
jest.spyOn(cmd as any, 'prepareApiClients').mockResolvedValue(undefined);
return { cmd: cmd as any, query };
};

describe('SecretsBaseCommand', () => {
let exitMock: jest.SpyInstance;

beforeEach(() => {
exitMock = jest.spyOn(process, 'exit').mockImplementation(((code?: number) => {
throw new Error(`process.exit:${code}`);
}) as any);
});

afterEach(() => {
Object.defineProperty(process, 'stdin', originalStdin);
jest.clearAllMocks();
});

it('selects the organization and project again in a terminal when --org or --project override the stored project', async () => {
stubStdin(true);
const { cmd } = buildProbe({ org: 'O2', project: 'P2', environment: 'Default' }, { uid: 'P1' });
jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await cmd.setupScope();

expect(selectOrg).toHaveBeenCalledTimes(1);
expect(selectProject).toHaveBeenCalledTimes(1);
});

it('keeps the stored project without selecting in a terminal when no scope flag is given', async () => {
stubStdin(true);
const { cmd } = buildProbe({ environment: 'Default' }, { uid: 'P1' });
jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await cmd.setupScope();

expect(selectOrg).not.toHaveBeenCalled();
expect(selectProject).not.toHaveBeenCalled();
});

it('overrides the stored project with --project and --org when not in a terminal', async () => {
stubStdin(false);
(getOrganizations as jest.Mock).mockResolvedValue([{ uid: 'O1' }, { uid: 'O2' }]);
const { cmd, query } = buildProbe({ org: 'O2', project: 'P2', environment: 'Default' }, { uid: 'P1', organizationUid: 'O1' });
jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await cmd.setupScope();

expect(cmd.sharedConfig.currentConfig).toEqual(expect.objectContaining({ uid: 'P2', organizationUid: 'O2' }));
expect(query).toHaveBeenCalledTimes(1);
expect(cmd.prepareApiClients).toHaveBeenCalledTimes(3);
expect(cliux.inquire).not.toHaveBeenCalled();
expect(selectOrg).not.toHaveBeenCalled();
expect(selectProject).not.toHaveBeenCalled();
});

it('keeps the stored project without any lookup when not in a terminal and no scope flag is given', async () => {
stubStdin(false);
const { cmd, query } = buildProbe({ environment: 'Default' }, { uid: 'P1', organizationUid: 'O1' });
jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await cmd.setupScope();

expect(cmd.sharedConfig.currentConfig.uid).toBe('P1');
expect(query).not.toHaveBeenCalled();
expect(getOrganizations).not.toHaveBeenCalled();
});

it('fails without prompting when not in a terminal and --org does not match an organization', async () => {
stubStdin(false);
(getOrganizations as jest.Mock).mockResolvedValue([{ uid: 'O1' }]);
const { cmd } = buildProbe({ org: 'WRONG', project: 'P1', environment: 'Default' });
jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await expect(cmd.setupScope()).rejects.toThrow('process.exit:1');

expect(cmd.log).toHaveBeenCalledWith('Organization UID not found!', 'error');
expect(cliux.inquire).not.toHaveBeenCalled();
expect(exitMock).toHaveBeenCalledWith(1);
});

it('fails without prompting when not in a terminal and --project does not match a project', async () => {
stubStdin(false);
(getOrganizations as jest.Mock).mockResolvedValue([{ uid: 'O1' }]);
const { cmd } = buildProbe({ org: 'O1', project: 'WRONG', environment: 'Default' });
jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await expect(cmd.setupScope()).rejects.toThrow('process.exit:1');

expect(cmd.log).toHaveBeenCalledWith('Project not found!', 'error');
expect(cliux.inquire).not.toHaveBeenCalled();
});

it('fails before loading the config when not in a terminal and --environment is missing', async () => {
stubStdin(false);
const { cmd } = buildProbe({ org: 'O1', project: 'P1' });
const getConfig = jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await expect(cmd.setupScope()).rejects.toThrow('process.exit:1');

expect(cmd.log).toHaveBeenCalledWith(expect.stringContaining('--org, --project and --environment are required'), 'error');
expect(getConfig).not.toHaveBeenCalled();
expect(cliux.inquire).not.toHaveBeenCalled();
});

it('fails without prompting when not in a terminal and no project is stored or given', async () => {
stubStdin(false);
const { cmd } = buildProbe({ environment: 'Default' });
jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await expect(cmd.setupScope()).rejects.toThrow('process.exit:1');

expect(cmd.log).toHaveBeenCalledWith(expect.stringContaining('--org, --project and --environment are required'), 'error');
expect(cliux.inquire).not.toHaveBeenCalled();
});

it('loads the config non-interactively when not in a terminal', async () => {
stubStdin(false);
const { cmd } = buildProbe({ environment: 'Default' }, { uid: 'P1' });
const getConfig = jest.spyOn(cmd, 'getConfig').mockResolvedValue(undefined);

await cmd.setupScope();

expect(getConfig).toHaveBeenCalledWith({ interactive: false });
});

it('fails without prompting when a branch must be chosen and the config is loaded non-interactively', async () => {
const config = writeConfig({ main: { uid: 'P1' }, develop: { uid: 'P1' } });
const { cmd } = buildProbe({}, {}, { config });

await expect(cmd.getConfig({ interactive: false })).rejects.toThrow('process.exit:1');

expect(cmd.log).toHaveBeenCalledWith('Multiple branches are configured; pass --branch to choose one.', 'error');
expect(cliux.inquire).not.toHaveBeenCalled();
});

it('uses the branch given with --branch without prompting when the config is loaded non-interactively', async () => {
const config = writeConfig({ main: { uid: 'P1' }, develop: { uid: 'P2' } });
const { cmd } = buildProbe({ branch: 'develop' }, {}, { config, providerMapper: {} });

await cmd.getConfig({ interactive: false });

expect(cmd.sharedConfig.currentConfig.uid).toBe('P2');
expect(cliux.inquire).not.toHaveBeenCalled();
});

it('still prompts for the branch by default', async () => {
const config = writeConfig({ main: { uid: 'P1' }, develop: { uid: 'P2' } });
(cliux.inquire as jest.Mock).mockResolvedValueOnce('develop');
const { cmd } = buildProbe({}, {}, { config, providerMapper: {} });

await cmd.getConfig();

expect(cmd.sharedConfig.currentConfig.uid).toBe('P2');
expect((cliux.inquire as jest.Mock).mock.calls[0][0]).toEqual(expect.objectContaining({ name: 'branch' }));
});

it('fails without prompting when not in a terminal and no environment is given to resolveEnvironment', async () => {
stubStdin(false);
const { cmd, query } = buildProbe({});
query.mockResolvedValue({ data: { Environments: { edges: [] } } });

await expect(cmd.resolveEnvironment()).rejects.toThrow('process.exit:1');

expect(cliux.inquire).not.toHaveBeenCalled();
});

it('shows read-context wording when the environments query fails with 404', async () => {
stubStdin(true);
const { cmd, query } = buildProbe({ environment: 'Default' });
query.mockRejectedValue({ message: 'x', graphQLErrors: [{ message: 'x', extensions: { exception: { status: 404 } } }] });

await expect(cmd.resolveEnvironment()).rejects.toThrow('process.exit:1');

expect(cmd.log).toHaveBeenCalledWith('The project or environment was not found.', 'error');
});

it.each([
['unexpected argument', new UnexpectedArgsError('Unexpected argument: SECRETVALUE')],
['short flag glued to a value', new NonExistentFlagsError('Nonexistent flag: -vSECRETVALUE')],
])('replaces the message of a parse error with a generic one for a %s', async (_label, error) => {
const value = randomUUID();
error.message = error.message.replace('SECRETVALUE', value);
error.stack = `${error.message}\n at parse`;
const { cmd } = buildProbe();

await expect(cmd.catch(error)).rejects.toThrow(/Invalid arguments/);

expect(error.message).not.toContain(value);
expect(error.stack).not.toContain(value);
});

it('keeps the message of a missing required flag error', async () => {
const error = new FailedFlagValidationError('Missing required flag key');
const { cmd } = buildProbe();

await expect(cmd.catch(error)).rejects.toThrow('Missing required flag key');
});

it.each([
['list', ListSecrets],
['set', SetSecret],
['unset', UnsetSecret],
])('declares the hidden --branch flag and the shared scope flags on %s', (_name, command) => {
const flags = command.flags as Record<string, any>;

expect(flags.branch.hidden).toBe(true);
expect(Object.keys(flags)).toEqual(expect.arrayContaining(['org', 'project', 'environment', 'branch']));
});
});
Loading
Loading