forked from triggerdotdev/trigger.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhance-release-pr.mjs
More file actions
333 lines (275 loc) · 9.48 KB
/
enhance-release-pr.mjs
File metadata and controls
333 lines (275 loc) · 9.48 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
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
#!/usr/bin/env node
/**
* Enhances the changeset release PR with a well-written, deduplicated summary.
*
* Reads:
* - The raw changeset PR body (via CHANGESET_PR_BODY env var or stdin)
* - .server-changes/*.md files for server-only changes
*
* Outputs a formatted PR body to stdout that includes:
* - A clean summary with categories
* - Server changes section
* - The raw changeset output in a collapsed <details> section
*
* Usage:
* CHANGESET_PR_BODY="..." node scripts/enhance-release-pr.mjs <version>
* echo "$PR_BODY" | node scripts/enhance-release-pr.mjs <version>
*/
import { promises as fs } from "fs";
import { execFile } from "child_process";
import { join } from "path";
const version = process.argv[2];
if (!version) {
console.error("Usage: node scripts/enhance-release-pr.mjs <version>");
process.exit(1);
}
const ROOT_DIR = join(import.meta.dirname, "..");
// --- Parse changeset PR body ---
function parsePrBody(body) {
const entries = [];
if (!body) return entries;
// Deduplicate by PR number
const seen = new Set();
const prPattern = /\[#(\d+)\]\(([^)]+)\)/;
for (const line of body.split("\n")) {
const trimmed = line.trim();
if (!trimmed.startsWith("- ") && !trimmed.startsWith("* ")) continue;
let text = trimmed.replace(/^[-*]\s+/, "").trim();
if (!text) continue;
// Skip dependency-only updates (e.g. "Updated dependencies:" or "@trigger.dev/core@4.4.2")
if (text.startsWith("Updated dependencies")) continue;
if (text.startsWith("`@trigger.dev/")) continue;
if (text.startsWith("@trigger.dev/")) continue;
if (text.startsWith("`trigger.dev@")) continue;
if (text.startsWith("trigger.dev@")) continue;
const prMatch = trimmed.match(prPattern);
if (prMatch) {
const prNumber = prMatch[1];
if (seen.has(prNumber)) continue;
seen.add(prNumber);
}
// Categorize
const lower = text.toLowerCase();
let type = "improvement";
if (lower.startsWith("fix") || lower.includes("bug fix")) {
type = "fix";
} else if (
lower.startsWith("feat") ||
lower.includes("new feature") ||
lower.includes("add support") ||
lower.includes("added support") ||
lower.includes("expose") ||
lower.includes("allow")
) {
type = "feature";
} else if (lower.includes("breaking")) {
type = "breaking";
}
entries.push({ text, type });
}
return entries;
}
// --- Git + GitHub helpers for finding PR numbers ---
const REPO = "triggerdotdev/trigger.dev";
function gitExec(args) {
return new Promise((resolve, reject) => {
execFile("git", args, { cwd: ROOT_DIR, maxBuffer: 1024 * 1024 }, (err, stdout) => {
if (err) reject(err);
else resolve(stdout.trim());
});
});
}
async function getCommitForFile(filePath) {
try {
// Find the commit that added this file
const sha = await gitExec(["log", "--diff-filter=A", "--format=%H", "--", filePath]);
return sha.split("\n")[0] || null;
} catch {
return null;
}
}
async function getPrForCommit(commitSha) {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (!token || !commitSha) return null;
try {
const res = await fetch(`https://api.github.com/repos/${REPO}/commits/${commitSha}/pulls`, {
headers: {
Authorization: `token ${token}`,
Accept: "application/vnd.github.v3+json",
},
});
if (!res.ok) return null;
const pulls = await res.json();
if (!pulls.length) return null;
// Prefer merged PRs, earliest merge first (same logic as @changesets/get-github-info)
const sorted = pulls.sort((a, b) => {
if (!a.merged_at && !b.merged_at) return 0;
if (!a.merged_at) return 1;
if (!b.merged_at) return -1;
return new Date(a.merged_at) - new Date(b.merged_at);
});
return sorted[0].number;
} catch {
return null;
}
}
// --- Parse .server-changes/ files ---
async function parseServerChanges() {
const dir = join(ROOT_DIR, ".server-changes");
const entries = [];
let files;
try {
files = await fs.readdir(dir);
} catch {
return entries;
}
// Collect file info and look up commits in parallel
const fileData = [];
for (const file of files) {
if (!file.endsWith(".md") || file === "README.md") continue;
const filePath = join(".server-changes", file);
const content = await fs.readFile(join(dir, file), "utf-8");
const parsed = parseFrontmatter(content);
if (!parsed.body.trim()) continue;
fileData.push({ filePath, parsed });
}
// Look up commits for all files in parallel
const commits = await Promise.all(fileData.map((f) => getCommitForFile(f.filePath)));
// Look up PRs for all commits in parallel
const prNumbers = await Promise.all(commits.map((sha) => getPrForCommit(sha)));
for (let i = 0; i < fileData.length; i++) {
const { parsed } = fileData[i];
let text = parsed.body.trim();
const pr = prNumbers[i];
// Append PR link if we found one and it's not already in the text
if (pr && !text.includes(`#${pr}`)) {
text += ` ([#${pr}](https://github.com/${REPO}/pull/${pr}))`;
}
entries.push({
text,
type: parsed.frontmatter.type || "improvement",
area: parsed.frontmatter.area || "webapp",
});
}
return entries;
}
function parseFrontmatter(content) {
const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
if (!match) return { frontmatter: {}, body: content };
const frontmatter = {};
for (const line of match[1].split("\n")) {
const [key, ...rest] = line.split(":");
if (key && rest.length) {
frontmatter[key.trim()] = rest.join(":").trim();
}
}
return { frontmatter, body: match[2] };
}
// --- Format the enhanced PR body ---
function formatPrBody({ version, packageEntries, serverEntries, rawBody }) {
const lines = [];
const features = packageEntries.filter((e) => e.type === "feature");
const fixes = packageEntries.filter((e) => e.type === "fix");
const improvements = packageEntries.filter((e) => e.type === "improvement" || e.type === "other");
const breaking = packageEntries.filter((e) => e.type === "breaking");
const serverFeatures = serverEntries.filter((e) => e.type === "feature");
const serverFixes = serverEntries.filter((e) => e.type === "fix");
const serverImprovements = serverEntries.filter((e) => e.type === "improvement");
const serverBreaking = serverEntries.filter((e) => e.type === "breaking");
const totalFeatures = features.length + serverFeatures.length;
const totalFixes = fixes.length + serverFixes.length;
const totalImprovements = improvements.length + serverImprovements.length;
// Summary line
const parts = [];
if (totalFeatures > 0) parts.push(`${totalFeatures} new feature${totalFeatures > 1 ? "s" : ""}`);
if (totalImprovements > 0)
parts.push(`${totalImprovements} improvement${totalImprovements > 1 ? "s" : ""}`);
if (totalFixes > 0) parts.push(`${totalFixes} bug fix${totalFixes > 1 ? "es" : ""}`);
if (parts.length > 0) {
lines.push(`## Summary`);
lines.push(`${parts.join(", ")}.`);
lines.push("");
}
// Breaking changes
if (breaking.length > 0 || serverBreaking.length > 0) {
lines.push("## Breaking changes");
for (const entry of [...breaking, ...serverBreaking]) lines.push(`- ${entry.text}`);
lines.push("");
}
// Highlights (features)
if (features.length > 0) {
lines.push("## Highlights");
lines.push("");
for (const entry of features) {
lines.push(`- ${entry.text}`);
}
lines.push("");
}
// Improvements
if (improvements.length > 0) {
lines.push("## Improvements");
for (const entry of improvements) lines.push(`- ${entry.text}`);
lines.push("");
}
// Bug fixes
if (fixes.length > 0) {
lines.push("## Bug fixes");
for (const entry of fixes) lines.push(`- ${entry.text}`);
lines.push("");
}
// Server changes
const allServer = [...serverFeatures, ...serverImprovements, ...serverFixes];
if (allServer.length > 0) {
lines.push("## Server changes");
lines.push("");
lines.push("These changes affect the self-hosted Docker image and Trigger.dev Cloud:");
lines.push("");
for (const entry of allServer) {
// Indent continuation lines so multi-line entries stay inside the list item
const indented = entry.text.replace(/\n/g, "\n ");
lines.push(`- ${indented}`);
}
lines.push("");
}
// Raw changeset output in collapsed section
if (rawBody) {
// Strip the Changesets action boilerplate from the raw body
const cleanedBody = rawBody
.replace(
/This PR was opened by the \[Changesets release\].*?If you're not ready to do a release yet.*?\n/gs,
""
)
.trim();
if (cleanedBody) {
lines.push("<details>");
lines.push("<summary>Raw changeset output</summary>");
lines.push("");
lines.push(cleanedBody);
lines.push("");
lines.push("</details>");
}
}
return lines.join("\n");
}
// --- Main ---
async function main() {
let rawBody = process.env.CHANGESET_PR_BODY || "";
if (!rawBody && !process.stdin.isTTY) {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
rawBody = Buffer.concat(chunks).toString("utf-8");
}
const packageEntries = parsePrBody(rawBody);
const serverEntries = await parseServerChanges();
const body = formatPrBody({
version,
packageEntries,
serverEntries,
rawBody,
});
process.stdout.write(body);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});