UNPKG

1.79 kBJavaScriptView Raw
1'use strict'
2
3const normalize = require('normalize-path')
4const debugLog = require('debug')('lint-staged:resolveGitRepo')
5const fs = require('fs')
6const path = require('path')
7const { promisify } = require('util')
8
9const execGit = require('./execGit')
10const { readFile } = require('./file')
11
12const fsLstat = promisify(fs.lstat)
13
14/**
15 * Resolve path to the .git directory, with special handling for
16 * submodules and worktrees
17 */
18const resolveGitConfigDir = async gitDir => {
19 const defaultDir = normalize(path.join(gitDir, '.git'))
20 const stats = await fsLstat(defaultDir)
21 // If .git is a directory, use it
22 if (stats.isDirectory()) return defaultDir
23 // Otherwise .git is a file containing path to real location
24 const file = (await readFile(defaultDir)).toString()
25 return path.resolve(gitDir, file.replace(/^gitdir: /, '')).trim()
26}
27
28/**
29 * Resolve git directory and possible submodule paths
30 */
31const resolveGitRepo = async cwd => {
32 try {
33 debugLog('Resolving git repo from `%s`', cwd)
34 // git cli uses GIT_DIR to fast track its response however it might be set to a different path
35 // depending on where the caller initiated this from, hence clear GIT_DIR
36 debugLog('Deleting GIT_DIR from env with value `%s`', process.env.GIT_DIR)
37 delete process.env.GIT_DIR
38
39 const gitDir = normalize(await execGit(['rev-parse', '--show-toplevel'], { cwd }))
40 const gitConfigDir = normalize(await resolveGitConfigDir(gitDir))
41
42 debugLog('Resolved git directory to be `%s`', gitDir)
43 debugLog('Resolved git config directory to be `%s`', gitConfigDir)
44
45 return { gitDir, gitConfigDir }
46 } catch (error) {
47 debugLog('Failed to resolve git repo with error:', error)
48 return { error, gitDir: null, gitConfigDir: null }
49 }
50}
51
52module.exports = resolveGitRepo