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.logger.error(
|
34 | { err: err },
|
35 | 'Plugin load failed: %s',
|
36 | chalk.magenta(name)
|
37 | );
|
38 | }
|
39 | });
|
40 |
|
41 | compose(...chain);
|
42 | pickConfig.registSubCommand(COMMAND_TYPE.PLUGIN_TYPE, ctx.commander.store);
|
43 | pickConfig.updateCache(COMMAND_TYPE.PLUGIN_TYPE);
|
44 | };
|
45 | }
|
46 |
|
47 |
|
48 | export function resolvePlugin(ctx: any, repoPath: string): Plugin {
|
49 | const pluginFile = path.join(repoPath, UNIVERSAL_PLUGIN_CONFIG);
|
50 | const exists = fs.existsSync(pluginFile);
|
51 | if (!exists) {
|
52 | throw `the ${UNIVERSAL_PLUGIN_CONFIG} file was not found`;
|
53 | }
|
54 | let config;
|
55 | try {
|
56 | config = parseYaml(pluginFile);
|
57 | } catch (e) {
|
58 | throw `the ${UNIVERSAL_PLUGIN_CONFIG} file failed to resolve, please check the syntax, e: ${e}`;
|
59 | }
|
60 | return new Plugin(ctx, repoPath, config);
|
61 | }
|