refactor: extract package root invariant

This commit is contained in:
Marc Cataford 2021-02-19 02:16:10 -05:00
parent da7571fba5
commit ef6fb52498
3 changed files with 19 additions and 8 deletions

View file

@ -53,7 +53,9 @@ describe('Packwatch', () => {
it('warns the user and errors if run away from package.json', async () => {
workspacePath = await prepareWorkspace()
await packwatch({ cwd: workspacePath })
await expect(async () =>
packwatch({ cwd: workspacePath }),
).rejects.toThrow('NOT_IN_PACKAGE_ROOT')
expect(mockLogger.mock.calls).toHaveLength(1)
expect(mockLogger.mock.calls[0][0]).toEqual(

View file

@ -7,6 +7,7 @@ import {
getPreviousPackageStats,
} from './utils'
import type { PackwatchArguments } from './index.d'
import { assertInPackageRoot } from './invariants'
const MANIFEST_FILENAME = '.packwatch.json'
@ -14,15 +15,9 @@ export default async function packwatch({
cwd,
isUpdatingManifest,
}: PackwatchArguments): Promise<void> {
const packageJsonPath = resolve(join(cwd, 'package.json'))
const manifestPath = resolve(join(cwd, MANIFEST_FILENAME))
if (!existsSync(packageJsonPath)) {
console.log(
'🤔 There is no package.json file here. Are you in the root directory of your project?',
)
return
}
assertInPackageRoot(cwd)
const currentStats = getCurrentPackageStats(cwd)

14
src/invariants.ts Normal file
View file

@ -0,0 +1,14 @@
import { existsSync } from 'fs'
import { join, resolve } from 'path'
export function assertInPackageRoot(cwd: string): void {
const packagePath = resolve(join(cwd, 'package.json'))
const packageJsonExists = existsSync(packagePath)
if (!packageJsonExists) {
console.log(
'🤔 There is no package.json file here. Are you in the root directory of your project?',
)
throw new Error('NOT_IN_PACKAGE_ROOT')
}
}