-
Notifications
You must be signed in to change notification settings - Fork 357
/
deploy.js
645 lines (568 loc) · 18.4 KB
/
deploy.js
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
const path = require('path')
const process = require('process')
const { flags: flagsLib } = require('@oclif/command')
const chalk = require('chalk')
const cliSpinnerNames = Object.keys(require('cli-spinners'))
const dotProp = require('dot-prop')
const inquirer = require('inquirer')
const get = require('lodash/get')
const isObject = require('lodash/isObject')
const logSymbols = require('log-symbols')
const ora = require('ora')
const prettyjson = require('prettyjson')
const randomItem = require('random-item')
const { cancelDeploy } = require('../lib/api')
const { getBuildOptions, runBuild } = require('../lib/build')
const { statAsync } = require('../lib/fs')
const { getLogMessage } = require('../lib/log')
const Command = require('../utils/command')
const { deployEdgeHandlers } = require('../utils/edge-handlers')
const { NETLIFYDEV, NETLIFYDEVLOG, NETLIFYDEVERR } = require('../utils/logo')
const openBrowser = require('../utils/open-browser')
const LinkCommand = require('./link')
const SitesCreateCommand = require('./sites/create')
const DEFAULT_DEPLOY_TIMEOUT = 1.2e6
const triggerDeploy = async ({ api, siteId, siteData, log, error }) => {
try {
const siteBuild = await api.createSiteBuild({ siteId })
log(
`${NETLIFYDEV} A new deployment was triggered successfully. Visit https://app.netlify.com/sites/${siteData.name}/deploys/${siteBuild.deploy_id} to see the logs.`,
)
} catch (error_) {
if (error_.status === 404) {
error('Site not found. Please rerun "netlify link" and make sure that your site has CI configured.')
} else {
error(error_.message)
}
}
}
const getDeployFolder = async ({ flags, config, site, siteData, log }) => {
let deployFolder
if (flags.dir) {
deployFolder = path.resolve(process.cwd(), flags.dir)
} else if (get(config, 'build.publish')) {
deployFolder = path.resolve(site.root, get(config, 'build.publish'))
} else if (get(siteData, 'build_settings.dir')) {
deployFolder = path.resolve(site.root, get(siteData, 'build_settings.dir'))
}
if (!deployFolder) {
log('Please provide a publish directory (e.g. "public" or "dist" or "."):')
log(process.cwd())
const { promptPath } = await inquirer.prompt([
{
type: 'input',
name: 'promptPath',
message: 'Publish directory',
default: '.',
filter: (input) => path.resolve(process.cwd(), input),
},
])
deployFolder = promptPath
}
return deployFolder
}
const validateDeployFolder = async ({ deployFolder, error }) => {
let stat
try {
stat = await statAsync(deployFolder)
} catch (error_) {
if (error_.code === 'ENOENT') {
return error(`No such directory ${deployFolder}! Did you forget to run a build?`)
}
// Improve the message of permission errors
if (error_.code === 'EACCES') {
return error('Permission error when trying to access deploy folder')
}
throw error_
}
if (!stat.isDirectory()) {
return error('Deploy target must be a path to a directory')
}
return stat
}
const getFunctionsFolder = ({ flags, config, site, siteData }) => {
let functionsFolder
// Support "functions" and "Functions"
const funcConfig = get(config, 'build.functions') || get(config, 'build.Functions')
if (flags.functions) {
functionsFolder = path.resolve(process.cwd(), flags.functions)
} else if (funcConfig) {
functionsFolder = path.resolve(site.root, funcConfig)
} else if (get(siteData, 'build_settings.functions_dir')) {
functionsFolder = path.resolve(site.root, get(siteData, 'build_settings.functions_dir'))
}
return functionsFolder
}
const validateFunctionsFolder = async ({ functionsFolder, log, error }) => {
let stat
if (functionsFolder) {
// we used to hard error if functions folder is specified but doesn't exist
// but this was too strict for onboarding. we can just log a warning.
try {
stat = await statAsync(functionsFolder)
} catch (error_) {
if (error_.code === 'ENOENT') {
log(
`Functions folder "${functionsFolder}" specified but it doesn't exist! Will proceed without deploying functions`,
)
}
// Improve the message of permission errors
if (error_.code === 'EACCES') {
error('Permission error when trying to access functions folder')
}
}
}
if (stat && !stat.isDirectory()) {
error('Functions folder must be a path to a directory')
}
return stat
}
const validateFolders = async ({ deployFolder, functionsFolder, error, log }) => {
const deployFolderStat = await validateDeployFolder({ deployFolder, error })
const functionsFolderStat = await validateFunctionsFolder({ functionsFolder, error, log })
return { deployFolderStat, functionsFolderStat }
}
const getDeployFilesFilter = ({ site, deployFolder }) => {
// site.root === deployFolder can happen when users run `netlify deploy --dir .`
// in that specific case we don't want to publish the repo node_modules
// when site.root !== deployFolder the behaviour matches our buildbot
const skipNodeModules = site.root === deployFolder
return (filename) => {
if (filename == null) {
return false
}
if (filename === deployFolder) {
return true
}
const basename = path.basename(filename)
const skipFile =
(skipNodeModules && basename === 'node_modules') ||
(basename.startsWith('.') && basename !== '.well-known') ||
basename.startsWith('__MACOSX') ||
basename.includes('/.')
return !skipFile
}
}
const SEC_TO_MILLISEC = 1e3
// 100 bytes
const SYNC_FILE_LIMIT = 1e2
const prepareProductionDeploy = async ({ siteData, api, log, exit }) => {
if (isObject(siteData.published_deploy) && siteData.published_deploy.locked) {
log(`\n${NETLIFYDEVERR} Deployments are "locked" for production context of this site\n`)
const { unlockChoice } = await inquirer.prompt([
{
type: 'confirm',
name: 'unlockChoice',
message: 'Would you like to "unlock" deployments for production context to proceed?',
default: false,
},
])
if (!unlockChoice) exit(0)
await api.unlockDeploy({ deploy_id: siteData.published_deploy.id })
log(`\n${NETLIFYDEVLOG} "Auto publishing" has been enabled for production context\n`)
}
log('Deploying to main site URL...')
}
const hasErrorMessage = (actual, expected) => {
if (typeof actual === 'string') {
return actual.includes(expected)
}
return false
}
const getJsonErrorMessage = (error) => dotProp.get(error, 'json.message', '')
const reportDeployError = ({ error, warn, failAndExit }) => {
switch (true) {
case error.name === 'JSONHTTPError': {
const message = getJsonErrorMessage(error)
if (hasErrorMessage(message, 'Background Functions not allowed by team plan')) {
return failAndExit(`\n${getLogMessage('functions.backgroundNotSupported')}`)
}
warn(`JSONHTTPError: ${message} ${error.status}`)
warn(`\n${JSON.stringify(error, null, ' ')}\n`)
failAndExit(error)
return
}
case error.name === 'TextHTTPError': {
warn(`TextHTTPError: ${error.status}`)
warn(`\n${error}\n`)
failAndExit(error)
return
}
case hasErrorMessage(error.message, 'Invalid filename'): {
warn(error.message)
failAndExit(error)
return
}
default: {
warn(`\n${JSON.stringify(error, null, ' ')}\n`)
failAndExit(error)
}
}
}
const runDeploy = async ({
flags,
deployToProduction,
site,
siteData,
api,
siteId,
deployFolder,
configPath,
functionsFolder,
alias,
log,
warn,
error,
exit,
}) => {
let results
let deployId
try {
if (deployToProduction) {
await prepareProductionDeploy({ siteData, api, log, exit })
} else {
log('Deploying to draft URL...')
}
const draft = !deployToProduction && !alias
const title = flags.message
results = await api.createSiteDeploy({ siteId, title, body: { draft, branch: alias } })
deployId = results.id
const silent = flags.json || flags.silent
await deployEdgeHandlers({
site,
deployId,
api,
silent,
error,
warn,
})
results = await api.deploy(siteId, deployFolder, {
configPath,
fnDir: functionsFolder,
statusCb: silent ? () => {} : deployProgressCb(),
deployTimeout: flags.timeout * SEC_TO_MILLISEC || DEFAULT_DEPLOY_TIMEOUT,
syncFileLimit: SYNC_FILE_LIMIT,
// pass an existing deployId to update
deployId,
filter: getDeployFilesFilter({ site, deployFolder }),
})
} catch (error_) {
if (deployId) {
await cancelDeploy({ api, deployId, warn })
}
reportDeployError({ error: error_, warn, failAndExit: error })
}
const siteUrl = results.deploy.ssl_url || results.deploy.url
const deployUrl = get(results, 'deploy.deploy_ssl_url') || get(results, 'deploy.deploy_url')
const logsUrl = `${get(results, 'deploy.admin_url')}/deploys/${get(results, 'deploy.id')}`
return {
siteId: results.deploy.site_id,
siteName: results.deploy.name,
deployId: results.deployId,
siteUrl,
deployUrl,
logsUrl,
}
}
const printResults = ({ flags, results, deployToProduction, log, logJson, exit }) => {
const msgData = {
Logs: `${results.logsUrl}`,
'Unique Deploy URL': results.deployUrl,
}
if (deployToProduction) {
msgData['Website URL'] = results.siteUrl
} else {
delete msgData['Unique Deploy URL']
msgData['Website Draft URL'] = results.deployUrl
}
// Spacer
log()
// Json response for piping commands
if (flags.json) {
const jsonData = {
name: results.name,
site_id: results.site_id,
site_name: results.siteName,
deploy_id: results.deployId,
deploy_url: results.deployUrl,
logs: results.logsUrl,
}
if (deployToProduction) {
jsonData.url = results.siteUrl
}
logJson(jsonData)
exit(0)
} else {
log(prettyjson.render(msgData))
if (!deployToProduction) {
log()
log('If everything looks good on your draft URL, deploy it to your main site URL with the --prod flag.')
log(`${chalk.cyanBright.bold('netlify deploy --prod')}`)
log()
}
}
}
class DeployCommand extends Command {
async run() {
const { flags } = this.parse(DeployCommand)
const { log, logJson, warn, error, exit } = this
const { api, site, config } = this.netlify
const alias = flags.alias || flags.branch
if (flags.branch) {
warn('--branch flag has been renamed to --alias and will be removed in future versions')
}
const deployToProduction = flags.prod
await this.authenticate(flags.auth)
await this.config.runHook('analytics', {
eventName: 'command',
payload: {
command: 'deploy',
open: flags.open,
prod: flags.prod,
json: flags.json,
alias: Boolean(alias),
},
})
let siteId = flags.site || site.id
let siteData = {}
if (siteId) {
try {
siteData = await api.getSite({ siteId })
} catch (error_) {
// TODO specifically handle known cases (e.g. no account access)
if (error_.status === 404) {
error('Site not found')
} else {
error(error_.message)
}
}
} else {
this.log("This folder isn't linked to a site yet")
const NEW_SITE = '+ Create & configure a new site'
const EXISTING_SITE = 'Link this directory to an existing site'
const initializeOpts = [EXISTING_SITE, NEW_SITE]
const { initChoice } = await inquirer.prompt([
{
type: 'list',
name: 'initChoice',
message: 'What would you like to do?',
choices: initializeOpts,
},
])
// create site or search for one
if (initChoice === NEW_SITE) {
// run site:create command
siteData = await SitesCreateCommand.run([])
site.id = siteData.id
siteId = site.id
} else if (initChoice === EXISTING_SITE) {
// run link command
siteData = await LinkCommand.run([], false)
site.id = siteData.id
siteId = site.id
}
}
if (flags.trigger) {
return triggerDeploy({ api, siteId, siteData, log, error })
}
if (flags.build) {
const options = await getBuildOptions({
context: this,
token: this.getConfigToken()[0],
flags,
})
const exitCode = await runBuild(options)
if (exitCode !== 0) {
this.exit(exitCode)
}
}
const deployFolder = await getDeployFolder({ flags, config, site, siteData, log })
const functionsFolder = getFunctionsFolder({ flags, config, site, siteData })
const { configPath } = site
log(
prettyjson.render({
'Deploy path': deployFolder,
'Functions path': functionsFolder,
'Configuration path': configPath,
}),
)
const { functionsFolderStat } = await validateFolders({
deployFolder,
functionsFolder,
error,
log,
})
const results = await runDeploy({
flags,
deployToProduction,
site,
siteData,
api,
siteId,
deployFolder,
configPath,
// pass undefined functionsFolder if doesn't exist
functionsFolder: functionsFolderStat && functionsFolder,
alias,
log,
warn,
error,
exit,
})
printResults({ flags, results, deployToProduction, log, logJson, exit })
if (flags.open) {
const urlToOpen = deployToProduction ? results.siteUrl : results.deployUrl
await openBrowser({ url: urlToOpen, log })
exit()
}
}
}
DeployCommand.description = `Create a new deploy from the contents of a folder
Deploys from the build settings found in the netlify.toml file, or settings from the API.
The following environment variables can be used to override configuration file lookups and prompts:
- \`NETLIFY_AUTH_TOKEN\` - an access token to use when authenticating commands. Keep this value private.
- \`NETLIFY_SITE_ID\` - override any linked site in the current working directory.
Lambda functions in the function folder can be in the following configurations for deployment:
Built Go binaries:
------------------
\`\`\`
functions/
└── nameOfGoFunction
\`\`\`
Build binaries of your Go language functions into the functions folder as part of your build process.
Single file Node.js functions:
-----------------------------
Build dependency bundled Node.js lambda functions with tools like netlify-lambda, webpack or browserify into the function folder as part of your build process.
\`\`\`
functions/
└── nameOfBundledNodeJSFunction.js
\`\`\`
Unbundled Node.js functions that have dependencies outside or inside of the functions folder:
---------------------------------------------------------------------------------------------
You can ship unbundled Node.js functions with the CLI, utilizing top level project dependencies, or a nested package.json.
If you use nested dependencies, be sure to populate the nested node_modules as part of your build process before deploying using npm or yarn.
\`\`\`
project/
├── functions
│ ├── functionName/
│ │ ├── functionName.js (Note the folder and the function name need to match)
│ │ ├── package.json
│ │ └── node_modules/
│ └── unbundledFunction.js
├── package.json
├── netlify.toml
└── node_modules/
\`\`\`
Any mix of these configurations works as well.
Node.js function entry points
-----------------------------
Function entry points are determined by the file name and name of the folder they are in:
\`\`\`
functions/
├── aFolderlessFunctionEntrypoint.js
└── functionName/
├── notTheEntryPoint.js
└── functionName.js
\`\`\`
Support for package.json's main field, and intrinsic index.js entrypoints are coming soon.
`
DeployCommand.examples = [
'netlify deploy',
'netlify deploy --prod',
'netlify deploy --prod --open',
'netlify deploy --message "A message with an $ENV_VAR"',
'netlify deploy --auth $NETLIFY_AUTH_TOKEN',
'netlify deploy --trigger',
]
DeployCommand.flags = {
dir: flagsLib.string({
char: 'd',
description: 'Specify a folder to deploy',
}),
functions: flagsLib.string({
char: 'f',
description: 'Specify a functions folder to deploy',
}),
prod: flagsLib.boolean({
char: 'p',
description: 'Deploy to production',
default: false,
exclusive: ['alias', 'branch'],
}),
alias: flagsLib.string({
description:
'Specifies the alias for deployment. Useful for creating predictable deployment URLs. Maximum 37 characters.',
}),
branch: flagsLib.string({
char: 'b',
description: 'Serves the same functionality as --alias. Deprecated and will be removed in future versions',
}),
open: flagsLib.boolean({
char: 'o',
description: 'Open site after deploy',
default: false,
}),
message: flagsLib.string({
char: 'm',
description: 'A short message to include in the deploy log',
}),
auth: flagsLib.string({
char: 'a',
description: 'Netlify auth token to deploy with',
env: 'NETLIFY_AUTH_TOKEN',
}),
site: flagsLib.string({
char: 's',
description: 'A site ID to deploy to',
env: 'NETLIFY_SITE_ID',
}),
json: flagsLib.boolean({
description: 'Output deployment data as JSON',
}),
timeout: flagsLib.integer({
description: 'Timeout to wait for deployment to finish',
}),
trigger: flagsLib.boolean({
description: 'Trigger a new build of your site on Netlify without uploading local files',
exclusive: ['build'],
}),
build: flagsLib.boolean({
description: 'Run build command before deploying',
}),
...DeployCommand.flags,
}
const deployProgressCb = function () {
const events = {}
// statusObj: {
// type: name-of-step
// msg: msg to print
// phase: [start, progress, stop]
// }
//
return (ev) => {
switch (ev.phase) {
case 'start': {
const spinner = ev.spinner || randomItem(cliSpinnerNames)
events[ev.type] = ora({
text: ev.msg,
spinner,
}).start()
return
}
case 'progress': {
const spinner = events[ev.type]
if (spinner) spinner.text = ev.msg
return
}
case 'stop':
default: {
const spinner = events[ev.type]
if (spinner) {
spinner.stopAndPersist({ text: ev.msg, symbol: logSymbols.success })
delete events[ev.type]
}
}
}
}
}
module.exports = DeployCommand