1 | import compose from './compose';
|
2 | import chalk from 'chalk';
|
3 | import osenv from 'osenv';
|
4 | import path from 'path';
|
5 | import { FEFLOW_ROOT, UNIVERSAL_PLUGIN_CONFIG } from '../../shared/constant';
|
6 | import { CommandPickConfig, COMMAND_TYPE } from '../command-picker';
|
7 | import logger from '../logger';
|
8 | import { Plugin } from '../universal-pkg/schema/plugin';
|
9 | import fs from 'fs';
|
10 | import { parseYaml } from '../../shared/yaml';
|
11 |
|
12 | export default function applyPlugins(plugins: any[]) {
|
13 | return (ctx: any) => {
|
14 | if (!plugins.length) {
|
15 | return;
|
16 | }
|
17 | const pickConfig = new CommandPickConfig(ctx);
|
18 |
|
19 | const chain = plugins.map((name: any) => {
|
20 | const home = path.join(osenv.home(), FEFLOW_ROOT);
|
21 | const pluginPath = path.join(home, 'node_modules', name);
|
22 | pickConfig.registSubCommand(COMMAND_TYPE.PLUGIN_TYPE, ctx.commander.store, name);
|
23 |
|
24 | try {
|
25 | ctx.logger.debug('Plugin loaded: %s', chalk.magenta(name));
|
26 | const pluginLogger = logger({
|
27 | debug: Boolean(ctx.args.debug),
|
28 | silent: Boolean(ctx.args.silent),
|
29 | name,
|
30 | });
|
31 | return require(pluginPath)(Object.assign({}, ctx, {logger: pluginLogger}));
|
32 | } catch (err) {
|
33 | ctx.fefError.printError({ error: err, msg: 'command load failed: %s', pluginPath });
|
34 | }
|
35 | });
|
36 |
|
37 | compose(...chain);
|
38 | pickConfig.registSubCommand(COMMAND_TYPE.PLUGIN_TYPE, ctx.commander.store);
|
39 | pickConfig.updateCache(COMMAND_TYPE.PLUGIN_TYPE);
|
40 | };
|
41 | }
|
42 |
|
43 |
|
44 | export function resolvePlugin(ctx: any, repoPath: string): Plugin {
|
45 | const pluginFile = path.join(repoPath, UNIVERSAL_PLUGIN_CONFIG);
|
46 | const exists = fs.existsSync(pluginFile);
|
47 | if (!exists) {
|
48 | throw `the ${UNIVERSAL_PLUGIN_CONFIG} file was not found`;
|
49 | }
|
50 | let config;
|
51 | try {
|
52 | config = parseYaml(pluginFile);
|
53 | } catch (e) {
|
54 | throw `the ${UNIVERSAL_PLUGIN_CONFIG} file failed to resolve, please check the syntax, e: ${e}`;
|
55 | }
|
56 | return new Plugin(ctx, repoPath, config);
|
57 | }
|