UNPKG

19.1 kBJavaScriptView Raw
1const path = require('path')
2const fsEx = require('fs-extra')
3const inquirer = require('inquirer')
4const request = require('request')
5const unzip = require('unzip')
6const replace = require('replace-in-file')
7const childProcess = require('child_process')
8const logger = require('../logger')
9const utils = require('../utils/utils')
10
11const DEFAULT_NAME = 'cloud-sdk-boilerplate-extension-master'
12const BOILERPLATE_URL = process.env['BOILERPLATE_URL'] || 'https://github.com/shopgate/cloud-sdk-boilerplate-extension/archive/master.zip'
13const EXTENSION_NAME_REGEX = /^@[A-Za-z][A-Za-z0-9-_]{0,213}\/[A-Za-z][A-Za-z0-9-_]{0,213}$/
14
15const { EXTENSIONS_FOLDER } = require('../app/Constants')
16
17class ExtensionAction {
18 static build (appSettings, userSettings) {
19 return new ExtensionAction(appSettings, userSettings)
20 }
21
22 /**
23 * @param {Command} caporal
24 * @param {AppSettings} appSettings
25 * @param {UserSettings} userSettings
26 */
27 static register (caporal, appSettings, userSettings) {
28 caporal
29 .command('extension create')
30 .description('Creates a new extension')
31 .argument('[types...]', 'Types of the extension. Possible types are: frontend, backend')
32 .option('--extension [extensionName]', 'Name of the new extension (e.g: @myAwesomeOrg/awesomeExtension)')
33 .option('--trusted [type]', 'only valid if you\'re about to create a backend extension')
34 .action(async (args, options) => {
35 try {
36 await ExtensionAction.build(appSettings, userSettings).createExtension(args, options)
37 } catch (err) {
38 logger.error(err.message)
39 process.exit(1)
40 }
41 })
42
43 caporal
44 .command('extension attach')
45 .argument('[extensions...]', 'Folder name of the extensions to attach')
46 .description('Attaches one or more extensions')
47 .action(async (args) => {
48 try {
49 await ExtensionAction.build(appSettings, userSettings).attachExtensions(args)
50 } catch (err) {
51 // istanbul ignore next
52 logger.error(err.message)
53 process.exit(1)
54 }
55 })
56
57 caporal
58 .command('extension detach')
59 .argument('[extensions...]', 'Folder name of the extensions to detach')
60 .description('Detaches one or more extensions')
61 .action(async (args) => {
62 try {
63 await ExtensionAction.build(appSettings, userSettings).detachExtensions(args)
64 } catch (err) /* istanbul ignore next */ {
65 logger.error(err.message)
66 process.exit(1)
67 }
68 })
69
70 caporal
71 .command('extension manage')
72 .description('Attaches and detaches extensions via a select picker')
73 .action(async () => {
74 try {
75 await ExtensionAction.build(appSettings, userSettings).manageExtensions()
76 } catch (err) /* istanbul ignore next */ {
77 logger.error(err.message)
78 process.exit(1)
79 }
80 })
81 }
82
83 /**
84 * @param {AppSettings} appSettings
85 * @param {UserSettings} userSettings
86 */
87 constructor (appSettings, userSettings) {
88 this.appSettings = appSettings
89 this.userSettings = userSettings
90 }
91
92 /**
93 * @param {object} options
94 * @param {string[]} types
95 * @param {object} externalUserInput
96 */
97 _getUserInput (options, types = [], externalUserInput) {
98 let trusted = false
99 if (options.trusted === null) trusted = true
100 else if (typeof options.trusted === 'boolean') trusted = options.trusted
101
102 const userInput = {
103 extensionName: options.extension,
104 trusted,
105 toBeCreated: {
106 frontend: types.includes('frontend'),
107 backend: types.includes('backend')
108 }
109 }
110
111 const questions = []
112
113 if (!userInput.toBeCreated.frontend && !userInput.toBeCreated.backend) {
114 questions.push({
115 name: 'types',
116 message: 'What type of extension are you about to create?',
117 type: 'checkbox',
118 validate: (input) => {
119 if (input.length === 0) return 'Please select at least one type'
120 return true
121 },
122 default: ['backend', 'frontend'],
123 choices: ['backend', 'frontend']
124 })
125 }
126
127 if (!userInput.extensionName || !EXTENSION_NAME_REGEX.test(userInput.extensionName)) {
128 questions.push({
129 name: 'extensionName',
130 message: 'Extension name (e.g: @myAwesomeOrg/awesomeExtension):',
131 validate: (input) => {
132 const valid = /^@[A-Za-z][A-Za-z0-9-_]{0,213}\/[A-Za-z][A-Za-z0-9-_]{0,213}$/.test(input)
133 if (!valid) return 'Please provide an extension name in the following format: @<organizationName>/<name>'
134 return true
135 },
136 when: (answers) => {
137 // Consider it unnecessary if there isn't a type neigher in answers.types nor types
138 return (answers.types && answers.types.length) > 0 || types.length > 0
139 }
140 })
141 }
142
143 if (userInput.trusted === null) {
144 questions.push({
145 name: 'trusted',
146 message: 'Does your backend extension need to run in a trusted environment?',
147 type: 'list',
148 choices: ['yes', 'no'],
149 default: 'no',
150 when: (answers) => {
151 // Consider unnecessary if there isn't a type or its only frontend
152 return (answers.types && answers.types.includes('backend')) || types.includes('backend')
153 }
154 })
155 }
156
157 return new Promise((resolve, reject) => {
158 if (questions.length > 0) {
159 return inquirer.prompt(questions).then((answers) => {
160 if (answers.extensionName) userInput.extensionName = answers.extensionName
161 if (answers.types && answers.types.includes('frontend')) userInput.toBeCreated.frontend = true
162 if (answers.types && answers.types.includes('backend')) userInput.toBeCreated.backend = true
163 if (answers.trusted) userInput.trusted = answers.trusted === 'yes'
164 if (userInput.toBeCreated.backend === false && userInput.toBeCreated.frontend === false) throw new Error('No extension type selected')
165 Object.assign(externalUserInput, userInput)
166 resolve()
167 }).catch(err => reject(err))
168 }
169
170 Object.assign(externalUserInput, userInput)
171 resolve()
172 })
173 .then(() => {
174 externalUserInput.organizationName = userInput.extensionName.split('/')[0].replace('@', '')
175 })
176 }
177
178 /**
179 * @param {string} extensionsFolder
180 * @param {object} state
181 */
182
183 _downloadBoilerplate (extensionsFolder, state) {
184 logger.debug('Downloading boilerplate ...')
185
186 return new Promise((resolve, reject) => {
187 const extractor = unzip.Extract({ path: extensionsFolder })
188 extractor.on('close', () => {
189 logger.debug('Downloading boilerplate ... done')
190 state.cloned = true
191 resolve()
192 })
193 extractor.on('error', (err) => {
194 if (process.env['LOG_LEVEL'] === 'debug') logger.error(err)
195 reject(new Error(`Error while downloading boilerplate: ${err.message}`))
196 })
197 request(BOILERPLATE_URL).pipe(extractor)
198 })
199 }
200
201 /**
202 * @param {object} userInput
203 * @param {string} defaultPath
204 * @param {string} extensionsFolder
205 * @param {object} state
206 */
207 _renameBoilerplate (userInput, defaultPath, extensionsFolder, state) {
208 logger.debug('Renamig boilerplate ...')
209 const ePath = path.join(extensionsFolder, userInput.extensionName.replace('/', '-'))
210 return new Promise((resolve, reject) => {
211 fsEx.rename(defaultPath, ePath, (err) => {
212 if (err) {
213 if (process.env['LOG_LEVEL'] === 'debug') logger.error(err)
214 return reject(new Error(`Error while renaming boilerplate ${err.message}`))
215 }
216 state.extensionPath = ePath
217 state.moved = true
218 logger.debug('Renamig boilerplate ... done')
219 resolve()
220 })
221 })
222 }
223
224 /**
225 * @param {object} userInput
226 * @param {object} state
227 */
228 _removeUnusedDirs (userInput, state) {
229 const promises = []
230
231 if (!userInput.toBeCreated.frontend) promises.push(fsEx.remove(path.join(state.extensionPath, 'frontend')))
232 if (!userInput.toBeCreated.backend) {
233 promises.push(fsEx.remove(path.join(state.extensionPath, 'extension')))
234 promises.push(fsEx.remove(path.join(state.extensionPath, 'pipelines')))
235 }
236
237 if (promises.length > 0) logger.debug('Removing unused dirs ...')
238
239 return Promise.all(promises).then(logger.debug('Removing unused dirs ... done'))
240 }
241
242 /**
243 * @param {object} userInput
244 * @param {object} state
245 */
246 _removePlaceholders (userInput, state) {
247 logger.debug(`Removing placeholders in ${state.extensionPath} ...`)
248 return replace({
249 files: [
250 `${state.extensionPath}/**/*.json`,
251 `${state.extensionPath}/*.json`
252 ],
253 from: [
254 /@awesomeOrganization\/awesomeExtension/g,
255 /awesomeOrganization/g
256 ],
257 to: [
258 userInput.extensionName,
259 userInput.organizationName
260 ]
261 })
262 .then((changes) => logger.debug(`Removing placeholders in ${changes} ... done`))
263 .catch(err => {
264 // Because replace fails if no files match the pattern ...
265 if (err.message.startsWith('No files match the pattern')) return logger.debug(err.message)
266 })
267 }
268
269 /**
270 * @param {object} userInput
271 * @param {object} state
272 */
273 _updateBackendFiles (userInput, state) {
274 if (!userInput.toBeCreated.backend) return
275
276 logger.debug('Updating backend files')
277
278 const promises = []
279 // Rename default pipeline
280 const pipelineDirPath = path.join(state.extensionPath, 'pipelines')
281 promises.push(fsEx.move(path.join(pipelineDirPath, 'awesomeOrganization.awesomePipeline.v1.json'), path.join(pipelineDirPath, `${userInput.organizationName}.awesomePipeline.v1.json`)))
282
283 // Add trusted if necessary
284 if (userInput.trusted) {
285 const exConfPath = path.join(state.extensionPath, 'extension-config.json')
286
287 const p = fsEx.readJSON(exConfPath)
288 .then((exConf) => {
289 exConf.trusted = userInput.trusted
290 return fsEx.writeJson(exConfPath, exConf, { spaces: 2 })
291 })
292
293 promises.push(p)
294 }
295
296 return Promise.all(promises).then(logger.debug('Updating backend files ... done'))
297 }
298
299 /**
300 * @param {object} userInput
301 * @param {object} state
302 * @param {object=} command
303 */
304 _installFrontendDependencies (userInput, state, command) {
305 if (!userInput.toBeCreated.frontend) return
306 command = command || { command: /^win/.test(process.platform) ? 'npm.cmd' : 'npm', params: ['i'] }
307
308 const frontendPath = path.join(state.extensionPath, 'frontend')
309
310 let stdioMode = 'inherit'
311 if (process.env.INTEGRATION_TEST === 'true') {
312 stdioMode = 'ignore'
313 }
314
315 return new Promise((resolve, reject) => {
316 logger.info('Installing frontend depenencies ...')
317 const installProcess = childProcess.spawn(command.command, command.params, {
318 env: process.env,
319 cwd: frontendPath,
320 stdio: stdioMode
321 })
322 installProcess.on('exit', (code, signal) => {
323 if (code === 0) return resolve()
324 reject(new Error(`Install process exited with code ${code} and signal ${signal}`))
325 })
326 })
327 }
328
329 async _cleanUp (state, defaultPath) {
330 if (state.cloned) await fsEx.remove(state.moved ? state.extensionPath : defaultPath)
331 }
332
333 /**
334 * @param {string[]} types
335 * @param {object} options
336 */
337 async createExtension ({ types }, options) {
338 await this.userSettings.validate()
339 await this.appSettings.validate()
340
341 const userInput = {}
342 let state = {
343 cloned: false,
344 moved: false,
345 extensionPath: null
346 }
347
348 const extensionsFolder = path.join(this.appSettings.getApplicationFolder(), EXTENSIONS_FOLDER)
349 const defaultPath = path.join(extensionsFolder, DEFAULT_NAME)
350
351 try {
352 await this._getUserInput(options, types, userInput)
353 await this._checkIfExtensionExists(userInput.extensionName)
354 await this._downloadBoilerplate(extensionsFolder, state)
355 await this._renameBoilerplate(userInput, defaultPath, extensionsFolder, state)
356 await this._removeUnusedDirs(userInput, state)
357 await this._removePlaceholders(userInput, state)
358 await this._updateBackendFiles(userInput, state)
359 await this._installFrontendDependencies(userInput, state)
360 logger.info(`Extension "${userInput.extensionName}" created successfully`)
361 } catch (err) {
362 logger.error(`An error occured while creating the extension: ${err}`)
363 await this._cleanUp(state, defaultPath)
364 }
365 }
366
367 /**
368 * @param {String[]} A list of extension folder names (path, relative to the "extensions" folder).
369 */
370 async attachExtensions ({ extensions = [] }) {
371 await this.userSettings.validate()
372 await this.appSettings.validate()
373
374 let force = false
375 if (!extensions.length) {
376 extensions = await this._getAllExtensions()
377 force = true
378 }
379
380 const extensionInfo = await Promise.all(extensions.map(extensionFolderName => this._getExtensionInfo(extensionFolderName, true)))
381
382 const proccessedExtensions = extensions
383 .reduce((processedExtensions, extensionFolderName, index) => {
384 if (!extensionInfo[index]) {
385 logger.warn(`There is no extension in folder: './extensions/${extensionFolderName}'. Skipping... Please make sure that you only pass the folder name of the extension as argument.`)
386 } else {
387 processedExtensions.push({ extensionFolderName, extensionInfo: extensionInfo[index] })
388 }
389
390 return processedExtensions
391 }, [])
392
393 while (proccessedExtensions.length > 0) {
394 const processedExtension = proccessedExtensions.pop()
395 await this.appSettings.attachExtension(
396 processedExtension.extensionFolderName,
397 {
398 id: processedExtension.extensionInfo.id,
399 trusted: processedExtension.extensionInfo.trusted
400 },
401 force
402 )
403 }
404 return utils.generateComponentsJson(this.appSettings)
405 }
406
407 /**
408 * @param {String[]} A list of extension folder names (path, relative to the "extensions" folder).
409 */
410 async detachExtensions ({ extensions = [] }) {
411 await this.userSettings.validate()
412 await this.appSettings.validate()
413
414 if (!extensions.length) {
415 await this.appSettings.detachAllExtensions()
416 return
417 }
418
419 const extensionInfo = await Promise.all(extensions.map(extensionFolderName => this._getExtensionInfo(extensionFolderName, true)))
420
421 const processedExtensions = extensions
422 .reduce((processedExtensions, extensionFolderName, index) => {
423 if (!extensionInfo[index]) {
424 logger.warn(`There is no extension in folder: './extensions/${extensionFolderName}'. Skipping... Please make sure that you only pass the folder name of the extension as argument.`)
425 } else {
426 processedExtensions.push({ extensionFolderName, extensionInfo: extensionInfo[index] })
427 }
428
429 return processedExtensions
430 }, [])
431
432 for (const processedExtension of processedExtensions) {
433 await this.appSettings.detachExtension(processedExtension.extensionInfo.id)
434 }
435 }
436
437 async manageExtensions () {
438 await this.userSettings.validate()
439 await this.appSettings.validate()
440
441 // Get the extension properties and sort the entries alphabetically for better readability within the picker
442 // const extensionsSummary = await this._getExtensionsSummary().sort((a, b) => a.id.localeCompare(b.id))
443 const extensionPropeties = await this._getAllExtensionProperties()
444
445 if (extensionPropeties.length === 0) {
446 return logger.warn('There are no extensions in folder \'./extensions/\'')
447 }
448
449 const selected = (await inquirer.prompt({
450 type: 'checkbox',
451 name: 'extensions',
452 message: 'Select extensions to attach',
453 pageSize: 10,
454 choices: extensionPropeties.map(({ id, attached }) => ({
455 name: id,
456 checked: attached
457 }))
458 })).extensions.map((selectedId) => {
459 // Collect the dirnames of the selected extensions
460 return extensionPropeties.find(({ id }) => id === selectedId).dir
461 })
462
463 // Create dirname lists of the available extensions since they are needed later to attach in detach
464 const attached = extensionPropeties.filter(({ attached }) => attached).map(({ dir }) => dir)
465 const detached = extensionPropeties.filter(({ attached }) => !attached).map(({ dir }) => dir)
466
467 const toBeAttached = selected.filter(entry => detached.includes(entry))
468 const toBeDetached = attached.filter(entry => !selected.includes(entry))
469
470 if (toBeDetached.length) await this.detachExtensions({ extensions: toBeDetached })
471 if (toBeAttached.length) await this.attachExtensions({ extensions: toBeAttached })
472 }
473
474 async _getAllExtensionProperties () {
475 let attachedExtensions = await this.appSettings.loadAttachedExtensions()
476 attachedExtensions = Object.keys(attachedExtensions)
477
478 const extensionsFolder = path.join(this.appSettings.getApplicationFolder(), EXTENSIONS_FOLDER)
479 const files = await fsEx.readdir(extensionsFolder)
480
481 const extensionInfo = await Promise.all(files.map(file => this._getExtensionInfo(file, true)))
482
483 return files.reduce((properties, file, index) => {
484 if (extensionInfo[index]) {
485 const { id } = extensionInfo[index]
486 properties.push({
487 id,
488 dir: file,
489 attached: attachedExtensions.includes(id)
490 })
491 }
492 return properties
493 }, [])
494 }
495
496 _checkIfExtensionExists (extensionName) {
497 const extensionsFolder = path.join(this.appSettings.getApplicationFolder(), EXTENSIONS_FOLDER, extensionName.replace('/', '-'))
498 return fsEx.pathExists(extensionsFolder)
499 .then((exists) => {
500 if (exists) throw new Error(`The extension '${extensionName}' already exists`)
501 })
502 }
503
504 /**
505 * @return {String[]} extensionId[]
506 */
507 async _getAllExtensions () {
508 const extensionsFolder = path.join(this.appSettings.getApplicationFolder(), EXTENSIONS_FOLDER)
509 const files = await fsEx.readdir(extensionsFolder)
510
511 const extensionInfo = await Promise.all(files.map(file => this._getExtensionInfo(file, true)))
512 return Promise.all(files.filter((file, index) => extensionInfo[index]))
513 }
514
515 /**
516 * @param {String} extensionFolderName
517 * @param {Boolean} ignoreNotExisting
518 * @return {Promise<ExtensionInfo|void>} extensionId
519 */
520 async _getExtensionInfo (extensionFolderName, ignoreNotExisting) {
521 const extensionsFolder = path.join(this.appSettings.getApplicationFolder(), EXTENSIONS_FOLDER)
522 const file = path.join(extensionsFolder, extensionFolderName, 'extension-config.json')
523 if (!await fsEx.exists(file)) {
524 if (!ignoreNotExisting) logger.error(`"${file}" does not exist`)
525 return
526 }
527
528 try {
529 const json = await fsEx.readJSON(file)
530 if (!json.id) return logger.warn(`"${file}" has no "id"-property`)
531 json.trusted = json.trusted || false
532 return json
533 } catch (e) {
534 logger.warn(`"${file}" is invalid json`)
535 }
536 }
537}
538
539module.exports = ExtensionAction