From 3ac6790ddd879969a8883f920a72a64593ca7de6 Mon Sep 17 00:00:00 2001 From: Inf1mum Date: Sat, 7 Nov 2026 20:22:37 +0300 Subject: [PATCH 1/5] fix(generator-cli): pass JAVA_OPTS as argv array without a shell JAVA_OPTS was interpolated into a single command string which was spawned with shell: true. Characters that are meaningful to a shell - most notably the pipe in -Dhttp.nonProxyHosts=127.*|localhost - were therefore interpreted by the shell instead of reaching the java process, breaking every command of the CLI (the command discovery via exec failed the same way). Joining the args into one string also triggered the Node.js DEP0190 deprecation warning. The command is now built as a proper argv array: JAVA_OPTS is split with a lightweight tokenizer that respects single/double quotes and backslash escapes, and java (or docker) is spawned with shell: false. This removes the whole class of shell-escaping problems. Fixes #1213 --- .../app/services/pass-through.service.spec.ts | 156 ++++++++++++++---- .../src/app/services/pass-through.service.ts | 124 +++++++++++--- 2 files changed, 224 insertions(+), 56 deletions(-) diff --git a/apps/generator-cli/src/app/services/pass-through.service.spec.ts b/apps/generator-cli/src/app/services/pass-through.service.spec.ts index 36e1c034fed..f5a44733b2c 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.spec.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.spec.ts @@ -1,6 +1,7 @@ import { Test } from '@nestjs/testing'; import chalk from 'chalk'; import { Command, createCommand } from 'commander'; +import { EventEmitter } from 'events'; import { COMMANDER_PROGRAM, LOGGER } from '../constants'; import { GeneratorService } from './generator.service'; import { PassThroughService } from './pass-through.service'; @@ -14,6 +15,16 @@ const childProcess = jest.mocked(require('child_process')); // eslint-disable-next-line @typescript-eslint/no-var-requires const fs = jest.mocked(require('fs')); +const makeChildProcess = () => { + const child = new EventEmitter() as EventEmitter & { + stdout: EventEmitter; + stderr: EventEmitter; + }; + child.stdout = new EventEmitter(); + child.stderr = new EventEmitter(); + return child; +}; + describe('PassThroughService', () => { let fixture: PassThroughService; let program: Command; @@ -58,7 +69,9 @@ describe('PassThroughService', () => { fixture = moduleRef.get(PassThroughService); - childProcess.spawn.mockReset().mockReturnValue({ on: jest.fn() }); + childProcess.spawn + .mockReset() + .mockImplementation(() => makeChildProcess()); fs.existsSync.mockReset().mockReturnValue(true); configServiceMock.get.mockClear(); configServiceMock.get.mockReset(); @@ -71,9 +84,14 @@ describe('PassThroughService', () => { let error: Error; beforeEach(async () => { - childProcess.exec.mockImplementation((cmd: string, cb) => - cb(true, undefined, 'Some error') - ); + childProcess.spawn.mockImplementation(() => { + const child = makeChildProcess(); + setImmediate(() => { + child.stderr.emit('data', 'Some error'); + child.emit('close', 1); + }); + return child; + }); try { await fixture.init(); } catch (e) { @@ -123,14 +141,22 @@ describe('PassThroughService', () => { ].join('\n'); beforeEach(async () => { - childProcess.exec.mockImplementation((cmd: string, cb) => { - if (cmd.endsWith('"/some/path/to/4.2.1.jar" help')) { - cb(undefined, helpText); - } - - if (cmd.endsWith('"/some/path/to/4.2.1.jar" completion')) { - cb(undefined, completionText); - } + childProcess.spawn.mockImplementation((command: string, args) => { + const child = makeChildProcess(); + const invoked = [command, ...(args ?? [])].join(' '); + const output = invoked.endsWith('/some/path/to/4.2.1.jar help') + ? helpText + : invoked.endsWith('/some/path/to/4.2.1.jar completion') + ? completionText + : undefined; + + setImmediate(() => { + if (output !== undefined) { + child.stdout.emit('data', output); + child.emit('close', 0); + } + }); + return child; }); await fixture.init(); }); @@ -181,11 +207,20 @@ describe('PassThroughService', () => { it('delegates to docker', async () => { await program.parseAsync([name, ...argv], { from: 'user' }); expect(childProcess.spawn).toHaveBeenNthCalledWith( - 1, - `docker run --rm -v "/foo/bar:/local" openapitools/openapi-generator-cli:v4.2.1 ${name} ${argv.join(' ')}`, + 3, + 'docker', + [ + 'run', + '--rm', + '-v', + '/foo/bar:/local', + 'openapitools/openapi-generator-cli:v4.2.1', + name, + ...argv, + ], { stdio: 'inherit', - shell: true, + shell: false, } ); }); @@ -194,11 +229,12 @@ describe('PassThroughService', () => { it('can delegate', async () => { await program.parseAsync([name, ...argv], { from: 'user' }); expect(childProcess.spawn).toHaveBeenNthCalledWith( - 1, - `java -jar "/some/path/to/4.2.1.jar" ${name} ${argv.join(' ')}`, + 3, + 'java', + ['-jar', '/some/path/to/4.2.1.jar', name, ...argv], { stdio: 'inherit', - shell: true, + shell: false, } ); }); @@ -207,11 +243,54 @@ describe('PassThroughService', () => { process.env['JAVA_OPTS'] = 'java-opt-1=1'; await program.parseAsync([name, ...argv], { from: 'user' }); expect(childProcess.spawn).toHaveBeenNthCalledWith( - 1, - `java java-opt-1=1 -jar "/some/path/to/4.2.1.jar" ${name} ${argv.join(' ')}`, + 3, + 'java', + ['java-opt-1=1', '-jar', '/some/path/to/4.2.1.jar', name, ...argv], { stdio: 'inherit', - shell: true, + shell: false, + } + ); + }); + + it('passes JAVA_OPTS with a pipe character through as a single argument', async () => { + process.env['JAVA_OPTS'] = '-Dhttp.nonProxyHosts=127.*|localhost'; + await program.parseAsync([name, ...argv], { from: 'user' }); + expect(childProcess.spawn).toHaveBeenNthCalledWith( + 3, + 'java', + [ + '-Dhttp.nonProxyHosts=127.*|localhost', + '-jar', + '/some/path/to/4.2.1.jar', + name, + ...argv, + ], + { + stdio: 'inherit', + shell: false, + } + ); + }); + + it('splits quoted JAVA_OPTS into separate arguments without a shell', async () => { + process.env['JAVA_OPTS'] = + '-Dhttp.nonProxyHosts="127.*|localhost|*.local" -Dsome.opt=\'a b\''; + await program.parseAsync([name, ...argv], { from: 'user' }); + expect(childProcess.spawn).toHaveBeenNthCalledWith( + 3, + 'java', + [ + '-Dhttp.nonProxyHosts=127.*|localhost|*.local', + '-Dsome.opt=a b', + '-jar', + '/some/path/to/4.2.1.jar', + name, + ...argv, + ], + { + stdio: 'inherit', + shell: false, } ); }); @@ -224,14 +303,20 @@ describe('PassThroughService', () => { const cpDelimiter = process.platform === 'win32' ? ';' : ':'; expect(childProcess.spawn).toHaveBeenNthCalledWith( - 1, - `java -cp "${[ - '/some/path/to/4.2.1.jar', - '../some/custom.jar', - ].join(cpDelimiter)}" org.openapitools.codegen.OpenAPIGenerator ${name} ${argv.join(' ')}`, + 3, + 'java', + [ + '-cp', + ['/some/path/to/4.2.1.jar', '../some/custom.jar'].join( + cpDelimiter + ), + 'org.openapitools.codegen.OpenAPIGenerator', + name, + ...argv, + ], { stdio: 'inherit', - shell: true, + shell: false, } ); }); @@ -244,11 +329,12 @@ describe('PassThroughService', () => { ); expect(childProcess.spawn).toHaveBeenNthCalledWith( - 1, - `java -jar "../some/custom.jar" ${name} ${argv.join(' ')}`, + 3, + 'java', + ['-jar', '../some/custom.jar', name, ...argv], { stdio: 'inherit', - shell: true, + shell: false, } ); }); @@ -311,17 +397,19 @@ describe('PassThroughService', () => { describe('process spawn', () => { it(`spawns ${spawn ? 1 : 0} times`, () => { + // init() already spawned help and completion discovery expect(childProcess.spawn).toHaveBeenCalledTimes( - spawn ? 1 : 0 + spawn ? 3 : 2 ); }); spawn && it('spawns the correct process', () => { expect(childProcess.spawn).toHaveBeenNthCalledWith( - 1, - `java -jar "/some/path/to/4.2.1.jar" ${cmd}`, - { stdio: 'inherit', shell: true } + 3, + 'java', + ['-jar', '/some/path/to/4.2.1.jar', ...cmd.split(' ')], + { stdio: 'inherit', shell: false } ); }); }); diff --git a/apps/generator-cli/src/app/services/pass-through.service.ts b/apps/generator-cli/src/app/services/pass-through.service.ts index dafee5437a4..39146a6934c 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.ts @@ -1,6 +1,6 @@ import { Inject, Injectable } from '@nestjs/common'; import chalk from 'chalk'; -import { exec, spawn } from 'child_process'; +import { spawn } from 'child_process'; import { Command } from 'commander'; import * as fs from 'fs'; import { COMMANDER_PROGRAM, LOGGER } from '../constants'; @@ -85,14 +85,15 @@ export class PassThroughService { } public passThrough = (cmd: Command) => { - const args = [cmd.name(), ...cmd.args]; - // Join command and args into a single string to avoid Node 24+ deprecation warning - // DEP0190: passing args to spawn with shell: true concatenates without escaping - const fullCommand = [this.cmd(), ...args].join(' '); + const [command, ...args] = [...this.cmd(), cmd.name(), ...cmd.args]; - spawn(fullCommand, { + // Spawned as an args array without a shell so that characters which are + // meaningful to a shell (e.g. the `|` in -Dhttp.nonProxyHosts=127.*|localhost + // coming from JAVA_OPTS) reach the java process verbatim. This also avoids + // the Node deprecation warning DEP0190. + spawn(command, args, { stdio: 'inherit', - shell: true, + shell: false, }).on('exit', process.exit); }; @@ -127,17 +128,35 @@ export class PassThroughService { private run = (subCmd: string) => new Promise((resolve, reject) => { - exec(`${this.cmd()} ${subCmd}`, (error, stdout, stderr) => { - error ? reject(new Error(stderr)) : resolve(stdout); - }); + const [command, ...args] = [...this.cmd(), subCmd]; + let stdout = ''; + let stderr = ''; + + const child = spawn(command, args, { shell: false }); + child.stdout.on('data', (chunk) => (stdout += chunk.toString())); + child.stderr.on('data', (chunk) => (stderr += chunk.toString())); + child + .on('error', reject) + .on('close', (code) => + code === 0 ? resolve(stdout) : reject(new Error(stderr)) + ); }); - private cmd() { + /** + * Returns the command which should be spawned as a proper argv array. + * JAVA_OPTS is split into separate arguments so that a shell is not needed + * (and must not misinterpret characters like `|` or `*`, see #1213). + */ + private cmd(): string[] { if (this.configService.useDocker) { return [ - `docker run --rm -v "${this.configService.cwd}:/local"`, + 'docker', + 'run', + '--rm', + '-v', + `${this.configService.cwd}:/local`, this.versionManager.getDockerImageName(), - ].join(' '); + ]; } const customGenerator = @@ -145,20 +164,81 @@ export class PassThroughService { this.getCustomGeneratorFromArgs(); const cliPath = this.versionManager.filePath(); - let subCmd: string; + let subCmd: string[]; if (customGenerator) { subCmd = fs.existsSync(cliPath) - ? `-cp "${[cliPath, customGenerator].join( - this.isWin() ? ';' : ':' - )}" org.openapitools.codegen.OpenAPIGenerator` - : `-jar "${customGenerator}"`; + ? [ + '-cp', + [cliPath, customGenerator].join(this.isWin() ? ';' : ':'), + 'org.openapitools.codegen.OpenAPIGenerator', + ] + : ['-jar', customGenerator]; } else { - subCmd = `-jar "${cliPath}"`; + subCmd = ['-jar', cliPath]; + } + + return ['java', ...this.splitArgs(process.env['JAVA_OPTS']), ...subCmd]; + } + + /** + * Splits a string into arguments the way a POSIX shell would, respecting + * single and double quotes as well as backslash escapes outside of quotes. + * A `|` inside JAVA_OPTS (legitimate for -Dhttp.nonProxyHosts) therefore + * stays part of its argument instead of splitting the command. + */ + private splitArgs(input?: string): string[] { + if (!input) { + return []; + } + + const args: string[] = []; + let arg = ''; + let hasArg = false; + let quote: '"' | "'" | undefined; + + for (let i = 0; i < input.length; i++) { + const char = input[i]; + + if (quote) { + if (char === quote) { + quote = undefined; + } else { + arg += char; + } + continue; + } + + switch (char) { + case '"': + case "'": + quote = char; + hasArg = true; + break; + case '\\': + if (i + 1 < input.length) { + arg += input[++i]; + hasArg = true; + } + break; + default: + if (/\s/.test(char)) { + if (hasArg) { + args.push(arg); + } + arg = ''; + hasArg = false; + } else { + arg += char; + hasArg = true; + } + } + } + + if (hasArg) { + args.push(arg); } - return ['java', process.env['JAVA_OPTS'], subCmd] - .filter((str): str is string => str != null && typeof str === 'string') - .join(' '); + return args; } private printHelp(cmd: Pick) { From 7d7e39c44ed9e781661da4e157e5da0494168cc0 Mon Sep 17 00:00:00 2001 From: Inf1mum Date: Sun, 8 Nov 2026 00:40:58 +0300 Subject: [PATCH 2/5] fix(generator-cli): keep backslashes of unquoted JAVA_OPTS verbatim splitArgs treated a backslash outside of quotes as an escape character the way a POSIX shell would, so a Windows path in JAVA_OPTS such as C:\certs\client.jks reached java as C:certsclient.jks. Unquoted backslashes are now kept verbatim; escaping is only interpreted inside double quotes, where it follows the typical shell rules. --- .../app/services/pass-through.service.spec.ts | 30 +++++++++++++++++++ .../src/app/services/pass-through.service.ts | 24 ++++++++++----- 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/apps/generator-cli/src/app/services/pass-through.service.spec.ts b/apps/generator-cli/src/app/services/pass-through.service.spec.ts index f5a44733b2c..2a55df292cf 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.spec.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.spec.ts @@ -295,6 +295,36 @@ describe('PassThroughService', () => { ); }); + // Unlike a POSIX shell, an unquoted backslash is NOT an escape + // character here: JAVA_OPTS on Windows typically carries paths such + // as C:\certs\client.jks, and shell-style escape handling would + // silently strip the separators (C:certsclient.jks). Since the args + // are handed to java verbatim (no shell in between), java itself + // does not interpret the backslashes either, so keeping them is + // always the faithful transfer of JAVA_OPTS. Escaping is only + // interpreted inside double quotes, see the escaped quote tests + // below. + it('keeps backslashes of unquoted JAVA_OPTS verbatim', async () => { + process.env['JAVA_OPTS'] = + '-Djavax.net.ssl.keyStore=C:\\certs\\client.jks'; + await program.parseAsync([name, ...argv], { from: 'user' }); + expect(childProcess.spawn).toHaveBeenNthCalledWith( + 3, + 'java', + [ + '-Djavax.net.ssl.keyStore=C:\\certs\\client.jks', + '-jar', + '/some/path/to/4.2.1.jar', + name, + ...argv, + ], + { + stdio: 'inherit', + shell: false, + } + ); + }); + it('can delegate with custom jar', async () => { await program.parseAsync( [name, ...argv, '--custom-generator=../some/custom.jar'], diff --git a/apps/generator-cli/src/app/services/pass-through.service.ts b/apps/generator-cli/src/app/services/pass-through.service.ts index 39146a6934c..c0adaf90cef 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.ts @@ -181,10 +181,17 @@ export class PassThroughService { } /** - * Splits a string into arguments the way a POSIX shell would, respecting - * single and double quotes as well as backslash escapes outside of quotes. - * A `|` inside JAVA_OPTS (legitimate for -Dhttp.nonProxyHosts) therefore - * stays part of its argument instead of splitting the command. + * Splits a string into arguments the way a shell tokenizes them, respecting + * single and double quotes. A `|` inside JAVA_OPTS (legitimate for + * -Dhttp.nonProxyHosts) therefore stays part of its argument instead of + * splitting the command. + * + * Unlike a POSIX shell, a backslash is kept verbatim in unquoted tokens: + * JAVA_OPTS on Windows regularly carries paths such as C:\certs\client.jks, + * and treating the backslash as an escape character outside of quotes would + * strip those separators (C:certsclient.jks). Backslash escapes are only + * interpreted inside double quotes, where they follow the typical shell + * rules (see below). */ private splitArgs(input?: string): string[] { if (!input) { @@ -215,10 +222,11 @@ export class PassThroughService { hasArg = true; break; case '\\': - if (i + 1 < input.length) { - arg += input[++i]; - hasArg = true; - } + // keep backslashes verbatim in unquoted tokens so Windows paths in + // JAVA_OPTS (e.g. C:\certs\client.jks) reach java unmodified; the + // backslash is only an escape character inside double quotes + arg += char; + hasArg = true; break; default: if (/\s/.test(char)) { From ab258df515b52ed57fd6484f8de8b88dd8bb7749 Mon Sep 17 00:00:00 2001 From: Inf1mum Date: Sun, 8 Nov 2026 00:41:45 +0300 Subject: [PATCH 3/5] fix(generator-cli): handle backslash escapes inside double-quoted JAVA_OPTS Within a double-quoted JAVA_OPTS segment a backslash closed nothing and a following quote always terminated the segment, so -Dfoo="a\"b" was passed to java as -Dfoo=a\b" with the trailing quote leaking out of the quotes. A backslash inside double quotes now escapes exactly the characters a typical shell lets it escape (quote, backslash, dollar, backtick), while single-quoted segments keep treating the backslash as a literal character. --- .../app/services/pass-through.service.spec.ts | 30 +++++++++++++++++++ .../src/app/services/pass-through.service.ts | 11 ++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/apps/generator-cli/src/app/services/pass-through.service.spec.ts b/apps/generator-cli/src/app/services/pass-through.service.spec.ts index 2a55df292cf..0a12ddb8dd1 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.spec.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.spec.ts @@ -325,6 +325,36 @@ describe('PassThroughService', () => { ); }); + // Inside double quotes the backslash keeps its typical shell + // meaning and escapes exactly the characters a shell would let it + // escape (" \ $ `), so the \" of -Dfoo="a\"b" is passed to java as + // a literal quote instead of ending the quoted segment early (and + // the rest of JAVA_OPTS being parsed as unquoted input). Inside + // single quotes a backslash has no special meaning at all. + it('passes escaped quotes inside double-quoted JAVA_OPTS through to java', async () => { + // runtime JAVA_OPTS: -Dfoo="a\"b" -Dbaz="c\\d" -Dqux='e\"f' + process.env['JAVA_OPTS'] = + '-Dfoo="a\\"b" -Dbaz="c\\\\d" -Dqux=\'e\\"f\''; + await program.parseAsync([name, ...argv], { from: 'user' }); + expect(childProcess.spawn).toHaveBeenNthCalledWith( + 3, + 'java', + [ + '-Dfoo=a"b', + '-Dbaz=c\\d', + '-Dqux=e\\"f', + '-jar', + '/some/path/to/4.2.1.jar', + name, + ...argv, + ], + { + stdio: 'inherit', + shell: false, + } + ); + }); + it('can delegate with custom jar', async () => { await program.parseAsync( [name, ...argv, '--custom-generator=../some/custom.jar'], diff --git a/apps/generator-cli/src/app/services/pass-through.service.ts b/apps/generator-cli/src/app/services/pass-through.service.ts index c0adaf90cef..ab6cb52bee6 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.ts @@ -207,7 +207,16 @@ export class PassThroughService { const char = input[i]; if (quote) { - if (char === quote) { + // inside double quotes a backslash escapes exactly the characters a + // typical shell would let it escape, so the `\"` of -Dfoo="a\"b" + // becomes a literal quote instead of ending the quoted segment early + if ( + char === '\\' && + quote === '"' && + ['"', '\\', '$', '`'].includes(input[i + 1]) + ) { + arg += input[++i]; + } else if (char === quote) { quote = undefined; } else { arg += char; From c4d9d86fd41576782f79d9ee6c3d2f406e53ec4c Mon Sep 17 00:00:00 2001 From: Inf1mum Date: Sun, 8 Nov 2026 00:43:56 +0300 Subject: [PATCH 4/5] test(generator-cli): assert exact argv of the discovery spawn calls The discovery of getCommands() was only exercised through a mock keyed on the joined command line; the first two spawn calls were never verified. The spec now asserts that help and completion are spawned on the exact argv (java, jar path, sub command) with { shell: false }, and the discovery beforeEach clears JAVA_OPTS so earlier tests cannot leak options into the asserted argv. --- .../app/services/pass-through.service.spec.ts | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/apps/generator-cli/src/app/services/pass-through.service.spec.ts b/apps/generator-cli/src/app/services/pass-through.service.spec.ts index 0a12ddb8dd1..219a2aeb6d7 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.spec.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.spec.ts @@ -141,6 +141,9 @@ describe('PassThroughService', () => { ].join('\n'); beforeEach(async () => { + // discovery must see a deterministic environment, regardless of + // what JAVA_OPTS an earlier test left behind + delete process.env['JAVA_OPTS']; childProcess.spawn.mockImplementation((command: string, args) => { const child = makeChildProcess(); const invoked = [command, ...(args ?? [])].join(' '); @@ -161,9 +164,31 @@ describe('PassThroughService', () => { await fixture.init(); }); - it('adds 10 commands', () => { - expect(program.commands).toHaveLength(10); - }); + it('adds 10 commands', () => { + expect(program.commands).toHaveLength(10); + }); + + // the first two spawns are the command discovery of getCommands(): + // `help` and `completion` are invoked on the exact argv (java, + // jar path, sub command - JAVA_OPTS unset) and without a shell, so + // regressions in the discovery process construction are caught + it('spawns help discovery with the exact argv and without a shell', () => { + expect(childProcess.spawn).toHaveBeenNthCalledWith( + 1, + 'java', + ['-jar', '/some/path/to/4.2.1.jar', 'help'], + { shell: false } + ); + }); + + it('spawns completion discovery with the exact argv and without a shell', () => { + expect(childProcess.spawn).toHaveBeenNthCalledWith( + 2, + 'java', + ['-jar', '/some/path/to/4.2.1.jar', 'completion'], + { shell: false } + ); + }); describe.each([ [ From 50911689d318cbef0b27800fe57d7b7f67e71701 Mon Sep 17 00:00:00 2001 From: Inf1mum Date: Sun, 8 Nov 2026 00:45:07 +0300 Subject: [PATCH 5/5] fix(generator-cli): decode spawned process output as utf8 The discovery run() accumulated stdout/stderr from Buffer chunks, so a multi-byte utf8 character split across two chunks was decoded twice and turned into replacement characters, corrupting non-ASCII help or error text. Both streams now set utf8 encoding before the data handlers are attached, and the spec asserts the encoding on the discovery streams. --- .../app/services/pass-through.service.spec.ts | 30 ++++++++++++++++--- .../src/app/services/pass-through.service.ts | 9 ++++-- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/apps/generator-cli/src/app/services/pass-through.service.spec.ts b/apps/generator-cli/src/app/services/pass-through.service.spec.ts index 219a2aeb6d7..622419ae0aa 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.spec.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.spec.ts @@ -17,11 +17,11 @@ const fs = jest.mocked(require('fs')); const makeChildProcess = () => { const child = new EventEmitter() as EventEmitter & { - stdout: EventEmitter; - stderr: EventEmitter; + stdout: EventEmitter & { setEncoding: jest.Mock }; + stderr: EventEmitter & { setEncoding: jest.Mock }; }; - child.stdout = new EventEmitter(); - child.stderr = new EventEmitter(); + child.stdout = Object.assign(new EventEmitter(), { setEncoding: jest.fn() }); + child.stderr = Object.assign(new EventEmitter(), { setEncoding: jest.fn() }); return child; }; @@ -140,12 +140,16 @@ describe('PassThroughService', () => { ' --help', ].join('\n'); + let spawnedChildren: ReturnType[]; + beforeEach(async () => { // discovery must see a deterministic environment, regardless of // what JAVA_OPTS an earlier test left behind delete process.env['JAVA_OPTS']; + spawnedChildren = []; childProcess.spawn.mockImplementation((command: string, args) => { const child = makeChildProcess(); + spawnedChildren.push(child); const invoked = [command, ...(args ?? [])].join(' '); const output = invoked.endsWith('/some/path/to/4.2.1.jar help') ? helpText @@ -190,6 +194,24 @@ describe('PassThroughService', () => { ); }); + // the discovery output is decoded as utf8 up front, so a multi-byte + // character split across two stdout chunks cannot turn into + // replacement characters in the parsed command list + it('decodes the discovery stdout as utf8', () => { + expect(spawnedChildren[0].stdout.setEncoding).toHaveBeenCalledWith( + 'utf8' + ); + expect(spawnedChildren[0].stderr.setEncoding).toHaveBeenCalledWith( + 'utf8' + ); + expect(spawnedChildren[1].stdout.setEncoding).toHaveBeenCalledWith( + 'utf8' + ); + expect(spawnedChildren[1].stderr.setEncoding).toHaveBeenCalledWith( + 'utf8' + ); + }); + describe.each([ [ 'author', diff --git a/apps/generator-cli/src/app/services/pass-through.service.ts b/apps/generator-cli/src/app/services/pass-through.service.ts index ab6cb52bee6..cc0508ec241 100644 --- a/apps/generator-cli/src/app/services/pass-through.service.ts +++ b/apps/generator-cli/src/app/services/pass-through.service.ts @@ -133,8 +133,13 @@ export class PassThroughService { let stderr = ''; const child = spawn(command, args, { shell: false }); - child.stdout.on('data', (chunk) => (stdout += chunk.toString())); - child.stderr.on('data', (chunk) => (stderr += chunk.toString())); + // decode the streams as utf8 so that a multi-byte character split + // across two chunks is reassembled instead of being emitted as + // replacement characters in the middle of the output + child.stdout.setEncoding('utf8'); + child.stdout.on('data', (chunk) => (stdout += chunk)); + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => (stderr += chunk)); child .on('error', reject) .on('close', (code) =>