UNPKG

2 kBJavaScriptView Raw
1const path = require('path')
2const util = require('util')
3const findUp = require('find-up')
4const gitRepoInfo = require('git-repo-info')
5const parseGitRemote = require('parse-github-url')
6const isEmpty = require('lodash.isempty')
7const gitconfiglocal = require('gitconfiglocal')
8
9async function getRepoData(remote) {
10 const cwd = process.cwd()
11 let repo = {}
12 try {
13 const gitConfig = await util.promisify(gitconfiglocal)(cwd)
14 const gitDirectory = findUp.sync(['.git'], { cwd: cwd })
15 const baseGitPath = path.dirname(gitDirectory)
16
17 if (cwd !== baseGitPath) {
18 console.log(`Git directory located in ${baseGitPath}`)
19 // TODO prompt for "is this the correct git remote"?
20 // If folder gitignored inside another git repo it could link to wrong repo.
21 }
22
23 if (isEmpty(gitConfig) || isEmpty(gitConfig.remote)) {
24 throw new Error('No Git remote found')
25 }
26
27 if (!remote) {
28 remote = gitConfig.hasOwnProperty('origin') ? 'origin' : Object.keys(gitConfig.remote).shift()
29 }
30
31 if (!gitConfig.remote.hasOwnProperty(remote) || isEmpty(gitConfig.remote[remote])) {
32 throw new Error(`The specified remote "${remote}" is not defined in Git repo. Please use --gitRemoteName flag to specify a remote.`)
33 }
34
35 const remoteData = parseGitRemote(gitConfig.remote[remote].url)
36 const repoData = gitRepoInfo()
37
38 // TODO refactor shape
39 repo = {
40 gitDirectoryPath: gitDirectory,
41 remoteData: remoteData,
42 repoData: repoData,
43 repo_path: remoteData.path,
44 repo_branch: repoData.branch,
45 allowed_branches: [repoData.branch],
46 host: remoteData.host
47 }
48
49 switch (remoteData.host) {
50 case 'github.com': {
51 repo.provider = 'github'
52 break
53 }
54 case 'gitlab.com': {
55 repo.provider = 'gitlab'
56 break
57 }
58 }
59 } catch (error) {
60 // console.log('error', error)
61 return {
62 error: error.message
63 }
64 }
65
66 return repo
67}
68
69module.exports = getRepoData