diff --git a/src/__tests__/index.test.ts b/src/__tests__/index.test.ts index e44cd52..f9cacdf 100644 --- a/src/__tests__/index.test.ts +++ b/src/__tests__/index.test.ts @@ -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( diff --git a/src/index.ts b/src/index.ts index a41a650..f464536 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 { - 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) diff --git a/src/invariants.ts b/src/invariants.ts new file mode 100644 index 0000000..ed8839e --- /dev/null +++ b/src/invariants.ts @@ -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') + } +}