From 92601db41d3cde34cbe06cca20c6ee915e5d7e77 Mon Sep 17 00:00:00 2001 From: patak Date: Sat, 25 Mar 2023 10:55:25 +0100 Subject: [PATCH] refactor: tryStatSync as util (#12575) --- packages/vite/src/node/optimizer/index.ts | 9 ++++----- packages/vite/src/node/plugins/resolve.ts | 9 +-------- packages/vite/src/node/utils.ts | 9 ++++++++- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index 580a6c8ceefba6..36a8bdc7be810c 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -23,6 +23,7 @@ import { removeDir, removeLeadingSlash, renameDir, + tryStatSync, writeFile, } from '../utils' import { transformWithEsbuild } from '../plugins/esbuild' @@ -1212,11 +1213,9 @@ export function getDepHash(config: ResolvedConfig, ssr: boolean): string { if (checkPatches) { // Default of https://github.com/ds300/patch-package const fullPath = path.join(path.dirname(lockfilePath), 'patches') - if (fs.existsSync(fullPath)) { - const stats = fs.statSync(fullPath) - if (stats.isDirectory()) { - content += stats.mtimeMs.toString() - } + const stat = tryStatSync(fullPath) + if (stat?.isDirectory()) { + content += stat.mtimeMs.toString() } } } diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 581b1a3368c4c8..3616a839c1098b 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -38,6 +38,7 @@ import { resolveFrom, safeRealpathSync, slash, + tryStatSync, } from '../utils' import { optimizedDepInfoFromFile, optimizedDepInfoFromId } from '../optimizer' import type { DepsOptimizer } from '../optimizer' @@ -648,14 +649,6 @@ function tryResolveRealFileWithExtensions( } } -function tryStatSync(file: string): fs.Stats | undefined { - try { - return fs.statSync(file, { throwIfNoEntry: false }) - } catch { - // Ignore errors - } -} - export type InternalResolveOptionsWithOverrideConditions = InternalResolveOptions & { /** diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 81ebda7b98e7db..078aa8ed99e4f3 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -392,6 +392,13 @@ export function isDefined(value: T | undefined | null): value is T { return value != null } +export function tryStatSync(file: string): fs.Stats | undefined { + try { + return fs.statSync(file, { throwIfNoEntry: false }) + } catch { + // Ignore errors + } +} interface LookupFileOptions { pathOnly?: boolean rootDir?: string @@ -405,7 +412,7 @@ export function lookupFile( ): string | undefined { for (const format of formats) { const fullPath = path.join(dir, format) - if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) { + if (tryStatSync(fullPath)?.isFile()) { const result = options?.pathOnly ? fullPath : fs.readFileSync(fullPath, 'utf-8')