Skip to content

Commit

Permalink
fix(cpa): detect package manager from command execution environment (#…
Browse files Browse the repository at this point in the history
…8087)

Previously, on some machines this command:
`pnpx create-payload-app@beta app` created a project using `npm`,
instead of `pnpm`, the same with `yarn`.

Also, the way we detected the package manager was always prioritizing
`pnpm`, even if they executed the command with `yarn` / `npm`. Now we
are relying only on from which package manager user executed
`create-payload-app`.

The code for detection is grabbed from create-next-app
https://github.com/vercel/next.js/blob/canary/packages/create-next-app/helpers/get-pkg-manager.ts
  • Loading branch information
r1tsuu authored Sep 6, 2024
1 parent b69826a commit c624661
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
37 changes: 18 additions & 19 deletions packages/create-payload-app/src/lib/get-package-manager.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import execa from 'execa'
import fse from 'fs-extra'

import type { CliArgs, PackageManager } from '../types.js'

export async function getPackageManager(args: {
cliArgs?: CliArgs
projectDir: string
}): Promise<PackageManager> {
export function getPackageManager(args: { cliArgs?: CliArgs; projectDir: string }): PackageManager {
const { cliArgs, projectDir } = args

try {
Expand All @@ -21,14 +17,8 @@ export async function getPackageManager(args: {
} else if (cliArgs?.['--use-bun'] || fse.existsSync(`${projectDir}/bun.lockb`)) {
detected = 'bun'
} else {
// Otherwise check for existing commands
if (await commandExists('pnpm')) {
detected = 'pnpm'
} else if (await commandExists('yarn')) {
detected = 'yarn'
} else {
detected = 'npm'
}
// Otherwise check the execution environment
detected = getEnvironmentPackageManager()
}

return detected
Expand All @@ -37,11 +27,20 @@ export async function getPackageManager(args: {
}
}

async function commandExists(command: string): Promise<boolean> {
try {
await execa.command(`command -v ${command}`)
return true
} catch {
return false
function getEnvironmentPackageManager(): PackageManager {
const userAgent = process.env.npm_config_user_agent || ''

if (userAgent.startsWith('yarn')) {
return 'yarn'
}

if (userAgent.startsWith('pnpm')) {
return 'pnpm'
}

if (userAgent.startsWith('bun')) {
return 'bun'
}

return 'npm'
}
2 changes: 1 addition & 1 deletion packages/create-payload-app/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export class Main {
? path.dirname(nextConfigPath)
: path.resolve(process.cwd(), slugify(projectName))

const packageManager = await getPackageManager({ cliArgs: this.args, projectDir })
const packageManager = getPackageManager({ cliArgs: this.args, projectDir })

if (nextConfigPath) {
p.log.step(
Expand Down

0 comments on commit c624661

Please sign in to comment.