1 | const spawn = require('child_process').spawn
|
2 | const Promise = require('bluebird')
|
3 | const fs = Promise.promisifyAll(require('fs'))
|
4 | const tmp = Promise.promisifyAll(require('temp').track())
|
5 | const gh = require('github-url-to-object')
|
6 |
|
7 | const NOT_A_GIT_REPOSITORY = 'Not a git repository'
|
8 | const RUN_IN_A_GIT_REPOSITORY = 'Please run this command from the directory containing your project\'s git repo'
|
9 |
|
10 | function 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 |
|
31 | function* getRef (branch) {
|
32 | return runGit('rev-parse', branch || 'HEAD')
|
33 | }
|
34 |
|
35 | function* getBranch (symbolicRef) {
|
36 | return runGit('symbolic-ref', '--short', symbolicRef)
|
37 | }
|
38 |
|
39 | function* getCommitTitle (ref) {
|
40 | return runGit('log', ref || '', '-1', '--pretty=format:%s')
|
41 | }
|
42 |
|
43 | function* 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 |
|
54 | function* 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 |
|
65 | function* 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 |
|
77 | module.exports = {
|
78 | createArchive,
|
79 | githubRepository,
|
80 | readCommit
|
81 | }
|