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: simplify lookupFile #12585

Merged
merged 2 commits into from
Mar 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -927,8 +927,9 @@ export async function loadConfigFromFile(
} else {
// check package.json for type: "module" and set `isESM` to true
try {
const pkg = lookupFile(configRoot, ['package.json'])
isESM = !!pkg && JSON.parse(pkg).type === 'module'
const pkg = lookupFile(configRoot, 'package.json')
isESM =
!!pkg && JSON.parse(fs.readFileSync(pkg, 'utf-8')).type === 'module'
} catch (e) {}
}

Expand Down
13 changes: 6 additions & 7 deletions packages/vite/src/node/env.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import fs from 'node:fs'
import path from 'node:path'
import { parse } from 'dotenv'
import { expand } from 'dotenv-expand'
import { arraify, lookupFile } from './utils'
import { arraify, tryStatSync } from './utils'
import type { UserConfig } from './config'

export function loadEnv(
Expand All @@ -26,12 +27,10 @@ export function loadEnv(

const parsed = Object.fromEntries(
envFiles.flatMap((file) => {
const path = lookupFile(envDir, [file], {
pathOnly: true,
rootDir: envDir,
})
if (!path) return []
return Object.entries(parse(fs.readFileSync(path)))
const filePath = path.join(envDir, file)
if (!tryStatSync(filePath)?.isFile()) return []

return Object.entries(parse(fs.readFileSync(filePath)))
Comment on lines +30 to +33
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were passing rootDir: envDir here, so only level would be checked by lookupFile but the call makes it seems env dirs are being looked up in the fs. Replaced it with a single tryStatSync

}),
)

Expand Down
21 changes: 15 additions & 6 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
flattenId,
getHash,
isOptimizable,
lookupFile,
normalizeId,
normalizePath,
removeDir,
Expand Down Expand Up @@ -1199,13 +1198,23 @@ const lockfileFormats = [
{ name: 'pnpm-lock.yaml', checkPatches: false }, // Included in lockfile
{ name: 'bun.lockb', checkPatches: true },
]
const lockfileNames = lockfileFormats.map((l) => l.name)

function findNearestLockfile(dir: string) {
while (dir) {
for (const fileName of lockfileNames) {
const fullPath = path.join(dir, fileName)
if (tryStatSync(fullPath)?.isFile()) return fullPath
}
const parentDir = path.dirname(dir)
if (parentDir === dir) return

dir = parentDir
}
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can have a specialized version of the lookup here, this was the reason the second argument to lookupFile was an array in all other places.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think It'd still prefer the array version instead so we don't have two similar code 🤔 There shouldn't be a huge perf hit for the case where an array isn't needed too.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, the function isn't used much now anyways


export function getDepHash(config: ResolvedConfig, ssr: boolean): string {
const lockfilePath = lookupFile(
config.root,
lockfileFormats.map((l) => l.name),
{ pathOnly: true },
)
const lockfilePath = findNearestLockfile(config.root)
let content = lockfilePath ? fs.readFileSync(lockfilePath, 'utf-8') : ''
if (lockfilePath) {
const lockfileName = path.basename(lockfilePath)
Expand Down
6 changes: 5 additions & 1 deletion packages/vite/src/node/ssr/ssrExternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,11 @@ function cjsSsrCollectExternals(
seen: Set<string>,
logger: Logger,
) {
const rootPkgContent = lookupFile(root, ['package.json'])
const rootPkgPath = lookupFile(root, 'package.json')
if (!rootPkgPath) {
return
}
const rootPkgContent = fs.readFileSync(rootPkgPath, 'utf-8')
if (!rootPkgContent) {
return
}
Expand Down
30 changes: 9 additions & 21 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,28 +387,16 @@ export function tryStatSync(file: string): fs.Stats | undefined {
// Ignore errors
}
}
interface LookupFileOptions {
pathOnly?: boolean
rootDir?: string
}

export function lookupFile(
dir: string,
formats: string[],
options?: LookupFileOptions,
): string | undefined {
for (const format of formats) {
const fullPath = path.join(dir, format)
if (tryStatSync(fullPath)?.isFile()) {
return options?.pathOnly ? fullPath : fs.readFileSync(fullPath, 'utf-8')
}
}
const parentDir = path.dirname(dir)
if (
parentDir !== dir &&
(!options?.rootDir || parentDir.startsWith(options?.rootDir))
) {
return lookupFile(parentDir, formats, options)
export function lookupFile(dir: string, fileName: string): string | undefined {
while (dir) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the recursion, this is the same scheme used by @bluwy in findNearestPackageData.

const fullPath = path.join(dir, fileName)
if (tryStatSync(fullPath)?.isFile()) return fullPath

const parentDir = path.dirname(dir)
if (parentDir === dir) return

dir = parentDir
}
}

Expand Down