Skip to content

Commit f2cbdfb

Browse files
committed
fix(filesystem): preserve utf8 across chunk boundaries
1 parent 562feeb commit f2cbdfb

2 files changed

Lines changed: 31 additions & 26 deletions

File tree

‎src/filesystem/__tests__/lib.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,26 @@ describe('Lib Functions', () => {
718718
});
719719

720720
describe('headFile', () => {
721+
it('preserves UTF-8 characters split across read chunks', async () => {
722+
const content = Buffer.concat([
723+
Buffer.from('a'.repeat(1023)),
724+
Buffer.from('中\nsecond line', 'utf8'),
725+
]);
726+
const mockFileHandle = {
727+
read: vi.fn(async (target: Buffer, _offset: number, length: number, position: number) => {
728+
const bytes = content.subarray(position, position + length);
729+
bytes.copy(target, 0);
730+
return { bytesRead: bytes.length };
731+
}),
732+
close: vi.fn().mockResolvedValue(undefined),
733+
} as any;
734+
mockFs.open.mockResolvedValue(mockFileHandle);
735+
736+
const result = await headFile('/test/file.txt', 1);
737+
738+
expect(result).toBe('a'.repeat(1023) + '中');
739+
});
740+
721741
it('opens file for reading', async () => {
722742
// Mock file handle with proper typing
723743
const mockFileHandle = {

‎src/filesystem/lib.ts‎

Lines changed: 11 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { diffLines, createTwoFilesPatch } from 'diff';
66
import { minimatch } from 'minimatch';
77
import { normalizePath, expandHome } from './path-utils.js';
88
import { isPathWithinAllowedDirectories } from './path-validation.js';
9+
import { StringDecoder } from 'string_decoder';
910

1011
// Global allowed directories - set by the main module
1112
let allowedDirectories: string[] = [];
@@ -308,42 +309,24 @@ export async function tailFile(filePath: string, numLines: number): Promise<stri
308309
// Open file for reading
309310
const fileHandle = await fs.open(filePath, 'r');
310311
try {
311-
const lines: string[] = [];
312312
let position = fileSize;
313313
let chunk = Buffer.alloc(CHUNK_SIZE);
314-
let linesFound = 0;
315-
let remainingText = '';
314+
let rawBytes = Buffer.alloc(0);
316315

317316
// Read chunks from the end of the file until we have enough lines
318-
while (position > 0 && linesFound < numLines) {
317+
while (position > 0 && rawBytes.toString('binary').split('\n').length <= numLines) {
319318
const size = Math.min(CHUNK_SIZE, position);
320319
position -= size;
321320

322321
const { bytesRead } = await fileHandle.read(chunk, 0, size, position);
323322
if (!bytesRead) break;
324323

325-
// Get the chunk as a string and prepend any remaining text from previous iteration
326-
const readData = chunk.slice(0, bytesRead).toString('utf-8');
327-
const chunkText = readData + remainingText;
328-
329-
// Split by newlines and count
330-
const chunkLines = normalizeLineEndings(chunkText).split('\n');
331-
332-
// If this isn't the end of the file, the first line is likely incomplete
333-
// Save it to prepend to the next chunk
334-
if (position > 0) {
335-
remainingText = chunkLines[0];
336-
chunkLines.shift(); // Remove the first (incomplete) line
337-
}
338-
339-
// Add lines to our result (up to the number we need)
340-
for (let i = chunkLines.length - 1; i >= 0 && linesFound < numLines; i--) {
341-
lines.unshift(chunkLines[i]);
342-
linesFound++;
343-
}
324+
// Keep bytes intact while reading backwards. Decoding each chunk can
325+
// split a multi-byte UTF-8 character at the chunk boundary.
326+
rawBytes = Buffer.concat([chunk.slice(0, bytesRead), rawBytes]);
344327
}
345-
346-
return lines.join('\n');
328+
const lines = normalizeLineEndings(rawBytes.toString('utf-8')).split('\n');
329+
return lines.slice(Math.max(0, lines.length - numLines)).join('\n');
347330
} finally {
348331
await fileHandle.close();
349332
}
@@ -357,13 +340,14 @@ export async function headFile(filePath: string, numLines: number): Promise<stri
357340
let buffer = '';
358341
let bytesRead = 0;
359342
const chunk = Buffer.alloc(1024); // 1KB buffer
343+
const decoder = new StringDecoder('utf8');
360344

361345
// Read chunks and count lines until we have enough or reach EOF
362346
while (lines.length < numLines) {
363347
const result = await fileHandle.read(chunk, 0, chunk.length, bytesRead);
364348
if (result.bytesRead === 0) break; // End of file
365349
bytesRead += result.bytesRead;
366-
buffer += chunk.slice(0, result.bytesRead).toString('utf-8');
350+
buffer += decoder.write(chunk.slice(0, result.bytesRead));
367351

368352
const newLineIndex = buffer.lastIndexOf('\n');
369353
if (newLineIndex !== -1) {
@@ -376,6 +360,7 @@ export async function headFile(filePath: string, numLines: number): Promise<stri
376360
}
377361
}
378362

363+
buffer += decoder.end();
379364
// If there is leftover content and we still need lines, add it
380365
if (buffer.length > 0 && lines.length < numLines) {
381366
lines.push(buffer);

0 commit comments

Comments
 (0)