generated from pabio/github-actions-starter
/
update-summary.ts
156 lines (155 loc) Β· 5.92 KB
/
update-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
import { debug } from "@actions/core";
import { Context } from "@actions/github/lib/context";
import type { GitHub } from "@actions/github/lib/utils";
import { config, cosmic } from "@anandchowdhary/cosmic";
import { promises } from "fs";
import humanizeDuration from "humanize-duration";
import { join } from "path";
import { format } from "prettier";
import { exec } from "shelljs";
import { addDetailsToLabels } from "../github";
import { BookResult } from "../google-books";
export const updateSummary = async (
owner: string,
repo: string,
context: Context,
octokit: InstanceType<typeof GitHub>
) => {
debug("Starting updateSummary");
try {
await cosmic("bookshelf");
debug("Got config object");
} catch (error) {}
const issues = await octokit.issues.listForRepo({
owner: context.issue.owner,
repo: context.issue.repo,
labels: "kind: book",
state: "all",
});
debug(`Got ${issues.data.length} issues`);
let api: (BookResult & {
state: "reading" | "completed";
issueNumber: number;
startedAt: string;
progressPercent: number;
completedAt?: string;
timeToComplete?: number;
timeToCompleteFormatted?: string;
})[] = [];
for await (const issue of issues.data) {
const comments = await octokit.issues.listComments({
owner: context.issue.owner,
repo: context.issue.repo,
issue_number: issue.number,
});
debug(`Got ${comments.data.length} comments in issue ${issue.number}`);
let json: BookResult | undefined = undefined;
try {
comments.data.forEach((comment) => {
if (comment.body.includes("Book details (JSON)"))
json = JSON.parse(comment.body.split("```json")[1].split("```")[0]) as BookResult;
});
} catch (error) {
console.log("JSON parsing error", error);
}
if (json) {
debug(`Found JSON data for ${(json as BookResult).title}`);
const currentPercentage = issue.title.match(/\(\d+\%\)/g);
const overwrites =
config("overwrites") || ({} as Record<number, { started: string; completed: string }>);
const openedAt = (overwrites[issue.number] || {}).started
? overwrites[issue.number].started
: issue.created_at;
const closedAt = (overwrites[issue.number] || {}).completed
? overwrites[issue.number].completed
: issue.closed_at;
api.push({
...(json as BookResult),
issueNumber: issue.number,
progressPercent:
currentPercentage && currentPercentage.length && !isNaN(parseInt(currentPercentage[0]))
? parseInt(currentPercentage[0])
: 0,
state: issue.state === "open" ? "reading" : "completed",
startedAt: new Date(openedAt).toISOString(),
completedAt: issue.state === "closed" ? new Date(closedAt).toISOString() : undefined,
timeToComplete:
issue.state === "closed"
? new Date(closedAt).getTime() - new Date(openedAt).getTime()
: undefined,
timeToCompleteFormatted:
issue.state === "closed"
? humanizeDuration(new Date(closedAt).getTime() - new Date(openedAt).getTime()).split(
","
)[0]
: undefined,
});
} else debug(`Unable to find JSON data for #${issue.id}`);
}
api = api.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());
await promises.writeFile(join(".", "api.json"), JSON.stringify(api, null, 2) + "\n");
debug("Written api.json file");
debug(`api has length ${api.length}`);
let mdContent = "";
const apiCompleted = api.filter((i) => i.state === "completed");
const apiReading = api.filter((i) => i.state === "reading");
if (apiReading.length)
mdContent += `### β Currently reading (${apiReading.length})\n\n${apiReading
.map(
(i) =>
`[![Book cover of ${i.title.replace(
/\"/g,
""
)}](https://images.weserv.nl/?url=${encodeURIComponent(
i.image
)}&w=128&h=196&fit=contain)](https://github.com/${owner}/${repo}/issues/${
i.issueNumber
} "${i.title.replace(/\"/g, "")} by ${i.authors.join(", ")}")`
)
.join("\n")}`;
if (apiCompleted.length)
mdContent += `${apiReading.length ? "\n\n" : ""}### β
Completed (${
apiCompleted.length
})\n\n${apiCompleted
.map(
(i) =>
`[![Book cover of ${i.title.replace(
/\"/g,
""
)}](https://images.weserv.nl/?url=${encodeURIComponent(
i.image
)}&w=128&h=196&fit=contain)](https://github.com/${owner}/${repo}/issues/${
i.issueNumber
} "${i.title.replace(/\"/g, "")} by ${i.authors
.join(", ")
.replace(/\"/g, "")} completed in ${i.timeToCompleteFormatted} on ${new Date(
i.completedAt || ""
).toLocaleDateString("en-us", {
month: "long",
year: "numeric",
})}")`
)
.join("\n")}`;
debug(`Generated README.md content of length ${mdContent.length}`);
const content = await promises.readFile(join(".", "README.md"), "utf8");
debug(`Read README.md file of length ${content.length}`);
await promises.writeFile(
join(".", "README.md"),
content.split("<!--start:bookshelf-action-->")[0] +
`<!--start:bookshelf-action-->\n${format(mdContent, {
parser: "markdown",
})}\n<!--end:bookshelf-action-->` +
content.split("<!--end:bookshelf-action-->")[1]
);
debug("Written README.md file");
exec(`git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"`);
exec(`git config --global user.name "github-actions[bot]"`);
debug("Added git config user details");
exec("git add .");
exec('git commit -m ":bento: Update API and README summary [skip ci]"');
debug("Committed to git history");
exec("git push");
debug("Pushed to repository");
await addDetailsToLabels(owner, repo, octokit);
debug("Updated label details");
};