index.js
1 const fs = require('./../../core/fs.js'); 2 const utils = require('./../../utils/utils.js'); 3 const async = require('async'); 4 5 class PluginCommand { 6 constructor(embark) { 7 this.embark = embark; 8 this.config = this.embark.pluginConfig; 9 this.embarkConfig = this.config.embarkConfig; 10 this.registerCommand(); 11 } 12 13 registerCommand() { 14 this.embark.registerConsoleCommand((cmd, _options) => { 15 let cmdArray = cmd.split(' '); 16 cmdArray = cmdArray.filter(cmd => cmd.trim().length > 0); 17 let cmdName = cmdArray[0]; 18 return { 19 match: () => cmdName === 'plugin', 20 process: this.installPlugin.bind(this, cmdArray) 21 }; 22 }); 23 } 24 25 installPlugin(cmdArray, callback) { 26 const self = this; 27 28 if (cmdArray.length < 3 || cmdArray[1] !== 'install' || typeof cmdArray[2] === 'undefined') { 29 return callback(__('Invalid use of plugin command. Please use `plugin install <package>`')); 30 } 31 let npmInstall = ['npm', 'install', '--save']; 32 npmInstall = npmInstall.concat(cmdArray.slice(2)); 33 let npmPackage = npmInstall[3]; 34 if (!npmPackage.startsWith('embark')) { 35 npmPackage = 'embark-' + npmPackage; 36 } 37 self.embark.logger.info(__('Installing npm package %s...', npmPackage)); 38 async.waterfall([ 39 function npmInstallAsync(cb) { 40 utils.runCmd(npmInstall.join(' '), {silent: false, exitOnError: false}, (err) => { 41 if (err) { 42 return cb(err); 43 } 44 cb(); 45 }); 46 }, 47 function addToEmbarkConfig(cb) { 48 // get the installed package from package.json 49 let packageFile = fs.readJSONSync(self.config.packageFile); 50 let dependencies = Object.keys(packageFile.dependencies); 51 let installedPackage = dependencies.filter((dep) => npmPackage.indexOf(dep) >= 0); 52 self.embarkConfig.plugins[installedPackage[0]] = {}; 53 fs.writeFile(self.config.embarkConfigFile, JSON.stringify(self.embarkConfig, null, 2), cb); 54 } 55 ], (err) => { 56 if (err) { 57 self.embark.logger.error(__('Error installing npm package %s. Please visit ' + 58 'https://embark.status.im/plugins/ for all supported plugins', npmPackage)); 59 return callback(__('Error occurred')); 60 } 61 callback(null, __('NPM package %s successfully installed as a plugin', npmPackage)); 62 }); 63 } 64 } 65 66 module.exports = PluginCommand;