Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: try using realpathSync.native in Windows #12580

Merged
merged 3 commits into from
Mar 26, 2023
Merged
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
46 changes: 44 additions & 2 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { exec } from 'node:child_process'
import { createHash } from 'node:crypto'
import { promisify } from 'node:util'
import { URL, URLSearchParams } from 'node:url'
Expand Down Expand Up @@ -597,10 +598,51 @@ export const renameDir = isWindows ? promisify(gracefulRename) : fs.renameSync
// `fs.realpathSync.native` resolves differently in Windows network drive,
// causing file read errors. skip for now.
// https://github.com/nodejs/node/issues/37737
export const safeRealpathSync = isWindows
? fs.realpathSync
export let safeRealpathSync = isWindows
? windowsSafeRealPathSync
: fs.realpathSync.native

// Based on https://github.com/larrybahr/windows-network-drive
// MIT License, Copyright (c) 2017 Larry Bahr
const windowsNetworkMap = new Map()
function windowsMappedRealpathSync(path: string) {
const realPath = fs.realpathSync.native(path)
if (realPath.startsWith('\\\\')) {
for (const [network, volume] of windowsNetworkMap) {
if (realPath.startsWith(network)) return realPath.replace(network, volume)
}
}
return realPath
}
const parseNetUseRE = /^(\w+) +(\w:) +([^ ]+)\s/
let firstSafeRealPathSyncRun = false

function windowsSafeRealPathSync(path: string): string {
if (!firstSafeRealPathSyncRun) {
optimizeSafeRealPathSync()
firstSafeRealPathSyncRun = true
}
return fs.realpathSync(path)
}

function optimizeSafeRealPathSync() {
exec('net use', (error, stdout) => {
if (error) return
const lines = stdout.split('\n')
// OK Y: \\NETWORKA\Foo Microsoft Windows Network
// OK Z: \\NETWORKA\Bar Microsoft Windows Network
for (const line of lines) {
const m = line.match(parseNetUseRE)
if (m) windowsNetworkMap.set(m[3], m[2])
}
if (windowsNetworkMap.size === 0) {
safeRealpathSync = fs.realpathSync.native
} else {
safeRealpathSync = windowsMappedRealpathSync
}
})
}

export function ensureWatchedFile(
watcher: FSWatcher,
file: string | null,
Expand Down