/
resolveGitRepo.js
45 lines (38 loc) · 1.46 KB
/
resolveGitRepo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'use strict'
const normalize = require('normalize-path')
const path = require('path')
const execGit = require('./execGit')
const { readBufferFromFile } = require('./file')
/**
* Resolve path to the .git directory, with special handling for
* submodules
*/
const resolveGitConfigDir = async ({ gitDir, isSubmodule }) => {
const defaultDir = path.resolve(gitDir, '.git')
if (!isSubmodule) return normalize(defaultDir)
const buffer = await readBufferFromFile(defaultDir)
const dotGit = buffer.toString()
const gitConfigDir = path.resolve(dotGit.replace(/^gitdir: /, ''))
return normalize(gitConfigDir)
}
/**
* Resolve git directory and possible submodule paths
*/
module.exports = async function resolveGitRepo(options = {}) {
try {
// git cli uses GIT_DIR to fast track its response however it might be set to a different path
// depending on where the caller initiated this from, hence clear GIT_DIR
delete process.env.GIT_DIR
const gitDir = await execGit(['rev-parse', '--show-toplevel'], options)
const superprojectWorkingTree = await execGit(
['rev-parse', '--show-superproject-working-tree'],
options
)
// A super-project working tree exists only in the context of submodules
const isSubmodule = !!superprojectWorkingTree
const gitConfigDir = await resolveGitConfigDir({ gitDir, isSubmodule })
return { gitDir: normalize(gitDir), gitConfigDir, isSubmodule }
} catch (error) {
return { error, gitDir: null }
}
}