-
Notifications
You must be signed in to change notification settings - Fork 29
/
cli.ts
195 lines (185 loc) · 6.09 KB
/
cli.ts
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
191
192
193
194
195
#!/usr/bin/env node
/* eslint-disable no-console */
import { Command } from 'commander';
import { LogLevel, WebClient } from '@slack/web-api';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { IncomingWebhook } from '@slack/webhook';
import path from 'path';
import ResultsParser from './src/ResultsParser';
import SlackClient from './src/SlackClient';
import doPreChecks from './src/cli/cli_pre_checks';
import { ICliConfig } from './src/cli/cli_schema';
import { Meta, SummaryResults } from './src';
import SlackWebhookClient from './src/SlackWebhookClient';
const program = new Command();
program
.name('playwright-slack-report - cli')
.version('1.0.0')
.description('📦 Send Playwright json results to directly Slack ')
.option(
'-c, --config <path>',
'Configuration file for the CLI app e.g ./config.json',
)
.option(
'-j, --json-results <path>',
'Generated Playwright json results file e.g. ./results.json',
)
.action(async (options) => {
const preCheckResult = await doPreChecks(
options.jsonResults,
options.config,
);
const config: ICliConfig = preCheckResult.config!;
if (preCheckResult.status === 'error') {
console.error(`❌ ${preCheckResult.message}`);
process.exit(1);
}
const agent = config.proxy ? new HttpsProxyAgent(config.proxy) : undefined;
const resultsParser = new ResultsParser();
const resultSummary = await resultsParser.parseFromJsonFile(
preCheckResult.jsonPath!,
);
if (config.sendUsingBot) {
const slackClient = new SlackClient(
new WebClient(process.env.SLACK_BOT_USER_OAUTH_TOKEN, {
logLevel: config.slackLogLevel,
agent,
}),
);
const success = await sendResultsUsingBot({
resultSummary,
slackClient,
config,
});
if (!success) {
console.error('❌ Failed to send results to Slack');
process.exit(1);
} else {
console.log('✅ Results sent to Slack');
process.exit(0);
}
}
if (config.sendUsingWebhook) {
const webhook = new IncomingWebhook(config.sendUsingWebhook.webhookUrl, {
agent,
});
const slackWebhookClient = new SlackWebhookClient(webhook);
let summaryResults = resultSummary;
const meta = replaceEnvVars(config.meta);
summaryResults = { ...resultSummary, meta };
const webhookResult = await slackWebhookClient.sendMessage({
customLayout: await attemptToImportLayout(
config.customLayout?.source,
config.customLayout?.functionName,
),
customLayoutAsync: await attemptToImportLayout(
config.customLayoutAsync?.source,
config.customLayoutAsync?.functionName,
),
maxNumberOfFailures: config.maxNumberOfFailures,
disableUnfurl: config.disableUnfurl,
summaryResults,
});
// eslint-disable-next-line no-console
console.log(JSON.stringify(webhookResult, null, 2));
console.log('✅ Results sent to Slack');
process.exit(0);
}
});
program.parse();
async function sendResultsUsingBot({
resultSummary,
slackClient,
config,
}: {
resultSummary: SummaryResults;
slackClient: SlackClient;
config: ICliConfig;
}): Promise<boolean> {
if (config.slackLogLevel === LogLevel.DEBUG) {
console.log({ config });
}
if (
resultSummary.failures.length === 0
&& config.sendResults === 'on-failure'
) {
console.log('⏩ Slack CLI reporter - no failures found');
return true;
}
let summaryResults = resultSummary;
const meta = replaceEnvVars(config.meta);
summaryResults = { ...resultSummary, meta };
if (config.sendUsingBot) {
const result = await slackClient.sendMessage({
options: {
channelIds: config.sendUsingBot.channels,
customLayout: await attemptToImportLayout(
config.customLayout?.source,
config.customLayout?.functionName,
),
customLayoutAsync: await attemptToImportLayout(
config.customLayoutAsync?.source,
config.customLayoutAsync?.functionName,
),
maxNumberOfFailures: config.maxNumberOfFailures,
disableUnfurl: config.disableUnfurl,
summaryResults,
showInThread: config.showInThread,
},
});
if (config.showInThread && resultSummary.failures.length > 0) {
for (let i = 0; i < result.length; i += 1) {
// eslint-disable-next-line no-await-in-loop
await slackClient.attachDetailsToThread({
channelIds: [result[i].channel],
ts: result[i].ts,
summaryResults: resultSummary,
maxNumberOfFailures: config.maxNumberOfFailures,
});
}
}
if (
result.filter((r) => !r.outcome.includes('✅ Message sent to')).length
!== 0
) {
return false;
}
return true;
}
throw new Error('sendUsingBot config is not set');
}
async function attemptToImportLayout(source: string, functionName: string) {
if (source && functionName) {
try {
const importPath = path.resolve(source);
const layout = await import(importPath);
if (layout.default[functionName]) {
return layout.default[functionName];
}
console.error(`Function [${functionName}] was not found in [${source}]`);
} catch (error) {
console.error(error);
}
}
return undefined;
}
function replaceEnvVars(originalMeta: Meta) {
const newMeta: Meta = [];
// eslint-disable-next-line no-restricted-syntax
for (const m of originalMeta) {
let metaValue = m.value;
if (m.value.startsWith('__ENV')) {
const environmentVarName = m.value.replace('__ENV_', '');
if (process.env[environmentVarName]) {
metaValue = process.env[environmentVarName];
} else {
const warningMessage = `❌ Environment variable [${environmentVarName}] was not set.
This variable was found in the [meta] section of the config file, ensure the variable is set in your environment.`;
console.log(warningMessage);
metaValue = warningMessage;
}
}
newMeta.push({ key: m.key, value: metaValue });
}
return newMeta;
}