1 | const execa = require('execa')
|
2 | const debug = require('debug')('commit-info')
|
3 | const la = require('lazy-ass')
|
4 | const is = require('check-more-types')
|
5 | const Promise = require('bluebird')
|
6 |
|
7 |
|
8 |
|
9 | const gitCommands = {
|
10 | branch: 'git rev-parse --abbrev-ref HEAD',
|
11 | message: 'git show -s --pretty=%B',
|
12 | subject: 'git show -s --pretty=%s',
|
13 | body: 'git show -s --pretty=%b',
|
14 | email: 'git show -s --pretty=%ae',
|
15 | author: 'git show -s --pretty=%an',
|
16 | sha: 'git show -s --pretty=%H',
|
17 | timestamp: 'git show -s --pretty=%ct',
|
18 | remoteOriginUrl: 'git config --get remote.origin.url'
|
19 | }
|
20 |
|
21 | const prop = name => object => object[name]
|
22 | const returnNull = () => null
|
23 | const returnNullIfEmpty = value => value || null
|
24 |
|
25 | const debugError = (gitCommand, folder, e) => {
|
26 | debug('got an error running command "%s" in folder "%s"', gitCommand, folder)
|
27 | debug(e)
|
28 | }
|
29 |
|
30 | const runGitCommand = (gitCommand, pathToRepo) => {
|
31 | la(is.unemptyString(gitCommand), 'missing git command', gitCommand)
|
32 | la(gitCommand.startsWith('git'), 'invalid git command', gitCommand)
|
33 |
|
34 | pathToRepo = pathToRepo || process.cwd()
|
35 | la(is.unemptyString(pathToRepo), 'missing repo path', pathToRepo)
|
36 |
|
37 | debug('running git command: %s', gitCommand)
|
38 | debug('in folder %s', pathToRepo)
|
39 |
|
40 | return Promise.try(() => execa.shell(gitCommand, { cwd: pathToRepo }))
|
41 | .then(prop('stdout'))
|
42 | .tap(stdout => debug('git stdout:', stdout))
|
43 | .then(returnNullIfEmpty)
|
44 | .catch(e => {
|
45 | debugError(gitCommand, pathToRepo, e)
|
46 | return returnNull()
|
47 | })
|
48 | }
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 | const checkIfDetached = branch => (branch === 'HEAD' ? null : branch)
|
60 |
|
61 | function getGitBranch (pathToRepo) {
|
62 | return runGitCommand(gitCommands.branch, pathToRepo)
|
63 | .then(checkIfDetached)
|
64 | .catch(returnNull)
|
65 | }
|
66 |
|
67 | const getMessage = runGitCommand.bind(null, gitCommands.message)
|
68 |
|
69 | const getSubject = runGitCommand.bind(null, gitCommands.subject)
|
70 |
|
71 | const getBody = runGitCommand.bind(null, gitCommands.body)
|
72 |
|
73 | const getEmail = runGitCommand.bind(null, gitCommands.email)
|
74 |
|
75 | const getAuthor = runGitCommand.bind(null, gitCommands.author)
|
76 |
|
77 | const getSha = runGitCommand.bind(null, gitCommands.sha)
|
78 |
|
79 | const getTimestamp = runGitCommand.bind(null, gitCommands.timestamp)
|
80 |
|
81 | const getRemoteOrigin = runGitCommand.bind(null, gitCommands.remoteOriginUrl)
|
82 |
|
83 | module.exports = {
|
84 | runGitCommand,
|
85 | getGitBranch,
|
86 | getSubject,
|
87 | getBody,
|
88 | getMessage,
|
89 | getEmail,
|
90 | getAuthor,
|
91 | getSha,
|
92 | getTimestamp,
|
93 | getRemoteOrigin,
|
94 | gitCommands
|
95 | }
|