UNPKG

2.04 kBJavaScriptView Raw
1const spawn = require('child_process').spawn
2const Promise = require('bluebird')
3const fs = Promise.promisifyAll(require('fs'))
4const tmp = Promise.promisifyAll(require('temp').track())
5const gh = require('github-url-to-object')
6
7const NOT_A_GIT_REPOSITORY = 'Not a git repository'
8const RUN_IN_A_GIT_REPOSITORY = 'Please run this command from the directory containing your project\'s git repo'
9
10function runGit (...args) {
11 const git = spawn('git', args)
12
13 return new Promise((resolve, reject) => {
14 git.on('exit', (exitCode) => {
15 if (exitCode === 0) {
16 return
17 }
18
19 const stderr = git.stderr.read() || ''
20 if (stderr.toString().includes(NOT_A_GIT_REPOSITORY)) {
21 reject(RUN_IN_A_GIT_REPOSITORY)
22 return
23 }
24 reject(exitCode)
25 })
26
27 git.stdout.on('data', (data) => resolve(data.toString().trim()))
28 })
29}
30
31function* getRef (branch) {
32 return runGit('rev-parse', branch || 'HEAD')
33}
34
35function* getBranch (symbolicRef) {
36 return runGit('symbolic-ref', '--short', symbolicRef)
37}
38
39function* getCommitTitle (ref) {
40 return runGit('log', ref || '', '-1', '--pretty=format:%s')
41}
42
43function* createArchive (ref) {
44 const tar = spawn('git', ['archive', '--format', 'tar.gz', ref])
45 const file = yield tmp.openAsync({ suffix: '.tar.gz' })
46 const write = tar.stdout.pipe(fs.createWriteStream(file.path))
47
48 return new Promise((resolve, reject) => {
49 write.on('close', () => resolve(file.path))
50 write.on('error', reject)
51 })
52}
53
54function* githubRepository () {
55 const remote = yield runGit('remote', 'get-url', 'origin')
56 const repository = gh(remote)
57
58 if (repository === null) {
59 throw new Error('Not a GitHub repository')
60 }
61
62 return repository
63}
64
65function* readCommit (commit) {
66 const branch = yield getBranch('HEAD')
67 const ref = yield getRef(commit)
68 const message = yield getCommitTitle(ref)
69
70 return Promise.resolve({
71 branch: branch,
72 ref: ref,
73 message: message
74 })
75}
76
77module.exports = {
78 createArchive,
79 githubRepository,
80 readCommit
81}