fix: prefer native realpath for canonical paths

This commit is contained in:
TabishB
2026-04-14 17:31:35 +10:00
parent 7d07101363
commit 493605756f
2 changed files with 29 additions and 4 deletions
+11 -3
View File
@@ -1,6 +1,9 @@
import { promises as fs, constants as fsConstants, realpathSync } from 'fs';
import * as nodeFs from 'fs';
import path from 'path';
const fs = nodeFs.promises;
const { constants: fsConstants } = nodeFs;
function isMarkerOnOwnLine(content: string, markerIndex: number, markerLength: number): boolean {
let leftIndex = markerIndex - 1;
while (leftIndex >= 0 && content[leftIndex] !== '\n') {
@@ -56,9 +59,14 @@ export class FileSystemUtils {
*/
static canonicalizeExistingPath(targetPath: string): string {
try {
return realpathSync(targetPath);
// Prefer the native resolver so Windows short-path aliases are expanded.
return nodeFs.realpathSync.native(targetPath);
} catch {
return path.resolve(targetPath);
try {
return nodeFs.realpathSync(targetPath);
} catch {
return path.resolve(targetPath);
}
}
}
+18 -1
View File
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as nodeFs from 'fs';
import { promises as fs } from 'fs';
import path from 'path';
import os from 'os';
@@ -92,6 +93,22 @@ describe('FileSystemUtils', () => {
});
});
describe('canonicalizeExistingPath', () => {
it('should prefer the native realpath resolver when available', async () => {
const filePath = path.join(testDir, 'canonical.txt');
await fs.writeFile(filePath, 'content');
const nativeSpy = vi.spyOn(nodeFs.realpathSync, 'native');
const resolved = FileSystemUtils.canonicalizeExistingPath(filePath);
expect(nativeSpy).toHaveBeenCalledWith(filePath);
expect(resolved).toBe(nodeFs.realpathSync.native(filePath));
nativeSpy.mockRestore();
});
});
describe('writeFile', () => {
it('should write content to file', async () => {
const filePath = path.join(testDir, 'output.txt');