Skip to content

Commit e069be6

Browse files
authored
fix(monorepo-tools): fix precommit hook (#618)
This script was broken in some bizarre ways -- for example, it assumed that "monorepo root" and "root" were a) different and b) located at a fixed relative path to the filename of the precommit script, or it assumed that the repository would always have a `.gitmodules` file -- that make it very unclear to me how these issues went unnoticed for as long as they did.
1 parent 14b6804 commit e069be6

1 file changed

Lines changed: 19 additions & 8 deletions

File tree

packages/monorepo-tools/src/precommit.ts

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,35 @@ import pkgUp from 'pkg-up';
66
import { promisify } from 'util';
77
import { execFile } from 'child_process';
88
import * as fs from 'fs/promises';
9+
import findUp from 'find-up';
910
const execFileAsync = promisify(execFile);
1011

11-
const monorepoRoot = path.resolve(__dirname, '..', '..');
12-
const repoRoot = path.resolve(monorepoRoot, '..');
13-
1412
async function main(fileList: string[]) {
13+
const monorepoGit = await findUp('.git', {
14+
cwd: __dirname,
15+
type: 'directory',
16+
});
17+
if (!monorepoGit) {
18+
throw new Error(
19+
`Could not find .git directory for monorepo starting from ${__dirname}`,
20+
);
21+
}
22+
const monorepoRoot = path.dirname(monorepoGit);
23+
1524
const filesToPrettify: string[] = [];
1625

1726
const submodules = [
1827
...(
19-
await fs.readFile(path.resolve(repoRoot, '.gitmodules'), {
20-
encoding: 'utf8',
21-
})
28+
await fs
29+
.readFile(path.resolve(monorepoRoot, '.gitmodules'), {
30+
encoding: 'utf8',
31+
})
32+
.catch(() => '')
2233
).matchAll(/^\s+path = (?<submodulePath>.*)$/gm),
2334
]
2435
.map((r) => r.groups?.submodulePath)
25-
.filter((p) => p)
26-
.map((p) => path.resolve(repoRoot, p!));
36+
.filter((p): p is string => !!p)
37+
.map((p) => path.resolve(monorepoRoot, p));
2738

2839
await Promise.all(
2940
fileList.map(async (filePath) => {

0 commit comments

Comments
 (0)