1 | const path = require('path')
|
2 | const util = require('util')
|
3 | const findUp = require('find-up')
|
4 | const gitRepoInfo = require('git-repo-info')
|
5 | const parseGitRemote = require('parse-github-url')
|
6 | const isEmpty = require('lodash.isempty')
|
7 | const gitconfiglocal = require('gitconfiglocal')
|
8 |
|
9 | async 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 |
|
20 |
|
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 |
|
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 |
|
61 | return {
|
62 | error: error.message
|
63 | }
|
64 | }
|
65 |
|
66 | return repo
|
67 | }
|
68 |
|
69 | module.exports = getRepoData
|