Skip to content

Bug: PosixCommands.tail counts newlines rather than lines #1787

@freva

Description

@freva

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();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions