Repository navigation
Expand file tree
/
Copy pathcheck-git-hooks.mjs
More file actions
86 lines (75 loc) · 2.52 KB
/
Copy pathcheck-git-hooks.mjs
File metadata and controls
86 lines (75 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env node
/**
* Warn when the Husky Git hooks are not installed (#3493).
*
* `core.hooksPath` points at `.husky/_`, which only `npm run prepare` creates.
* A checkout installed with `npm ci --ignore-scripts` (worktrees, bots) has no
* `.husky/_`, and Git then runs no hooks at all, without any warning. This
* check makes that visible.
*
* Usage: node scripts/check-git-hooks.mjs [--strict]
* Exits 0 with a warning by default; `--strict` exits 1 instead.
* Skipped in CI, where hooks are not used and workflows are the gate.
*/
import { execFileSync } from 'node:child_process';
import { accessSync, constants, existsSync, statSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const HOOKS = ['pre-commit', 'pre-push'];
function git(...args) {
try {
return execFileSync('git', args, {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
} catch {
return '';
}
}
function isExecutableFile(file) {
try {
if (!statSync(file).isFile()) return false;
if (process.platform !== 'win32') accessSync(file, constants.X_OK);
return true;
} catch {
return false;
}
}
export function findProblems() {
const root = git('rev-parse', '--show-toplevel');
if (!root) return [];
const hooksPath = git('config', 'core.hooksPath');
if (!hooksPath) {
return ['core.hooksPath is not set, so the Husky hooks are not active.'];
}
const expectedDirectory = path.join(root, '.husky', '_');
const directory = path.resolve(root, hooksPath);
if (path.relative(expectedDirectory, directory) !== '') {
return [
`core.hooksPath is ${hooksPath}, not .husky/_; Git will not run the repository Husky hooks.`,
];
}
if (!existsSync(directory)) {
return [`core.hooksPath is ${hooksPath}, which does not exist, so Git runs no hooks.`];
}
return HOOKS.filter((hook) => !isExecutableFile(path.join(directory, hook))).map(
(hook) => `${hook} is missing or not executable in ${hooksPath}.`
);
}
function main() {
if (process.env.CI === 'true') return;
const problems = findProblems();
if (!problems.length) return;
const strict = process.argv.includes('--strict');
console.warn(
[
'⚠️ Git hooks are not installed; pre-commit and pre-push checks will not run.',
...problems.map((problem) => ` - ${problem}`),
' Fix: npm run prepare',
].join('\n')
);
if (strict) process.exitCode = 1;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main();
}