1 | 'use strict'
|
2 | const got = require('got')
|
3 | const api = require('./heroku-api')
|
4 | const git = require('./git')
|
5 | const Promise = require('bluebird')
|
6 | const fs = Promise.promisifyAll(require('fs'))
|
7 |
|
8 | function * uploadArchive (url, filePath) {
|
9 | const request = got.stream.put(url, {
|
10 | headers: {
|
11 | 'content-length': (yield fs.statAsync(filePath)).size
|
12 | }
|
13 | })
|
14 |
|
15 | fs.createReadStream(filePath).pipe(request)
|
16 |
|
17 | return new Promise((resolve, reject) => {
|
18 | request.on('error', reject)
|
19 | request.on('response', resolve)
|
20 | })
|
21 | }
|
22 |
|
23 | function * prepareSource (ref, context, heroku) {
|
24 | const [filePath, source] = yield [
|
25 | git.createArchive(ref),
|
26 | api.createSource(heroku)
|
27 | ]
|
28 | yield uploadArchive(source.source_blob.put_url, filePath)
|
29 | return Promise.resolve(source)
|
30 | }
|
31 |
|
32 | function * urlExists (url) {
|
33 | return yield got.head(url)
|
34 | }
|
35 |
|
36 | function * createSourceBlob (ref, context, heroku) {
|
37 | try {
|
38 | const githubRepository = yield git.githubRepository()
|
39 | const { user, repo } = githubRepository
|
40 | const archiveLink = yield api.githubArchiveLink(heroku, user, repo, ref)
|
41 |
|
42 | if (yield urlExists(archiveLink.archive_link)) {
|
43 | return archiveLink.archive_link
|
44 | }
|
45 | } catch (ex) { }
|
46 |
|
47 | const sourceBlob = yield prepareSource(ref, context, heroku)
|
48 | return sourceBlob.source_blob.get_url
|
49 | }
|
50 |
|
51 | module.exports = {
|
52 | createSourceBlob,
|
53 | prepareSource
|
54 | }
|