Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 42 additions & 7 deletions packages/cli/src/utils/commands.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,48 @@
import { spawnSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'

const DEFAULT_PACKAGE_MANAGER = 'yarn'

const supportedPackageManagers = {
yarn: true,
pnpm: true,
bun: true,
npm: true,
}

// Retrieves the package manager based on the developer lockfile, using `ni`.
export function getPreferredPackageManager() {
const agent = spawnSync('na', ['?'], {
encoding: 'utf8',
shell: true,
}).stdout.trim()
const packageJsonPath = path.resolve(process.cwd(), 'package.json')

if (!existsSync(packageJsonPath)) {
console.warn(
`package.json not found! Using default package manager: ${DEFAULT_PACKAGE_MANAGER}.`
)
return DEFAULT_PACKAGE_MANAGER // TODO threat errors
}

const fileContent = readFileSync(packageJsonPath)
const { packageManager } = JSON.parse(fileContent.toString())

if (!packageManager) {
console.warn(
`Corepack not enabled! Using default package manager: ${DEFAULT_PACKAGE_MANAGER}.`
)
return DEFAULT_PACKAGE_MANAGER // corepack not enabled
}

const [packageManagerName] = packageManager.split('@')

if (agent === '') return 'yarn' // Default to Yarn
if (
!supportedPackageManagers[
packageManagerName as keyof typeof supportedPackageManagers
]
) {
console.warn(
`${packageManagerName} is not supported: Use one of ${Object.keys(supportedPackageManagers).join(',')}.`
)
return DEFAULT_PACKAGE_MANAGER // TODO threat errors
}

return agent
return packageManagerName
}
Loading