forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode-analysis-bot.js
331 lines (291 loc) · 8.5 KB
/
code-analysis-bot.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
if (!process.env.GITHUB_OWNER) {
console.error('Missing GITHUB_OWNER. Example: facebook');
process.exit(1);
}
if (!process.env.GITHUB_REPO) {
console.error('Missing GITHUB_REPO. Example: react-native');
process.exit(1);
}
// https://octokit.github.io/rest.js/
const octokit = require('@octokit/rest')();
const path = require('path');
function push(arr, key, value) {
if (!arr[key]) {
arr[key] = [];
}
arr[key].push(value);
}
const converterSummary = {
eslint:
'`eslint` found some issues. Run `yarn lint --fix` to automatically fix problems.',
flow: '`flow` found some issues.',
shellcheck: '`shellcheck` found some issues.',
};
/**
* There is unfortunately no standard format to report an error, so we have
* to write a specific converter for each tool we want to support.
*
* Those functions take a json object as input and fill the output with the
* following format:
*
* { [ path: string ]: Array< { message: string, line: number }> }
*
* This is an object where the keys are the path of the files and values
* is an array of objects of the shape message and line.
*/
const converters = {
raw: function(output, input) {
for (let key in input) {
input[key].forEach(function(message) {
push(output, key, message);
});
}
},
flow: function(output, input) {
if (!input || !input.errors) {
return;
}
input.errors.forEach(function(error) {
push(output, error.message[0].path, {
message: error.message.map(message => message.descr).join(' '),
line: error.message[0].line,
converter: 'flow',
});
});
},
eslint: function(output, input) {
if (!input) {
return;
}
input.forEach(function(file) {
file.messages.forEach(function(message) {
push(output, file.filePath, {
message: message.ruleId + ': ' + message.message,
line: message.line,
converter: 'eslint',
});
});
});
},
shellcheck: function(output, input) {
if (!input) {
return;
}
input.forEach(function(report) {
push(output, report.file, {
message:
'**[SC' +
report.code +
'](https://github.com/koalaman/shellcheck/wiki/SC' +
report.code +
'):** (' +
report.level +
') ' +
report.message,
line: report.line,
endLine: report.endLine,
column: report.column,
endColumn: report.endColumn,
converter: 'shellcheck',
});
});
},
};
function getShaFromPullRequest(owner, repo, number, callback) {
octokit.pullRequests.get({owner, repo, number}, (error, res) => {
if (error) {
console.error(error);
return;
}
callback(res.data.head.sha);
});
}
function getFilesFromPullRequest(owner, repo, number, callback) {
octokit.pullRequests.listFiles(
{owner, repo, number, per_page: 100},
(error, res) => {
if (error) {
console.error(error);
return;
}
callback(res.data);
},
);
}
/**
* Sadly we can't just give the line number to github, we have to give the
* line number relative to the patch file which is super annoying. This
* little function builds a map of line number in the file to line number
* in the patch file
*/
function getLineMapFromPatch(patchString) {
let diffLineIndex = 0;
let fileLineIndex = 0;
let lineMap = {};
patchString.split('\n').forEach(line => {
if (line.match(/^@@/)) {
fileLineIndex = line.match(/\+([0-9]+)/)[1] - 1;
return;
}
diffLineIndex++;
if (line[0] !== '-') {
fileLineIndex++;
if (line[0] === '+') {
lineMap[fileLineIndex] = diffLineIndex;
}
}
});
return lineMap;
}
function sendReview(owner, repo, number, commit_id, body, comments) {
if (process.env.GITHUB_TOKEN) {
if (comments.length === 0) {
// Do not leave an empty review.
return;
}
const event = 'REQUEST_CHANGES';
const opts = {
owner,
repo,
number,
commit_id,
body,
event,
comments,
};
octokit.pullRequests.createReview(opts, function(error, res) {
if (error) {
console.error(error);
return;
}
});
} else {
if (comments.length === 0) {
console.log('No issues found.');
return;
}
if (process.env.CIRCLE_CI) {
console.error(
'Code analysis found issues, but the review cannot be posted to GitHub without an access token.',
);
process.exit(1);
}
let results = body + '\n';
comments.forEach(comment => {
results +=
comment.path + ':' + comment.position + ': ' + comment.body + '\n';
});
console.log(results);
}
}
function main(messages, owner, repo, number) {
// No message, we don't need to do anything :)
if (Object.keys(messages).length === 0) {
return;
}
if (process.env.GITHUB_TOKEN) {
octokit.authenticate({
type: 'oauth',
token: process.env.GITHUB_TOKEN,
});
} else {
console.log(
'Missing GITHUB_TOKEN. Example: 5fd88b964fa214c4be2b144dc5af5d486a2f8c1e. Review feedback with code analysis results will not be provided on GitHub.',
);
}
getShaFromPullRequest(owner, repo, number, sha => {
getFilesFromPullRequest(owner, repo, number, files => {
let comments = [];
let convertersUsed = [];
files
.filter(file => messages[file.filename])
.forEach(file => {
// github api sometimes does not return a patch on large commits
if (!file.patch) {
return;
}
const lineMap = getLineMapFromPatch(file.patch);
messages[file.filename].forEach(message => {
if (lineMap[message.line]) {
const comment = {
path: file.filename,
position: lineMap[message.line],
body: message.message,
};
convertersUsed.push(message.converter);
comments.push(comment);
}
}); // forEach
}); // filter
let body = '**Code analysis results:**\n\n';
const uniqueconvertersUsed = [...new Set(convertersUsed)];
uniqueconvertersUsed.forEach(converter => {
body += '* ' + converterSummary[converter] + '\n';
});
sendReview(owner, repo, number, sha, body, comments);
}); // getFilesFromPullRequest
}); // getShaFromPullRequest
}
let content = '';
process.stdin.resume();
process.stdin.on('data', function(buf) {
content += buf.toString();
});
process.stdin.on('end', function() {
let messages = {};
// Since we send a few http requests to setup the process, we don't want
// to run this file one time per code analysis tool. Instead, we write all
// the results in the same stdin stream.
// The format of this stream is
//
// name-of-the-converter
// {"json":"payload"}
// name-of-the-other-converter
// {"other": ["json", "payload"]}
//
// In order to generate such stream, here is a sample bash command:
//
// cat <(echo eslint; npm run lint --silent -- --format=json; echo flow; flow --json) | node code-analysis-bot.js
const lines = content.trim().split('\n');
for (let i = 0; i < Math.ceil(lines.length / 2); ++i) {
const converter = converters[lines[i * 2]];
if (!converter) {
throw new Error('Unknown converter ' + lines[i * 2]);
}
let json;
try {
json = JSON.parse(lines[i * 2 + 1]);
} catch (e) {}
converter(messages, json);
}
// The paths are returned in absolute from code analysis tools but github works
// on paths relative from the root of the project. Doing the normalization here.
const pwd = path.resolve('.');
for (let absolutePath in messages) {
const relativePath = path.relative(pwd, absolutePath);
if (relativePath === absolutePath) {
continue;
}
messages[relativePath] = messages[absolutePath];
delete messages[absolutePath];
}
const owner = process.env.GITHUB_OWNER;
const repo = process.env.GITHUB_REPO;
if (!process.env.GITHUB_PR_NUMBER) {
console.error('Missing GITHUB_PR_NUMBER. Example: 4687');
// for master branch, don't throw an error
process.exit(0);
}
const number = process.env.GITHUB_PR_NUMBER;
// intentional lint warning to make sure that the bot is working :)
main(messages, owner, repo, number);
});