generated from pabio/github-actions-starter
-
Notifications
You must be signed in to change notification settings - Fork 136
/
summary.ts
369 lines (340 loc) Β· 15.2 KB
/
summary.ts
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
import slugify from "@sindresorhus/slugify";
import { mkdirp, readdir, readFile, writeFile } from "fs-extra";
import { join } from "path";
import { format } from "prettier";
import { getResponseTimeForSite } from "./helpers/calculate-response-time";
import { getUptimePercentForSite } from "./helpers/calculate-uptime";
import { getConfig } from "./helpers/config";
import { commit, push } from "./helpers/git";
import { getOctokit } from "./helpers/github";
import { shouldContinue } from "./helpers/init-check";
import { SiteStatus } from "./interfaces";
import { parse } from "url";
export const generateSummary = async () => {
if (!(await shouldContinue())) return;
await mkdirp("history");
let [owner, repo] = (process.env.GITHUB_REPOSITORY || "").split("/");
const config = await getConfig();
const octokit = await getOctokit();
let readmeContent = await readFile(join(".", "README.md"), "utf8");
const startText = readmeContent.split(
config.summaryStartHtmlComment || "<!--start: status pages-->"
)[0];
const endText = readmeContent.split(
config.summaryEndHtmlComment || "<!--end: status pages-->"
)[1];
// This object will track the summary data of all sites
const pageStatuses: Array<SiteStatus> = [];
// We'll keep incrementing this if there are down/degraded sites
// This is used to show the overall status later
let numberOfDown = 0;
let numberOfDegraded = 0;
// Loop through each site and add compute the current status
for await (const site of config.sites) {
const slug = site.slug || slugify(site.name);
const uptimes = await getUptimePercentForSite(slug);
console.log("Uptimes", uptimes);
const responseTimes = await getResponseTimeForSite(slug);
console.log("Response times", responseTimes);
let fallbackIcon = "";
try {
fallbackIcon = `https://favicons.githubusercontent.com/${parse(site.url).hostname}`;
} catch (error) {}
pageStatuses.push({
name: site.name,
url: site.url,
icon: site.icon || fallbackIcon,
slug,
status: responseTimes.currentStatus,
uptime: uptimes.all,
uptimeDay: uptimes.day,
uptimeWeek: uptimes.week,
uptimeMonth: uptimes.month,
uptimeYear: uptimes.year,
time: Math.floor(responseTimes.all),
timeDay: responseTimes.day,
timeWeek: responseTimes.week,
timeMonth: responseTimes.month,
timeYear: responseTimes.year,
dailyMinutesDown: uptimes.dailyMinutesDown,
});
if (responseTimes.currentStatus === "down") numberOfDown++;
if (responseTimes.currentStatus === "degraded") numberOfDegraded++;
}
let website = `https://${config.owner}.github.io/${config.repo}`;
if (config["status-website"] && config["status-website"].cname)
website = `https://${config["status-website"].cname}`;
const i18n = config.i18n || {};
if (readmeContent.includes(config.summaryStartHtmlComment || "<!--start: status pages-->")) {
readmeContent = `${startText}${config.summaryStartHtmlComment || "<!--start: status pages-->"}
<!-- This summary is generated by Upptime (https://github.com/upptime/upptime) -->
<!-- Do not edit this manually, your changes will be overwritten -->
<!-- prettier-ignore -->
| ${i18n.url || "URL"} | ${i18n.status || "Status"} | ${i18n.history || "History"} | ${
i18n.responseTime || "Response Time"
} | ${i18n.uptime || "Uptime"} |
| --- | ------ | ------- | ------------- | ------ |
${pageStatuses
.map(
(page) =>
`| <img alt="" src="${page.icon}" height="13"> ${
page.url.includes("$") ? page.name : `[${page.name}](${page.url})`
} | ${
page.status === "up"
? i18n.up || "π© Up"
: page.status === "degraded"
? i18n.degraded || "π¨ Degraded"
: i18n.down || "π₯ Down"
} | [${page.slug}.yml](https://github.com/${owner}/${repo}/commits/master/history/${
page.slug
}.yml) | <details><summary><img alt="${
i18n.responseTimeGraphAlt || "Response time graph"
}" src="./graphs/${page.slug}/response-time-week.png" height="20"> ${page.timeWeek}${
i18n.ms || "ms"
}</summary><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.responseTime || "Response time"
} ${
page.time
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fresponse-time.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.responseTimeDay || "24-hour response time"
} ${
page.timeDay
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fresponse-time-day.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.responseTimeWeek || "7-day response time"
} ${
page.timeWeek
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fresponse-time-week.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.responseTimeMonth || "30-day response time"
} ${
page.timeMonth
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fresponse-time-month.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.responseTimeYear || "1-year response time"
} ${
page.timeYear
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fresponse-time-year.json"></a></details> | <details><summary><a href="${website}/history/${
page.slug
}">${page.uptimeWeek}</a></summary><a href="${website}/history/${page.slug}"><img alt="${
i18n.uptime || "All-time uptime"
} ${
page.uptime
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fuptime.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.uptimeDay || "24-hour uptime"
} ${
page.uptimeDay
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fuptime-day.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.uptimeWeek || "7-day uptime"
} ${
page.uptimeWeek
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fuptime-week.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.uptimeMonth || "30-day uptime"
} ${
page.uptimeMonth
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fuptime-month.json"></a><br><a href="${website}/history/${page.slug}"><img alt="${
i18n.uptimeYear || "1-year uptime"
} ${
page.uptimeYear
}" src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2F${owner}%2F${repo}%2Fmaster%2Fapi%2F${
page.slug
}%2Fuptime-year.json"></a></details>`
)
.join("\n")}
${config.summaryEndHtmlComment || "<!--end: status pages-->"}${endText}`;
}
// Skip running this in the template repository
if (`${owner}/${repo}` !== "upptime/upptime") {
// Remove Upptime logo and add heaading
readmeContent = readmeContent
.split("\n")
.map((line, index) => {
if (index === 0 && line.includes("https://upptime.js.org"))
return `# [π ${i18n.liveStatus || "Live Status"}](${website}): ${
i18n.liveStatusHtmlComment || "<!--live status-->"
} **${i18n.allSystemsOperational || "π© All systems operational"}**`;
if (
line.includes("[![Summary CI](https://github.com") &&
readmeContent.includes("<!--start: description-->")
)
return `${line}\n\nWith [Upptime](https://upptime.js.org), you can get your own unlimited and free uptime monitor and status page, powered entirely by a GitHub repository. We use [Issues](https://github.com/${config.owner}/${config.repo}/issues) as incident reports, [Actions](https://github.com/${config.owner}/${config.repo}/actions) as uptime monitors, and [Pages](${website}) for the status page.`;
return line;
})
.filter((line) => !line.startsWith(`## [π ${i18n.liveStatus || "Live Status"}]`))
.join("\n");
// Remove default documentation
const docsStartText = readmeContent.split("<!--start: docs-->")[0];
const docsEndText = readmeContent.split("<!--end: docs-->")[1];
if (readmeContent.includes("<!--start: docs-->"))
readmeContent = `${docsStartText}[**Visit our status website β**](${website})${docsEndText}`;
// Remove Koj logo
const logoStartText = readmeContent.split("<!--start: logo-->")[0];
const logoEndText = readmeContent.split("<!--end: logo-->")[1];
if (readmeContent.includes("<!--start: logo-->"))
readmeContent = `${logoStartText}${logoEndText}`;
let name = `[${config.owner}](${website})`;
if (
readmeContent.includes("[MIT](./LICENSE) Β© [Koj](https://koj.co)") ||
readmeContent.includes("<!--start: description-->")
) {
try {
const org = await octokit.users.getByUsername({ username: config.owner });
name = `[${org.data.name || config.owner}](${org.data.blog || website})`;
} catch (error) {}
// Remove Koj description
const descriptionStartText = readmeContent.split("<!--start: description-->")[0];
const descriptionEndText = readmeContent.split("<!--end: description-->")[1];
if (readmeContent.includes("<!--start: description-->"))
readmeContent = `${descriptionStartText}This repository contains the open-source uptime monitor and status page for ${name}, powered by [Upptime](https://github.com/upptime/upptime).${descriptionEndText}`;
// Change copyright
readmeContent = readmeContent.replace(
"[MIT](./LICENSE) Β© [Koj](https://koj.co)",
`[MIT](./LICENSE) Β© ${name}`
);
// Add powered by Upptime
if (!config.skipPoweredByReadme) {
readmeContent = readmeContent.replace(
"## π License\n\n- Code: [MIT](./LICENSE)",
"## π License\n\n- Powered by: [Upptime](https://github.com/upptime/upptime)\n- Code: [MIT](./LICENSE)"
);
}
}
// Change badges
readmeContent = readmeContent.replace(
new RegExp("upptime/upptime/workflows", "g"),
`${config.owner}/${config.repo}/workflows`
);
// Add repo description, topics, etc.
try {
const repoInfo = await octokit.repos.get({ owner, repo });
if (!repoInfo.data.description && !config.skipDescriptionUpdate)
await octokit.repos.update({
owner,
repo,
description: `π Uptime monitor and status page for ${name
.split("]")[0]
.replace("[", "")}, powered by @upptime`,
});
console.log("Current topics are", repoInfo.data.topics);
if (!(repoInfo.data.topics || []).includes("upptime") && !config.skipTopicsUpdate)
await octokit.repos.replaceAllTopics({
owner,
repo,
names: [
...(repoInfo.data.topics || []),
"uptime-monitor",
"status-page",
"upptime",
].filter((value, index, array) => array.indexOf(value) === index),
});
console.log(
"Possibly updated to to",
[...(repoInfo.data.topics || []), "uptime-monitor", "status-page", "upptime"].filter(
(value, index, array) => array.indexOf(value) === index
)
);
console.log("Topics are", (await octokit.repos.get({ owner, repo })).data.topics);
if (!repoInfo.data.homepage && !config.skipHomepageUpdate)
await octokit.repos.update({
owner,
repo,
homepage: website,
});
} catch (error) {
console.log(error);
}
}
// Add live status line
readmeContent = readmeContent
.split("\n")
.map((line) => {
if (line.includes("<!--live status-->")) {
line = `${line.split("<!--live status-->")[0]}<!--live status--> **${
numberOfDown === 0
? numberOfDegraded === 0
? i18n.allSystemsOperational || "π© All systems operational"
: i18n.degradedPerformance || "π¨ Degraded performance"
: numberOfDown === config.sites.length
? i18n.completeOutage || "π₯ Complete outage"
: i18n.partialOutage || "π§ Partial outage"
}**`;
}
return line;
})
.join("\n");
await writeFile(join(".", "README.md"), format(readmeContent, { parser: "markdown" }));
commit(
(config.commitMessages || {}).readmeContent ||
":pencil: Update summary in README [skip ci] [upptime]",
(config.commitMessages || {}).commitAuthorName,
(config.commitMessages || {}).commitAuthorEmail
);
// If there are any old workflows left, fix them
const workflows = (await readdir(join(".", ".github", "workflows"))).filter((i) =>
i.endsWith(".yml")
);
for await (const workflow of workflows) {
const content = await readFile(join(".", ".github", "workflows", workflow), "utf8");
const newContent = content.replace("actions/setup-node@v2.1.1", "actions/setup-node@v1.4.4");
if (content !== newContent) {
console.log("Updating workflow", workflow);
await writeFile(join(".", ".github", "workflows", workflow), newContent);
}
}
await writeFile(join(".", "history", "summary.json"), JSON.stringify(pageStatuses, null, 2));
commit(
(config.commitMessages || {}).summaryJson ||
":card_file_box: Update status summary [skip ci] [upptime]",
(config.commitMessages || {}).commitAuthorName,
(config.commitMessages || {}).commitAuthorEmail
);
push();
if (!config.skipDeleteIssues) {
// Find all the opened issues that shouldn't have opened
// Say, Upptime found a down monitor and it was back up within 5 min
const issuesRecentlyClosed = await octokit.issues.listForRepo({
owner,
repo,
state: "closed",
labels: "status",
per_page: 10,
});
console.log("Found recently closed issues", issuesRecentlyClosed.data.length);
for await (const issue of issuesRecentlyClosed.data) {
if (
// If this issue was closed within 15 minutes
new Date(issue.closed_at).getTime() - new Date(issue.created_at).getTime() < 900000 &&
// It has 1 comment (the default Upptime one)
issue.comments === 1
) {
try {
console.log("Trying to delete issue", issue.number, issue.node_id);
const result = await octokit.graphql(`
mutation deleteIssue {
deleteIssue(input:{issueId:"${issue.node_id}"}) {
clientMutationId
}
}`);
console.log("Success", result);
} catch (error) {
console.log("Error deleting this issue", error);
}
}
}
}
};