forked from magento/pwa-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dangerfile.js
305 lines (289 loc) · 9.92 KB
/
dangerfile.js
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
const fs = require('fs');
const path = require('path');
const execa = require('execa');
const mkdirp = require('mkdirp');
const xml = require('xml');
const { fail, warn, markdown, danger } = require('danger');
const prettierVersion = require('prettier/package.json').version;
const eslintJUnitReporter = require('eslint/lib/formatters/junit');
const fromRoot = p => path.relative('', p);
const packageNames = {
'venia-concept': 'Venia',
'pwa-buildpack': 'Buildpack',
peregrine: 'Peregrine'
};
const pathToPackageName = filepath => {
const packageDir = path
.normalize(path.relative('packages', filepath))
.split(path.sep)[0];
return packageNames[packageDir] || packageDir;
};
const reportDir = './test-results/';
const reportFile = name => {
const subdir = path.join(reportDir, name);
mkdirp.sync(subdir);
return path.join(subdir, 'results.xml');
};
const fence = '```';
const codeFence = str => `${fence}\n${str.trim()}\n${fence}`;
function timer() {
const msPerSec = 1e3;
const nsPerMillisec = 1e6;
const formatTime = ([seconds, nanoseconds]) =>
Math.round(seconds * msPerSec + nanoseconds / nsPerMillisec) / msPerSec;
const startTime = process.hrtime();
let lastLap = startTime;
return {
lap() {
const lapTime = process.hrtime(lastLap);
lastLap = process.hrtime();
return formatTime(lapTime);
},
stop() {
return formatTime(process.hrtime(startTime));
}
};
}
function jUnitSuite(title) {
const stopwatch = timer();
let failureCount = 0;
let errorCount = 0;
const cases = [];
function testCase(name, type, message, trace) {
const tcAttrs = {
_attr: { classname: '', name, time: stopwatch.lap() }
};
return {
testcase: type
? [
tcAttrs,
{
[type]: trace
? { _attr: { message }, _cdata: trace }
: {
_attr: { message }
}
}
]
: [tcAttrs]
};
}
return {
pass(name) {
cases.push(testCase(name));
},
fail(name, message, trace) {
cases.push(testCase(name, 'failure', message, trace));
failureCount++;
},
error(name, message, trace) {
cases.push(testCase(name, 'error', message, trace));
errorCount++;
},
save(filename) {
const time = stopwatch.stop();
fs.writeFileSync(
filename,
xml({
testsuites: [
{
_attr: {
tests: cases.length,
failures: failureCount,
time
}
},
{
testsuite: [
{
_attr: {
name: title,
errors: errorCount,
failures: failureCount,
skipped: 0,
timestamp: new Date().toISOString(),
time,
tests: cases.length
}
},
...cases
]
}
]
}),
'utf8'
);
}
};
}
const tasks = [
function prettierCheck() {
const junit = jUnitSuite('Prettier');
let stdout, stderr;
try {
const result = execa.sync('npm', [
'run',
'--silent',
'prettier:check',
'--',
'--loglevel=debug'
]);
stdout = result.stdout;
stderr = result.stderr;
} catch (err) {
stdout = err.stdout;
stderr = err.stderr;
}
const failedFiles = stdout.split('\n').filter(s => s.trim());
// Prettier doesn't normally print the files it covered, but in debug
// mode, you can extract them with these regex (as of Prettier 1.13.5)
// This is a hack based on debug output not guaranteed to stay the same.
const errorLineStartRE = /^\[error\]\s*/;
const errors = stderr.match(/(\[error\].+?\n)+/gim);
const errorMap = {};
if (errors) {
errors.forEach(block => {
const lines = block.split('\n[error] ');
const firstLine = lines.shift();
if (errorLineStartRE.test(firstLine)) {
// parseable
const [name, message] = firstLine
.replace(errorLineStartRE, '')
.split(':')
.map(s => s.trim());
if (name && message) {
errorMap[name] = {
message,
trace: lines.join('\n')
};
}
}
});
}
const coveredFiles = stderr.match(
/\[debug\]\s*resolve config from '[^']+'\n/gim
);
if (!coveredFiles || coveredFiles.length === 0) {
let warning = 'Prettier did not appear to cover any files.';
if (prettierVersion !== '1.13.5') {
warning +=
'\nThis may be due to an unexpected change in debug output in a version of Prettier later than 1.13.5.';
}
warn(warning);
}
coveredFiles.forEach(line => {
const filename = line.match(/'([^']+)'/)[1];
if (errorMap[filename]) {
junit.error(
filename,
errorMap[filename].message,
errorMap[filename].trace
);
} else if (failedFiles.includes(filename)) {
junit.fail(filename, 'was not formatted with Prettier');
} else {
junit.pass(filename);
}
});
junit.save(reportFile('prettier'));
if (failedFiles.length > 0) {
fail(
'The following file(s) were not ' +
'formatted with **prettier**. Make sure to execute `npm run prettier` ' +
`locally prior to committing.\n${codeFence(stdout)}`
);
}
},
function eslintCheck() {
const stopwatch = timer();
let stdout;
try {
({ stdout } = execa.sync('npm', [
'run',
'--silent',
'lint',
'--',
'-f',
'json'
]));
} catch (err) {
({ stdout } = err);
}
const results = JSON.parse(stdout);
// TODO: build as XML DOM so we can customize
const eslintXml = eslintJUnitReporter(results);
const eslintXmlWithTime = eslintXml.replace(
/testsuite package="org\.eslint" time="0"/m,
`testsuite package="org.eslint" time="${stopwatch.stop()}"`
);
fs.writeFileSync(reportFile('eslint'), eslintXmlWithTime, 'utf8');
const errFiles = results
.filter(r => r.errorCount)
.map(r => fromRoot(r.filePath));
if (errFiles.length > 0) {
fail(
'The following file(s) did not pass **ESLint**. Execute ' +
'`npm run lint` locally for more details\n' +
codeFence(errFiles.join('\n'))
);
}
},
function unitTests() {
let summary;
try {
summary = require('./test-results.json');
} catch (e) {
execa.sync('npm', ['run', '-s', 'test:ci']);
summary = require('./test-results.json');
}
const failedTests = summary.testResults.filter(
t => t.status !== 'passed'
);
if (failedTests.length === 0) {
return;
}
// prettier-ignore
const failSummary = failedTests.map(t =>
`<details>
<summary>${fromRoot(t.name)}</summary>
<pre>${t.message}</pre>
</details>`
).join('\n');
fail(
'The following unit tests did _not_ pass 😔. ' +
'All tests must pass before this PR can be merged\n\n\n' +
failSummary
);
}
// function mergeJunitReports() {
// execa.sync('junit-merge', [
// '--dir',
// reportDir,
// '--out',
// reportFile('all-junit.xml')
// ]);
// }
// Disabled for now, but leaving in for future implementation.
// Can't use right now due to the lack of permissions granularity
// in GitHub
// async function addProjectLabels() {
// const allChangedFiles = [
// ...danger.git.created_files,
// ...danger.git.deleted_files,
// ...danger.git.modified_files
// ];
// const touchedPackages = allChangedFiles.reduce((touched, path) => {
// const matches = path.match(/packages\/([\w-]+)\//);
// return matches ? touched.add(matches[1]) : touched;
// }, new Set());
// if (!touchedPackages.size) return;
// await danger.github.api.issues.addLabels(
// Object.assign({}, danger.github.thisPR, {
// labels: Array.from(touchedPackages).map(s => `pkg:${s}`)
// })
// );
// }
];
(async () => {
for (const task of tasks) await task();
})();