nx/packages/create-nx-plugin/bin/detect-invoked-package-manager.ts
Chau Tran 3bcfaf018d
feat(core): detect package manager used to invoke create-nx-(plugin|workspace) (#6749)
* feat(core): detect package manager used to invoke create-nx-(plugin|workspace)

When consumers create a new Workspace (or Plugin) using the create-nx-workspace (or
create-nx-plugin) generator, the package manager used to invoke the generator will be detected and
used as packageManager. For example: pnpx create-nx-workspace will use pnpm, yarn create
nx-workspace will use yarn. Explicit `--packageManager` flag will be priority over the detection.

* cleanup(core): reassign SELECTED_PM after each test run

* fix(core): augment args instead of hardcode --packageManager flag

* cleanup(core): use packageManagerLockFile instead of magic strings

* cleanup(core): fix typo in create-nx-workspace

* cleanup(core): ensure new workspace name for every test

* feat(core): detect package manager used to invoke create-nx-(plugin|workspace)

When consumers create a new Workspace (or Plugin) using the create-nx-workspace (or
create-nx-plugin) generator, the package manager used to invoke the generator will be detected and
used as packageManager. For example: pnpx create-nx-workspace will use pnpm, yarn create
nx-workspace will use yarn. Explicit `--packageManager` flag will be priority over the detection.

* cleanup(core): reassign SELECTED_PM after each test run

* fix(core): augment args instead of hardcode --packageManager flag

* cleanup(core): use packageManagerLockFile instead of magic strings

* cleanup(core): fix typo in create-nx-workspace

* cleanup(core): ensure new workspace name for every test

* fix(core): move detectInvokedPackageManager off of tao

Co-authored-by: Chau Tran <ctran@Chaus-MacBook-Pro.local>
2021-08-18 12:09:00 -04:00

31 lines
855 B
TypeScript

export type PackageManager = 'yarn' | 'pnpm' | 'npm';
/**
* Detects which package manager was used to invoke create-nx-{plugin|workspace} command
* based on the main Module process that invokes the command
* - npx returns 'npm'
* - pnpx returns 'pnpm'
* - yarn create returns 'yarn'
*
* Default to 'npm'
*/
export function detectInvokedPackageManager(): PackageManager {
let detectedPackageManager: PackageManager = 'npm';
// mainModule is deprecated since Node 14, fallback for older versions
const invoker = require.main || process['mainModule'];
// default to `npm`
if (!invoker) {
return detectedPackageManager;
}
for (const pkgManager of ['pnpm', 'yarn', 'npm'] as const) {
if (invoker.path.includes(pkgManager)) {
detectedPackageManager = pkgManager;
break;
}
}
return detectedPackageManager;
}