diff --git a/.talismanrc b/.talismanrc index f29926f..358b42c 100644 --- a/.talismanrc +++ b/.talismanrc @@ -116,7 +116,7 @@ fileignoreconfig: allowed_patterns: - "assertArray\\(response, key, `\\$\\{key\\} response`\\)" - filename: src/environments/environment.inputs.ts - checksum: 3fc2802c79457f7c7e93cd5f32c00a7986dc6f686fe3c346de4b8436a66cc0b9 + checksum: 1d7e451146125afe8f489c980aef06c5124bcdee2b1ea77c03a2c08264651355 ignore_detectors: - filename - filename: src/environments/environment.builder.ts @@ -127,11 +127,11 @@ fileignoreconfig: - filename checksum: 8b7e3207630f19170dd08ca639ebca8af6bc0d70db633b98e66eedde6d2ea641 - filename: src/environments/environment.update.ts - checksum: b1e15e174f98a875f97e0683182638f93966ef4c498135d36df620a28338aacb + checksum: a34957100a694d97a14333c8a2c5dc238d7dd0a09c159f64839dc27f25955216 ignore_detectors: - filename - filename: src/environments/environment.update.test.ts - checksum: 5e90c3dd231ede1b890f7c750c7063412116a2e4be536d2f290d56d28205ceae + checksum: 615f87b080bea3972202d26d338326559f4d930d40cb39b22fe6528c5caabf92 ignore_detectors: - filename - filename: src/environments/environment.create.ts @@ -145,11 +145,11 @@ fileignoreconfig: ignore_detectors: - filename - filename: src/environments/environment.update.prompt.ts - checksum: 5f2da5ae044eda92f9e555c997d23f065b5454cda8a340c12595597795ecfbb9 + checksum: 60fa6750226d15fc5d70e8e55c6e2edc17558a55fbfe0b6d8bf653f924639ebe ignore_detectors: - filename - filename: src/environments/environment.update.prompt.test.ts - checksum: 6653e245baac00cef348acfc0aa2f32d03a7ff63ca3c320ee56a0c6250775004 + checksum: eeebb3e7a86c41056d7405b8666a42bc2883af177126739779404692403f0de6 ignore_detectors: - filename - filename: src/environments/environment.presenter.ts @@ -311,7 +311,7 @@ fileignoreconfig: - filename: test/credential-guard.setup.ts checksum: 519ccbeb0552fdb1d5f27308c56477c0258ee6cc0adec8f618e8e5bc047cbf6d - filename: src/environments/types.ts - checksum: 2825d0e70757022e518465b134878b8cc8f9eccaf4e9ad088d73a31b9a35a826 + checksum: d40a622cfd8f4425d017e12180b55d72159747a2663b67bb690ade6604d1bbe5 - filename: src/commands/launch/env/get.test.ts checksum: 6e739ef12bc0d887e652e23ee54d9fac30dd6a3505cf464cdaefc0e696cf3e51 - filename: test/integration/environments-delete.test.ts @@ -325,7 +325,7 @@ fileignoreconfig: - filename: src/core/prompt.test.ts checksum: 7be5497acf4cee870667751d44aa230e309784df76dc9e95d5ec2c4e6e6a57e0 - filename: test/integration/environments-update.test.ts - checksum: 249f27ad679b68f40eac3af90c616229838bceffad57ba508dd298ab053fa51a + checksum: 511fbfaac6e4ac978217da2d1ee99b84cd6b543cbacaa74e977c9ff5652d024b - filename: src/commands/launch/env/update.ts checksum: 06add97108d878eaf415e32160439b8963683e63a0e37ce77a56f66b88383c7a - filename: src/commands/launch/env/update.test.ts diff --git a/src/environments/environment.inputs.ts b/src/environments/environment.inputs.ts index 5c48246..1903ad3 100644 --- a/src/environments/environment.inputs.ts +++ b/src/environments/environment.inputs.ts @@ -36,6 +36,22 @@ export const TOGGLE_VALUES = ['enable', 'disable'] as const; export type ToggleValue = (typeof TOGGLE_VALUES)[number]; +export function toggleOf(value: boolean | undefined): ToggleValue | undefined { + if (value === undefined) { + return undefined; + } + + return value ? 'enable' : 'disable'; +} + +export function responseModeOf(streaming: boolean | undefined): ResponseMode | undefined { + if (streaming === undefined) { + return undefined; + } + + return streaming ? 'streaming' : 'buffered'; +} + export function frameworkPresetOf(value: string): FrameworkPreset { return FRAMEWORK_PRESET_BY_LABEL[oneOf('framework', value, FRAMEWORK_CHOICES).toLowerCase()]; } diff --git a/src/environments/environment.update.prompt.test.ts b/src/environments/environment.update.prompt.test.ts index 311488f..d03805e 100644 --- a/src/environments/environment.update.prompt.test.ts +++ b/src/environments/environment.update.prompt.test.ts @@ -168,6 +168,22 @@ describe('promptForEnvironmentUpdate', () => { expect(asked[1].default).toBe('buffered'); }); + it.each([ + [true, 'streaming', {}], + [true, 'buffered', { resMode: 'buffered' }], + [false, 'buffered', {}], + ])( + 'defaults the response mode to the current one when the API reports it (streaming %p) and drops an unchanged %s', + async (isStreamingEnabled, answer, expected) => { + const { services, asked } = servicesAnswering({ [SETTINGS_QUESTION]: ['resMode'], 'Response mode': answer }); + + await expect( + promptForEnvironmentUpdate(services, githubContext({ ...CURRENT, isStreamingEnabled })), + ).resolves.toEqual(expected); + expect(asked[1].default).toBe(isStreamingEnabled ? 'streaming' : 'buffered'); + }, + ); + it('skips the server command, saying why, when the framework it would run under takes none', async () => { const { services, asked, lines } = servicesAnswering({ [SETTINGS_QUESTION]: ['serverCmd'] }); diff --git a/src/environments/environment.update.prompt.ts b/src/environments/environment.update.prompt.ts index 56aabaf..d7130c0 100644 --- a/src/environments/environment.update.prompt.ts +++ b/src/environments/environment.update.prompt.ts @@ -2,13 +2,14 @@ import { askChoices, askOption, askOptionalText, askText } from '../core/prompt' import type { ServiceContext } from '../core/service-context'; import { askBranch } from '../git/git.prompt'; import { frameworkLabelOf } from './environment.builder'; -import type { ToggleValue } from './environment.inputs'; import { ENVIRONMENT_DESCRIPTION_MAX_LENGTH, ENVIRONMENT_NAME_MAX_LENGTH, RESPONSE_MODES, TOGGLE_VALUES, frameworkPresetOf, + responseModeOf, + toggleOf, } from './environment.inputs'; import type { ProjectRepository } from './environment.rules'; import { gitScopeOf } from './environment.rules'; @@ -60,14 +61,6 @@ const SETTINGS: { setting: Setting; label: string; repositoryOnly?: boolean }[] { setting: 'passwordProtection', label: 'Password protection' }, ]; -function toggleOf(value: boolean | undefined): ToggleValue | undefined { - if (value === undefined) { - return undefined; - } - - return value ? 'enable' : 'disable'; -} - function changed(answer: T | undefined, current: T | undefined): T | undefined { return answer === current ? undefined : answer; } @@ -128,7 +121,7 @@ class SettingAsker { case 'outputDir': return this.text(askText(ux, 'Output directory', current.outputDirectory), current.outputDirectory); case 'resMode': - return askOption(ux, 'Response mode', RESPONSE_MODES.map((value) => ({ name: value, value })), 'buffered'); + return this.responseMode(); case 'autoDeploy': return this.toggle('Auto deploy', current.autoDeployOnPush); case 'csAuth': @@ -144,6 +137,18 @@ class SettingAsker { return changed(await answer, current); } + private async responseMode(): Promise { + const current = responseModeOf(this.context.current.isStreamingEnabled); + const answer = await askOption( + this.services.ux, + 'Response mode', + RESPONSE_MODES.map((value) => ({ name: value, value })), + current ?? 'buffered', + ); + + return changed(answer, current); + } + private async framework(): Promise { const current = this.context.current.frameworkPreset; const label = await askOption( diff --git a/src/environments/environment.update.test.ts b/src/environments/environment.update.test.ts index 435eb8e..f50b7e4 100644 --- a/src/environments/environment.update.test.ts +++ b/src/environments/environment.update.test.ts @@ -21,6 +21,7 @@ interface Harness { fails?: 'project' | 'environment' | 'update'; passwordProtected?: boolean; piped?: string; + current?: Record; } function updaterUnderTest(harness: Harness = {}) { @@ -63,6 +64,7 @@ function updaterUnderTest(harness: Harness = {}) { uid: 'env1', frameworkPreset: 'frameworkPreset' in harness ? harness.frameworkPreset : 'NEXTJS', passwordProtection: { isEnabled: harness.passwordProtected ?? false }, + ...harness.current, }; }, update: async (params: unknown) => { @@ -99,7 +101,7 @@ function request(fields: Partial): EnvironmentUpdateRe describe('EnvironmentUpdater', () => { it('maps every supplied flag onto its body field and sends one PUT', async () => { - const { updater, sent, lines } = updaterUnderTest(); + const { updater, sent, lines } = updaterUnderTest({ frameworkPreset: 'GATSBY' }); await expect( updater.update( @@ -185,6 +187,81 @@ describe('EnvironmentUpdater', () => { expect(sent).toEqual([{ ...SCOPE, update: { name: 'renamed' } }]); }); + it.each([ + [{ resMode: 'streaming' as const }, { isStreamingEnabled: true }], + [{ resMode: 'buffered' as const }, { isStreamingEnabled: false }], + [{ csAuth: 'disable' as const }, { isContentstackAuthenticationEnabled: false }], + [{ autoDeploy: 'enable' as const }, { autoDeployOnPush: true }], + [{ cachePriming: 'disable' as const }, { isCachePrimingEnabled: false }], + [{ passwordProtection: 'disable' as const }, {}], + [ + { buildCmd: 'npm run build', outputDir: '.next', framework: 'NEXTJS' as const, branch: 'sample', name: 'staging' }, + { buildCommand: 'npm run build', outputDirectory: '.next', gitBranch: 'sample', name: 'staging' }, + ], + [{ description: 'the live site', serverCmd: 'npm start' }, { description: 'the live site', serverCommand: 'npm start' }], + ])( + 'says nothing changed, asks nothing and sends nothing when %p matches the current settings', + async (fields, current) => { + const { updater, calls, lines, questions } = updaterUnderTest({ current }); + + await expect(updater.update(request(fields))).resolves.toBe('unchanged'); + + expect(calls).not.toContain('update'); + expect(questions).toEqual([]); + expect(lines).toEqual(['Environment not updated. No changes were entered.']); + }, + ); + + it('sends only the flags whose values differ from the current settings', async () => { + const { updater, sent } = updaterUnderTest({ + current: { name: 'staging', isStreamingEnabled: true, isContentstackAuthenticationEnabled: false }, + }); + + await expect( + updater.update(request({ name: 'staging', resMode: 'streaming', csAuth: 'enable', buildCmd: 'npm run build' })), + ).resolves.toBe('updated'); + + expect(sent).toEqual([ + { ...SCOPE, update: { isContentstackAuthenticationEnabled: true, buildCommand: 'npm run build' } }, + ]); + }); + + it('checks a changed --server-cmd against the current framework when an unchanged --framework is dropped', async () => { + const { updater, sent } = updaterUnderTest({ frameworkPreset: 'NUXT' }); + + await expect(updater.update(request({ framework: 'NUXT', serverCmd: 'node server' }))).resolves.toBe('updated'); + + expect(sent).toEqual([{ ...SCOPE, update: { serverCommand: 'node server' } }]); + }); + + it('refuses a changed --server-cmd when an unchanged --framework is dropped and that framework takes none', async () => { + const { updater, calls } = updaterUnderTest({ frameworkPreset: 'GATSBY' }); + + await expect(updater.update(request({ framework: 'GATSBY', serverCmd: 'node server' }))).rejects.toThrow( + '--server-cmd is only supported when --framework is one of ANALOG, ANGULAR, NUXT, ASTRO, REMIX, OTHER; ' + + '--framework is GATSBY.', + ); + expect(calls).not.toContain('update'); + }); + + it('sends --res-mode when the environment does not report its current response mode', async () => { + const { updater, sent } = updaterUnderTest(); + + await updater.update(request({ resMode: 'streaming' })); + + expect(sent).toEqual([{ ...SCOPE, update: { isStreamingEnabled: true } }]); + }); + + it('still enables password protection that is already on, so its credentials can be rotated', async () => { + const { updater, sent } = updaterUnderTest({ passwordProtected: true, answers: { Password: NEW_PASSWORD } }); + + await expect(updater.update(request({ passwordProtection: 'enable', username: 'admin2' }))).resolves.toBe('updated'); + + expect(sent).toEqual([ + { ...SCOPE, update: { passwordProtection: { isEnabled: true, username: 'admin2', password: NEW_PASSWORD } } }, + ]); + }); + it('reads the project and the environment before sending the update', async () => { const { updater, calls } = updaterUnderTest({ projectType: 'FILEUPLOAD' }); @@ -257,7 +334,7 @@ describe('EnvironmentUpdater', () => { }); it('asks before disabling password protection and sends only isEnabled false once confirmed', async () => { - const { updater, questions, sent } = updaterUnderTest(); + const { updater, questions, sent } = updaterUnderTest({ passwordProtected: true }); await updater.update(request({ passwordProtection: 'disable' })); @@ -266,7 +343,7 @@ describe('EnvironmentUpdater', () => { }); it('asks both questions, cache priming first, when both are being disabled', async () => { - const { updater, questions } = updaterUnderTest(); + const { updater, questions } = updaterUnderTest({ passwordProtected: true }); await updater.update(request({ cachePriming: 'disable', passwordProtection: 'disable' })); @@ -279,7 +356,7 @@ describe('EnvironmentUpdater', () => { it.each([[[false]], [[true, false]]])( 'says the environment was not updated and sends nothing when an answer is no (%p)', async (confirmations) => { - const { updater, calls, lines } = updaterUnderTest({ confirmations }); + const { updater, calls, lines } = updaterUnderTest({ confirmations, passwordProtected: true }); await expect( updater.update(request({ cachePriming: 'disable', passwordProtection: 'disable' })), diff --git a/src/environments/environment.update.ts b/src/environments/environment.update.ts index 6234d3b..bdf9e7c 100644 --- a/src/environments/environment.update.ts +++ b/src/environments/environment.update.ts @@ -4,7 +4,7 @@ import { readPipedInput } from '../core/piped-input'; import { requireValueOf } from '../core/rules'; import type { ServiceContext } from '../core/service-context'; import type { ResponseMode, ToggleValue } from './environment.inputs'; -import { usernameOf } from './environment.inputs'; +import { responseModeOf, toggleOf, usernameOf } from './environment.inputs'; import { withoutRepositoryFlags } from './environment.rules'; import { disableQuestion, @@ -12,10 +12,11 @@ import { environmentNotUpdatedLine, environmentUpdatedLine, } from './environment.presenter'; +import type { EnvironmentChanges } from './environment.update.prompt'; import { promptForEnvironmentUpdate } from './environment.update.prompt'; import type { FrameworkPreset } from './frameworks'; import { SERVER_COMMAND_FRAMEWORKS } from './frameworks'; -import type { EnvironmentUpdate, PasswordProtectionUpdate } from './types'; +import type { Environment, EnvironmentUpdate, PasswordProtectionUpdate } from './types'; export interface EnvironmentUpdateRequest { org: string; @@ -80,6 +81,37 @@ function hasChanges(request: EnvironmentUpdateRequest): boolean { return UPDATABLE_FLAGS.some(([field]) => request[field] !== undefined); } +// Enabling password protection is never unchanged: enabling it again is how its credentials are rotated. +function currentValuesOf(existing: Environment): EnvironmentChanges { + return { + name: existing.name, + description: existing.description, + branch: existing.gitBranch, + framework: existing.frameworkPreset as FrameworkPreset | undefined, + buildCmd: existing.buildCommand, + serverCmd: existing.serverCommand, + outputDir: existing.outputDirectory, + resMode: responseModeOf(existing.isStreamingEnabled), + autoDeploy: toggleOf(existing.autoDeployOnPush), + csAuth: toggleOf(existing.isContentstackAuthenticationEnabled), + cachePriming: toggleOf(existing.isCachePrimingEnabled), + passwordProtection: existing.passwordProtection?.isEnabled === false ? 'disable' : undefined, + }; +} + +function withoutCurrentValues(request: EnvironmentUpdateRequest, existing: Environment): EnvironmentUpdateRequest { + const current = currentValuesOf(existing); + const kept = { ...request }; + + for (const field of Object.keys(current) as (keyof EnvironmentChanges)[]) { + if (current[field] !== undefined && kept[field] === current[field]) { + delete kept[field]; + } + } + + return kept; +} + function emptyUpdateMessage(): string { const flags = UPDATABLE_FLAGS.map(([, flag]) => `--${flag}`).join(', '); @@ -166,11 +198,9 @@ export class EnvironmentUpdater { })), } : given; - const request = withoutRepositoryFlags( - answered, - current.projectType, - this.services.ux, - this.services.outputIsTTY === true, + const request = withoutCurrentValues( + withoutRepositoryFlags(answered, current.projectType, this.services.ux, this.services.outputIsTTY === true), + existing, ); if (!hasChanges(request)) { diff --git a/src/environments/types.ts b/src/environments/types.ts index c725e78..c20009c 100644 --- a/src/environments/types.ts +++ b/src/environments/types.ts @@ -46,6 +46,7 @@ export interface Environment { serverCommand?: string; domains?: EnvironmentDomain[]; autoDeployOnPush?: boolean; + isStreamingEnabled?: boolean; isContentstackAuthenticationEnabled?: boolean; isCachePrimingEnabled?: boolean; passwordProtection?: EnvironmentPasswordProtection; diff --git a/test/integration/environments-update.test.ts b/test/integration/environments-update.test.ts index 80a2851..7861557 100644 --- a/test/integration/environments-update.test.ts +++ b/test/integration/environments-update.test.ts @@ -41,12 +41,12 @@ function updateArgs(...extra: string[]): string[] { return ['launch:env:update', '--org', ORG_UID, '--project', PROJECT_UID, '--env', ENV_UID, '--data-dir', DATA_DIR, ...extra]; } -function reads(project: unknown = projectFixture) { +function reads(project: unknown = projectFixture, environment: unknown = getFixture) { projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID); return [ nock(LAUNCH_HUB_URL).get(`/manage/projects/${PROJECT_UID}`).reply(200, project as nock.Body), - nock(LAUNCH_HUB_URL).get(ENV_PATH).reply(200, getFixture), + nock(LAUNCH_HUB_URL).get(ENV_PATH).reply(200, environment as nock.Body), ]; } @@ -107,6 +107,29 @@ describe('integration: launch:env:update on the wire', () => { expect(onWire).toEqual([]); }); + it('exits 0 saying nothing changed, and never sends the PUT, when every flag matches the current settings', async () => { + const [project, environment] = reads(); + const put = update([]); + + const { error, stdout } = await runCommand( + updateArgs( + '--name', 'production', + '--branch', 'main', + '--output-dir', './_site', + '--auto-deploy', 'enable', + '--cs-auth', 'enable', + '--cache-priming', 'disable', + '--password-protection', 'disable', + ), + config, + ); + + expect(error).toBeUndefined(); + expect([project.isDone(), environment.isDone(), put.isDone()]).toEqual([true, true, false]); + expect(stdout).toBe('Environment not updated. No changes were entered.\n'); + expect(onWire).toEqual([]); + }); + it('refuses a password value on the command line with exit 2 before any request, without echoing it', async () => { const password = randomBytes(8).toString('hex'); @@ -134,7 +157,7 @@ describe('integration: launch:env:update on the wire', () => { it('exits 2 naming --yes, and never sends the PUT, when disabling cache priming without a terminal', async () => { const sent: unknown[] = []; - reads(); + reads(projectFixture, { environment: { ...getFixture.environment, isCachePrimingEnabled: true } }); const put = update(sent); const { error } = await runCommand(updateArgs('--cache-priming', 'disable'), config);