UNPKG

2.72 kBJavaScriptView Raw
1const execa = require('execa')
2const debug = require('debug')('commit-info')
3const la = require('lazy-ass')
4const is = require('check-more-types')
5const Promise = require('bluebird')
6
7// common git commands for getting basic info
8// https://git-scm.com/docs/git-show
9const 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
21const prop = name => object => object[name]
22const returnNull = () => null
23const returnNullIfEmpty = value => value || null
24
25const debugError = (gitCommand, folder, e) => {
26 debug('got an error running command "%s" in folder "%s"', gitCommand, folder)
27 debug(e)
28}
29
30const 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 "gift" module returns "" for detached checkouts
52 and our current command returns "HEAD"
53 and we changed the behavior to return null
54
55 example:
56 git checkout <commit sha>
57 get git branch returns "HEAD"
58*/
59const checkIfDetached = branch => (branch === 'HEAD' ? null : branch)
60
61function getGitBranch (pathToRepo) {
62 return runGitCommand(gitCommands.branch, pathToRepo)
63 .then(checkIfDetached)
64 .catch(returnNull)
65}
66
67const getMessage = runGitCommand.bind(null, gitCommands.message)
68
69const getSubject = runGitCommand.bind(null, gitCommands.subject)
70
71const getBody = runGitCommand.bind(null, gitCommands.body)
72
73const getEmail = runGitCommand.bind(null, gitCommands.email)
74
75const getAuthor = runGitCommand.bind(null, gitCommands.author)
76
77const getSha = runGitCommand.bind(null, gitCommands.sha)
78
79const getTimestamp = runGitCommand.bind(null, gitCommands.timestamp)
80
81const getRemoteOrigin = runGitCommand.bind(null, gitCommands.remoteOriginUrl)
82
83module.exports = {
84 runGitCommand,
85 getGitBranch,
86 getSubject,
87 getBody,
88 getMessage,
89 getEmail,
90 getAuthor,
91 getSha,
92 getTimestamp,
93 getRemoteOrigin,
94 gitCommands
95}