-
Notifications
You must be signed in to change notification settings - Fork 2
/
helpers.ts
223 lines (181 loc) · 5.23 KB
/
helpers.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import * as core from '@actions/core';
import * as github from '@actions/github';
import { formatDuration, getDurationInMillis, prepareReportActions } from '@moonrepo/report';
import type { ActionStatus, Duration, RunReport } from '@moonrepo/types';
export function getCommentToken() {
return `<!-- moon-run-report: ${core.getInput('matrix') || 'unknown'} -->`;
}
export function getCommitInfo() {
const { repo, serverUrl, sha: baseSha } = github.context;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment
const sha = github.context.payload.pull_request?.head?.sha ?? baseSha;
if (!sha || !repo) {
return null;
}
return {
sha: String(sha),
url: `${serverUrl}/${repo.owner}/${repo.repo}/commit/${sha}`,
};
}
export function getMoonEnvVars() {
const env: Record<string, string> = {};
let count = 0;
Object.entries(process.env).forEach(([key, value]) => {
if (
(key.startsWith('MOON_') || key.startsWith('PROTO_')) &&
value &&
process.env.NODE_ENV !== 'test'
) {
env[key] = value;
count += 1;
}
});
if (count === 0) {
return null;
}
return env;
}
export function calculateSavingsPercentage(projected: Duration, savings: Duration) {
const base = getDurationInMillis(projected);
const diff = getDurationInMillis(savings);
return Math.round((diff / base) * 100);
}
export function createCodeBlock(map: Record<string, unknown> | string[]): string[] {
const code = ['```'];
if (Array.isArray(map)) {
code.push(...map);
} else {
Object.entries(map).forEach(([key, value]) => {
code.push(`${key} = ${value}`);
});
}
code.push('```');
return code;
}
export function createDetailsSection(title: string, body: string[]): string[] {
return [
'',
`<details><summary><strong>${title}</strong></summary><div>`,
'',
...body,
'',
'</div></details>',
];
}
export function formatTotalTime({ duration, comparisonEstimate }: RunReport): string {
const parts = [`Total time: ${formatDuration(duration)}`];
if (comparisonEstimate) {
parts.push(`Comparison time: ${formatDuration(comparisonEstimate.duration)}`);
if (comparisonEstimate.percent !== 0) {
if (comparisonEstimate.percent > 0 && comparisonEstimate.gain) {
parts.push(
`Estimated savings: ${formatDuration(
comparisonEstimate.gain,
)} (${comparisonEstimate.percent.toFixed(1)}% faster)`,
);
} else if (comparisonEstimate.percent < 0 && comparisonEstimate.loss) {
parts.push(
`Estimated loss: ${formatDuration(comparisonEstimate.loss)} (${Math.abs(
comparisonEstimate.percent,
).toFixed(1)}% slower)`,
);
}
}
}
return parts.join(' | ');
}
function formatStatusLabel(status: ActionStatus): string {
switch (status) {
case 'aborted':
return 'Aborted';
case 'cached':
case 'cached-from-remote':
return 'Cached';
case 'failed':
case 'failed-and-abort':
return 'Failed';
case 'invalid':
return 'Invalid';
case 'passed':
return 'Passed';
case 'skipped':
return 'Skipped';
case 'timed-out':
return 'Timed out';
default:
return 'Running';
}
}
export interface FormatReportOptions {
limit: number;
slowThreshold: number;
workspaceRoot: string;
}
// eslint-disable-next-line complexity
export function formatReportToMarkdown(
report: RunReport,
{ limit, slowThreshold, workspaceRoot }: FormatReportOptions,
): string {
const commit = getCommitInfo();
const matrix = core.getInput('matrix');
const matrixData = matrix ? (JSON.parse(matrix) as Record<string, unknown>) : null;
const markdown = [
getCommentToken(),
'',
commit ? `## Run report for [${commit.sha.slice(0, 8)}](${commit.url})` : '## Run report',
];
if (matrixData) {
markdown[2] += ` \`(${Object.values(matrixData).join(', ')})\``;
}
if (report.duration) {
markdown.push(formatTotalTime(report));
}
// ACTIONS
const tableHeaders = [
'| | Action | Time | Status | Info |',
'| :-: | :----- | ---: | :----- | :--- |',
];
const overflowRows: string[] = [];
markdown.push(...tableHeaders);
prepareReportActions(report, slowThreshold).forEach((action, index) => {
const row = `| ${action.icon} | \`${action.label}\` | ${action.time} | ${formatStatusLabel(
action.status,
)} | ${action.comments.join(', ')} |`;
if (index < limit) {
markdown.push(row);
} else {
overflowRows.push(row);
}
});
if (overflowRows.length > 0) {
markdown.push(
`| | And ${overflowRows.length} more... | | | |`,
...createDetailsSection('Expanded report', [...tableHeaders, ...overflowRows]),
);
}
// ENVIRONMENT
const envVars = getMoonEnvVars();
if (matrixData ?? envVars) {
const section = [
`**OS:** ${process.env.NODE_ENV === 'test' ? 'Test' : process.env.RUNNER_OS ?? 'unknown'}`,
];
if (matrixData) {
section.push('**Matrix:**', ...createCodeBlock(matrixData));
}
if (envVars) {
section.push('**Variables:**', ...createCodeBlock(envVars));
}
markdown.push(...createDetailsSection('Environment', section));
}
// TOUCHED FILES
const { touchedFiles } = report.context;
if (touchedFiles.length > 0) {
markdown.push(
...createDetailsSection(
'Touched files',
createCodeBlock(touchedFiles.map((file) => `${file.replace(workspaceRoot, '')}`).sort()),
),
);
}
return markdown.join('\n');
}