1 | 'use strict'
|
2 |
|
3 | const normalize = require('normalize-path')
|
4 | const debugLog = require('debug')('lint-staged:resolveGitRepo')
|
5 | const fs = require('fs')
|
6 | const path = require('path')
|
7 | const { promisify } = require('util')
|
8 |
|
9 | const execGit = require('./execGit')
|
10 | const { readFile } = require('./file')
|
11 |
|
12 | const fsLstat = promisify(fs.lstat)
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | const resolveGitConfigDir = async (gitDir) => {
|
19 | const defaultDir = normalize(path.join(gitDir, '.git'))
|
20 | const stats = await fsLstat(defaultDir)
|
21 |
|
22 | if (stats.isDirectory()) return defaultDir
|
23 |
|
24 | const file = (await readFile(defaultDir)).toString()
|
25 | return path.resolve(gitDir, file.replace(/^gitdir: /, '')).trim()
|
26 | }
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | const resolveGitRepo = async (cwd) => {
|
32 | try {
|
33 | debugLog('Resolving git repo from `%s`', cwd)
|
34 |
|
35 |
|
36 | debugLog('Unset GIT_DIR (was `%s`)', process.env.GIT_DIR)
|
37 | delete process.env.GIT_DIR
|
38 | debugLog('Unset GIT_WORK_TREE (was `%s`)', process.env.GIT_WORK_TREE)
|
39 | delete process.env.GIT_WORK_TREE
|
40 |
|
41 | const gitDir = normalize(await execGit(['rev-parse', '--show-toplevel'], { cwd }))
|
42 | const gitConfigDir = normalize(await resolveGitConfigDir(gitDir))
|
43 |
|
44 | debugLog('Resolved git directory to be `%s`', gitDir)
|
45 | debugLog('Resolved git config directory to be `%s`', gitConfigDir)
|
46 |
|
47 | return { gitDir, gitConfigDir }
|
48 | } catch (error) {
|
49 | debugLog('Failed to resolve git repo with error:', error)
|
50 | return { error, gitDir: null, gitConfigDir: null }
|
51 | }
|
52 | }
|
53 |
|
54 | module.exports = resolveGitRepo
|