Skip to content

Commit

Permalink
fix(info): use pkg-types to read package info
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Jan 6, 2025
1 parent 978569e commit b96a454
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 70 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@
"clipboardy": "^4.0.0",
"consola": "^3.3.3",
"defu": "^6.1.4",
"destr": "^2.0.3",
"eslint": "^9.17.0",
"execa": "^9.5.2",
"fuse.js": "^7.0.0",
Expand Down
3 changes: 0 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

62 changes: 11 additions & 51 deletions src/commands/info.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import os from 'node:os'
import { existsSync, readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { resolve } from 'pathe'
import { createJiti } from 'jiti'
import destr from 'destr'
import type { PackageJson } from 'pkg-types'
import { readPackageJSON } from 'pkg-types'
import { splitByCase } from 'scule'
import clipboardy from 'clipboardy'
import type { NuxtConfig, NuxtModule } from '@nuxt/schema'
import { defineCommand } from 'citty'
import { detectPackageManager } from 'nypm'
import { getPackageManagerVersion } from '../utils/packageManagers'
import { findup } from '../utils/fs'

import nuxiPkg from '../../package.json' assert { type: 'json' }
import { cwdArgs, legacyRootDirArgs } from './_shared'
Expand All @@ -33,13 +29,14 @@ export default defineCommand({
const nuxtConfig = await getNuxtConfig(cwd)

// Find nearest package.json
const { dependencies = {}, devDependencies = {} } = findPackage(cwd)
const { dependencies = {}, devDependencies = {} } = await readPackageJSON(cwd)

// Utils to query a dependency version
const getDepVersion = (name: string) =>
getPkg(name, cwd)?.version || dependencies[name] || devDependencies[name]
async function getDepVersion(name: string) {
return await readPackageJSON(name, { url: cwd }).then(r => r.version).catch(() => null) || dependencies[name] || devDependencies[name]
}

function listModules(arr: NonNullable<NuxtConfig['modules']> = []) {
async function listModules(arr: NonNullable<NuxtConfig['modules']> = []) {
const info: string[] = []
for (let m of arr) {
if (Array.isArray(m)) {
Expand All @@ -48,15 +45,15 @@ export default defineCommand({
const name = normalizeConfigModule(m, cwd)
if (name) {
const npmName = name!.split('/').splice(0, 2).join('/') // @foo/bar/baz => @foo/bar
const v = getDepVersion(npmName)
const v = await getDepVersion(npmName)
info.push('`' + (v ? `${name}@${v}` : name) + '`')
}
}
return info.join(', ')
}

// Check Nuxt version
const nuxtVersion = getDepVersion('nuxt') || getDepVersion('nuxt-nightly') || getDepVersion('nuxt-edge') || getDepVersion('nuxt3') || '-'
const nuxtVersion = await getDepVersion('nuxt') || await getDepVersion('nuxt-nightly') || await getDepVersion('nuxt-edge') || await getDepVersion('nuxt3') || '-'
const isLegacy = nuxtVersion.startsWith('2')
const builder = !isLegacy
? nuxtConfig.builder /* latest schema */ || '-'
Expand All @@ -77,14 +74,14 @@ export default defineCommand({
NodeVersion: process.version,
NuxtVersion: nuxtVersion,
CLIVersion: nuxiPkg.version,
NitroVersion: getDepVersion('nitropack'),
NitroVersion: await getDepVersion('nitropack'),
PackageManager: packageManager ?? 'unknown',
Builder: typeof builder === 'string' ? builder : 'custom',
UserConfig: Object.keys(nuxtConfig)
.map(key => '`' + key + '`')
.join(', '),
RuntimeModules: listModules(nuxtConfig.modules),
BuildModules: listModules((nuxtConfig as any /* nuxt v2 */).buildModules || []),
RuntimeModules: await listModules(nuxtConfig.modules),
BuildModules: await listModules((nuxtConfig as any /* nuxt v2 */).buildModules || []),
}

console.log('Working directory:', cwd)
Expand Down Expand Up @@ -176,40 +173,3 @@ async function getNuxtConfig(rootDir: string) {
return {}
}
}

function getPkg(name: string, rootDir: string) {
// Assume it is in {rootDir}/node_modules/${name}/package.json
let pkgPath = resolve(rootDir, 'node_modules', name, 'package.json')

// Try to resolve for more accuracy
const _require = createRequire(rootDir)
try {
pkgPath = _require.resolve(name + '/package.json')
}
catch {
// console.log('not found:', name)
}

return readJSONSync(pkgPath) as PackageJson
}

function findPackage(rootDir: string) {
return (
findup(rootDir, (dir) => {
const p = resolve(dir, 'package.json')
if (existsSync(p)) {
return readJSONSync(p) as PackageJson
}
}) || {}
)
}

function readJSONSync(filePath: string) {
try {
return destr(readFileSync(filePath, 'utf-8'))
}
catch {
// TODO: Warn error
return null
}
}
15 changes: 0 additions & 15 deletions src/utils/fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,3 @@ export async function touchFile(path: string) {
consola.error(`Failed to create file: ${path}`)
})
}

export function findup<T>(
rootDir: string,
fn: (dir: string) => T | undefined,
): T | null {
let dir = rootDir
while (dir !== dirname(dir)) {
const res = fn(dir)
if (res) {
return res
}
dir = dirname(dir)
}
return null
}

0 comments on commit b96a454

Please sign in to comment.