microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
3040a83d6de0cc6876163b48ec9be61eefa3ebdd

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

eng/scripts/create-tryit-comment.js

132lines · modecode

1// @ts-check
2import { execSync } from "child_process";
3import https from "https";
4
5const AZP_USERID = "azure-pipelines[bot]";
6const TRY_ID_COMMENT_IDENTIFIER = "_CADL_TRYIT_COMMENT_";
7main().catch((e) => {
8 console.error(e);
9 // @ts-ignore
10 process.exit(1);
11});
12
13/**
14 * Retrieve github authentication header from the git config.
15 * MUST have `persistCredentials: true` in the checkout step.
16 */
17function getGithubAuthHeader(repo) {
18 const stdout = execSync(`git config --get http.https://github.com/${repo}.extraheader`)
19 .toString()
20 .trim();
21 const authHeader = stdout.split(": ")[1];
22 return authHeader;
23}
24
25async function main() {
26 const folderName = process.argv.length > 2 ? `/${process.argv[2]}` : "";
27 const repo = process.env["BUILD_REPOSITORY_ID"];
28 const prNumber = process.env["SYSTEM_PULLREQUEST_PULLREQUESTNUMBER"];
29 const ghToken = process.env.GH_TOKEN;
30 if (ghToken === undefined) {
31 throw new Error("GH_TOKEN environment variable is not set");
32 }
33 const ghAuth = `Bearer ${ghToken}`;
34
35 console.log("Looking for comments in", { repo, prNumber });
36 const data = await listComments(repo, prNumber, ghAuth);
37 const azoComments = data.filter((x) => x.user?.login === AZP_USERID);
38 console.log(`Found ${azoComments.length} comment(s) from Azure Pipelines.`);
39
40 const tryItComments = data.filter((x) => x.body.includes(TRY_ID_COMMENT_IDENTIFIER));
41 console.log(`Found ${azoComments.length} Cadl Try It comment(s)`);
42 if (tryItComments.length > 0) {
43 console.log("##vso[task.setvariable variable=SKIP_COMMENT;]true");
44 return;
45 }
46
47 const comment = [
48 `<!-- ${TRY_ID_COMMENT_IDENTIFIER} -->`,
49 `You can try these changes at https://cadlplayground.z22.web.core.windows.net${folderName}/prs/${prNumber}/`,
50 "",
51 `Check the website changes at https://tspwebsitepr.z22.web.core.windows.net${folderName}/prs/${prNumber}/`,
52 ].join("\n");
53 await writeComment(repo, prNumber, comment, ghAuth);
54}
55
56async function listComments(repo, prNumber, ghAuth) {
57 const url = `https://api.github.com/repos/${repo}/issues/${prNumber}/comments?per_page=100`;
58 const result = await request("GET", url, { ghAuth });
59 return JSON.parse(result);
60}
61
62async function writeComment(repo, prNumber, comment, ghAuth) {
63 const url = `https://api.github.com/repos/${repo}/issues/${prNumber}/comments`;
64 const body = {
65 body: comment,
66 };
67 const headers = {
68 "Content-Type": "application/json",
69 };
70
71 const response = await request("POST", url, {
72 headers,
73 body: JSON.stringify(body),
74 ghAuth,
75 });
76
77 console.log("Comment created", response);
78}
79
80async function request(method, url, data) {
81 const lib = https;
82 const value = new URL(url);
83
84 const params = {
85 method,
86 host: value.host,
87 port: 443,
88 path: value.pathname,
89 headers: {
90 "User-Agent": "nodejs",
91 ...data.headers,
92 },
93 };
94
95 console.log("Params", params);
96
97 params.headers.Authorization = data.ghAuth;
98
99 return new Promise((resolve, reject) => {
100 const req = lib.request(params, (res) => {
101 const data = [];
102
103 res.on("data", (chunk) => {
104 data.push(chunk);
105 });
106
107 res.on("end", () => {
108 if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
109 return reject(
110 new Error(
111 `Status Code: ${res.statusCode}, statusMessage: ${
112 res.statusMessage
113 }, headers: ${JSON.stringify(res.headers, null, 2)}, body: ${Buffer.concat(
114 data
115 ).toString()}`
116 )
117 );
118 } else {
119 resolve(Buffer.concat(data).toString());
120 }
121 });
122 });
123
124 req.on("error", reject);
125
126 if (data.body) {
127 req.write(data.body);
128 }
129
130 req.end();
131 });
132}
133