Bug: PosixCommands.tail counts newlines rather than lines (original) (raw)
PosixCommands.tail -n N returns one more line than requested when the input does not end with a newline character. The implementation counts newline characters rather than lines.
@TempDir Path tempDir;
@Test void tail_noTrailingNewline_returnsOneExtraLine() throws Exception { String input = "a\nb\nc\nd\ne"; String actual = runTail(input, "tail", "-n", "2"); assertEquals("d\ne", actual); // Fails, returns "c\nd\ne" instead of "d\ne" }
@Test void tail_withTrailingNewline_returnsCorrectLines() throws Exception { String input = "a\nb\nc\nd\ne\n"; String actual = runTail(input, "tail", "-n", "2"); assertEquals("d\ne\n", actual); // Fails, returns "d\ne" instead of "d\ne\n" }
private String runTail(String input, String... args) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); try (DumbTerminal terminal = new DumbTerminal(in, out)) { PosixCommands.Context ctx = new PosixCommands.Context( in, new PrintStream(out), new PrintStream(new ByteArrayOutputStream()), tempDir, terminal, k -> null);
PosixCommands.tail(ctx, args);
}
return out.toString(StandardCharsets.UTF_8).trim();}