This repository has been archived by the owner on Dec 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathnow-travis
executable file
·234 lines (203 loc) · 5.77 KB
/
now-travis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#! /usr/bin/env node
const github = require('octonode')
const spawn = require('cross-spawn')
const normalizeUrl = require('normalize-url')
const urlRegex = require('url-regex')
const awaitUrl = require('await-url')
const {fallbackLocale} = require('../config.json')
if (!process.env.CI || !process.env.TRAVIS) {
throw new Error('Could not detect Travis CI environment')
}
// eslint-disable-next-line max-statements
async function deploy(context, sha) {
if (isFork()) {
console.log(`▲ Now ${context} deployment is skipped for forks...`)
return
}
const {
LOCALE: locale,
NOW_TOKEN: nowToken,
GH_TOKEN: githubToken,
} = process.env
if (!githubToken) {
throw new Error('Missing required environment variable GH_TOKEN')
}
if (!nowToken) {
throw new Error('Missing required environment variable NOW_TOKEN')
}
const {TRAVIS_REPO_SLUG, TRAVIS_BUILD_ID} = process.env
let target_url = `https://travis-ci.org/${TRAVIS_REPO_SLUG}/builds/${TRAVIS_BUILD_ID}`
const client = github.client(githubToken)
const ghRepo = client.repo(process.env.TRAVIS_REPO_SLUG)
const isProd = context === 'production'
updateStatus({
state: 'pending',
description: `▲ Now ${context} deployment pending`,
})
const cliArgs = ['--token', nowToken, '--no-clipboard', '--public']
safeLog('spawning shell with command:', `now ${cliArgs.join(' ')}`)
const result = await spawnPromise('now', [
'--token',
nowToken,
'--no-clipboard',
'--public',
'--static',
'--name',
`${locale}-glamorous`,
`out/${locale}`,
]).catch(err => {
onError(err)
throw err
})
target_url = getUrl(result)
updateStatus({
state: 'pending',
description: `▲ Now ${context} deployment build started...`,
})
console.log(
`🤠 Alrighty, deploy started. Now we're going to ping ${target_url} until it's ready!`
)
// check on the site for ten minutes every 5 seconds
await awaitUrl(target_url, {interval: 5000, tries: 120}).catch(err => {
console.error('Error waiting for the deployment to be ready.')
onError(err)
throw err
})
console.log(`💪 it's up and ready!`)
if (isProd) {
await aliasDeploy()
}
console.log('🏁 all done!')
updateStatus({
state: 'success',
description: `▲ Now ${context} deployment complete`,
})
function onError(err) {
safeError(err)
updateStatus({
state: 'error',
description: `▲ Now ${context} deployment failed. See Travis logs for details.`,
})
}
function updateStatus(options) {
const mergedOptions = Object.assign({context, target_url}, options)
const {description, target_url: url} = mergedOptions
console.log(`${description}: ${url}`)
if (locale === fallbackLocale) {
// we can't report status for more than one locale.
ghRepo.status(sha, mergedOptions, logError('setting complete status'))
}
}
function aliasDeploy() {
// if we're production, then we need to alias things
console.log(`↪️ We're building for production, so let's alias this!`)
const prefix = locale === fallbackLocale ? '' : `${locale}.`
const domain = 'glamorous.rocks'
const alias = `${prefix}${domain}`
const aliasArgs = ['alias', 'set', target_url, alias, '--token', nowToken]
safeLog('spawning shell with command:', `now ${aliasArgs.join(' ')}`)
return spawnPromise('now', aliasArgs)
}
function spawnPromise(...args) {
return new Promise((resolve, reject) => {
const child = spawn(...args)
let stdout = ''
let stderr = ''
child.stdout.on('data', data => {
stdout += data
safeLog(String(data))
})
child.stderr.on('data', data => {
safeError(String(data))
stderr += String(safeify(data))
})
child.on('error', error => {
onError(error)
reject(safeify(error))
})
child.on('close', () => {
if (stderr) {
reject(stderr)
} else {
resolve(stdout)
}
})
})
}
function safeLog(...args) {
const safeArgs = args.map(s => safeify(s))
console.log(...safeArgs)
}
function safeError(...args) {
const safeArgs = args.map(s => safeify(s))
console.error(...safeArgs)
}
function safeify(s, safed = []) {
if (safed.indexOf(s) !== -1) {
return 'CIRCULAR'
}
safed.push(s)
if (typeof s === 'string') {
return s
.split(nowToken)
.join('NOW_TOKEN')
.split(githubToken)
.join('GITHUB_TOKEN')
} else if (typeof s === 'object' && s !== null) {
return Object.keys(s).reduce((acc, k) => {
acc[k] = safeify(s, safed)
return acc
}, {})
} else {
return s
}
}
}
const {TRAVIS_EVENT_TYPE, TRAVIS_PULL_REQUEST_SHA, TRAVIS_COMMIT} = process.env
switch (TRAVIS_EVENT_TYPE) {
case 'pull_request': {
deploy('staging', TRAVIS_PULL_REQUEST_SHA)
break
}
case 'push': {
deploy('production', TRAVIS_COMMIT)
break
}
default: {
console.log(`${TRAVIS_EVENT_TYPE} is not supported by now-travis`)
}
}
function isFork() {
const {TRAVIS_PULL_REQUEST_SLUG, TRAVIS_REPO_SLUG} = process.env
if (!TRAVIS_PULL_REQUEST_SLUG) {
return false
}
const [prOwner] = TRAVIS_PULL_REQUEST_SLUG.split('/')
const [owner] = TRAVIS_REPO_SLUG.split('/')
return owner !== prOwner
}
function getUrl(content) {
const urls = content.match(urlRegex()) || []
return urls.map(url => normalizeUrl(url.trim().replace(/\.+$/, '')))[0]
}
function logError(message) {
return function onError(error) {
if (error) {
console.log(message, error)
}
}
}
// This is not transpiled
/*
eslint
no-console: 0,
camelcase: 0,
comma-dangle: [
2,
{
arrays: 'always-multiline',
objects: 'always-multiline',
functions: 'never'
}
]
*/