UNPKG

1.82 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
35 // Unset GIT_DIR before running any git operations in case it's pointing to an incorrect location
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
54module.exports = resolveGitRepo