rsnext/packages/next/lib/get-package-version.ts
Shu Ding 37b859f36d
Small code improvements (#37227)
Two small things noticed today. When calling `getDependencies` concurrently (which is happening right now) the cache doesn't work as it's after the `await`, so here we move it to cache the promise instead. Also `NUM_OF_MICROSEC_IN_SEC` isn't accurate and it should be `NANOSEC` actually.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
2022-05-26 23:19:47 +00:00

64 lines
1.5 KiB
TypeScript

import { promises as fs } from 'fs'
import findUp from 'next/dist/compiled/find-up'
import JSON5 from 'next/dist/compiled/json5'
import * as path from 'path'
type PackageJsonDependencies = {
dependencies: Record<string, string>
devDependencies: Record<string, string>
}
let cachedDeps: Promise<PackageJsonDependencies>
function getDependencies({
cwd,
}: {
cwd: string
}): Promise<PackageJsonDependencies> {
if (cachedDeps) {
return cachedDeps
}
return (cachedDeps = (async () => {
const configurationPath: string | undefined = await findUp('package.json', {
cwd,
})
if (!configurationPath) {
return { dependencies: {}, devDependencies: {} }
}
const content = await fs.readFile(configurationPath, 'utf-8')
const packageJson: any = JSON5.parse(content)
const { dependencies = {}, devDependencies = {} } = packageJson || {}
return { dependencies, devDependencies }
})())
}
export async function getPackageVersion({
cwd,
name,
}: {
cwd: string
name: string
}): Promise<string | null> {
const { dependencies, devDependencies } = await getDependencies({ cwd })
if (!(dependencies[name] || devDependencies[name])) {
return null
}
const cwd2 =
cwd.endsWith(path.posix.sep) || cwd.endsWith(path.win32.sep)
? cwd
: `${cwd}/`
try {
const targetPath = require.resolve(`${name}/package.json`, {
paths: [cwd2],
})
const targetContent = await fs.readFile(targetPath, 'utf-8')
return JSON5.parse(targetContent).version ?? null
} catch {
return null
}
}