|
1 | 1 | // @ts-check |
2 | 2 | import pico from 'picocolors' |
3 | | -import { existsSync, readFileSync } from 'node:fs' |
| 3 | +import { existsSync, readFileSync, statSync } from 'node:fs' |
4 | 4 | import path from 'node:path' |
5 | 5 |
|
| 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 | + |
6 | 38 | const resolveMsgPath = () => { |
7 | 39 | const argPath = process.argv[2] |
8 | 40 | if (argPath && existsSync(argPath)) { |
9 | 41 | return argPath |
10 | 42 | } |
11 | 43 |
|
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') |
22 | 57 | } |
23 | 58 | } |
24 | 59 |
|
|
0 commit comments