Skip to content

Commit

Permalink
perf: try using realpathSync.native in Windows (#12580)
Browse files Browse the repository at this point in the history
Co-authored-by: sapphi-red <green@sapphi.red>
Co-authored-by: Bjorn Lu <bjorn@bjornlu.com>
  • Loading branch information
3 people committed Mar 26, 2023
1 parent 9925a72 commit 1cc99f8
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 additions & 2 deletions packages/vite/src/node/utils.ts
@@ -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

0 comments on commit 1cc99f8

Please sign in to comment.