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

refactor: replace duplicate code with tryStatSync #14461

Merged
merged 3 commits into from
Sep 25, 2023
Merged
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
15 changes: 10 additions & 5 deletions packages/vite/src/node/packages.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import fs from 'node:fs'
import path from 'node:path'
import { createRequire } from 'node:module'
import { createFilter, isInNodeModules, safeRealpathSync } from './utils'
import {
createFilter,
isInNodeModules,
safeRealpathSync,
tryStatSync,
} from './utils'
import type { Plugin } from './plugin'

let pnp: typeof import('pnpapi') | undefined
Expand Down Expand Up @@ -125,17 +130,17 @@ export function findNearestPackageData(
}

const pkgPath = path.join(basedir, 'package.json')
try {
if (fs.statSync(pkgPath, { throwIfNoEntry: false })?.isFile()) {
if (tryStatSync(pkgPath)?.isFile()) {
try {
const pkgData = loadPackageData(pkgPath)

if (packageCache) {
setFnpdCache(packageCache, pkgData, basedir, originalBasedir)
}

return pkgData
}
} catch {}
} catch {}
}

const nextBasedir = path.dirname(basedir)
if (nextBasedir === basedir) break
Expand Down
10 changes: 5 additions & 5 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,7 @@ export function isDefined<T>(value: T | undefined | null): value is T {

export function tryStatSync(file: string): fs.Stats | undefined {
try {
// The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
return fs.statSync(file, { throwIfNoEntry: false })
} catch {
// Ignore errors
Expand Down Expand Up @@ -501,12 +502,11 @@ export function generateCodeFrame(
}

export function isFileReadable(filename: string): boolean {
try {
// The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
if (!fs.statSync(filename, { throwIfNoEntry: false })) {
return false
}
if (!tryStatSync(filename)) {
return false
}

try {
// Check if current process has read permission to the file
fs.accessSync(filename, fs.constants.R_OK)

Expand Down