Repository navigation
Expand file tree
/
Copy pathcommitRecords.js
More file actions
195 lines (181 loc) · 6.44 KB
/
Copy pathcommitRecords.js
File metadata and controls
195 lines (181 loc) · 6.44 KB
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
#!/usr/bin/env node
// @ts-check
/* Draws commit records as a Semantic Diff page: one card per commit, each
* the commit's identity and its message drawn. A record is a commit message
* in the format of the `records` skill (.claude/skills/records/SKILL.md).
* This file reads git; scripts/recordRender.js draws.
*
* node scripts/commitRecords.js --out review.html <rev>...
* node scripts/commitRecords.js --out review.html <base>..<tip>...
* --pr <number> and --title <text> head the page with the pull request.
* --markdown <file> also draws the records as the pull request's comment
* (scripts/recordMarkdown.js), linking the page at --url <url>.
* --logins <file>, lines `<sha> <login>`, names the GitHub accounts of
* the commits' authors, drawn in place of their names. With
* --previous <rev>, the pull request's head before the last push, the
* comment marks the commits that push added or whose message it edited.
*/
import { execFileSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { commentMarkdown } from "./recordMarkdown.js";
import { CSS, esc, pageBody, pageTitle, parseRecord } from "./recordRender.js";
/** @import { CommitRecord, Group } from "./recordRender.js" */
/** @param {string[]} args */
const git = args =>
execFileSync("git", args, {
encoding: "utf8",
maxBuffer: 1 << 28,
stdio: ["ignore", "pipe", "ignore"],
});
const MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ");
/** A time as `Oct 23, 2026, 14:41 UTC`, as the cards and the comment print it. */
const utc = (/** @type {Date} */ d) => {
const two = (/** @type {number} */ n) => String(n).padStart(2, "0");
return `${MONTHS[d.getUTCMonth()]} ${two(d.getUTCDate())}, ${d.getUTCFullYear()}, ${two(d.getUTCHours())}:${two(d.getUTCMinutes())} UTC`;
};
/** A commit's message, trimmed. @param {string} rev */
const message = rev => git(["show", "-s", "--format=%B", rev]).trim();
/** The messages of the records read, by short hash. */
const messages = new Map();
/**
* The record of one commit: its short hash, author, author date (in UTC,
* to the minute) and message.
* @param {string} rev
* @returns {CommitRecord}
*/
function readRecord(rev) {
const show = (/** @type {string[]} */ ...format) =>
git(["show", "-s", ...format, rev]);
const record = parseRecord({
sha: show("--format=%h", "--abbrev=9").trim(),
author: show("--format=%an").trim(),
login: logins.get(show("--format=%H").trim()),
date: utc(new Date(show("--format=%aI").trim())),
message: show("--format=%B"),
});
messages.set(record.sha, message(rev));
return record;
}
/**
* What the last push changed, against the head before it: the records it
* added (`new`) or whose message it edited under the same subject
* (`edited`), by short hash. The previous commits are those of `previous`
* that the range's base lacks.
* @param {CommitRecord[]} records
* @param {string} base
* @param {string} previous
*/
function lastPush(records, base, previous) {
const before = git([
"rev-list",
"--no-merges",
previous,
`^${git(["merge-base", base, previous]).trim()}`,
])
.split("\n")
.filter(Boolean)
.map(message);
const subject = (/** @type {string} */ m) => m.split("\n")[0];
const kept = new Set(before);
const subjects = new Set(before.map(subject));
/** @type {Map<string, "new" | "edited">} */
const changes = new Map();
for (const r of records) {
const m = messages.get(r.sha) ?? "";
if (!kept.has(m))
changes.set(r.sha, subjects.has(subject(m)) ? "edited" : "new");
}
return changes;
}
/**
* The comment's marks of the last push, or none when the previous head
* can't be read, so that the comment is still drawn.
* @param {CommitRecord[]} records
* @param {string} base
* @param {string} previous
*/
function marks(records, base, previous) {
try {
return { changes: lastPush(records, base, previous) };
} catch {
return {};
}
}
/**
* A revision is one card; a range `base..tip` is its commits, oldest first.
* @param {string} arg
* @returns {Group}
*/
function group(arg) {
if (!arg.includes("..")) return { records: [readRecord(arg)] };
const revs = git(["rev-list", "--reverse", "--no-merges", arg])
.split("\n")
.filter(Boolean);
return { range: arg, records: revs.map(readRecord) };
}
const args = process.argv.slice(2);
/** @type {Record<string, string>} */
const options = {};
/** @type {string[]} */
const targets = [];
for (let i = 0; i < args.length; i++) {
if (
[
"--out",
"--pr",
"--title",
"--markdown",
"--url",
"--previous",
"--logins",
].includes(args[i]) &&
i + 1 < args.length
)
options[args[i].slice(2)] = args[++i];
else targets.push(args[i]);
}
const outFile = options.out;
if (!outFile) {
console.error(
"usage: commitRecords.js --out <page.html> [--pr <number>] [--title <text>] [--markdown <comment.md> [--url <page url>] [--previous <rev>]] [--logins <file>] <rev | base..tip>...",
);
process.exit(1);
}
/** The GitHub logins of the commits' authors, by full sha. */
const logins = new Map(
(options.logins ? readFileSync(options.logins, "utf8") : "")
.split("\n")
.map(l => l.trim().split(/\s+/))
.filter(f => f.length === 2)
.map(([sha, login]) => [sha, login]),
);
const heading = {
pr: (options.pr ?? "").replace(/\D/g, ""),
title: options.title ?? "",
};
const groups = targets.map(group);
const body = pageBody(groups, heading);
if (options.markdown) {
const [base, tip] = targets[targets.length - 1].split("..");
const records = groups.flatMap(g => g.records);
writeFileSync(
options.markdown,
commentMarkdown(groups, {
url: options.url,
head: git(["rev-parse", "--short=9", tip ?? base]).trim(),
updated: utc(new Date()),
...(options.previous && tip
? marks(records, base, options.previous)
: {}),
}),
);
console.log(options.markdown);
}
const head = `<title>${esc(pageTitle(heading))}</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,600&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&family=STIX+Two+Text:ital,wght@0,400;0,500;1,400&display=swap">
<style>${CSS}</style>`;
writeFileSync(
outFile,
`<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">\n${head}</head><body>${body}</body></html>\n`,
);
console.log(outFile);