forked from vuestorefront/vue-storefront
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstaller.js
661 lines (564 loc) · 16.6 KB
/
installer.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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
'use strict'
const shell = require('shelljs')
const mkdirp = require('mkdirp')
const exists = require('fs-exists-sync')
const message = require('print-message')
const inquirer = require('inquirer')
const jsonFile = require('jsonfile')
const urlParser = require('url-parse')
const isWindows = require('is-windows')
const isEmptyDir = require('empty-dir')
const commandExists = require('command-exists')
const SAMPLE_DATA_PATH = 'var/magento2-sample-data'
const TARGET_CONFIG_FILE = 'src/config.json'
const SOURCE_CONFIG_FILE = 'src/config.example.json'
const STOREFRONT_GIT_URL = 'https://github.com/DivanteLtd/vue-storefront'
const STOREFRONT_BACKEND_GIT_URL = 'https://github.com/DivanteLtd/vue-storefront-api'
const MAGENTO_SAMPLE_DATA_GIT_URL = 'https://github.com/magento/magento2-sample-data.git'
const STOREFRONT_REMOTE_BACKEND_URL = 'https://demo.vuestorefront.io'
const STOREFRONT_DIRECTORY = shell.pwd()
const LOG_DIR = `${STOREFRONT_DIRECTORY}/var/log`
const INSTALL_LOG_FILE = `${STOREFRONT_DIRECTORY}/var/log/install.log`
const VUE_STOREFRONT_LOG_FILE = `${STOREFRONT_DIRECTORY}/var/log/vue-storefront.log`
const VUE_STOREFRONT_BACKEND_LOG_FILE = `${STOREFRONT_DIRECTORY}/var/log/vue-storefront-api.log`
/**
* Message management
*/
class Message {
/**
* Renders informative message
*
* @param text
*/
static info (text) {
text = Array.isArray(text) ? text : [text]
message([
...text
], {color: 'blue', border: false, marginTop: 1})
}
/**
* Renders error message
*
* @param text
* @param logFile
*/
static error (text, logFile = INSTALL_LOG_FILE) {
text = Array.isArray(text) ? text : [text]
// show trace if exception occurred
if (text[0] instanceof Error) {
text = text[0].stack.split('\n')
}
let logDetailsInfo = `Please check log file for details: ${logFile}`
if (!Abstract.logsWereCreated) {
logDetailsInfo = 'Try to fix problem with logs to see the error details.'
}
message([
'ERROR',
'',
...text,
'',
logDetailsInfo
], {borderColor: 'red', marginBottom: 1})
shell.exit(1)
}
/**
* Render warning message
*
* @param text
*/
static warning (text) {
text = Array.isArray(text) ? text : [text]
message([
'WARNING:',
...text
], {color: 'yellow', border: false, marginTop: 1})
}
/**
* Render block info message
*
* @param text
* @param isLastMessage
*/
static greeting (text, isLastMessage = false) {
text = Array.isArray(text) ? text : [text]
message([
...text
], Object.assign(isLastMessage ? {marginTop: 1} : {}, {borderColor: 'green', marginBottom: 1}))
}
}
/**
* Abstract class for field initialization
*/
class Abstract {
/**
* Constructor
*
* Initialize fields
*/
constructor (answers) {
this.answers = answers
}
}
/**
* Scripts for initialization backend
*/
class Backend extends Abstract {
/**
* Clone API repository
*
* @returns {Promise}
*/
cloneRepository () {
return new Promise((resolve, reject) => {
Message.info(`Cloning backend into '${this.answers.backend_dir}'...`)
if (shell.exec(`${this.answers.git_path} clone ${STOREFRONT_BACKEND_GIT_URL} ${this.answers.backend_dir} > ${Abstract.infoLogStream} 2>&1`).code !== 0) {
reject(`Can't clone backend into '${this.answers.backend_dir}'.`)
}
resolve()
})
}
/**
* Go to backend directory
*
* @returns {Promise}
*/
goToDirectory (backendDir = null) {
return new Promise((resolve, reject) => {
let dir = this.answers ? this.answers.backend_dir : backendDir
Message.info(`Trying change directory to '${dir}'...`)
if (shell.cd(dir).code !== 0) {
reject(`Can't change directory to '${dir}'.`)
}
Message.info(`Working in directory '${shell.pwd()}'...`)
resolve()
})
}
/**
* Run 'npm install' in backend directory
*
* @returns {Promise}
*/
npmInstall () {
return new Promise((resolve, reject) => {
Message.info('Installing backend npm...')
if (shell.exec(`npm i >> ${Abstract.infoLogStream} 2>&1`).code !== 0) {
reject('Can\'t install backend npm.')
}
resolve()
})
}
/**
* Run 'docker-compose up' in background
*
* @returns {Promise}
*/
dockerComposeUp () {
return new Promise((resolve, reject) => {
Message.info('Starting docker in background...')
if (shell.exec(`docker-compose up -d > /dev/null 2>&1`).code !== 0) {
reject('Can\'t start docker in background.')
}
// Adding 20sec timer for ES to get up and running
// before starting restoration and migration processes
setTimeout(() => { resolve() }, 20000)
})
}
/**
* Creating backend src/config.json
*
* @returns {Promise}
*/
createConfig () {
return new Promise((resolve, reject) => {
let config
Message.info(`Creating backend config '${TARGET_CONFIG_FILE}'...`)
try {
config = jsonFile.readFileSync(SOURCE_CONFIG_FILE)
let host = urlParser(this.answers.images_endpoint).hostname
if (!host.length) {
throw new Error()
}
config.imageable.whitelist.allowedHosts.push(host)
config.imageable.whitelist.trustedHosts.push(host)
jsonFile.writeFileSync(TARGET_CONFIG_FILE, config, {spaces: 2})
} catch (e) {
reject('Can\'t create backend config.')
}
resolve()
})
}
/**
* Run 'npm run restore'
*
* @returns {Promise}
*/
restoreElasticSearch () {
return new Promise((resolve, reject) => {
Message.info('Restoring data for ElasticSearch...')
if (shell.exec(`npm run restore >> ${Abstract.infoLogStream} 2>&1`).code !== 0) {
reject('Can\'t restore data for ElasticSearch.')
}
resolve()
})
}
/**
* Run 'npm run migrate'
*
* @returns {Promise}
*/
migrateElasticSearch () {
return new Promise((resolve, reject) => {
Message.info('Migrating data into ElasticSearch...')
if (shell.exec(`npm run migrate >> ${Abstract.infoLogStream} 2>&1`).code !== 0) {
reject('Can\'t migrate data into ElasticSearch.')
}
resolve()
})
}
/**
* Cloning magento sample data
*
* @returns {Promise}
*/
cloneMagentoSampleData () {
return new Promise((resolve, reject) => {
Message.info(`Cloning Magento 2 Sample Data into '${SAMPLE_DATA_PATH}'...`)
if (shell.exec(`${this.answers.git_path} clone ${MAGENTO_SAMPLE_DATA_GIT_URL} ${SAMPLE_DATA_PATH} >> ${Abstract.infoLogStream} 2>&1`).code !== 0) {
reject(`Can't clone Magento 2 Sample Data into '${SAMPLE_DATA_PATH}'...`)
}
resolve()
})
}
/**
* Start 'npm run dev' in background
*
* @returns {Promise}
*/
runDevEnvironment () {
return new Promise((resolve, reject) => {
Message.info('Starting backend server...')
if (shell.exec(`nohup npm run dev > ${Abstract.backendLogStream} 2>&1 &`).code !== 0) {
reject('Can\'t start dev server.', VUE_STOREFRONT_BACKEND_LOG_FILE)
}
resolve()
})
}
}
/**
* Scripts for initialization storefront
*/
class Storefront extends Abstract {
/**
* Go to storefront directory
*
* @returns {Promise}
*/
goToDirectory () {
return new Promise((resolve, reject) => {
if (Abstract.wasLocalBackendInstalled) {
Message.info(`Trying change directory to '${STOREFRONT_DIRECTORY}'...`)
if (shell.cd(STOREFRONT_DIRECTORY).code !== 0) {
reject(`Can't change directory to '${STOREFRONT_DIRECTORY}'.`)
}
Message.info(`Working in directory '${STOREFRONT_DIRECTORY}'...`)
}
resolve()
})
}
/**
* Creating storefront src/config.json
*
* @returns {Promise}
*/
createConfig () {
return new Promise((resolve, reject) => {
let config
Message.info(`Creating storefront config '${TARGET_CONFIG_FILE}'...`)
try {
config = jsonFile.readFileSync(SOURCE_CONFIG_FILE)
let backendPath
if (Abstract.wasLocalBackendInstalled) {
backendPath = 'http://localhost:8080'
} else {
backendPath = STOREFRONT_REMOTE_BACKEND_URL
}
config.elasticsearch.host = `${backendPath}/api/catalog`
config.orders.endpoint = `${backendPath}/api/order`
config.users.endpoint = `${backendPath}/api/user`
config.stock.endpoint = `${backendPath}/api/stock`
config.mailchimp.endpoint = `${backendPath}/api/ext/mailchimp-subscribe/subscribe`
config.images.baseUrl = this.answers.images_endpoint
config.install = {
is_local_backend: Abstract.wasLocalBackendInstalled,
backend_dir: this.answers.backend_dir || false
}
jsonFile.writeFileSync(TARGET_CONFIG_FILE, config, {spaces: 2})
} catch (e) {
reject('Can\'t create storefront config.')
}
resolve()
})
}
/**
* Run 'npm run build' on storefront
*
* @returns {Promise}
*/
npmBuild () {
return new Promise((resolve, reject) => {
Message.info('Build storefront npm...')
if (shell.exec(`npm run build > ${Abstract.storefrontLogStream} 2>&1`).code !== 0) {
reject('Can\'t build storefront npm.', VUE_STOREFRONT_LOG_FILE)
}
resolve()
})
}
/**
* Start 'npm run dev' in background
*
* @returns {Promise}
*/
runDevEnvironment (answers) {
return new Promise((resolve, reject) => {
Message.info('Starting storefront server...')
if (shell.exec(`nohup npm run dev >> ${Abstract.storefrontLogStream} 2>&1 &`).code !== 0) {
reject('Can\'t start storefront server.', VUE_STOREFRONT_LOG_FILE)
}
resolve(answers)
})
}
}
class Manager extends Abstract {
/**
* {@inheritDoc}
*
* Assign backend and storefront entities
*/
constructor (answers) {
super(answers)
this.backend = new Backend(answers)
this.storefront = new Storefront(answers)
}
/**
* Trying to create log files
* If is impossible - warning shows
*
* @returns {Promise}
*/
tryToCreateLogFiles () {
return new Promise((resolve, reject) => {
Message.info('Trying to create log files...')
try {
mkdirp.sync(LOG_DIR, {mode: parseInt('0755', 8)})
let logFiles = [
INSTALL_LOG_FILE,
VUE_STOREFRONT_BACKEND_LOG_FILE,
VUE_STOREFRONT_LOG_FILE
]
for (let logFile of logFiles) {
if (shell.touch(logFile).code !== 0 || !exists(logFile)) {
throw new Error()
}
}
Abstract.logsWereCreated = true
Abstract.infoLogStream = INSTALL_LOG_FILE
Abstract.storefrontLogStream = VUE_STOREFRONT_LOG_FILE
Abstract.backendLogStream = VUE_STOREFRONT_BACKEND_LOG_FILE
} catch (e) {
Message.warning('Can\'t create log files.')
}
resolve()
})
}
/**
* Initialize all processes for backend (if selected)
*
* @returns {Promise}
*/
initBackend () {
if (this.answers.is_remote_backend === false) {
Abstract.wasLocalBackendInstalled = true
return this.backend.cloneRepository()
.then(this.backend.goToDirectory.bind(this.backend))
.then(this.backend.npmInstall.bind(this.backend))
.then(this.backend.createConfig.bind(this.backend))
.then(this.backend.dockerComposeUp.bind(this.backend))
.then(this.backend.restoreElasticSearch.bind(this.backend))
.then(this.backend.migrateElasticSearch.bind(this.backend))
.then(this.backend.cloneMagentoSampleData.bind(this.backend))
.then(this.backend.runDevEnvironment.bind(this.backend))
} else {
return Promise.resolve()
}
}
/**
* Initialize all processes for storefront
*
* @returns {Promise}
*/
initStorefront () {
return this.storefront.goToDirectory()
.then(this.storefront.createConfig.bind(this.storefront))
.then(this.storefront.npmBuild.bind(this.storefront))
.then(this.storefront.runDevEnvironment.bind(this.storefront))
}
/**
* Check user OS and shows error if not supported
*/
static checkUserOS () {
if (isWindows()) {
Message.error([
'Unfortunately currently only Linux and OSX are supported.',
'To install vue-storefront on your mac please go threw manual installation process provided in documentation:',
`${STOREFRONT_GIT_URL}/blob/master/doc/Installing%20on%20Windows.md`
])
}
}
/**
* Shows message rendered on the very beginning
*/
static showWelcomeMessage () {
Message.greeting([
'Hi, welcome to the vue-storefront installation.',
'Let\'s configure it together :)'
])
}
/**
* Shows details about successful installation finish
*
* @returns {Promise}
*/
showGoodbyeMessage () {
return new Promise((resolve, reject) => {
Message.greeting([
'Congratulations!',
'',
'You\'ve just successfully installed vue-storefront.',
'All required servers are running in background',
'',
'Storefront: http://localhost:3000',
'Backend: ' + (Abstract.wasLocalBackendInstalled ? 'http://localhost:8080' : STOREFRONT_REMOTE_BACKEND_URL),
'',
Abstract.logsWereCreated ? `Logs: ${LOG_DIR}/` : 'You don\'t have log files created.',
'',
'Good Luck!'
], true)
resolve()
})
}
}
/**
* Here we configure questions
*
* @type {[Object,Object,Object,Object]}
*/
let questions = [
{
type: 'confirm',
name: 'is_remote_backend',
message: `Would you like to use ${STOREFRONT_REMOTE_BACKEND_URL} as the backend?`,
default: true
},
{
type: 'input',
name: 'git_path',
message: 'Please provide Git path (if it\'s not globally installed)',
default: 'git',
when: function (answers) {
return answers.is_remote_backend === false
},
validate: function (value) {
if (!commandExists.sync(value)) {
return 'Invalid git path. Try again ;)'
}
return true
}
},
{
type: 'input',
name: 'backend_dir',
message: 'Please provide path for installing backend locally',
default: '../vue-storefront-api',
when: function (answers) {
return answers.is_remote_backend === false
},
validate: function (value) {
try {
mkdirp.sync(value, {mode: parseInt('0755', 8)})
if (!isEmptyDir.sync(value)) {
return 'Please provide path to empty directory.'
}
} catch (error) {
return 'Can\'t access to write in this directory. Try again ;)'
}
return true
}
},
{
type: 'list',
name: 'images_endpoint',
message: 'Choose path for images endpoint',
choices: [
`${STOREFRONT_REMOTE_BACKEND_URL}/img/`,
'http://localhost:8080/img/',
'Custom url'
],
when: function (answers) {
return answers.is_remote_backend === false
}
},
{
type: 'input',
name: 'images_endpoint',
message: 'Please provide path for images endpoint',
default: `${STOREFRONT_REMOTE_BACKEND_URL}/img/`,
when: function (answers) {
let isProvideByYourOwn = answers.images_endpoint === 'Custom url'
return isProvideByYourOwn || answers.is_remote_backend === true
},
filter: function (url) {
let prefix = 'http://'
let prefixSsl = 'https://'
url = url.trim()
// add http:// if no protocol set
if (url.substr(0, prefix.length) !== prefix && url.substr(0, prefixSsl.length) !== prefixSsl) {
url = prefix + url
}
// add extra slash as suffix if was not set
return url.slice(-1) === '/' ? url : `${url}/`
}
}
]
/**
* Predefine class static variables
*/
Abstract.wasLocalBackendInstalled = false
Abstract.logsWereCreated = false
Abstract.infoLogStream = '/dev/null'
Abstract.storefrontLogStream = '/dev/null'
Abstract.backendLogStream = '/dev/null'
if (require.main.filename === __filename) {
/**
* Pre-loading staff
*/
Manager.checkUserOS()
Manager.showWelcomeMessage()
/**
* This is where all the magic happens
*/
inquirer.prompt(questions).then(async function (answers) {
let manager = new Manager(answers)
await manager.tryToCreateLogFiles()
.then(manager.initBackend.bind(manager))
.then(manager.initStorefront.bind(manager))
.then(manager.showGoodbyeMessage.bind(manager))
.catch(Message.error)
shell.exit(0)
})
} else {
module.exports.Message = Message
module.exports.Manager = Manager
module.exports.Abstract = Abstract
module.exports.STOREFRONT_REMOTE_BACKEND_URL = STOREFRONT_REMOTE_BACKEND_URL
module.exports.TARGET_CONFIG_FILE = TARGET_CONFIG_FILE
}