diff --git a/.talismanrc b/.talismanrc index ce2a0e5..dc5a37c 100644 --- a/.talismanrc +++ b/.talismanrc @@ -116,7 +116,7 @@ fileignoreconfig: allowed_patterns: - "assertArray\\(response, key, `\\$\\{key\\} response`\\)" - filename: src/environments/environment.inputs.ts - checksum: fd3a8f925444e44b0477d7c907d77526d5a4315d627bf29768912b6799a45c80 + checksum: aad346ce288f2f72c7e88c3cea21e9bd6939dfc3c76d1cf997688cd31fcbf460 ignore_detectors: - filename - filename: src/environments/environment.builder.ts @@ -127,11 +127,11 @@ fileignoreconfig: - filename checksum: 8b7e3207630f19170dd08ca639ebca8af6bc0d70db633b98e66eedde6d2ea641 - filename: src/environments/environment.update.ts - checksum: 85b625c571ef1a4e0c177b78fe5538f6c9506c4b692c6212d9faa63681d77ffe + checksum: 3c667fee5d8c93de351ab117527acd9170dcb0444228022275fe12849fd70ede ignore_detectors: - filename - filename: src/environments/environment.update.test.ts - checksum: 451f42cd81d25088ec05f5ededc9375bfcac7cda6a29db60ccda792768afdd0e + checksum: 7e5aa33a6958e9141a2f7215df87dfc8111b9bba03edc5a84407f42601b7213d ignore_detectors: - filename - filename: src/environments/environment.create.ts @@ -145,19 +145,19 @@ fileignoreconfig: ignore_detectors: - filename - filename: src/environments/environment.update.prompt.ts - checksum: 992d52bfb924105691c90fbdee53ca66fc0a585bb3273e7bcb23974ec2ef4c5c + checksum: 0c93fdf5d542a9ef2e1655a4591d5cea8f0fd5e404d204a999c4d5b6a292e895 ignore_detectors: - filename - filename: src/environments/environment.update.prompt.test.ts - checksum: 2be66b5b7a394e0f2440163ee94c46fdd3884e594673b03de9d8c2eef0ca1ed0 + checksum: 6130ccd6446fe9dba5736fc53b8ebb8f02dbd3956c68ae2c4aa24e3a22dbe105 ignore_detectors: - filename - filename: src/environments/environment.presenter.ts - checksum: 3808d26ca5eb7f345568b56fe48f5756e14f0cdb15ef68b2ae72e9556bc6bab2 + checksum: 505f5e76e34ab9081cb0d57d6c017799bf0c7d86a08bb77201c6737a1affbaef ignore_detectors: - filename - filename: src/environments/environment.presenter.test.ts - checksum: 3e28f6188a450b47d874453a37e22193d9e5036762d34f55315118ed54a73c0a + checksum: 9120a7bc0ce7e7307be8bc76e5e7133f13c0ed186bcb932de9e9fba364a30c99 ignore_detectors: - filename - filename: src/environments/environment.resolver.ts @@ -311,7 +311,7 @@ fileignoreconfig: - filename: test/credential-guard.setup.ts checksum: 519ccbeb0552fdb1d5f27308c56477c0258ee6cc0adec8f618e8e5bc047cbf6d - filename: src/environments/types.ts - checksum: d5506fb4ea67ef8cac77b43724ad6b0e438503d7198d68db8fb2f6d718e89f00 + checksum: c45a2ed513e295ef56da5a6a014e31cb7de3612fc699a3d3b157e525843e8303 - filename: src/commands/launch/env/get.test.ts checksum: 6b79822734553c7417c0a8774fae221609d008be22834113661c9925f17017b9 - filename: test/integration/environments-delete.test.ts @@ -325,13 +325,13 @@ fileignoreconfig: - filename: src/core/prompt.test.ts checksum: 7be5497acf4cee870667751d44aa230e309784df76dc9e95d5ec2c4e6e6a57e0 - filename: test/integration/environments-update.test.ts - checksum: 249f27ad679b68f40eac3af90c616229838bceffad57ba508dd298ab053fa51a + checksum: 312cbf02b41fd9fbfe2c20d78a92129f370753cc7172f0ecc244be3e3dd8eae7 - filename: src/commands/launch/env/update.ts checksum: 981c3267005bca0453131b532c9b62ca501bc67cfd25511c261e99082677882a - filename: src/commands/launch/env/update.test.ts checksum: 82c76af721bfdfd8eb7cf49494ffbe15d98b988e98bca1015b9d34b42b5226bd - filename: README.md - checksum: 6386fbf38075484d6c0eb32bb40ab246a1c94dff41a107e14713f944b4f1d2b5 + checksum: 3ec134160b8ba10ad28c9fe0dc7f2b264461033a1d62c0d7d466a1c84d347000 allowed_patterns: - "password-protection" - "-p, --password" diff --git a/README.md b/README.md index 8ecd87f..f5a9141 100644 --- a/README.md +++ b/README.md @@ -317,9 +317,9 @@ Create an environment in a Launch project and follow its first deployment ``` USAGE $ csdx launch:env:create [--config ] [-d ] [--org ] [--project ] [--name ] - [--branch ] [--framework ] [--build-cmd ] [--server-cmd ] - [--output-dir ] [--res-mode ] [--auto-deploy ] [--cs-auth ] [--var ...] [--dotenv - ...] [--from-stack] [-a ] + [--branch ] [--framework ] [--build-cmd ] [--server-cmd ] [--output-dir ] + [--res-mode ] [--auto-deploy ] [--cs-auth ] [--var ...] [--dotenv ...] + [--from-stack] [-a ] FLAGS -a, --alias= Alias of a delivery token saved with csdx auth:tokens:add, used with --from-stack without a @@ -439,9 +439,9 @@ Update an environment of a Launch project ``` USAGE $ csdx launch:env:update [--config ] [-d ] [--org ] [--project ] [--env ] [--name - ] [--branch ] [--framework ] [--build-cmd ] [--server-cmd - ] [--output-dir ] [--res-mode ] [--auto-deploy ] [--cs-auth ] [--cache-priming - ] [--password-protection ] [-u ] [-p] [--yes] + ] [--branch ] [--framework ] [--build-cmd ] [--server-cmd ] [--output-dir + ] [--res-mode ] [--auto-deploy ] [--cs-auth ] [--cache-priming ] + [--password-protection ] [-u ] [-p] [--yes] FLAGS -d, --data-dir= Current working directory diff --git a/src/environments/environment.inputs.ts b/src/environments/environment.inputs.ts index 562cc59..e67aba9 100644 --- a/src/environments/environment.inputs.ts +++ b/src/environments/environment.inputs.ts @@ -33,6 +33,22 @@ export const TOGGLE_VALUES = ['enable', 'disable'] as const; export type ToggleValue = (typeof TOGGLE_VALUES)[number]; +export function toggleOf(value: boolean | null | undefined): ToggleValue | undefined { + if (value === undefined || value === null) { + return undefined; + } + + return value ? 'enable' : 'disable'; +} + +export function responseModeOf(streaming: boolean | null | undefined): ResponseMode | undefined { + if (streaming === undefined || streaming === null) { + 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.presenter.test.ts b/src/environments/environment.presenter.test.ts index bb107d0..8dc0299 100644 --- a/src/environments/environment.presenter.test.ts +++ b/src/environments/environment.presenter.test.ts @@ -5,6 +5,7 @@ import { ENVIRONMENT_VALUE_COLUMN, environmentColumns, environmentDeletedLine, + environmentAlreadyMatchesLine, environmentDetailRows, environmentNoChangesLine, environmentNotDeletedLine, @@ -94,6 +95,23 @@ describe('environmentDetailRows', () => { ]); }); + it('renders a placeholder, not "disabled", for a toggle or server command the API reports as null', () => { + const rows = environmentDetailRows({ + serverCommand: null, + autoDeployOnPush: null, + isCachePrimingEnabled: null, + isContentstackAuthenticationEnabled: null, + }); + const valueOf = (field: string) => rows.find((row) => row.field === field)?.value; + + expect(['SERVER COMMAND', 'AUTO DEPLOY', 'CACHE PRIMING', 'CONTENTSTACK AUTHENTICATION'].map(valueOf)).toEqual([ + '-', + '-', + '-', + '-', + ]); + }); + it('renders a placeholder for every field an environment arrives without, and a zero variable count', () => { expect(environmentDetailRows({}).map((row) => row.value)).toEqual([ '-', @@ -169,6 +187,23 @@ describe('environment delete wording', () => { }); }); +describe('environmentAlreadyMatchesLine', () => { + it('names one matching flag in the singular, in yellow on a terminal and plain otherwise', () => { + expect(environmentAlreadyMatchesLine(['cs-auth'], true)).toBe( + '\u001b[33mEnvironment not updated: --cs-auth already matches the current settings.\u001b[39m', + ); + expect(environmentAlreadyMatchesLine(['cs-auth'], false)).toBe( + 'Environment not updated: --cs-auth already matches the current settings.', + ); + }); + + it('names several matching flags in the plural, in the order given', () => { + expect(environmentAlreadyMatchesLine(['cs-auth', 'cache-priming'], false)).toBe( + 'Environment not updated: --cs-auth, --cache-priming already match the current settings.', + ); + }); +}); + describe('environmentNoChangesLine', () => { it('says nothing was changed in yellow on a terminal and plain otherwise', () => { expect(environmentNoChangesLine(true)).toBe('\u001b[33mEnvironment not updated. No changes were entered.\u001b[39m'); diff --git a/src/environments/environment.presenter.ts b/src/environments/environment.presenter.ts index 652aa7c..de32a07 100644 --- a/src/environments/environment.presenter.ts +++ b/src/environments/environment.presenter.ts @@ -9,12 +9,12 @@ export interface DetailRow { value: string; } -function text(value: string | undefined): string { - return value === undefined || isAbsent(value) ? '-' : value; +function text(value: string | null | undefined): string { + return value === undefined || value === null || isAbsent(value) ? '-' : value; } -function toggle(value: boolean | undefined): string { - if (value === undefined) { +function toggle(value: boolean | null | undefined): string { + if (value === undefined || value === null) { return '-'; } @@ -124,3 +124,10 @@ export function environmentDeploymentFailureMessage(failure: EnvironmentDeployme export function environmentNoChangesLine(outputIsTTY: boolean): string { return styled('Environment not updated. No changes were entered.', 'yellow', outputIsTTY); } + +export function environmentAlreadyMatchesLine(flags: readonly string[], outputIsTTY: boolean): string { + const named = flags.map((flag) => `--${flag}`).join(', '); + const verb = flags.length === 1 ? 'matches' : 'match'; + + return styled(`Environment not updated: ${named} already ${verb} the current settings.`, 'yellow', outputIsTTY); +} diff --git a/src/environments/environment.update.prompt.test.ts b/src/environments/environment.update.prompt.test.ts index 61c2991..d5b483e 100644 --- a/src/environments/environment.update.prompt.test.ts +++ b/src/environments/environment.update.prompt.test.ts @@ -156,13 +156,39 @@ describe('promptForEnvironmentUpdate', () => { expect(asked[1].default).toBe('NextJs'); }); - it('asks the response mode and always sends it, since the API never reports the current one', async () => { + it('lists streaming first and starts on it when the API does not report the current mode, sending the answer', async () => { const { services, asked } = servicesAnswering({ [SETTINGS_QUESTION]: ['resMode'], 'Response mode': 'buffered' }); await expect(promptForEnvironmentUpdate(services, githubContext())).resolves.toEqual({ resMode: 'buffered' }); - expect(asked[1].default).toBe('buffered'); + expect(asked[1].choices).toEqual([ + { name: 'streaming', value: 'streaming' }, + { name: 'buffered', value: 'buffered' }, + ]); + expect(asked[1].default).toBe('streaming'); + }); + + it('sends the Contentstack Authentication answer even when it matches the current setting', async () => { + const { services } = servicesAnswering({ [SETTINGS_QUESTION]: ['csAuth'], 'Contentstack Authentication': 'disable' }); + + await expect(promptForEnvironmentUpdate(services, githubContext())).resolves.toEqual({ csAuth: 'disable' }); }); + 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 991ec81..6f8642b 100644 --- a/src/environments/environment.update.prompt.ts +++ b/src/environments/environment.update.prompt.ts @@ -2,12 +2,13 @@ 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_NAME_MAX_LENGTH, RESPONSE_MODES, TOGGLE_VALUES, frameworkPresetOf, + responseModeOf, + toggleOf, } from './environment.inputs'; import type { ProjectRepository } from './environment.rules'; import { gitScopeOf } from './environment.rules'; @@ -17,6 +18,8 @@ import type { Environment } from './types'; export const SETTINGS_QUESTION = 'Select the fields to update:'; +const STREAMING_FIRST = [...RESPONSE_MODES].reverse(); + export type EnvironmentChanges = Partial< Pick< EnvironmentUpdateRequest, @@ -57,14 +60,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; } @@ -120,11 +115,11 @@ 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': - return this.toggle('Contentstack Authentication', current.isContentstackAuthenticationEnabled); + return this.toggle('Contentstack Authentication', current.isContentstackAuthenticationEnabled, true); case 'cachePriming': return this.toggle('Cache priming', current.isCachePrimingEnabled); default: @@ -136,6 +131,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', + STREAMING_FIRST.map((value) => ({ name: value, value })), + current ?? 'streaming', + ); + + return changed(answer, current); + } + private async framework(): Promise { const current = this.context.current.frameworkPreset; const label = await askOption( @@ -161,7 +168,9 @@ class SettingAsker { return undefined; } - return this.text(askOptionalText(this.services.ux, 'Server command', current.serverCommand), current.serverCommand); + const serverCommand = current.serverCommand ?? undefined; + + return this.text(askOptionalText(this.services.ux, 'Server command', serverCommand), serverCommand); } private async passwordProtection(current: boolean | undefined): Promise { @@ -170,7 +179,11 @@ class SettingAsker { return answer ?? (current === true ? 'enable' : undefined); } - private async toggle(message: string, current: boolean | undefined): Promise { + private async toggle( + message: string, + current: boolean | null | undefined, + sendUnchanged = false, + ): Promise { const state = toggleOf(current); const answer = await askOption( this.services.ux, @@ -179,6 +192,6 @@ class SettingAsker { state, ); - return changed(answer, state); + return sendUnchanged ? answer : changed(answer, state); } } diff --git a/src/environments/environment.update.test.ts b/src/environments/environment.update.test.ts index 7b42300..5143f5e 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,14 +101,14 @@ 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( request({ name: 'renamed', branch: 'release', - framework: 'NEXTJS', + framework: 'NUXT', buildCmd: 'npm run build', serverCmd: 'npm start', outputDir: './.next', @@ -124,7 +126,7 @@ describe('EnvironmentUpdater', () => { update: { name: 'renamed', gitBranch: 'release', - frameworkPreset: 'NEXTJS', + frameworkPreset: 'NUXT', buildCommand: 'npm run build', serverCommand: 'npm start', outputDirectory: './.next', @@ -183,6 +185,130 @@ describe('EnvironmentUpdater', () => { expect(sent).toEqual([{ ...SCOPE, update: { name: 'renamed' } }]); }); + it.each([ + [{ resMode: 'streaming' as const }, { isStreamingEnabled: true }, '--res-mode already matches'], + [{ resMode: 'buffered' as const }, { isStreamingEnabled: false }, '--res-mode already matches'], + [{ autoDeploy: 'enable' as const }, { autoDeployOnPush: true }, '--auto-deploy already matches'], + [{ cachePriming: 'disable' as const }, { isCachePrimingEnabled: false }, '--cache-priming already matches'], + [{ passwordProtection: 'disable' as const }, {}, '--password-protection already matches'], + [ + { buildCmd: 'npm run build', outputDir: '.next', framework: 'NEXTJS' as const, branch: 'sample', name: 'staging' }, + { buildCommand: 'npm run build', outputDirectory: '.next', gitBranch: 'sample', name: 'staging' }, + '--name, --branch, --framework, --build-cmd, --output-dir already match', + ], + [{ serverCmd: 'npm start' }, { serverCommand: 'npm start', frameworkPreset: 'NUXT' }, '--server-cmd already matches'], + ])( + 'names the flags, asks nothing and sends nothing when %p matches the current settings', + async (fields, current, named) => { + 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: ${named} the current settings.`]); + }, + ); + + it.each([ + [{ csAuth: 'enable' as const }, true, { isContentstackAuthenticationEnabled: true }], + [{ csAuth: 'disable' as const }, false, { isContentstackAuthenticationEnabled: false }], + ])('always sends %p, even when it matches, so the server re-applies Contentstack Authentication', async (fields, isEnabled, update) => { + const { updater, sent } = updaterUnderTest({ current: { isContentstackAuthenticationEnabled: isEnabled } }); + + await expect(updater.update(request(fields))).resolves.toBe('updated'); + + expect(sent).toEqual([{ ...SCOPE, update }]); + }); + + it('refuses an unchanged --server-cmd when the current framework takes no server command, sending nothing', async () => { + const { updater, calls } = updaterUnderTest({ current: { frameworkPreset: 'GATSBY', serverCommand: 'npm start' } }); + + await expect(updater.update(request({ serverCmd: 'npm start' }))).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('names only the matching flags when a FileUpload project also drops a repository-only flag', async () => { + const { updater, lines } = updaterUnderTest({ projectType: 'FILEUPLOAD', current: { name: 'staging' } }); + + await expect(updater.update(request({ name: 'staging', branch: 'release' }))).resolves.toBe('unchanged'); + + expect(lines).toEqual([ + 'warn: --branch is not supported for FileUpload projects.', + 'Environment not updated: --name already matches the current settings.', + ]); + }); + + it.each([ + [{ cachePriming: 'disable' as const }, { isCachePrimingEnabled: null }, { isCachePrimingEnabled: false }], + [{ autoDeploy: 'disable' as const }, { autoDeployOnPush: null }, { autoDeployOnPush: false }], + [ + { csAuth: 'disable' as const }, + { isContentstackAuthenticationEnabled: null }, + { isContentstackAuthenticationEnabled: false }, + ], + [{ resMode: 'buffered' as const }, { isStreamingEnabled: null }, { isStreamingEnabled: false }], + ])('sends %p when the API reports the current setting as null, since null is not a known value', async (fields, current, update) => { + const { updater, sent } = updaterUnderTest({ current }); + + await expect(updater.update(request(fields))).resolves.toBe('updated'); + + expect(sent).toEqual([{ ...SCOPE, update }]); + }); + + 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' }); @@ -255,7 +381,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' })); @@ -264,7 +390,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' })); @@ -277,7 +403,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 f225c34..7a35639 100644 --- a/src/environments/environment.update.ts +++ b/src/environments/environment.update.ts @@ -4,18 +4,20 @@ 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, + environmentAlreadyMatchesLine, environmentNoChangesLine, 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; @@ -78,6 +80,40 @@ function hasChanges(request: EnvironmentUpdateRequest): boolean { return UPDATABLE_FLAGS.some(([field]) => request[field] !== undefined); } +function currentValuesOf(existing: Environment): EnvironmentChanges { + return { + name: existing.name, + branch: existing.gitBranch, + framework: existing.frameworkPreset as FrameworkPreset | undefined, + buildCmd: existing.buildCommand, + serverCmd: existing.serverCommand ?? undefined, + outputDir: existing.outputDirectory, + resMode: responseModeOf(existing.isStreamingEnabled), + autoDeploy: toggleOf(existing.autoDeployOnPush), + 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 flagsMatchingCurrent(before: EnvironmentUpdateRequest, after: EnvironmentUpdateRequest): string[] { + return UPDATABLE_FLAGS.filter(([field]) => before[field] !== undefined && after[field] === undefined).map( + ([, flag]) => flag, + ); +} + function emptyUpdateMessage(): string { const flags = UPDATABLE_FLAGS.map(([, flag]) => `--${flag}`).join(', '); @@ -163,22 +199,33 @@ export class EnvironmentUpdater { })), } : given; - const request = withoutRepositoryFlags( + const supported = withoutRepositoryFlags( answered, current.projectType, this.services.ux, this.services.outputIsTTY === true, ); + if (supported.serverCmd !== undefined) { + requireValueOf( + 'server-cmd', + 'framework', + SERVER_COMMAND_FRAMEWORKS, + supported.framework ?? existing.frameworkPreset ?? 'not set', + ); + } + + const request = withoutCurrentValues(supported, existing); if (!hasChanges(request)) { - this.services.ux.print(environmentNoChangesLine(this.services.outputIsTTY === true)); + const matching = asking ? [] : flagsMatchingCurrent(supported, request); + this.services.ux.print( + matching.length > 0 + ? environmentAlreadyMatchesLine(matching, this.services.outputIsTTY === true) + : environmentNoChangesLine(this.services.outputIsTTY === true), + ); return 'unchanged'; } - if (request.serverCmd !== undefined && request.framework === undefined) { - requireValueOf('server-cmd', 'framework', SERVER_COMMAND_FRAMEWORKS, existing.frameworkPreset ?? 'not set'); - } - if (!(await this.confirmDisabling(request))) { this.services.ux.print(environmentNotUpdatedLine(this.services.outputIsTTY === true)); return 'cancelled'; diff --git a/src/environments/types.ts b/src/environments/types.ts index fb432f5..f7a2ae6 100644 --- a/src/environments/types.ts +++ b/src/environments/types.ts @@ -42,11 +42,12 @@ export interface Environment { frameworkPreset?: string; buildCommand?: string; outputDirectory?: string; - serverCommand?: string; + serverCommand?: string | null; domains?: EnvironmentDomain[]; - autoDeployOnPush?: boolean; - isContentstackAuthenticationEnabled?: boolean; - isCachePrimingEnabled?: boolean; + autoDeployOnPush?: boolean | null; + isStreamingEnabled?: boolean | null; + isContentstackAuthenticationEnabled?: boolean | null; + isCachePrimingEnabled?: boolean | null; passwordProtection?: EnvironmentPasswordProtection; environmentVariables?: EnvironmentVariable[]; organizationUid?: string; diff --git a/test/integration/environments-update.test.ts b/test/integration/environments-update.test.ts index 80a2851..4b732b8 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,31 @@ 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', + '--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: --name, --branch, --output-dir, --auto-deploy, --cache-priming, ' + + '--password-protection already match the current settings.\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 +159,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);