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
27 changes: 27 additions & 0 deletions src/filesystem/__tests__/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,33 @@ describe('Lib Functions', () => {
expect(mockFileHandle.close).toHaveBeenCalled();
});

it('ignores trailing newline when returning last lines', async () => {
const content = Buffer.from('line1\nline2\n');
mockFs.stat.mockResolvedValue({ size: content.length } as any);

const mockFileHandle = {
read: vi.fn(
(buffer: Buffer, offset: number, length: number, position: number) => {
const bytesRead = content.copy(
buffer,
offset,
position,
Math.min(position + length, content.length)
);
return Promise.resolve({ bytesRead });
}
),
close: vi.fn().mockResolvedValue(undefined)
} as any;

mockFs.open.mockResolvedValue(mockFileHandle);

const result = await tailFile('/test/file.txt', 1);

expect(result).toBe('line2');
expect(mockFileHandle.close).toHaveBeenCalled();
});

it('handles read errors gracefully', async () => {
mockFs.stat.mockResolvedValue({ size: 100 } as any);

Expand Down
8 changes: 7 additions & 1 deletion src/filesystem/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ export async function tailFile(filePath: string, numLines: number): Promise<stri
let chunk = Buffer.alloc(CHUNK_SIZE);
let linesFound = 0;
let remainingText = '';
let isLastChunk = true;

// Read chunks from the end of the file until we have enough lines
while (position > 0 && linesFound < numLines) {
Expand All @@ -311,7 +312,12 @@ export async function tailFile(filePath: string, numLines: number): Promise<stri
const chunkText = readData + remainingText;

// Split by newlines and count
const chunkLines = normalizeLineEndings(chunkText).split('\n');
const normalizedChunkText = normalizeLineEndings(chunkText);
const chunkLines = normalizedChunkText.split('\n');
if (isLastChunk && normalizedChunkText.endsWith('\n')) {
chunkLines.pop();
}
isLastChunk = false;

// If this isn't the end of the file, the first line is likely incomplete
// Save it to prepend to the next chunk
Expand Down