Skip to content

Commit

Permalink
feat: add resolveLockfile (#14)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
danielroe and pi0 committed Sep 6, 2022
1 parent 0d8319e commit 6b12948
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
9 changes: 9 additions & 0 deletions README.md
Expand Up @@ -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.
Expand Down
13 changes: 13 additions & 0 deletions src/index.ts
Expand Up @@ -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<string> {
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)
}
Empty file added test/fixture/sub/yarn.lock
Empty file.
12 changes: 11 additions & 1 deletion test/index.test.ts
Expand Up @@ -10,7 +10,8 @@ import {
writePackageJSON,
writeTSConfig,
TSConfig,
ResolveOptions
ResolveOptions,
resolveLockfile
} from '../src'

const fixtureDir = resolve(dirname(fileURLToPath(import.meta.url)), 'fixture')
Expand Down Expand Up @@ -87,3 +88,12 @@ describe('tsconfig.json', () => {
// expectTypeOf(options.maxNodeModuleJsDepth).toEqualTypeOf<number | undefined>()
})
})

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'))
})
})

0 comments on commit 6b12948

Please sign in to comment.