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