Skip to content

Commit 5a92db8

Browse files
committed
fix(hooks): resolve commit msg path
1 parent c789233 commit 5a92db8

File tree

1 file changed

+46
-11
lines changed

1 file changed

+46
-11
lines changed

scripts/verify-commit.js

Lines changed: 46 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,59 @@
11
// @ts-check
22
import pico from 'picocolors'
3-
import { existsSync, readFileSync } from 'node:fs'
3+
import { existsSync, readFileSync, statSync } from 'node:fs'
44
import path from 'node:path'
55

6+
const findGitPath = (startDir) => {
7+
let current = startDir
8+
while (true) {
9+
const candidate = path.join(current, '.git')
10+
if (existsSync(candidate)) {
11+
return candidate
12+
}
13+
const parent = path.dirname(current)
14+
if (parent === current) {
15+
return null
16+
}
17+
current = parent
18+
}
19+
}
20+
21+
const resolveGitDir = (gitPath) => {
22+
try {
23+
const stat = statSync(gitPath)
24+
if (stat.isDirectory()) {
25+
return gitPath
26+
}
27+
const content = readFileSync(gitPath, 'utf-8').trim()
28+
if (content.startsWith('gitdir:')) {
29+
const gitDir = content.replace('gitdir:', '').trim()
30+
return path.resolve(path.dirname(gitPath), gitDir)
31+
}
32+
} catch {
33+
// ignore and fall through
34+
}
35+
return null
36+
}
37+
638
const resolveMsgPath = () => {
739
const argPath = process.argv[2]
840
if (argPath && existsSync(argPath)) {
941
return argPath
1042
}
1143

12-
const gitPath = path.resolve('.git')
13-
if (existsSync(gitPath)) {
14-
try {
15-
const stat = readFileSync(gitPath, 'utf-8').trim()
16-
if (stat.startsWith('gitdir:')) {
17-
const gitDir = stat.replace('gitdir:', '').trim()
18-
return path.resolve(gitDir, 'COMMIT_EDITMSG')
19-
}
20-
} catch {
21-
// ignore and fall through
44+
const envGitDir = process.env.GIT_DIR
45+
if (envGitDir && existsSync(envGitDir)) {
46+
const resolved = resolveGitDir(envGitDir)
47+
if (resolved) {
48+
return path.resolve(resolved, 'COMMIT_EDITMSG')
49+
}
50+
}
51+
52+
const gitPath = findGitPath(process.cwd())
53+
if (gitPath) {
54+
const resolved = resolveGitDir(gitPath)
55+
if (resolved) {
56+
return path.resolve(resolved, 'COMMIT_EDITMSG')
2257
}
2358
}
2459

0 commit comments

Comments
 (0)