-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathexecute-plugin.ts
More file actions
190 lines (176 loc) · 4.74 KB
/
execute-plugin.ts
File metadata and controls
190 lines (176 loc) · 4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import { bold } from 'ansis';
import type {
Audit,
AuditOutput,
AuditReport,
CacheConfigObject,
PersistConfig,
PluginConfig,
PluginReport,
} from '@code-pushup/models';
import {
type ProgressBar,
getProgressBar,
groupByStatus,
logMultipleResults,
pluralizeToken,
} from '@code-pushup/utils';
import {
executePluginRunner,
readRunnerResults,
writeRunnerResults,
} from './runner.js';
/**
* Execute a plugin.
*
* @public
* @param pluginConfig - {@link ProcessConfig} object with runner and meta
* @param opt
* @returns {Promise<AuditOutput[]>} - audit outputs from plugin runner
* @throws {AuditOutputsMissingAuditError} - if plugin runner output is invalid
*
* @example
* // plugin execution
* const pluginCfg = pluginConfigSchema.parse({...});
* const output = await executePlugin(pluginCfg);
*
* @example
* // error handling
* try {
* await executePlugin(pluginCfg);
* } catch (e) {
* console.error(e.message);
* }
*/
export async function executePlugin(
pluginConfig: PluginConfig,
opt: {
cache: CacheConfigObject;
persist: Required<Pick<PersistConfig, 'outputDir'>>;
},
): Promise<PluginReport> {
const { cache, persist } = opt;
const {
runner,
audits: pluginConfigAudits,
description,
docsUrl,
groups,
...pluginMeta
} = pluginConfig;
const { write: cacheWrite = false, read: cacheRead = false } = cache;
const { outputDir } = persist;
const { audits, ...executionMeta } = cacheRead
? // IF not null, take the result from cache
((await readRunnerResults(pluginMeta.slug, outputDir)) ??
// ELSE execute the plugin runner
(await executePluginRunner(pluginConfig, persist)))
: await executePluginRunner(pluginConfig, persist);
if (cacheWrite) {
await writeRunnerResults(pluginMeta.slug, outputDir, {
...executionMeta,
audits,
});
}
// enrich `AuditOutputs` to `AuditReport`
const auditReports: AuditReport[] = audits.map(
(auditOutput: AuditOutput) => ({
...auditOutput,
...(pluginConfigAudits.find(
audit => audit.slug === auditOutput.slug,
) as Audit),
}),
);
// create plugin report
return {
...pluginMeta,
...executionMeta,
audits: auditReports,
...(description && { description }),
...(docsUrl && { docsUrl }),
...(groups && { groups }),
};
}
const wrapProgress = async (
cfg: {
plugin: PluginConfig;
persist: Required<Pick<PersistConfig, 'outputDir'>>;
cache: CacheConfigObject;
},
steps: number,
progressBar: ProgressBar | null,
) => {
const { plugin: pluginCfg, ...rest } = cfg;
progressBar?.updateTitle(`Executing ${bold(pluginCfg.title)}`);
try {
const pluginReport = await executePlugin(pluginCfg, rest);
progressBar?.incrementInSteps(steps);
return pluginReport;
} catch (error) {
progressBar?.incrementInSteps(steps);
throw new Error(
error instanceof Error
? `- Plugin ${bold(pluginCfg.title)} (${bold(
pluginCfg.slug,
)}) produced the following error:\n - ${error.message}`
: String(error),
);
}
};
/**
* Execute multiple plugins and aggregates their output.
* @public
* @param cfg
* @param {Object} [options] execution options
* @param {boolean} options.progress show progress bar
* @returns {Promise<PluginReport[]>} plugin report
*
* @example
* // plugin execution
* const plugins = [pluginConfigSchema.parse({...})];
*
* @example
* // error handling
* try {
* await executePlugins(plugins);
* } catch (e) {
* console.error(e.message); // Plugin output is invalid
* }
*
*/
export async function executePlugins(
cfg: {
plugins: PluginConfig[];
persist: Required<Pick<PersistConfig, 'outputDir'>>;
cache: CacheConfigObject;
},
options?: { progress?: boolean },
): Promise<PluginReport[]> {
const { plugins, ...cacheCfg } = cfg;
const { progress = false } = options ?? {};
const progressBar = progress ? getProgressBar('Run plugins') : null;
const pluginsResult = plugins.map(pluginCfg =>
wrapProgress(
{ plugin: pluginCfg, ...cacheCfg },
plugins.length,
progressBar,
),
);
const errorsTransform = ({ reason }: PromiseRejectedResult) => String(reason);
const results = await Promise.allSettled(pluginsResult);
progressBar?.endProgress('Done running plugins');
logMultipleResults(results, 'Plugins', undefined, errorsTransform);
const { fulfilled, rejected } = groupByStatus(results);
if (rejected.length > 0) {
const errorMessages = rejected
.map(({ reason }) => String(reason))
.join('\n');
throw new Error(
`Executing ${pluralizeToken(
'plugin',
rejected.length,
)} failed.\n\n${errorMessages}\n\n`,
);
}
return fulfilled.map(result => result.value);
}