UNPKG

2.14 kBJavaScriptView Raw
1'use strict'
2
3const exec = require('./exec')
4const debug = require('debug')('ggit')
5const path = require('path')
6const alwaysError = require('always-error')
7const findUp = require('find-up')
8const R = require('ramda')
9
10function parentFolder () {
11 return path.normalize(path.join(process.cwd(), '..'))
12}
13
14// when we are inside <repo>/.git folder
15// the usual command does NOT work
16// it just returns nothing, so must detect this
17function checkFolder (folder) {
18 if (!folder) {
19 if (isInDotGit()) {
20 debug('could not get git folder, but we are inside .git')
21 return parentFolder()
22 }
23 throw new Error('Could not get git root folder')
24 }
25 return folder
26}
27
28function tryDotGit (err) {
29 if (isInDotGit()) {
30 debug('failed to get repo root folder, but we are inside .git')
31 return parentFolder()
32 }
33 debug('tryDotGit error', err)
34 debug('environment')
35 debug(process.env)
36 debug('current folder', process.cwd())
37 throw alwaysError(err)
38}
39
40function isInDotGit () {
41 return /\.git$/.test(process.cwd())
42}
43
44// if everything else fails (for example during commit)
45// we can walk up the parent tree to find the git folder, typically ".git"
46function searchUpForGitFolder () {
47 const GIT = process.env.GIT_DIR || '.git'
48 debug('searching for %s up from %s', GIT, process.cwd())
49 return findUp(GIT).then(gitDirectory => {
50 if (gitDirectory) {
51 if (R.endsWith(GIT, gitDirectory)) {
52 gitDirectory = gitDirectory.replace(GIT, '')
53 }
54 debug('found %s', gitDirectory)
55 return gitDirectory
56 }
57 throw new Error(`Could not find ${GIT} folder up from ${process.cwd()}`)
58 })
59}
60
61function stripSeparator (folder) {
62 if (R.endsWith(path.sep, folder)) {
63 return folder.substr(0, folder.length - path.sep.length)
64 }
65 return folder
66}
67
68function getGitFolder () {
69 const cmd = 'git rev-parse --show-toplevel'
70 const verbose = /ggit/.test(process.env.DEBUG)
71 return exec(cmd, verbose)
72 .then(checkFolder, tryDotGit)
73 .catch(searchUpForGitFolder)
74 .then(folder => folder.trim())
75 .then(folder => path.normalize(folder))
76 .then(stripSeparator)
77}
78
79module.exports = getGitFolder