Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/main/java/picocli/CommandLine.java
Original file line number Diff line number Diff line change
Expand Up @@ -2187,6 +2187,25 @@ public int execute(String... args) {
}
} catch (Exception ex) {
return handleUnhandled(ex, this, getCommandSpec().exitCodeOnExecutionException());
} finally {
// #2514 print() does not auto-flush; ensure out/err buffers are flushed after execute
flush(this);
if (parseResult[0] != null) {
for (CommandLine parsed : parseResult[0].asCommandLineList()) {
flush(parsed);
}
}
}
}
private static void flush(CommandLine cmd) {
if (cmd == null) {
return;
}
if (cmd.out != null) {
cmd.out.flush();
}
if (cmd.err != null) {
cmd.err.flush();
}
}
private static int handleUnhandled(Exception ex, CommandLine cmd, int defaultExitCode) {
Expand Down
41 changes: 41 additions & 0 deletions src/test/java/picocli/ExecuteTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1626,5 +1626,46 @@ public int handleParseException(ParameterException ex, String[] args) throws Exc
}
assertEquals(expected, lines);
}

@Command(name = "demo")
static class Issue2514Command implements Callable<Integer> {
@Spec CommandSpec spec;
private final boolean writeErr;

Issue2514Command(boolean writeErr) {
this.writeErr = writeErr;
}

public Integer call() {
if (writeErr) {
spec.commandLine().getErr().print("err-hello");
} else {
spec.commandLine().getOut().print("hello");
}
return 0;
}
}

@Test
public void testExecuteFlushesOutAfterPrintWithoutNewline() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter out = CommandLine.newPrintWriter(baos, getStdoutEncoding());

int exit = new CommandLine(new Issue2514Command(false)).setOut(out).execute();

assertEquals(ExitCode.OK, exit);
assertEquals("hello", baos.toString());
}

@Test
public void testExecuteFlushesErrAfterPrintWithoutNewline() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter err = CommandLine.newPrintWriter(baos, getStdoutEncoding());

int exit = new CommandLine(new Issue2514Command(true)).setErr(err).execute();

assertEquals(ExitCode.OK, exit);
assertEquals("err-hello", baos.toString());
}
}