|
| 1 | +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; |
| 2 | +import { tmpdir } from 'node:os'; |
| 3 | +import { join } from 'node:path'; |
| 4 | +import { detectPackageManager as detectFromDir } from 'nypm'; |
| 5 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 6 | + |
| 7 | +import { detectProjectPackageManager } from './detect-package-manager'; |
| 8 | + |
| 9 | +// nypm's own fallback sniffs process.argv[1] for a package manager's name, which |
| 10 | +// spuriously matches 'pnpm' in this pnpm-managed monorepo (test runner path |
| 11 | +// contains `.pnpm`). Spy on it so the "nothing detectable" case below tests our |
| 12 | +// fallback instead of that environment artifact. |
| 13 | +vi.mock('nypm', async (importOriginal) => { |
| 14 | + const actual = await importOriginal<typeof import('nypm')>(); |
| 15 | + |
| 16 | + return { ...actual, detectPackageManager: vi.fn(actual.detectPackageManager) }; |
| 17 | +}); |
| 18 | + |
| 19 | +let projectDir: string; |
| 20 | + |
| 21 | +beforeEach(() => { |
| 22 | + projectDir = mkdtempSync(join(tmpdir(), 'catalyst-detect-pm-')); |
| 23 | +}); |
| 24 | + |
| 25 | +afterEach(() => { |
| 26 | + rmSync(projectDir, { recursive: true, force: true }); |
| 27 | +}); |
| 28 | + |
| 29 | +describe('detectProjectPackageManager', () => { |
| 30 | + it('detects pnpm from a pnpm-lock.yaml', async () => { |
| 31 | + writeFileSync(join(projectDir, 'pnpm-lock.yaml'), ''); |
| 32 | + |
| 33 | + await expect(detectProjectPackageManager(projectDir)).resolves.toBe('pnpm'); |
| 34 | + }); |
| 35 | + |
| 36 | + it('detects npm from a package-lock.json', async () => { |
| 37 | + writeFileSync(join(projectDir, 'package-lock.json'), '{}'); |
| 38 | + |
| 39 | + await expect(detectProjectPackageManager(projectDir)).resolves.toBe('npm'); |
| 40 | + }); |
| 41 | + |
| 42 | + it('detects yarn from a yarn.lock', async () => { |
| 43 | + writeFileSync(join(projectDir, 'yarn.lock'), ''); |
| 44 | + |
| 45 | + await expect(detectProjectPackageManager(projectDir)).resolves.toBe('yarn'); |
| 46 | + }); |
| 47 | + |
| 48 | + it('detects bun from a bun.lock', async () => { |
| 49 | + writeFileSync(join(projectDir, 'bun.lock'), ''); |
| 50 | + |
| 51 | + await expect(detectProjectPackageManager(projectDir)).resolves.toBe('bun'); |
| 52 | + }); |
| 53 | + |
| 54 | + it('honors the package.json packageManager field', async () => { |
| 55 | + writeFileSync( |
| 56 | + join(projectDir, 'package.json'), |
| 57 | + JSON.stringify({ packageManager: 'yarn@4.0.0' }), |
| 58 | + ); |
| 59 | + |
| 60 | + await expect(detectProjectPackageManager(projectDir)).resolves.toBe('yarn'); |
| 61 | + }); |
| 62 | + |
| 63 | + it('falls back to npm when nothing is detectable', async () => { |
| 64 | + vi.mocked(detectFromDir).mockResolvedValueOnce(undefined); |
| 65 | + |
| 66 | + await expect(detectProjectPackageManager(projectDir)).resolves.toBe('npm'); |
| 67 | + }); |
| 68 | +}); |
0 commit comments