diff --git a/.talismanrc b/.talismanrc index be3f278..f29926f 100644 --- a/.talismanrc +++ b/.talismanrc @@ -2,7 +2,7 @@ fileignoreconfig: - filename: src/logs/logs.inputs.test.ts checksum: 7b4df8790179c7dc4385acd1d380bb91397523bab111593742e2fc53c94da375 - filename: test/integration/logs-get.test.ts - checksum: 89ce4f3864c6316e8075e08fb86fb07d848cbe717f434c3b3e228622b263eed2 + checksum: b608797028bb0191d53630d2ff95d096b8a2b83019fed2aa096754dc5c50b1bb - filename: src/commands/launch/logs/get.test.ts checksum: d94d390de150956c799f64a84adfe0e02b5b21c66ddcc5cf55a1329aa67ec1a7 - filename: src/core/failure.test.ts @@ -236,7 +236,7 @@ fileignoreconfig: - "a project name passed on argv to the project resolver" - "expect\\(Object.keys\\(DEPENDENCIES\\)\\).toEqual\\(\\['project', 'env'\\]\\)" - filename: AGENTS.md - checksum: ecab79e8abbaae85038afe4f9e8e90e310eef5b0c002cee2b014926850be2c56 + checksum: c20a023e033c6222c645e94bf9fba4bdf884aa75d6c52f5c74ab185b8c335b01 allowed_patterns: - "Do not add an exemption to a guard to make a new file pass" - "passes its own error wording to `client.request\\(req, MESSAGES\\)`" @@ -263,15 +263,15 @@ fileignoreconfig: - filename: src/commands/launch/projects/delete.test.ts checksum: d67d8a804d14f9b809153d10b0cf9d5e52b70f9e0b65678ebb1663a7d2da22c1 - filename: test/integration/projects-delete.test.ts - checksum: bb59cbe1f4f7b3ac6aa7944067c1ab1214a7c5d20229e9d6577cdaabec56622e + checksum: 19784ba572daac76e6ef0b004c19cdb9c3f9cb22f738b3ab0e22c694e049026c - filename: src/core/launch-command.ts - checksum: 999468661532665870b81face9086998e543df648175e2417045840dc97cb1dd + checksum: 91ec87522df77d8ed593c95e1a2259d1555acbd1dee95ad8ca4d6c3fa9c61468 - filename: src/core/launch-command.test.ts - checksum: 40c554e420c60e38d738190128588bc43c6f347da2d1e648b65d93419ca9f2c3 + checksum: 44f0639fe66598ba2f3ba0ddc7edd68381f7aa36e3be5323ecbe5d101a1953a2 - filename: src/projects/project.inputs.test.ts checksum: 8242f4d40388f1a7f1d08c11d2571cb45a9294069a8248a5272bc5606807bb60 - filename: test/integration/projects-command-flows.test.ts - checksum: 30858bb3dff8a22406efa4ac82d882d1501797cdda24e09555aecc0bcd8dca0b + checksum: 1731d2350269ae9b6f7c2837db8e14575f94a9a3fa11f8f86c532717378d99ce - filename: src/core/redact.test.ts checksum: ae497ea8c3a4c3f12217d2c4c028a1da3d1324e18362d68c355ba8120902bcb3 - filename: src/commands/launch/projects/list.test.ts @@ -305,7 +305,7 @@ fileignoreconfig: - filename: src/transport/cma-client.test.ts checksum: 85d62ef350b450cb09f1a840db79bdfb212d4f5fd650789d60d722915a892a59 - filename: src/core/search-list.test.ts - checksum: 0c324ecf8de5cc2fc1ccc27223cae555d7db6c8061c4bd7288e0dc7fb28f6b87 + checksum: 4e5db3cd6a213db71c51bf5ac8d6a5547ea9ca137d425c00026453e5c3b543b7 - filename: src/core/catalog.test.ts checksum: 950d5cbb8ebdbe13cf13908b72d5409f7fdf7515c9d93a7c84045efcf4420543 - filename: test/credential-guard.setup.ts @@ -445,9 +445,9 @@ fileignoreconfig: - filename: src/deployments/deployment.create.test.ts checksum: 6545afa21a23b7e5de18ad8ff417f88a184577e7042713cfda90758ccbcd9869 - filename: test/integration/deployments-rollback.test.ts - checksum: 08400c5435c84cd162fefc585f6c32cddfcaa8909d2369341748b421e7f12073 + checksum: 98a9f7001eb5bf01e0e2f46677eeea61ad5d38c595d17ef27d366c93e603f0d5 - filename: test/integration/deployments-cancel.test.ts - checksum: 8972ed5f23e7dee8acf677ae9a26d2d28ef8144d03bc7623c5fd29f096a3aed0 + checksum: 2e14190da534dda23176c44618b5f0cc0ef6f5c563b529658e171e509be10f4e - filename: src/commands/launch/deployments/cancel.test.ts checksum: da8d09de7f03cfe67df75ebc1636b36feb6688cf85984c357fd5304852d126e5 - filename: src/commands/launch/deployments/rollback.test.ts @@ -489,7 +489,7 @@ fileignoreconfig: - filename: package.json checksum: ae6f7fdb23fd9476dd4fca5b84d0f3999b578a73b8187af2f94edbb0a2172b16 - filename: test/integration/secrets-set.test.ts - checksum: f01f5673125c48f537c593b9f8f3a728b6b16b42a3253c01f44558176ef48d89 + checksum: 2527d5d35198cc08e1859ab79941338392b6d4fcbc87506adef6d7b096089963 - filename: src/secrets/secret.rules.test.ts checksum: 29f1c5842b7d7c895ccf4c2611af52f824168e264e228b2493bededfdd7a2e8e - filename: src/commands/launch/secrets/set.ts @@ -507,7 +507,7 @@ fileignoreconfig: - filename: src/secrets/secret.set.test.ts checksum: 80b6b9c56280b6f5cb4be03fffd05b0421ea558997d9295ddde50b773f22b05f - filename: test/integration/secrets-unset.test.ts - checksum: ed2f37b50516817ef70e2dc11ed4d801374ade1f3588fa2320f71cac5033448e + checksum: 431d7601ecb9d09d291bd271164da8da1bdd93329b217186db1de75ae185a2bb - filename: src/secrets/secret.unset.ts checksum: 597d7797c24716f443092fd40d077232ec1d9b2118707ee3aca453bacf38fa86 - filename: src/commands/launch/secrets/unset.ts @@ -520,4 +520,6 @@ fileignoreconfig: checksum: 22a5aa7d95c6a5113a034d2cc9af4f152f8a366f1c271f86cd317ea2046f5b1d - filename: src/core/password-argv.test.ts checksum: df87a19d09ff07b95d8118dd7e6bae5a13a86f0ecb8dce97e6022481d1e11256 +- filename: test/integration/prompt-ctrl-c-on-a-terminal.test.ts + checksum: f712885cded1bef4d64a8e1d7532f95b6696e7d7522dfeba55edf211d07fb837 version: "1.0" diff --git a/AGENTS.md b/AGENTS.md index 8ce30da..70d8c0a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,12 +55,12 @@ file and line that broke its rule, and each was proven red by reintroducing its | Guard | Rule it enforces | Found by | |---|---|---| -| `test/guards/prompt-types.test.ts` | Every prompt call in `src` names a literal `type`, and every such type is registered with the real inquirer `cliux.inquire` uses once `LaunchCommand.init` has run. inquirer silently turns an unregistered type into a plain text box. | D1: `search-list` used, never registered | +| `test/guards/prompt-types.test.ts` | Every prompt call in `src` names a literal `type`, and every such type is registered with the real inquirer `terminalUx` prompts through once `LaunchCommand.init` has run. inquirer silently turns an unregistered type into a plain text box. | D1: `search-list` used, never registered | | `test/integration/transport-content-type.test.ts` | For every method in `HTTP_METHODS`, a bodyless request carries no content type and a request with a body carries `application/json`, asserted on the wire. `withoutDefaultContentType` suppresses the utility client's default, so a bodyless POST, PUT or PATCH (for example `deployments:cancel`) no longer goes out as `application/x-www-form-urlencoded`. Only `utility-http-client.ts` builds an `HttpClient` and only `rest-client.ts` sets the JSON type. | D5: every DELETE sent `Content-Type: application/json` | | `test/guards/tty-streams.test.ts` | `stdin.isTTY`, and the `isTTY` it becomes on the service context, are read only to decide whether the CLI may prompt (a read next to a prompt or a refusal to prompt) or on the plumbing lines that carry it there. Anything deciding what to draw reads `outputIsTTY` / `process.stdout.isTTY`. | D6: heartbeat drawn into a redirected file | | `test/integration/deployments-request-bodies.test.ts` | A deployments mutation puts on the wire only the fields the management service DTO declares - `{commitHash?, uploadUid?}` for a create, `{deployment, reason?}` for a rollback - and never `environment`, which is the URL path. The service validates with `whitelist` and `forbidNonWhitelisted`, so any other key is a bare 400. | Live harness: `deployments:create` and `:rollback` sent `{environment, ...}` and failed with `Bad request` | | `test/integration/retired-commands.test.ts` (named commands) | Every `launch:…` command named anywhere in `src` - a retirement message, a failure hint, an example - is either a registered command or on `PLANNED_COMMANDS` with the ticket that builds it, and a command drops off that list once it ships. | Review: retirement messages and hints pointed at commands the beta does not have | -| `test/guards/prompt-funnel.test.ts` | Every prompt goes through `LaunchCommand`'s `ux`, built once as `cancelOnInterrupt(cliux)`, so Ctrl-C at any prompt exits 3. The wrapper stays attached to `SIGINT` until the signal has reached every listener (it detaches in a microtask): inquirer's `cli-cursor` loads `signal-exit`, which re-raises `SIGINT` - exit 130 - when it finds itself the only listener, so a `once` listener made every list and checkbox prompt exit 130 (`src/core/interruptible-ux.test.ts` pins it). No source calls `cliux.inquire` / `prompt` / `confirm` under any name, hands `cliux` on as a value, or imports a prompt library; `search-list.ts` may register a type but never prompt. | D2: Ctrl-C exited 130 | +| `test/guards/prompt-funnel.test.ts` | Every prompt goes through `LaunchCommand`'s `ux`, built once as `cancelOnInterrupt(terminalUx)`, so Ctrl-C at any prompt exits 3. `terminalUx` (`src/core/terminal-ux.ts`) asks cli-utilities' own inquirer instance (`promptLibrary()`) directly, because `cliux.inquire` catches inquirer 12's `ExitPromptError` and calls `process.exit(130)` itself. In raw mode Ctrl-C reaches inquirer as typed input, not as a process `SIGINT`: an `@inquirer/core` prompt (input, list, checkbox, confirm) rejects with `ExitPromptError`, which the wrapper turns into `CancelledError`; the legacy `search-list` rejects with `AbortPromptError` and then raises a real `SIGINT`, so the wrapper cancels on the rejection at once and stays attached only to absorb that signal. The wrapper stays attached to `SIGINT` until the signal has reached every listener (it detaches in a microtask): inquirer's `cli-cursor` loads `signal-exit`, which re-raises `SIGINT` - exit 130 - when it finds itself the only listener, so a `once` listener made every list and checkbox prompt exit 130 (`src/core/interruptible-ux.test.ts` pins it). No source calls `cliux.inquire` / `prompt` / `confirm` under any name, hands `cliux` on as a value, imports a prompt library, uses `promptLibrary` outside `search-list.ts` and `terminal-ux.ts`, or uses `terminalUx` anywhere but that one funnel line; `search-list.ts` may register a type but never prompt. `test/integration/prompt-ctrl-c-on-a-terminal.test.ts` types a real Ctrl-C at each kind of prompt on a pseudo-terminal, because a simulated `SIGINT` is what let CL-8790 through. `test/support/pty/press-ctrl-c.py ` (Python's stdlib `pty`, so `npm test` needs `python3`) runs the command on a pty, types Ctrl-C once `` is on screen and prints the exit code: negative for a signal death (-2 is SIGINT), 124 if `` never appeared, 125 if the command was still running 30 s later (it is killed). `ctrl-c-prompt.fixture.ts` calls `process.exit` with the error's exit code, as oclif's `Errors.handle` does for the CLI. | D2: Ctrl-C exited 130; CL-8790: it did again after cli-utilities 2 | A new prompt, request, render path or command is covered by these guards without being listed in them. Do not add an exemption to a guard to make a new file pass: if a guard is wrong about a file, @@ -110,8 +110,10 @@ stdin is not a terminal and `LaunchCommand` reads it to decide whether prompting descriptor, not by assignment: once another suite in the same process has turned stdin into a real stream, `process.stdin.isTTY = true` throws, and jest orders test files by their previous runtime, so that shows up as an intermittent failure rather than a stable one. `answerPrompts({ message: answer })` -installs the `cliux.inquire` spy, records every prompt's message and payload in order, and throws on a -prompt it was not given an answer for. `projects-create.test.ts` uses the three together to drive all +installs the `terminalUx.inquire` spy, records every prompt's message and payload in order, and throws on a +prompt it was not given an answer for; an answer of `CTRL_C` rejects the way a real Ctrl-C does: `ExitPromptError`, or for a +`search-list` prompt `AbortPromptError` followed by a `SIGINT`. `stubPrompts(handler)` installs the same spy with your own handler, and `test/no-terminal.setup.ts` +uses it to fail any test that reaches a prompt it did not stub. `projects-create.test.ts` uses the three together to drive all eleven GitHub prompts through `launch:projects:create`, asserting their order, their offered defaults and the submitted body, and to prove that a flag-supplied value is never asked for. diff --git a/src/core/interruptible-ux.test.ts b/src/core/interruptible-ux.test.ts index c1341bf..8a587a1 100644 --- a/src/core/interruptible-ux.test.ts +++ b/src/core/interruptible-ux.test.ts @@ -88,6 +88,41 @@ describe('cancelOnInterrupt', () => { expect(signals.listenerCount('SIGINT')).toBe(1); }); + it('rejects with CancelledError when the prompt itself reports Ctrl-C, as inquirer 12 does in raw mode, then stops listening', async () => { + const signals = new EventEmitter(); + const inner = pendingUx(); + const loop = recordingHold(); + const ctrlC = Object.assign(new Error('User force closed the prompt with SIGINT'), { name: 'ExitPromptError' }); + + const answer = cancelOnInterrupt(inner.ux, { signals, hold: loop.hold }).inquire(QUESTION); + inner.settle({ error: ctrlC }); + + await expect(answer).rejects.toBeInstanceOf(CancelledError); + expect(signals.listenerCount('SIGINT')).toBe(0); + expect(loop.events).toEqual(['held', 'released']); + }); + + it('cancels as soon as a search-list prompt is aborted, and stays attached only to absorb the SIGINT inquirer raises next', async () => { + const signals = new EventEmitter(); + const inner = pendingUx(); + const loop = recordingHold(); + const aborted = Object.assign(new Error('Prompt was aborted'), { name: 'AbortPromptError' }); + + const answer = cancelOnInterrupt(inner.ux, { signals, hold: loop.hold }).inquire(QUESTION); + inner.settle({ error: aborted }); + const error = await answer.catch((e: unknown) => e); + const listeningBeforeSignal = signals.listenerCount('SIGINT'); + const loopBeforeSignal = [...loop.events]; + signals.emit('SIGINT'); + await new Promise((done) => setImmediate(done)); + + expect(error).toBeInstanceOf(CancelledError); + expect(listeningBeforeSignal).toBe(1); + expect(loopBeforeSignal).toEqual(['held', 'released']); + expect(signals.listenerCount('SIGINT')).toBe(0); + expect(loop.events).toEqual(['held', 'released']); + }); + it('propagates the prompt failure unchanged rather than calling it a cancellation, then stops listening', async () => { const signals = new EventEmitter(); const inner = pendingUx(); diff --git a/src/core/interruptible-ux.ts b/src/core/interruptible-ux.ts index bd50bc0..5e54064 100644 --- a/src/core/interruptible-ux.ts +++ b/src/core/interruptible-ux.ts @@ -34,6 +34,14 @@ export function onInterrupt(listener: () => void, signals: InterruptSource = pro return release; } +function isPromptExit(error: unknown): boolean { + return error instanceof Error && error.name === 'ExitPromptError'; +} + +function isPromptAbort(error: unknown): boolean { + return error instanceof Error && error.name === 'AbortPromptError'; +} + export interface InterruptOptions { signals?: InterruptSource; hold?: () => Release; @@ -46,9 +54,13 @@ export function cancelOnInterrupt(ux: UxLike, options: InterruptOptions = {}): U print: (message) => ux.print(message), inquire: (payload: unknown) => new Promise((resolve, reject) => { - const releaseLoop = hold(); + let releaseLoop: Release | undefined = hold(); + const freeLoop = (): void => { + releaseLoop?.(); + releaseLoop = undefined; + }; const release = (): void => { - releaseLoop(); + freeLoop(); signals.removeListener('SIGINT', cancel); }; const cancel = (): void => { @@ -57,8 +69,14 @@ export function cancelOnInterrupt(ux: UxLike, options: InterruptOptions = {}): U }; const fail = (error: unknown): void => { + if (isPromptAbort(error)) { + freeLoop(); + reject(new CancelledError()); + return; + } + release(); - reject(error); + reject(isPromptExit(error) ? new CancelledError() : error); }; signals.on('SIGINT', cancel); diff --git a/src/core/launch-command.test.ts b/src/core/launch-command.test.ts index 9db1980..426b09b 100644 --- a/src/core/launch-command.test.ts +++ b/src/core/launch-command.test.ts @@ -338,7 +338,7 @@ describe('LaunchCommand.init', () => { restoreTTY(); }); - it('registers the searchable picker on the inquirer cliux prompts with before anything can prompt', async () => { + it('registers the searchable picker on the inquirer terminalUx prompts through before anything can prompt', async () => { const prompts = promptLibrary().prompt.prompts; delete prompts['search-list']; const instance = probe(); diff --git a/src/core/launch-command.ts b/src/core/launch-command.ts index 46b518f..1ced48a 100644 --- a/src/core/launch-command.ts +++ b/src/core/launch-command.ts @@ -1,7 +1,7 @@ import { resolve as resolvePath } from 'node:path'; import { Command } from '@contentstack/cli-command'; -import { cliux, configHandler, isAuthenticated } from '@contentstack/cli-utilities'; +import { configHandler, isAuthenticated } from '@contentstack/cli-utilities'; import { EXIT_RUNTIME, PROJECT_CONFIG_FILE, STDIN_MAX_LISTENERS } from './constants'; import type { ProjectConfig } from './project-config'; @@ -18,6 +18,7 @@ import { cancelOnInterrupt } from './interruptible-ux'; import { refusePasswordOnArgv } from './password-argv'; import type { UxLike } from './prompt'; import { registerSearchList } from './search-list'; +import { terminalUx } from './terminal-ux'; import type { FailureOutput } from './failure'; import { failWith, failureOutputOf, reportFailure } from './failure'; import type { ServiceContext } from './service-context'; @@ -109,7 +110,7 @@ export abstract class LaunchCommand extends Com protected resolved!: Resolved; protected dataDir!: string; protected configPath!: string; - protected ux: UxLike = cancelOnInterrupt(cliux); + protected ux: UxLike = cancelOnInterrupt(terminalUx); protected get launchRegion(): RegionLike | undefined { return configHandler.get('region') as RegionLike | undefined; diff --git a/src/core/search-list.test.ts b/src/core/search-list.test.ts index daf8a7f..12ab25d 100644 --- a/src/core/search-list.test.ts +++ b/src/core/search-list.test.ts @@ -327,7 +327,7 @@ describe('promptLibrary', () => { }); describe('registerSearchList', () => { - it('registers the launch search list under search-list on the inquirer that cliux prompts with, and nothing else', () => { + it('registers the launch search list under search-list on the inquirer that terminalUx prompts through, and nothing else', () => { const registered: [string, unknown][] = []; const loaded: string[] = []; const fakeLoad = (id: string): unknown => { diff --git a/src/core/search-list.ts b/src/core/search-list.ts index b688150..3fda1fb 100644 --- a/src/core/search-list.ts +++ b/src/core/search-list.ts @@ -26,7 +26,7 @@ export type SearchListClass = new (...params: never[]) => SearchListPrompt; export type ModuleLoader = (id: string) => unknown; export interface PromptRegistry { - prompt: { prompts: Record }; + prompt: ((question: unknown) => Promise>) & { prompts: Record }; registerPrompt(name: string, prompt: unknown): void; restoreDefaultPrompts(): void; } @@ -144,7 +144,7 @@ export function utilitiesLoader(): ModuleLoader { return createRequire(require.resolve('@contentstack/cli-utilities')); } -// cli-utilities 2 ships inquirer 12, which exposes the prompt registry cliux prompts with as its default export. +// cli-utilities 2 ships inquirer 12, whose default export is the prompt registry every Launch prompt goes through. export function promptLibrary(load: ModuleLoader = utilitiesLoader()): PromptRegistry { return (load('inquirer') as { default: PromptRegistry }).default; } diff --git a/src/core/terminal-ux.test.ts b/src/core/terminal-ux.test.ts new file mode 100644 index 00000000..59440d6 --- /dev/null +++ b/src/core/terminal-ux.test.ts @@ -0,0 +1,50 @@ +import { promptLibrary } from './search-list'; +import { libraryUx, terminalUx } from './terminal-ux'; + +const QUESTION = { type: 'list', name: 'value', message: 'Choose an environment', choices: ['Default'] }; + +describe('libraryUx', () => { + it('asks the question through the prompt library and resolves with the answer to the named question', async () => { + const asked: unknown[] = []; + const library = { + prompt: async (question: unknown) => { + asked.push(question); + return { value: 'Default' }; + }, + }; + + const answer = await libraryUx(() => library, noPrinting).inquire(QUESTION); + + expect(answer).toBe('Default'); + expect(asked).toEqual([QUESTION]); + }); + + it('prints through the printer it was given', () => { + const printed: string[] = []; + + libraryUx(unusedLibrary, (message) => printed.push(message)).print('Using the organization Acme.'); + + expect(printed).toEqual(['Using the organization Acme.']); + }); +}); + +describe('terminalUx', () => { + beforeEach(() => jest.mocked(terminalUx.inquire).mockRestore()); + + it('asks through the inquirer cli-utilities ships, the one search-list is registered with', async () => { + const prompt = jest.spyOn(promptLibrary(), 'prompt').mockResolvedValue({ value: 'Default' }); + + const answer = await terminalUx.inquire(QUESTION); + + expect(answer).toBe('Default'); + expect(prompt).toHaveBeenCalledWith(QUESTION); + }); +}); + +function noPrinting(): void { + return undefined; +} + +function unusedLibrary(): never { + throw new Error('printing must not reach the prompt library'); +} diff --git a/src/core/terminal-ux.ts b/src/core/terminal-ux.ts new file mode 100644 index 00000000..796fef3 --- /dev/null +++ b/src/core/terminal-ux.ts @@ -0,0 +1,22 @@ +import { cliux } from '@contentstack/cli-utilities'; + +import type { UxLike } from './prompt'; +import { promptLibrary } from './search-list'; + +export interface Prompter { + prompt(question: unknown): Promise>; +} + +export function libraryUx(library: () => Prompter, print: (message: string) => void): UxLike { + return { + print, + inquire: async (payload: unknown): Promise => { + const { name } = payload as { name: string }; + const answers = await library().prompt(payload); + + return answers[name] as T; + }, + }; +} + +export const terminalUx: UxLike = libraryUx(promptLibrary, (message) => cliux.print(message)); diff --git a/test/guards/prompt-funnel.test.ts b/test/guards/prompt-funnel.test.ts index 8970376..05ff37b 100644 --- a/test/guards/prompt-funnel.test.ts +++ b/test/guards/prompt-funnel.test.ts @@ -1,15 +1,16 @@ -import { cliux } from '@contentstack/cli-utilities'; - import { EXIT_CANCELLED } from '../../src/core/constants'; import { CancelledError } from '../../src/core/errors'; import { LaunchCommand } from '../../src/core/launch-command'; import type { UxLike } from '../../src/core/prompt'; +import { terminalUx } from '../../src/core/terminal-ux'; import type { Occurrence, SourceFile } from '../support/sources'; import { describeOccurrence, occurrences, productionSources } from '../support/sources'; +import { ctrlC } from '../support/terminal'; const FUNNEL_FILE = 'core/launch-command.ts'; -const FUNNEL_CALL = 'cancelOnInterrupt(cliux)'; +const FUNNEL_CALL = 'cancelOnInterrupt(terminalUx)'; const REGISTRATION_FILE = 'core/search-list.ts'; +const TERMINAL_FILE = 'core/terminal-ux.ts'; const PROMPT_LIBRARIES = /['"](inquirer|inquirer-[\w-]+|@inquirer\/[\w-]+|enquirer|prompts|(node:)?readline)['"]/; const PROMPT_METHODS = 'inquire|prompt|confirm'; @@ -22,35 +23,55 @@ class FreshCommand extends LaunchCommand { } } -function cliuxNames(source: SourceFile): string[] { - const imports = [...source.text.matchAll(/import\s*\{([^}]*)\}\s*from\s*'@contentstack\/cli-utilities'/g)]; +function importedAs(source: SourceFile, imported: string, from = "[^']+"): string[] { + const imports = [...source.text.matchAll(new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*'${from}'`, 'g'))]; return imports.flatMap((match) => match[1] .split(',') .map((specifier) => specifier.trim().split(/\s+as\s+/)) - .filter(([imported]) => imported === 'cliux') + .filter(([name]) => name === imported) .map((parts) => parts[parts.length - 1]), ); } +function namesFor(source: SourceFile, imported: string): string[] { + return [...new Set([imported, ...importedAs(source, imported)])]; +} + +function isImport(use: Occurrence): boolean { + return /^import\b/.test(use.text); +} + +function isTheFunnel(use: Occurrence): boolean { + return use.path === FUNNEL_FILE && use.text.includes(FUNNEL_CALL); +} + +function usesOf(source: SourceFile, names: string[]): Occurrence[] { + return occurrences(source, new RegExp(`\\b(${names.join('|')})\\b`)); +} + function detours(source: SourceFile): Occurrence[] { - const direct = cliuxNames(source).flatMap((name) => [ + const direct = importedAs(source, 'cliux', '@contentstack\\/cli-utilities').flatMap((name) => [ ...occurrences(source, new RegExp(`\\b${name}\\s*(\\??\\.)\\s*(${PROMPT_METHODS})\\b`)), - ...occurrences(source, new RegExp(`\\b${name}\\b(?!\\s*\\??\\.)`)).filter( - (use) => - !/^import\b/.test(use.text) && !(source.path === FUNNEL_FILE && use.text.includes(FUNNEL_CALL)), - ), + ...occurrences(source, new RegExp(`\\b${name}\\b(?!\\s*\\??\\.)`)).filter((use) => !isImport(use)), ]); const libraries = source.path === REGISTRATION_FILE ? [] : occurrences(source, PROMPT_LIBRARIES); const registrationPrompts = source.path === REGISTRATION_FILE ? occurrences(source, new RegExp(`\\.(${PROMPT_METHODS})\\s*\\(`)) : []; + const libraryCalls = [REGISTRATION_FILE, TERMINAL_FILE].includes(source.path) + ? [] + : usesOf(source, namesFor(source, 'promptLibrary')).filter((use) => !isImport(use)); + const unwrappedTerminal = + source.path === TERMINAL_FILE + ? [] + : usesOf(source, namesFor(source, 'terminalUx')).filter((use) => !isImport(use) && !isTheFunnel(use)); const wholeModule = [ ...occurrences(source, /import\s*\*\s*as\s+\w+\s+from\s*'@contentstack\/cli-utilities'/), ...occurrences(source, /\brequire\(\s*'@contentstack\/cli-utilities'/), ]; - return [...direct, ...libraries, ...registrationPrompts, ...wholeModule]; + return [...direct, ...libraries, ...registrationPrompts, ...libraryCalls, ...unwrappedTerminal, ...wholeModule]; } function promptDetoursIn(sources: SourceFile[]): string[] { @@ -68,7 +89,7 @@ describe('guard: every prompt goes through the one wrapper that maps Ctrl-C to e expect(promptDetoursIn(productionSources())).toEqual([]); }); - it('builds the command ux from cliux exactly once, through the Ctrl-C wrapper', () => { + it('builds the command ux from terminalUx exactly once, through the Ctrl-C wrapper', () => { const funnels = productionSources().flatMap((source) => occurrences(source, /(? `${use.path} ${use.text}`), ); @@ -77,11 +98,10 @@ describe('guard: every prompt goes through the one wrapper that maps Ctrl-C to e }); it('turns Ctrl-C at any prompt a LaunchCommand issues into CancelledError with exit 3', async () => { - jest.spyOn(cliux, 'inquire').mockImplementation(() => new Promise(() => undefined)); + jest.spyOn(terminalUx, 'inquire').mockRejectedValue(ctrlC()); const ux = (new FreshCommand([], {} as never) as unknown as { ux: UxLike }).ux; const answer = ux.inquire({ type: 'input', name: 'value', message: 'Project name' }); - process.emit('SIGINT'); await expect(answer).rejects.toBeInstanceOf(CancelledError); await expect(answer).rejects.toHaveProperty('exitCode', EXIT_CANCELLED); @@ -103,6 +123,17 @@ describe('guard: every prompt goes through the one wrapper that maps Ctrl-C to e { path: 'logs/logs.prompt.ts', text: 'import * as utilities from \'@contentstack/cli-utilities\';' }, { path: 'core/search-list.ts', text: 'await load(\'inquirer\').prompt([question]);' }, { path: 'core/launch-command.ts', text: 'protected ux: UxLike = cliux;\nimport { cliux } from \'@contentstack/cli-utilities\';' }, + { path: 'cache/purge.prompt.ts', text: 'const answers = await promptLibrary().prompt(question);' }, + { path: 'environments/environment.prompt.ts', text: 'const name = await terminalUx.inquire(question);' }, + { path: 'deployments/deployment.prompt.ts', text: 'const ux = libraryUx(promptLibrary, print);' }, + { + path: 'projects/project.prompt.ts', + text: 'import { terminalUx as tty } from \'../core/terminal-ux\';\nconst name = await tty.inquire(question);', + }, + { + path: 'functions/function.prompt.ts', + text: 'import { promptLibrary as lib } from \'../core/search-list\';\nawait lib().prompt(question);', + }, ]; expect(promptDetoursIn(sources).map((detour) => detour.split(' <-')[0])).toEqual([ @@ -113,6 +144,11 @@ describe('guard: every prompt goes through the one wrapper that maps Ctrl-C to e 'src/logs/logs.prompt.ts:1 import * as utilities from \'@contentstack/cli-utilities\';', 'src/core/search-list.ts:1 await load(\'inquirer\').prompt([question]);', 'src/core/launch-command.ts:1 protected ux: UxLike = cliux;', + 'src/cache/purge.prompt.ts:1 const answers = await promptLibrary().prompt(question);', + 'src/environments/environment.prompt.ts:1 const name = await terminalUx.inquire(question);', + 'src/deployments/deployment.prompt.ts:1 const ux = libraryUx(promptLibrary, print);', + 'src/projects/project.prompt.ts:2 const name = await tty.inquire(question);', + 'src/functions/function.prompt.ts:2 await lib().prompt(question);', ]); }); @@ -126,6 +162,10 @@ describe('guard: every prompt goes through the one wrapper that maps Ctrl-C to e path: 'core/search-list.ts', text: 'const inquirer = load(\'inquirer\');\ninquirer.registerPrompt(\'search-list\', SearchList);', }, + { + path: 'core/terminal-ux.ts', + text: 'export const terminalUx: UxLike = libraryUx(promptLibrary, (message) => cliux.print(message));', + }, ]; expect(promptDetoursIn(sources)).toEqual([]); diff --git a/test/guards/prompt-types.test.ts b/test/guards/prompt-types.test.ts index 2a2c1a0..1f3909e 100644 --- a/test/guards/prompt-types.test.ts +++ b/test/guards/prompt-types.test.ts @@ -82,7 +82,7 @@ describe('guard: every prompt type the CLI asks for is registered with the real .map( (call) => `${call.site} asks for a '${call.type}' prompt, which LaunchCommand.init never registers ` + - 'with the inquirer cliux.inquire uses - register it there or the prompt degrades to a text box', + 'with the inquirer terminalUx prompts through - register it there or the prompt degrades to a text box', ); expect(unregistered).toEqual([]); }); diff --git a/test/integration/deployments-cancel.test.ts b/test/integration/deployments-cancel.test.ts index 482c2ba..21b0aa7 100644 --- a/test/integration/deployments-cancel.test.ts +++ b/test/integration/deployments-cancel.test.ts @@ -1,13 +1,13 @@ import { tmpdir } from 'node:os'; -import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; import getFixture from '../fixtures/deployment-get.json'; import notFoundFixture from '../fixtures/deployment-not-found.json'; -import { CTRL_C, answerPrompts, onTerminal, pretendTerminal } from '../support/terminal'; +import { answerPrompts, CTRL_C, onTerminal, pretendTerminal, stubPrompts } from '../support/terminal'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; import { projectOwnership } from '../support/project-ownership'; @@ -181,7 +181,7 @@ describe('integration: launch:deployments:cancel on the wire', () => { const cancel = cancelScope().post(CANCEL_PATH).reply(200, {}); const restore = pretendTerminal(); const inquired: unknown[] = []; - jest.spyOn(cliux, 'inquire').mockImplementation(async (payload: unknown) => { + stubPrompts((payload) => { inquired.push(payload); return false as never; }); diff --git a/test/integration/deployments-rollback.test.ts b/test/integration/deployments-rollback.test.ts index fff80ec..e501649 100644 --- a/test/integration/deployments-rollback.test.ts +++ b/test/integration/deployments-rollback.test.ts @@ -1,6 +1,6 @@ import { tmpdir } from 'node:os'; -import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; @@ -8,7 +8,7 @@ import nock from 'nock'; import * as watcher from '../../src/deployments/deployment.watcher'; import getFixture from '../fixtures/deployment-get.json'; import notFoundFixture from '../fixtures/deployment-not-found.json'; -import { CTRL_C, answerPrompts, onTerminal, pretendTerminal } from '../support/terminal'; +import { answerPrompts, CTRL_C, onTerminal, pretendTerminal, stubPrompts } from '../support/terminal'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; import { projectOwnership } from '../support/project-ownership'; @@ -189,7 +189,7 @@ describe('integration: launch:deployments:rollback on the wire', () => { const rollback = hub().post(`${DEPLOYMENTS}/rollback`).reply(200, {}); const restore = pretendTerminal(); const inquired: unknown[] = []; - jest.spyOn(cliux, 'inquire').mockImplementation(async (payload: unknown) => { + stubPrompts((payload) => { inquired.push(payload); return false as never; }); diff --git a/test/integration/logs-get.test.ts b/test/integration/logs-get.test.ts index 76cbdd5..cd28e4a 100644 --- a/test/integration/logs-get.test.ts +++ b/test/integration/logs-get.test.ts @@ -7,6 +7,7 @@ import { runCommand } from '@oclif/test'; import nock from 'nock'; import * as watcher from '../../src/deployments/deployment.watcher'; +import { terminalUx } from '../../src/core/terminal-ux'; import { EVENT_STREAM_IDLE_TIMEOUT_MS } from '../../src/transport/event-stream'; import listFixture from '../fixtures/deployments-list.json'; import notFoundFixture from '../fixtures/deployment-not-found.json'; @@ -198,7 +199,7 @@ describe('integration: launch:logs:get on the wire', () => { expect(other.isDone()).toBe(false); expect(outputLines(stdout)).toEqual(['2026-10-28 10:00:00.000: Installing dependencies...', 'Deployment #4 is LIVE.']); expect(answered.messages).toEqual([]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); expect(onWire).toEqual([]); } finally { restoreStdin(); diff --git a/test/integration/organization-prompt.test.ts b/test/integration/organization-prompt.test.ts index fa4adcb..5eb07b5 100644 --- a/test/integration/organization-prompt.test.ts +++ b/test/integration/organization-prompt.test.ts @@ -1,12 +1,12 @@ import { randomUUID } from 'node:crypto'; import { tmpdir } from 'node:os'; -import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; -import { pretendTerminal } from '../support/terminal'; +import { pretendTerminal, stubPrompts } from '../support/terminal'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; import { projectOwnership } from '../support/project-ownership'; @@ -65,7 +65,7 @@ function answering(answers: unknown[]): unknown[] { const inquired: unknown[] = []; let index = 0; - jest.spyOn(cliux, 'inquire').mockImplementation(async (payload: unknown) => { + stubPrompts((payload) => { inquired.push(payload); const answer = answers[index]; index += 1; diff --git a/test/integration/projects-command-flows.test.ts b/test/integration/projects-command-flows.test.ts index 2fb37c8..d7908e8 100644 --- a/test/integration/projects-command-flows.test.ts +++ b/test/integration/projects-command-flows.test.ts @@ -3,12 +3,12 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; -import { pretendTerminal } from '../support/terminal'; +import { answerPrompts, CTRL_C, pretendTerminal, stubPrompts } from '../support/terminal'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; import getFixture from '../fixtures/project-get.json'; @@ -256,7 +256,7 @@ describe('integration: end-to-end command flows', () => { useSession(basicSession()); const restoreTTY = pretendTerminal(); const inquired: unknown[] = []; - jest.spyOn(cliux, 'inquire').mockImplementation(async (payload: unknown) => { + stubPrompts((payload) => { inquired.push(payload); return PROJECT_UID as never; }); @@ -288,7 +288,7 @@ describe('integration: end-to-end command flows', () => { it('exits 3 when the picker comes back with nothing chosen', async () => { useSession(basicSession()); const restoreTTY = pretendTerminal(); - jest.spyOn(cliux, 'inquire').mockResolvedValue(undefined as never); + stubPrompts(() => undefined); nock(LAUNCH_HUB_URL).get('/manage/projects').query({ limit: '100', skip: '0' }).reply(200, listFixture); const { error } = await runLaunch(['launch:projects:get', '--org', ORG_UID, '--data-dir', tmpdir()]); @@ -298,4 +298,20 @@ describe('integration: end-to-end command flows', () => { expect(error?.oclif?.exit).toBe(3); expect(error?.message).toBe('Cancelled. Nothing was changed.'); }); + + it('exits 3 when Ctrl-C aborts the searchable project picker', async () => { + useSession(basicSession()); + const restoreTTY = pretendTerminal(); + answerPrompts({ 'Choose a project': CTRL_C }); + nock(LAUNCH_HUB_URL).get('/manage/projects').query({ limit: '100', skip: '0' }).reply(200, listFixture); + + const { error } = await runLaunch(['launch:projects:get', '--org', ORG_UID, '--data-dir', tmpdir()]); + await new Promise((done) => setImmediate(done)); + + restoreTTY(); + + expect(error?.oclif?.exit).toBe(3); + expect(error?.message).toBe('Cancelled. Nothing was changed.'); + expect(process.listenerCount('SIGINT')).toBe(0); + }); }); diff --git a/test/integration/projects-delete.test.ts b/test/integration/projects-delete.test.ts index 3f1b332..3a2a625 100644 --- a/test/integration/projects-delete.test.ts +++ b/test/integration/projects-delete.test.ts @@ -1,11 +1,11 @@ import { tmpdir } from 'node:os'; -import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; -import { CTRL_C, answerPrompts, onTerminal, pretendTerminal } from '../support/terminal'; +import { answerPrompts, CTRL_C, onTerminal, pretendTerminal, stubPrompts } from '../support/terminal'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; import { projectOwnership } from '../support/project-ownership'; @@ -151,7 +151,7 @@ describe('integration: launch:projects:delete on the wire', () => { const removal = nock(LAUNCH_HUB_URL, BODYLESS).delete(`/manage/projects/${PROJECT_UID}`).query({}).reply(204); const restore = pretendTerminal(); const inquired: unknown[] = []; - jest.spyOn(cliux, 'inquire').mockImplementation(async (payload: unknown) => { + stubPrompts((payload) => { inquired.push(payload); return false as never; }); diff --git a/test/integration/prompt-ctrl-c-on-a-terminal.test.ts b/test/integration/prompt-ctrl-c-on-a-terminal.test.ts new file mode 100644 index 00000000..7946b9f --- /dev/null +++ b/test/integration/prompt-ctrl-c-on-a-terminal.test.ts @@ -0,0 +1,36 @@ +import { execFileSync } from 'node:child_process'; +import { join } from 'node:path'; + +import { EXIT_CANCELLED } from '../../src/core/constants'; + +const PTY = join(__dirname, '..', 'support', 'pty'); +const PROMPT_ON_SCREEN = 'Choose an environment'; + +function exitCodeAfterCtrlC(promptType: string): number { + const output = execFileSync( + 'python3', + [ + '-I', + join(PTY, 'press-ctrl-c.py'), + PROMPT_ON_SCREEN, + process.execPath, + '-r', + 'ts-node/register/transpile-only', + join(PTY, 'ctrl-c-prompt.fixture.ts'), + promptType, + ], + { encoding: 'utf8', timeout: 45_000 }, + ); + + return Number(output.trim()); +} + +describe('Ctrl-C at a real prompt on a terminal', () => { + it.each(['input', 'password', 'list', 'checkbox', 'confirm', 'search-list'])( + 'exits 3 as cancelled at the %s prompt', + (promptType) => { + expect(exitCodeAfterCtrlC(promptType)).toBe(EXIT_CANCELLED); + }, + 60_000, + ); +}); diff --git a/test/integration/secrets-set.test.ts b/test/integration/secrets-set.test.ts index eb8eb98..0080ba0 100644 --- a/test/integration/secrets-set.test.ts +++ b/test/integration/secrets-set.test.ts @@ -4,12 +4,13 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Readable } from 'node:stream'; -import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; import { DEFAULT_SECRET_IO } from '../../src/secrets/secret.value'; +import { terminalUx } from '../../src/core/terminal-ux'; import { projectOwnership } from '../support/project-ownership'; import { gluedValue } from '../support/glued-value'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; @@ -160,7 +161,7 @@ describe('integration: launch:secrets:set on the wire', () => { expect([list.isDone(), write.isDone()]).toEqual([true, true]); expect(sent).toEqual([{ method: 'POST', path: COLLECTION_PATH, body: { key: 'API_TOKEN', value } }]); expect(onWire).toEqual([]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); expect(stdout).toBe('āœ” Secret API_TOKEN added.\n'); expect(stdout + stderr).not.toContain(value); }); @@ -276,7 +277,7 @@ describe('integration: launch:secrets:set on the wire', () => { expect(error?.message).toContain('Pass --yes when piping the value'); expect(reads).toEqual([]); expect([list.isDone(), write.isDone()]).toEqual([false, false]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); }); it.each([['NEXT_PUBLIC_API'], ['NUXT_PUBLIC_API'], ['VITE_API'], ['GATSBY_API'], ['PUBLIC_API']])( @@ -365,7 +366,7 @@ describe('integration: launch:secrets:set on the wire', () => { expect(reads).toEqual([]); expect([list.isDone(), write.isDone()]).toEqual([false, false]); expect(onWire).toEqual([]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); }); it('S5 sends a key with a slash as one encoded segment on a PUT', async () => { @@ -521,7 +522,7 @@ describe('integration: launch:secrets:set on the wire', () => { expect(error?.oclif?.exit).toBe(2); expect(error?.message).toContain(`Missing required value for ${flag}`); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); expect(sent).toEqual([]); }); diff --git a/test/integration/secrets-unset.test.ts b/test/integration/secrets-unset.test.ts index a762b43..96c6b55 100644 --- a/test/integration/secrets-unset.test.ts +++ b/test/integration/secrets-unset.test.ts @@ -2,11 +2,12 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { authHandler, cliux, configHandler } from '@contentstack/cli-utilities'; +import { authHandler, configHandler } from '@contentstack/cli-utilities'; import type { Interfaces } from '@oclif/core'; import { runCommand } from '@oclif/test'; import nock from 'nock'; +import { terminalUx } from '../../src/core/terminal-ux'; import { projectOwnership } from '../support/project-ownership'; import { gluedValue } from '../support/glued-value'; import { loadCliConfig, routeConsoleLogToStdout } from '../support/oclif'; @@ -116,7 +117,7 @@ describe('integration: launch:secrets:unset on the wire', () => { expect([first.isDone(), second.isDone()]).toEqual([true, true]); expect(deleted).toEqual([`${COLLECTION_PATH}/DB_PASSWORD`, `${COLLECTION_PATH}/API_TOKEN`]); expect(onWire).toEqual([]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); expect(stdout).toBe('āœ” Secret DB_PASSWORD removed.\nāœ” Secret API_TOKEN removed.\n'); expect(stderr).toBe(''); }); @@ -175,7 +176,7 @@ describe('integration: launch:secrets:unset on the wire', () => { expect(write.isDone()).toBe(false); expect(deleted).toEqual([]); expect(onWire).toEqual([]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); expect(stdout).toBe(''); }); @@ -229,7 +230,7 @@ describe('integration: launch:secrets:unset on the wire', () => { expect(write.isDone()).toBe(false); expect(deleted).toEqual([]); expect(onWire).toEqual([]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); }); it('U5 words a 403 as a permission failure for the key and exits 1', async () => { @@ -263,7 +264,7 @@ describe('integration: launch:secrets:unset on the wire', () => { expect(error?.message).toContain('--key'); expect(write.isDone()).toBe(false); expect(onWire).toEqual([]); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); }); it('U7 encodes a key with special characters as one path segment', async () => { @@ -306,7 +307,7 @@ describe('integration: launch:secrets:unset on the wire', () => { expect(error?.oclif?.exit).toBe(2); expect(error?.message).toContain(`Missing required value for ${flag}`); - expect(cliux.inquire).not.toHaveBeenCalled(); + expect(terminalUx.inquire).not.toHaveBeenCalled(); expect(deleted).toEqual([]); }); diff --git a/test/no-terminal.setup.ts b/test/no-terminal.setup.ts index 2df6c42..d43a5c5 100644 --- a/test/no-terminal.setup.ts +++ b/test/no-terminal.setup.ts @@ -1,6 +1,4 @@ -import { cliux } from '@contentstack/cli-utilities'; - -import { stdinReportingTTY, stdoutOfWidth, stdoutReportingTTY } from './support/terminal'; +import { stdinReportingTTY, stdoutOfWidth, stdoutReportingTTY, stubPrompts } from './support/terminal'; let restoreTerminal: (() => void)[] = []; @@ -10,8 +8,8 @@ beforeEach(() => { // and no table truncation that depends on how wide the window happens to be. restoreTerminal = [stdinReportingTTY(false), stdoutReportingTTY(false), stdoutOfWidth(undefined)]; - jest.spyOn(cliux, 'inquire').mockImplementation(async (payload: unknown) => { - const message = String((payload as Record | undefined)?.message ?? ''); + stubPrompts((payload) => { + const message = String(payload.message ?? ''); throw new Error( `A test reached a real interactive prompt ("${message}"). Mock it with answerPrompts, or it would ` + 'block on stdin whenever the suite runs in a real terminal.', diff --git a/test/support/pty/ctrl-c-prompt.fixture.ts b/test/support/pty/ctrl-c-prompt.fixture.ts new file mode 100644 index 00000000..768ca3a --- /dev/null +++ b/test/support/pty/ctrl-c-prompt.fixture.ts @@ -0,0 +1,24 @@ +import { LaunchCommand } from '../../../src/core/launch-command'; +import type { UxLike } from '../../../src/core/prompt'; +import { registerSearchList } from '../../../src/core/search-list'; + +class PromptingCommand extends LaunchCommand { + static flags = {}; + static inputs = {}; + + async run(): Promise { + return undefined; + } +} + +registerSearchList(); +const ux = (new PromptingCommand([], {} as never) as unknown as { ux: UxLike }).ux; +const choices = [ + { name: 'Default', value: 'default' }, + { name: 'Staging', value: 'staging' }, +]; + +ux.inquire({ type: process.argv[2], name: 'value', message: 'Choose an environment', choices }).then( + () => process.exit(0), + (error: { exitCode?: number }) => process.exit(error.exitCode ?? 1), +); diff --git a/test/support/pty/press-ctrl-c.py b/test/support/pty/press-ctrl-c.py new file mode 100644 index 00000000..af4c2ae --- /dev/null +++ b/test/support/pty/press-ctrl-c.py @@ -0,0 +1,66 @@ +import os +import pty +import select +import sys +import time + +TIMEOUT_SECONDS = 30 +SETTLE_SECONDS = 0.3 + + +def read_chunk(fd): + if not select.select([fd], [], [], 0.1)[0]: + return None + try: + return os.read(fd, 4096) + except OSError: + return b'' + + +def read_until(fd, marker, deadline): + seen = b'' + while marker not in seen and time.time() < deadline: + chunk = read_chunk(fd) + if chunk == b'': + return False + seen += chunk or b'' + return marker in seen + + +def drain(fd, deadline): + while time.time() < deadline and read_chunk(fd) != b'': + pass + + +def wait_for_exit(pid, deadline): + while time.time() < deadline: + finished, status = os.waitpid(pid, os.WNOHANG) + if finished: + return os.waitstatus_to_exitcode(status) + time.sleep(0.05) + os.kill(pid, 9) + os.waitpid(pid, 0) + return 125 + + +def main(): + marker = sys.argv[1].encode() + command = sys.argv[2:] + pid, fd = pty.fork() + if pid == 0: + os.execvp(command[0], command) + + deadline = time.time() + TIMEOUT_SECONDS + if not read_until(fd, marker, deadline): + os.kill(pid, 9) + os.waitpid(pid, 0) + print(124) + return + + time.sleep(SETTLE_SECONDS) + os.write(fd, b'\x03') + drain(fd, deadline) + print(wait_for_exit(pid, deadline)) + + +main() diff --git a/test/support/terminal.ts b/test/support/terminal.ts index 09ebf58..60d62fc 100644 --- a/test/support/terminal.ts +++ b/test/support/terminal.ts @@ -1,4 +1,4 @@ -import { cliux } from '@contentstack/cli-utilities'; +import { terminalUx } from '../../src/core/terminal-ux'; type Stream = NodeJS.ReadStream | NodeJS.WriteStream; @@ -50,25 +50,41 @@ export interface AnsweredPrompts { payloads: Record[]; } +export type PromptHandler = (payload: Record) => unknown; + +export function stubPrompts(answer: PromptHandler): jest.SpyInstance { + return jest + .spyOn(terminalUx, 'inquire') + .mockImplementation(async (payload: unknown) => answer(payload as Record) as never); +} + +export function ctrlC(): Error { + return Object.assign(new Error('User force closed the prompt with SIGINT'), { name: 'ExitPromptError' }); +} + +export function ctrlCAtSearchList(): Error { + setImmediate(() => process.emit('SIGINT')); + + return Object.assign(new Error('Prompt was aborted'), { name: 'AbortPromptError' }); +} + export function answerPrompts(answers: Record): AnsweredPrompts { const recorded: AnsweredPrompts = { messages: [], payloads: [] }; - jest.spyOn(cliux, 'inquire').mockImplementation(async (payload: unknown) => { - const record = payload as Record; - const message = String(record.message); + stubPrompts((payload) => { + const message = String(payload.message); recorded.messages.push(message); - recorded.payloads.push(record); + recorded.payloads.push(payload); if (!(message in answers)) { throw new Error(`Unexpected prompt: ${message}`); } if (answers[message] === CTRL_C) { - setImmediate(() => process.emit('SIGINT')); - return new Promise(() => undefined); + throw payload.type === 'search-list' ? ctrlCAtSearchList() : ctrlC(); } - return answers[message] as never; + return answers[message]; }); return recorded;