1 | 'use strict'
|
2 |
|
3 | const exec = require('./exec')
|
4 | const debug = require('debug')('ggit')
|
5 | const path = require('path')
|
6 | const alwaysError = require('always-error')
|
7 | const findUp = require('find-up')
|
8 | const R = require('ramda')
|
9 |
|
10 | function parentFolder () {
|
11 | return path.normalize(path.join(process.cwd(), '..'))
|
12 | }
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | function 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 |
|
28 | function 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 |
|
40 | function isInDotGit () {
|
41 | return /\.git$/.test(process.cwd())
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 | function 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 |
|
61 | function 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 |
|
68 | function 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 |
|
79 | module.exports = getGitFolder
|