1 | import { promises as fs } from 'fs'
|
2 | import path from 'path'
|
3 |
|
4 | import debug from 'debug'
|
5 | import normalize from 'normalize-path'
|
6 |
|
7 | import { execGit } from './execGit.js'
|
8 | import { readFile } from './file.js'
|
9 |
|
10 | const debugLog = debug('lint-staged:resolveGitRepo')
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | const resolveGitConfigDir = async (gitDir) => {
|
17 |
|
18 | const defaultDir = normalize(await fs.realpath(path.join(gitDir, '.git')))
|
19 | const stats = await fs.lstat(defaultDir)
|
20 |
|
21 | if (stats.isDirectory()) return defaultDir
|
22 |
|
23 | const file = (await readFile(defaultDir)).toString()
|
24 | return path.resolve(gitDir, file.replace(/^gitdir: /, '')).trim()
|
25 | }
|
26 |
|
27 |
|
28 | export const determineGitDir = (cwd, relativeDir) => {
|
29 |
|
30 |
|
31 | if (relativeDir && relativeDir.endsWith(path.sep)) {
|
32 | relativeDir = relativeDir.slice(0, -1)
|
33 | }
|
34 | if (relativeDir) {
|
35 |
|
36 | return normalize(cwd.substring(0, cwd.lastIndexOf(relativeDir)))
|
37 | } else {
|
38 |
|
39 | return normalize(cwd)
|
40 | }
|
41 | }
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | export const resolveGitRepo = async (cwd = process.cwd()) => {
|
47 | try {
|
48 | debugLog('Resolving git repo from `%s`', cwd)
|
49 |
|
50 |
|
51 | debugLog('Unset GIT_DIR (was `%s`)', process.env.GIT_DIR)
|
52 | delete process.env.GIT_DIR
|
53 | debugLog('Unset GIT_WORK_TREE (was `%s`)', process.env.GIT_WORK_TREE)
|
54 | delete process.env.GIT_WORK_TREE
|
55 |
|
56 |
|
57 |
|
58 | const gitRel = normalize(await execGit(['rev-parse', '--show-prefix'], { cwd }))
|
59 | const gitDir = determineGitDir(normalize(cwd), gitRel)
|
60 | const gitConfigDir = normalize(await resolveGitConfigDir(gitDir))
|
61 |
|
62 | debugLog('Resolved git directory to be `%s`', gitDir)
|
63 | debugLog('Resolved git config directory to be `%s`', gitConfigDir)
|
64 |
|
65 | return { gitDir, gitConfigDir }
|
66 | } catch (error) {
|
67 | debugLog('Failed to resolve git repo with error:', error)
|
68 | return { error, gitDir: null, gitConfigDir: null }
|
69 | }
|
70 | }
|