Skip to content

Commit e117095

Browse files
committed
fix(exec): 子进程输出按 UTF-8 解码——toString() 平台默认字符集在非 UTF-8 locale 下损坏中文;附 printf 八进制转义回归测试
1 parent 3c4b58d commit e117095

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

‎src/main/java/io/github/easy4j/comfy/cli/ComfyCliExecutor.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -180,8 +180,8 @@ private ComfyCliResult runProcess(String stdin, String... args) {
180180
long startNanos = System.nanoTime();
181181
try {
182182
int exitCode = childEnv == null ? executor.execute(cmd) : executor.execute(cmd, childEnv);
183-
String out = stdout.toString().trim();
184-
String err = stderr.toString().trim();
183+
String out = stdout.toString(StandardCharsets.UTF_8).trim();
184+
String err = stderr.toString(StandardCharsets.UTF_8).trim();
185185
log.debug("comfy CLI executed: exitCode={}, stdout.len={}", exitCode, out.length());
186186
if (watchdog.killedProcess()) {
187187
return new ComfyCliResult(-1, out, "comfy CLI timed out after " + timeoutMs + " ms\n" + err);
@@ -194,8 +194,8 @@ private ComfyCliResult runProcess(String stdin, String... args) {
194194
// with the real exit code instead of discarding the output. The
195195
// deadline check makes the timeout verdict race-free even when
196196
// {@code watchdog.killedProcess()} has not observed the kill yet.
197-
String out = stdout.toString().trim();
198-
String err = stderr.toString().trim();
197+
String out = stdout.toString(StandardCharsets.UTF_8).trim();
198+
String err = stderr.toString(StandardCharsets.UTF_8).trim();
199199
boolean timedOut = watchdog.killedProcess()
200200
|| System.nanoTime() - startNanos >= timeoutMs * 1_000_000L;
201201
if (timedOut) {

‎src/test/java/io/github/easy4j/comfy/cli/ComfyCliExecutorTest.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,20 @@ void shouldReturnIoExceptionMessageWhenExecutableMissing() {
8888
assertTrue(result.getStderr() != null && !result.getStderr().isEmpty());
8989
}
9090

91+
@Test
92+
void shouldDecodeUtf8OutputRegardlessOfPlatformCharset() {
93+
// POSIX printf octal escapes emit 你好 as raw UTF-8 bytes; with a
94+
// platform-default-charset decode this corrupts on C-locale JVMs.
95+
// NOTE: the backslashes are doubled in Java source so the shell
96+
// receives single ones — an octal escape like \344 must be written
97+
// \\344 here or the compiler eats it at compile time.
98+
ComfyCliExecutor executor = new ComfyCliExecutor(configFor("/bin/sh"));
99+
100+
ComfyCliResult result = executor.execute("-c", "printf '\\344\\275\\240\\345\\245\\275'");
101+
102+
assertEquals("你好", result.getStdout());
103+
}
104+
91105
@Test
92106
void shouldIgnoreNullArguments() {
93107
ComfyCliExecutor executor = new ComfyCliExecutor(configFor(ECHO));

0 commit comments

Comments
 (0)