|
| 1 | +const fs = require('fs') |
| 2 | +const path = require('path') |
| 3 | +const chalk = require('chalk') |
| 4 | +const resolve = require('resolve') |
| 5 | +const Generator = require('./Generator') |
| 6 | +const { |
| 7 | + log, |
| 8 | + error, |
| 9 | + logWithSpinner, |
| 10 | + stopSpinner |
| 11 | +} = require('@vue/cli-shared-utils') |
| 12 | + |
| 13 | +async function invoke (pluginName, options) { |
| 14 | + delete options._ |
| 15 | + const context = process.cwd() |
| 16 | + const pkgPath = path.resolve(context, 'package.json') |
| 17 | + |
| 18 | + if (!fs.existsSync(pkgPath)) { |
| 19 | + error(`package.json not found in ${chalk.yellow(context)}`) |
| 20 | + process.exit(1) |
| 21 | + } |
| 22 | + |
| 23 | + const pkg = require(pkgPath) |
| 24 | + |
| 25 | + // attempt to locate the plugin in package.json |
| 26 | + const findPlugin = deps => { |
| 27 | + if (!deps) return |
| 28 | + let name |
| 29 | + if (deps[name = pluginName] || |
| 30 | + deps[name = `@vue/cli-plugin-${pluginName}`] || |
| 31 | + deps[name = `vue-cli-plugin-${pluginName}`]) { |
| 32 | + return name |
| 33 | + } |
| 34 | + } |
| 35 | + const resolvedPluginName = ( |
| 36 | + findPlugin(pkg.devDependencies) || |
| 37 | + findPlugin(pkg.dependencies) |
| 38 | + ) |
| 39 | + |
| 40 | + if (!resolvedPluginName) { |
| 41 | + error(`Cannot resolve plugin ${chalk.yellow(pluginName)} from package.json.`) |
| 42 | + process.exit(1) |
| 43 | + } |
| 44 | + |
| 45 | + const generatorURI = `${resolvedPluginName}/generator` |
| 46 | + const generatorPath = resolve.sync(generatorURI, { basedir: context }) |
| 47 | + const plugin = { |
| 48 | + id: resolvedPluginName, |
| 49 | + apply: require(generatorPath), |
| 50 | + options |
| 51 | + } |
| 52 | + |
| 53 | + const createCompleteCbs = [] |
| 54 | + const generator = new Generator( |
| 55 | + context, |
| 56 | + pkg, |
| 57 | + [plugin], |
| 58 | + createCompleteCbs |
| 59 | + ) |
| 60 | + |
| 61 | + await generator.generate() |
| 62 | + |
| 63 | + // TODO check if package.json was changed, |
| 64 | + // if yes installDeps |
| 65 | + logWithSpinner('📦', `Installing additional dependencies...`) |
| 66 | + |
| 67 | + if (createCompleteCbs.lenght) { |
| 68 | + logWithSpinner('⚓', `Running completion hooks...`) |
| 69 | + for (const cb of createCompleteCbs) { |
| 70 | + await cb() |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + stopSpinner() |
| 75 | + log() |
| 76 | + log(` Successfully invoked generator for plugin: ${chalk.cyan(resolvedPluginName)}`) |
| 77 | + log(` You should review and commit the changes.`) |
| 78 | + log() |
| 79 | +} |
| 80 | + |
| 81 | +module.exports = (pluginName, options) => { |
| 82 | + invoke(pluginName, options).catch(err => { |
| 83 | + error(err) |
| 84 | + process.exit(1) |
| 85 | + }) |
| 86 | +} |
0 commit comments