forked from github/copilot-survey-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
482 lines (447 loc) · 14.4 KB
/
index.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
/**
* This is the main entrypoint to your Probot app
* @param {import('probot').Probot} app
*/
const dedent = require("dedent");
const fs = require("fs");
const path = require("path");
const sql = require("mssql");
require("dotenv").config();
const {
TextAnalysisClient,
AzureKeyCredential,
} = require("@azure/ai-language-text");
const { LANGUAGE_API_KEY, LANGUAGE_API_ENDPOINT, DATABASE_CONNECTION_STRING } =
process.env;
module.exports = (app) => {
// Your code here
app.log.info("Yay, the app was loaded!");
let appInsights = new AppInsights();
app.on("pull_request.closed", async (context) => {
appInsights.trackEvent({
name: "Pull Request Close Payload",
properties: context.payload,
});
let pr_number = context.payload.pull_request.number;
let pr_body = context.payload.pull_request.body;
let result = [{ primaryLanguage: { iso6391Name: "en" } }];
// check language for pr_body
if (LANGUAGE_API_ENDPOINT && LANGUAGE_API_KEY) {
const TAclient = new TextAnalysisClient(
LANGUAGE_API_ENDPOINT,
new AzureKeyCredential(LANGUAGE_API_KEY)
);
if (pr_body) {
try {
let startTime = Date.now();
result = await TAclient.analyze("LanguageDetection", [pr_body]);
let duration = Date.now() - startTime;
appInsights.trackDependency({
target: "API:Language Detection",
name: "detect pull request description language",
duration: duration,
resultCode: 0,
success: true,
dependencyTypeName: "HTTP",
});
if (
!["en", "es", "pt", "fr"].includes(
result[0].primaryLanguage.iso6391Name
)
) {
result[0].primaryLanguage.iso6391Name = "en";
}
} catch (err) {
app.log.error(err);
appInsights.trackException({ exception: err });
}
}
}
// read file that aligns with detected language
const issue_body = fs.readFileSync(
"./issue_template/copilot-usage-" +
result[0].primaryLanguage.iso6391Name +
".md",
"utf-8"
);
// find XXX in file and replace with pr_number
let fileContent = dedent(
issue_body.replace(/XXX/g, "#" + pr_number.toString())
);
// display the body for the issue
app.log.info(fileContent);
// create an issue using fileContent as body
try {
await context.octokit.issues.create({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
title: "Copilot Usage - PR#" + pr_number.toString(),
body: fileContent,
assignee: context.payload.pull_request.user.login,
});
} catch (err) {
app.log.error(err);
appInsights.trackException({ exception: err });
}
});
app.on("issues.edited", async (context) => {
if (context.payload.issue.title.startsWith("Copilot Usage - PR#")) {
appInsights.trackEvent({
name: "Issue Edited Payload",
properties: context.payload,
});
await GetSurveyData(context);
}
});
app.on("issue_comment.created", async (context) => {
if (context.payload.issue.title.startsWith("Copilot Usage - PR#")) {
appInsights.trackEvent({
name: "Issue Comment Created Payload",
properties: context.payload,
});
await GetSurveyData(context);
}
});
async function GetSurveyData(context) {
let issue_body = context.payload.issue.body;
let issue_id = context.payload.issue.id;
// save comment body if present
let comment = null;
if(context.payload.comment) {
comment = context.payload.comment.body;
}
// find regex [0-9]\+ in issue_body and get first result
let pr_number = issue_body.match(/[0-9]+/)[0];
// find regex \[x\] in issue_body and get complete line in an array
let checkboxes = issue_body.match(/\[x\].*/g);
// find if checkboxes array contains Sim o Si or Yes
let isCopilotUsed = checkboxes.some((checkbox) => {
return (
checkbox.includes("Sim") ||
checkbox.includes("Si") ||
checkbox.includes("Yes") ||
checkbox.includes("Oui")
);
});
// if there's a comment, insert it into the DB regardless of whether the user answered the survey or not
if (comment) {
let startTime = Date.now();
let query = await insertIntoDB(context, issue_id, pr_number, isCopilotUsed, null, null, comment);
let duration = Date.now() - startTime;
appInsights.trackDependency({
target: "DB:copilotUsage",
name: "insert when comment is present",
data: query,
duration: duration,
resultCode: 0,
success: true,
dependencyTypeName: "SQL",
});
}
if (isCopilotUsed) {
let startTime = Date.now();
let query = await insertIntoDB(context, issue_id, pr_number, isCopilotUsed, null, null, comment);
let duration = Date.now() - startTime;
appInsights.trackDependency({
target: "DB:copilotUsage",
name: "insert when Yes is selected",
data: query,
duration: duration,
resultCode: 0,
success: true,
dependencyTypeName: "SQL",
});
// loop through checkboxes and find the one that contains %
let pctSelected = false;
let pctValue = new Array();
for (const checkbox of checkboxes) {
if (checkbox.includes("%")) {
pctSelected = true;
copilotPercentage = checkbox;
copilotPercentage = copilotPercentage.replace(/\[x\] /g, "");
pctValue.push(copilotPercentage);
app.log.info(copilotPercentage);
}
}
if (pctSelected) {
//if percentage is selected, insert into DB
let startTime = Date.now();
let query = await insertIntoDB(context, issue_id, pr_number, isCopilotUsed, pctValue, null, comment);
let duration = Date.now() - startTime;
appInsights.trackDependency({
target: "DB:copilotUsage",
name: "insert when pct is selected",
data: query,
duration: duration,
resultCode: 0,
success: true,
dependencyTypeName: "SQL",
});
}
// loop through checkboxes and find the ones that do not contain % and are not Yes or No
let freqSelected = false;
let freqValue = new Array();
for (const checkbox of checkboxes) {
if (
!checkbox.includes("%") &&
!checkbox.includes("Sim") &&
!checkbox.includes("Si") &&
!checkbox.includes("Yes") &&
!checkbox.includes("Oui") &&
!checkbox.includes("Não") &&
!checkbox.includes("No") &&
!checkbox.includes("Non")
) {
freqSelected = true;
frequencyValue = checkbox;
frequencyValue = frequencyValue.replace(/\[x\] /g, "");
freqValue.push(frequencyValue);
app.log.info(frequencyValue);
}
}
if (freqSelected) {
//if frequency is selected, insert into DB
let startTime = Date.now();
let query = await insertIntoDB(context, issue_id, pr_number, isCopilotUsed, null, freqValue, comment);
let duration = Date.now() - startTime;
appInsights.trackDependency({
target: "DB:copilotUsage",
name: "insert when freq is selected",
data: query,
duration: duration,
resultCode: 0,
success: true,
dependencyTypeName: "SQL",
});
}
if( pctSelected && freqSelected ){
// close the issue
try {
await context.octokit.issues.update({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
issue_number: context.payload.issue.number,
state: "closed",
});
} catch (err) {
app.log.error(err);
appInsights.trackException({ exception: err });
}
}
} else {
if (
checkboxes.some((checkbox) => {
return (
checkbox.includes("Não") ||
checkbox.includes("No") ||
checkbox.includes("Non")
);
})
) {
let startTime = Date.now();
let query = await insertIntoDB(context, issue_id, pr_number, isCopilotUsed, null, null, comment);
let duration = Date.now() - startTime;
appInsights.trackDependency({
target: "DB:copilotUsage",
name: "insert when No is selected",
data: query,
duration: duration,
resultCode: 0,
success: true,
dependencyTypeName: "SQL",
});
if (comment) {
try {
// close the issue
await context.octokit.issues.update({
owner: context.payload.repository.owner.login,
repo: context.payload.repository.name,
issue_number: context.payload.issue.number,
state: "closed",
});
} catch (err) {
app.log.error(err);
appInsights.trackException({ exception: err });
}
}
}
}
}
async function insertIntoDB(
context,
issue_id,
pr_number,
isCopilotUsed,
pctValue,
freqValue,
comment
) {
let conn = null;
try {
conn = await sql.connect(DATABASE_CONNECTION_STRING);
// Check if table exists
let tableCheckResult = await sql.query`
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'SurveyResults'
`;
if (tableCheckResult.recordset.length === 0) {
// Create table if it doesn't exist
await sql.query`
CREATE TABLE SurveyResults (
record_ID int IDENTITY(1,1),
enterprise_name varchar(50),
organization_name varchar(50),
repository_name varchar(50),
issue_id int,
issue_number varchar(20),
PR_number varchar(20),
assignee_name varchar(50),
is_copilot_used BIT,
saving_percentage varchar(25),
usage_frequency varchar(50),
comment varchar(255),
created_at DATETIME,
completed_at DATETIME
);
`;
}
let result =
await sql.query`SELECT * FROM SurveyResults WHERE Issue_id = ${issue_id}`;
app.log.info("Database has been created and issue id existence has been confirmed");
// convert pctValue to string
if (pctValue) {
pctValue = pctValue.toString();
}
// convert freqValue to string
if (freqValue) {
freqValue = freqValue.toString();
}
let assignee_name = null;
if (context.payload.issue.assignee) {
assignee_name = context.payload.issue.assignee.login;
}
if (result.recordset.length > 0) {
// create query
let update_query = `UPDATE [SurveyResults] SET [is_copilot_used] = ${isCopilotUsed? 1 : 0}, [completed_at] = '${context.payload.issue.updated_at}'`;
if (assignee_name) {
update_query += `, [assignee_name] = '${assignee_name}'`;
}
if (pctValue) {
update_query += `, [saving_percentage] = '${pctValue}'`;
}
if (freqValue) {
update_query += `, [usage_frequency] = '${freqValue}'`;
}
if (comment) {
update_query += `, [comment] = '${comment}'`;
}
update_query += ` WHERE [issue_id] = ${issue_id}`;
// update existing record
let update_result = await sql.query(update_query);
app.log.info(update_result);
return update_query;
} else {
// check if dynamic values are present in context.payload
let enterprise_name = null;
let organization_name = null;
if (context.payload.enterprise) {
enterprise_name = context.payload.enterprise.name;
}
if(context.payload.organization){
organization_name = context.payload.organization.login;
}
if(context.payload.organization){
organization_name = context.payload.organization.login;
}
let insert_query = `INSERT INTO SurveyResults (
enterprise_name,
organization_name,
repository_name,
issue_id,
issue_number,
PR_number,
assignee_name,
is_copilot_used,
saving_percentage,
usage_frequency,
comment,
created_at,
completed_at
)
VALUES (
${enterprise_name},
${organization_name},
${context.payload.repository.name},
${issue_id},
${context.payload.issue.number},
${pr_number},
${assignee_name},
${isCopilotUsed},
${pctValue},
${freqValue},
${comment},
${context.payload.issue.created_at},
${context.payload.issue.updated_at}
)`;
let insert_result = await sql.query(insert_query);
app.log.info(insert_result);
return insert_query;
}
} catch (err) {
app.log.error(err);
appInsights.trackException({ exception: err });
} finally {
if (conn) {
conn.close();
}
}
}
// For more information on building apps:
// https://probot.github.io/docs/
// To get your app running against GitHub, see:
// https://probot.github.io/docs/development/
};
// Define class for app insights. If no instrumentation key is provided, then no app insights will be used.
class AppInsights {
constructor() {
if (process.env.APPINSIGHTS_INSTRUMENTATIONKEY) {
this.appInsights = require("applicationinsights");
this.appInsights.setup().start();
this.appIClient = this.appInsights.defaultClient;
} else {
this.appIClient = null;
}
}
trackEvent(name, properties) {
if (this.appIClient) {
this.appIClient.trackEvent({ name: name, properties: properties });
}
}
trackDependency(
target,
name,
data,
duration,
resultCode,
success,
dependencyTypeName
) {
if (this.appIClient) {
this.appIClient.trackDependency({
target: target,
name: name,
data: data,
duration: duration,
resultCode: resultCode,
success: success,
dependencyTypeName: dependencyTypeName,
});
}
}
trackException(exception) {
if (this.appIClient) {
this.appIClient.trackException({ exception: exception });
}
}
}