Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(package-manager): use npm_config_user_agent env var #510

Merged
merged 1 commit into from
Dec 30, 2023
Merged
Show file tree
Hide file tree
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
6 changes: 6 additions & 0 deletions .changeset/tough-news-allow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'onerepo': minor
'@onerepo/package-manager': minor
---

Potentially speed up package manager determination by using the `npm_config_user_agent` environment variable.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ import path from 'path';
import { getPackageManagerName } from '../get-package-manager';

describe('getPackageManagerName', () => {
let ua: string | undefined;
beforeAll(() => {
ua = process.env.npm_config_user_agent;
});

afterAll(() => {
process.env.npm_config_user_agent = ua;
});

test.concurrent.each([
['yarn', 'yarn@latest'],
['yarn', '[email protected]'],
Expand All @@ -22,6 +31,16 @@ describe('getPackageManagerName', () => {
['yarn', 'yarnrcyml'],
['npm', 'unknown'],
])('gets "%s" from %s fixture', async (expected, fixture) => {
process.env.npm_config_user_agent = undefined;
expect(getPackageManagerName(path.join(__dirname, '__fixtures__', fixture))).toEqual(expected);
});

test.each([
['pnpm', 'pnpm/7.29.3 npm/? node/v20.5.1 darwin x64'],
['yarn', 'yarn/3.3.1 npm/? node/v20.5.1 darwin x64'],
['npm', 'npm/9.8.0 node/v20.5.1 darwin x64 workspaces/false'],
])('gets %s from the npm_config_user_agent var', async (expected, envvar) => {
process.env.npm_config_user_agent = envvar;
expect(getPackageManagerName('.')).toEqual(expected);
});
});
11 changes: 11 additions & 0 deletions modules/package-manager/src/get-package-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ export function getPackageManagerName(cwd: string, fromPkgJson?: string): 'npm'
}
}

const ua = process.env.npm_config_user_agent;
if (ua?.includes('yarn/')) {
return 'yarn';
}
if (ua?.includes('pnpm/')) {
return 'pnpm';
}
if (ua?.includes('npm/')) {
return 'npm';
}

return guessPackageManager(cwd) ?? 'npm';
}

Expand Down