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 | const NOT_ON_A_BRANCH = 'not a symbolic ref'
|
11 | const CHECKOUT_A_BRANCH = 'Please checkout a branch before running this command'
|
12 |
|
13 | function runGit (...args) {
|
14 | const git = spawn('git', args)
|
15 |
|
16 | return new Promise((resolve, reject) => {
|
17 | git.on('exit', (exitCode) => {
|
18 | if (exitCode === 0) {
|
19 | return
|
20 | }
|
21 |
|
22 | const error = (git.stderr.read() || 'unknown error').toString().trim()
|
23 | if (error.toLowerCase().includes(NOT_A_GIT_REPOSITORY)) {
|
24 | reject(RUN_IN_A_GIT_REPOSITORY)
|
25 | return
|
26 | }
|
27 | if (error.includes(NOT_ON_A_BRANCH)) {
|
28 | reject(CHECKOUT_A_BRANCH)
|
29 | return
|
30 | }
|
31 | reject(`Error while running 'git ${args.join(' ')}' (${error})`)
|
32 | })
|
33 |
|
34 | git.stdout.on('data', (data) => resolve(data.toString().trim()))
|
35 | })
|
36 | }
|
37 |
|
38 | function * getRef (branch) {
|
39 | return runGit('rev-parse', branch || 'HEAD')
|
40 | }
|
41 |
|
42 | function * getBranch (symbolicRef) {
|
43 | return runGit('symbolic-ref', '--short', symbolicRef)
|
44 | }
|
45 |
|
46 | function * getCommitTitle (ref) {
|
47 | return runGit('log', ref || '', '-1', '--pretty=format:%s')
|
48 | }
|
49 |
|
50 | function * createArchive (ref) {
|
51 | const tar = spawn('git', ['archive', '--format', 'tar.gz', ref])
|
52 | const file = yield tmp.openAsync({ suffix: '.tar.gz' })
|
53 | const write = tar.stdout.pipe(fs.createWriteStream(file.path))
|
54 |
|
55 | return new Promise((resolve, reject) => {
|
56 | write.on('close', () => resolve(file.path))
|
57 | write.on('error', reject)
|
58 | })
|
59 | }
|
60 |
|
61 | function * githubRepository () {
|
62 | const remote = yield runGit('remote', 'get-url', 'origin')
|
63 | const repository = gh(remote)
|
64 |
|
65 | if (repository === null) {
|
66 | throw new Error('Not a GitHub repository')
|
67 | }
|
68 |
|
69 | return repository
|
70 | }
|
71 |
|
72 | function * readCommit (commit) {
|
73 | const branch = yield getBranch('HEAD')
|
74 | const ref = yield getRef(commit)
|
75 | const message = yield getCommitTitle(ref)
|
76 |
|
77 | return Promise.resolve({
|
78 | branch: branch,
|
79 | ref: ref,
|
80 | message: message
|
81 | })
|
82 | }
|
83 |
|
84 | module.exports = {
|
85 | createArchive,
|
86 | githubRepository,
|
87 | readCommit
|
88 | }
|