Skip to content

Commit

Permalink
feat: add getCurrentPackageManager (#9505)
Browse files Browse the repository at this point in the history
Co-authored-by: Niklas Mischkulnig <[email protected]>
  • Loading branch information
bestlyg and mischnic authored Jan 26, 2024
1 parent 642d9ca commit fdf495b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/core/package-manager/src/getCurrentPackageManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// @flow

export default function getCurrentPackageManager(
userAgent: ?string = process.env.npm_config_user_agent,
): ?{|name: string, version: string|} {
if (!userAgent) {
return undefined;
}

const pmSpec = userAgent.split(' ')[0];
const separatorPos = pmSpec.lastIndexOf('/');
const name = pmSpec.substring(0, separatorPos);
return {
name: name,
version: pmSpec.substring(separatorPos + 1),
};
}
10 changes: 10 additions & 0 deletions packages/core/package-manager/src/installPackage.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {Npm} from './Npm';
import {Yarn} from './Yarn';
import {Pnpm} from './Pnpm.js';
import {getConflictingLocalDependencies} from './utils';
import getCurrentPackageManager from './getCurrentPackageManager';
import validateModuleSpecifier from './validateModuleSpecifier';

async function install(
Expand Down Expand Up @@ -173,6 +174,15 @@ async function determinePackageInstaller(
return new Yarn();
}

let currentPackageManager = getCurrentPackageManager()?.name;
if (currentPackageManager === 'npm') {
return new Npm();
} else if (currentPackageManager === 'yarn') {
return new Yarn();
} else if (currentPackageManager === 'pnpm') {
return new Pnpm();
}

if (await Yarn.exists()) {
return new Yarn();
} else if (await Pnpm.exists()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// @flow
import assert from 'assert';
import getCurrentPackageManager from '../src/getCurrentPackageManager';

describe('getCurrentPackageManager', () => {
it('yarn', () => {
const npm_config_user_agent = 'yarn/1.22.21 npm/? node/v21.1.0 darwin x64';
const currentPackageManager = getCurrentPackageManager(
npm_config_user_agent,
);
assert(currentPackageManager?.name, 'yarn');
});
it('npm', () => {
const npm_config_user_agent =
'npm/10.2.0 node/v21.1.0 darwin x64 workspaces/true';
const currentPackageManager = getCurrentPackageManager(
npm_config_user_agent,
);
assert(currentPackageManager?.name, 'npm');
});
it('pnpm', () => {
const npm_config_user_agent = 'pnpm/8.14.2 npm/? node/v18.17.1 darwin x64';
const currentPackageManager = getCurrentPackageManager(
npm_config_user_agent,
);
assert(currentPackageManager?.name, 'pnpm');
});
});

0 comments on commit fdf495b

Please sign in to comment.