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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
|
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
/* eslint-disable no-unused-vars */
// This module contains a number of functions for interacting with Gerrit.
const safeJsonStringify = require('safe-json-stringify');
const axios = require('axios');
const config = require('./config.json');
const { logger } = require('./logger.js');
// Set default values with the config file, but prefer environment variable.
function envOrConfig(ID) {
return process.env[ID] || config[ID];
}
let gerritURL = envOrConfig("GERRIT_URL");
let gerritAuth = {
username: envOrConfig("GERRIT_USER"),
password: envOrConfig("GERRIT_PASS")
};
// Trim )]}' off of a gerrit response. This magic prefix in the response
// from gerrit helpts to prevent against XSSI attacks and will
// always be included in a genuine response from gerrit.
// See https://gerrit-review.googlesource.com/Documentation/rest-api.html
exports.trimResponse = trimResponse;
function trimResponse(response) {
if (response.startsWith(")]}'"))
return response.slice(4);
else
return response;
}
exports.getSnippedTestSource = getSnippedTestSource;
async function getSnippedTestSource(changeId, { repo = "", branch = "" } = {}, testPath, testFunctionName) {
return new Promise((resolve, reject) => {
if (!repo || !branch) {
// try to parse from the changeId
try {
repo = changeId.split('~')[0];
branch = changeId.split('~')[1];
} catch {
// parse the repo from the change ID, can't fetch the file reliably.
reject("Failed to parse repo and branch from changeId");
}
}
// Replace \ with / in the path for Windows.
testPath = testPath.replace(/\\/g, '/');
logger.info(`Getting source file for ${testPath}`);
if (testPath.includes("C:/Users/qt/work/"))
testPath = testPath.replace("C:/Users/qt/work/", "");
if (testPath.includes(repo + '/'))
testPath = testPath.replace(repo + '/', "");
testPath = testPath.replace(/\/Users\/qt\/work\//g, '');
testPath = testPath.replace(/\/home\/qt\/work\//g, '');
if (testPath.includes("standalone_tests"))
testPath = testPath.replace(/qt\/.+standalone_tests\//, "");
if (testPath.includes("/android-build/"))
testPath = testPath.replace(/\/android-build\//, "/");
if (testPath.includes("-build/")) {
testPath = testPath.replace(/\/[a-z A-Z 0-9-]+-build\//, "/");
// replace suffix with .cpp
testPath = testPath.replace(/\.[a-z]+$/, ".cpp");
}
if (!testPath.includes(".cpp")) {
testPath = testPath + ".cpp";
}
logger.info(`Getting source file for ${testPath}`);
getFileFromGerrit(changeId, { repo, branch }, testPath)
.then(testSource => {
resolve(snipTestFile(testSource, testPath.split('/').pop(), testFunctionName));
})
.catch(error => {
reject(error);
});
}
);
}
exports.getFileFromGerrit = getFileFromGerrit;
async function getFileFromGerrit(changeId, { repo = "", branch = "" } = {}, filePath) {
return new Promise((resolve, reject) => {
if (!changeId) {
reject("No changeId provided for file fetch");
return;
}
// First, list the files modified by the change.
let url = `${gerritURL}/a/changes/${encodeURIComponent(changeId)}/revisions/current/files`;
logger.info(`GET request for ${url}`);
axios.get(url, { auth: gerritAuth })
.then(response => {
let files = Object.keys(JSON.parse(trimResponse(response.data)));
if (files.includes(filePath)) {
logger.info(`File ${filePath} was modified by the change`);
// If the change modified the file, get it.
url = `${gerritURL}/a/changes/${encodeURIComponent(changeId)}`
+ `/revisions/current/files/${encodeURIComponent(filePath)}/content`;
logger.info(`GET request for ${url}`);
axios.get(url, { auth: gerritAuth })
.then(response => {
// decode from base64
let file = Buffer.from(response.data, 'base64').toString();
resolve(file);
})
.catch(error => {
reject(error);
})
} else {
if (!repo || !branch) {
// try to parse from the changeId
repo = changeId.split('~')[0];
branch = changeId.split('~')[1];
if (!repo || !branch) {
reject("Failed to parse repo and branch from changeId");
return;
}
}
logger.info(`File ${filePath} was not modified by the change.`
+ ` Pulling from ${repo} ${branch}`);
// If the change didn't modify the file, try the root tree.
url = `${gerritURL}/a/projects/${encodeURIComponent(repo)}/branches/`
+ `${encodeURIComponent(branch)}/files/${encodeURIComponent(filePath)}/content`;
logger.info(`GET request for ${url}`);
axios.get(url, { auth: gerritAuth })
.then(response => {
let file = Buffer.from(response.data, 'base64').toString();
resolve(file);
})
.catch(error => {
reject(error);
});
}
});
});
}
function removeSuffix(str) {
if (str.endsWith('.cpp')) {
return str.slice(0, str.length - 4);
}
return str;
}
exports.snipTestFile = snipTestFile;
function snipTestFile(fileText, testName, testFunctionName) {
let compiledSearch = removeSuffix(testName);
if (testFunctionName)
compiledSearch += "::" + testFunctionName;
logger.info(`Searching for ${compiledSearch}`);
let instances = [];
let searchStart = 0;
while (searchStart < fileText.length) {
let testStart = fileText.toLowerCase().indexOf(compiledSearch.toLowerCase(), searchStart);
if (testStart === -1) break;
// Find the closing } by regex so we can handle nested classes
let testEnd = fileText.slice(testStart).search(/^};?$/m) + testStart;
let testSnippet = fileText.slice(testStart, testEnd + 2);
// Find what line the test starts on
let testStartLine = fileText.slice(0, testStart).split('\n').length;
let linecount = testSnippet.split('\n').length;
instances.push([testSnippet, testStartLine, linecount]);
// Move searchStart to the end of the current test snippet
searchStart = testEnd + 2;
}
// combine all the instances into one string
let snipped = instances.map((instance) => {
return instance[0].split('\n').map((line, index) => {
return `${instance[1] + index}: ${line}\n`;
}).join('');
}).join('\n');
if (snipped.length < 50 || snipped.split('\n').length > 2000) {
logger.info(`Failed to find usable snip about ${compiledSearch} in ${testName}`);
if (fileText.split('\n').length <= 2000)
return fileText;
else
return `The test source for ${testName} is too large, and a valid snip could not be found.`;
}
return snipped;
}
exports.getChangeDiff = getChangeDiff;
async function getChangeDiff(changeId) {
return new Promise((resolve, reject) => {
let url = `${gerritURL}/a/changes/${encodeURIComponent(changeId)}/revisions/current/patch`;
logger.info(`GET request for ${url}`);
axios.get(url, { auth: gerritAuth })
.then(response => {
// decode from base64
let diff = Buffer.from(response.data, 'base64').toString();
resolve(diff);
})
.catch(error => {
reject(error);
})
}
);
}
exports.findIntegrationIDFromChange = findIntegrationIDFromChange;
async function findIntegrationIDFromChange(changeId) {
return new Promise((resolve, reject) => {
let url = `${gerritURL}/a/changes/${encodeURIComponent(changeId)}/messages`;
logger.info(`GET request for ${url}`);
axios
.get(url, { auth: gerritAuth })
.then(function (response) {
const messages = JSON.parse(trimResponse(response.data));
messages.reverse();
let found = false;
for (let i = 0; i < messages.length; i++) { // CI passed messages are usually near the end.
if (messages[i].message.includes("Continuous Integration: Cancelled")) {
// We dont need to analyze cancelled CI
reject("CI was cancelled");
break;
}
if (messages[i].message.includes("Continuous Integration: Failed")
|| messages[i].message.includes("Quick Check: Failed")) {
// Capture the integration ID or return false.
// Though a change with the above line should never *not*
// have an IntegrationID
try {
let integrationId = messages[i].message.match(/^Details:.+\/tasks\/(.+)$/m)[1];
let testedChanges = "";
// Includes a negative lookahead to ensure we don't match trailing
// text posted after the tested changes.
const regex = /Tested changes \((?:refs\/builds\/qtci\/[\w\-/.]+\/\d+|dev|master)\):\n((?:(?!\n\n)[\s\S])*)/;
const match = messages[i].message.match(regex);
if (match) {
testedChanges = match[1];
} else {
logger.info("No tested changes found.");
}
found = true;
resolve([integrationId, testedChanges]);
} catch (e) {
logger.info(e);
reject("Failed to find IntegrationID in message");
}
break;
}
}
if (!found)
reject("Failed to find failed CI message");
})
.catch((error) => {
logger.info(`Failed to get IntegrationId for ${changeId}\n${error}`);
reject(error);
});
});
}
// Post a comment to the change on the latest revision.
exports.postGerritComment = postGerritComment;
function postGerritComment(
changeId, revision, message, reviewers,
notifyScope, customAuth, callback
) {
function _postComment(resolve) {
let url = `${gerritURL}/a/changes/${encodeURIComponent(changeId)}`
+ `/revisions/${revision || "current"}/review`;
message = message + "\n\n========================\n"
+ "The above analysis is generated from an LLM examination of the COIN failure log,"
+ " change diff, and test source code if relevant and available.\n"
+ " Be aware that the bot may make mistakes, or provide misleading/incorrect results.\n"
+ " Contact Daniel Smith for more information or to report issues."
let data = { message: message, notify: notifyScope || "OWNER_REVIEWERS" };
if (reviewers) {
// format reviewers as a list of ReviewInput entities
data.reviewers = reviewers.map((reviewer) => { return { reviewer: reviewer }; });
}
logger.info(
`POST request to: ${url}\nRequest Body: ${safeJsonStringify(data)}`,
"debug"
);
axios({ method: "post", url: url, data: data, auth: customAuth || gerritAuth })
.then(function (response) {
logger.info(`Posted comment "${message}" to change "${changeId}"`, "info");
resolve([true, undefined]);
})
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
logger.info(
`An error occurred in POST (gerrit comment) to "${url}".`
+ ` Error ${error.response.status}: ${error.response.data}`
);
resolve([false, error.response]);
} else if (error.request) {
// The request was made but no response was received
setTimeout(() => {
// Post the comment again after a delay.
_postComment(resolve);
}
, 5000);
} else {
// Something happened in setting up the request that triggered an Error
logger.info(
`Error in HTTP request while posting comment. Error: ${safeJsonStringify(error)}`
);
resolve([false, error.message]);
}
});
}
return new Promise((resolve, reject) => {
// Query the change first to see if we've posted the same comment on the current revision before
const message_url = `${gerritURL}/a/changes/${encodeURIComponent(changeId)}/messages`;
logger.info(`GET request to: ${message_url}`, "debug");
axios({ method: "get", url: message_url, auth: customAuth || gerritAuth })
.then(function (response) {
let parsedResponse = JSON.parse(trimResponse(response.data));
let messages = parsedResponse
.filter((message) => message.author.name == "Qt Cherry-pick Bot")
.map((message) => message.message);
if (messages.length == 0) {
// If there are no messages, then the bot hasn't posted a comment yet.
_postComment(resolve);
return;
}
let patchset = parsedResponse[parsedResponse.length - 1]._revision_number;
// Reverse messages so that we can find the most recent comment first.
// Then iterate and check for message in the current patchset.
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].includes(message) && messages[i].includes(`Patch Set ${patchset}:`)) {
logger.info(
`Comment "${message}" already posted on patchset ${patchset} of ${changeId}`,
"verbose"
);
resolve([true, undefined]);
return;
}
}
// If we get here, then the comment hasn't been posted yet.
_postComment(resolve);
});
});
}
|