diff --git a/README.md b/README.md index 18c17b0..a6cb39b 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,15 @@ const filename = await resolveFile('README.md', { }) ``` +### `resolveLockFile` + +Find path to the lock file (`yarn.lock`, `package-lock.json`, `pnpm-lock.yaml`, `npm-shrinkwrap.json`) or throws an error. + +```js +import { resolveLockFile } from 'pkg-types' +const lockfile = await resolveFile('.') +``` + ## Types **Note:** In order to make types working, you need to install `typescript` as a devDependency. diff --git a/src/index.ts b/src/index.ts index 7f0b146..12e37d9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,3 +47,16 @@ export async function resolveTSConfig (id: string = process.cwd(), opts: Resolve const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, opts) return findNearestFile('tsconfig.json', { startingFrom: resolvedPath, ...opts }) } + +const lockFiles = ['yarn.lock', 'package-lock.json', 'pnpm-lock.yaml', 'npm-shrinkwrap.json'] + +export async function resolveLockfile (id: string = process.cwd(), opts: ResolveOptions = {}): Promise { + const resolvedPath = isAbsolute(id) ? id : await resolvePath(id, opts) + const _opts = { startingFrom: resolvedPath, ...opts } + for (const lockFile of lockFiles) { + try { + return await findNearestFile(lockFile, _opts) + } catch { } + } + throw new Error('No lockfile found from ' + id) +} diff --git a/test/fixture/sub/yarn.lock b/test/fixture/sub/yarn.lock new file mode 100644 index 0000000..e69de29 diff --git a/test/index.test.ts b/test/index.test.ts index 379b144..b2e2670 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -10,7 +10,8 @@ import { writePackageJSON, writeTSConfig, TSConfig, - ResolveOptions + ResolveOptions, + resolveLockfile } from '../src' const fixtureDir = resolve(dirname(fileURLToPath(import.meta.url)), 'fixture') @@ -87,3 +88,12 @@ describe('tsconfig.json', () => { // expectTypeOf(options.maxNodeModuleJsDepth).toEqualTypeOf() }) }) + +describe('resolveLockfile', () => { + it('works for subdir', async () => { + expect(await resolveLockfile(rFixture('./sub'))).to.equal(rFixture('./sub/yarn.lock')) + }) + it('works for root dir', async () => { + expect(await resolveLockfile(rFixture('.'))).to.equal(rFixture('../..', 'pnpm-lock.yaml')) + }) +})