forked from remix-run/react-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate-changesets.ts
More file actions
252 lines (208 loc) · 6.89 KB
/
migrate-changesets.ts
File metadata and controls
252 lines (208 loc) · 6.89 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
/**
* Migrates changeset files from `.changeset/` to `packages/<pkg>/.changes/<bump>.<name>.md`.
*
* Changeset files use YAML frontmatter to declare which packages they affect and with
* what semver bump type, followed by the change description:
*
* ---
* "react-router": minor
* "@react-router/node": patch
* ---
*
* Description of the change
*
* Each package entry becomes a separate change file in the new system.
*
* Usage:
* node scripts/changes/migrate-changesets-files.ts [--dry-run]
*/
import * as cp from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import {
GITHUB_REPO_URL,
packageNameToDirectoryName,
} from "../utils/packages.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, "..", "..");
const changesetsDir = path.join(repoRoot, ".changeset");
const packagesDir = path.join(repoRoot, "packages");
const args = process.argv.slice(2);
const dryRun = args.includes("--dry-run");
const validBumps = new Set(["major", "minor", "patch"]);
interface ParsedChangeset {
/** Map from npm package name to bump type */
packages: Map<string, string>;
/** The change description (everything after the frontmatter) */
description: string;
}
function parseChangeset(content: string): ParsedChangeset | null {
// Changeset files start and end frontmatter with "---"
if (!content.startsWith("---")) {
return null;
}
let closingIndex = content.indexOf("\n---", 3);
if (closingIndex === -1) {
return null;
}
let frontmatter = content.slice(3, closingIndex).trim();
let description = content.slice(closingIndex + 4).trim();
let packages = new Map<string, string>();
for (let line of frontmatter.split("\n")) {
line = line.trim();
if (!line) continue;
// Lines look like: "package-name": bump
// The package name may be quoted with double quotes.
let match = line.match(/^"([^"]+)":\s*(\S+)$/);
if (!match) {
console.warn(` ⚠️ Could not parse frontmatter line: ${line}`);
continue;
}
let [, packageName, bump] = match;
packages.set(packageName, bump);
}
return { packages, description };
}
/**
* Returns a markdown link to the PR or commit that introduced the given file.
* Prefers a PR link like `([#123](...))`, falls back to a short SHA link.
*/
function getSourceLink(filePath: string): string {
let result = cp.spawnSync(
"git",
["log", "--format=%H %s", "-1", "--", filePath],
{ encoding: "utf-8" },
);
let line = result.stdout.trim();
if (!line) return "";
let spaceIndex = line.indexOf(" ");
let sha = line.slice(0, spaceIndex);
let subject = line.slice(spaceIndex + 1);
let prMatch = subject.match(/\(#(\d+)\)$/);
if (prMatch) {
let pr = prMatch[1];
return ` ([#${pr}](${GITHUB_REPO_URL}/pull/${pr}))`;
}
let shortSha = sha.slice(0, 8);
return ` ([${shortSha}](${GITHUB_REPO_URL}/commit/${sha}))`;
}
function slugify(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
async function main() {
if (!fs.existsSync(changesetsDir)) {
console.log("No .changeset directory found — nothing to migrate.");
return;
}
let files = fs
.readdirSync(changesetsDir)
.filter((f) => f.endsWith(".md") && f !== "README.md");
if (files.length === 0) {
console.log("No changeset files found — nothing to migrate.");
return;
}
console.log(
`${dryRun ? "[DRY RUN] " : ""}Migrating ${files.length} changeset file${files.length === 1 ? "" : "s"}...\n`,
);
let totalCreated = 0;
let totalSkipped = 0;
let totalDeleted = 0;
for (let file of files) {
let filePath = path.join(changesetsDir, file);
let content = fs.readFileSync(filePath, "utf-8");
let baseName = path.basename(file, ".md");
console.log(`📄 ${file}`);
let parsed = parseChangeset(content);
if (!parsed) {
console.warn(` ⚠️ Could not parse changeset file — skipping\n`);
totalSkipped++;
continue;
}
if (parsed.packages.size === 0) {
console.warn(` ⚠️ No packages found in frontmatter — skipping\n`);
totalSkipped++;
continue;
}
if (!parsed.description) {
console.warn(` ⚠️ Empty description — skipping\n`);
totalSkipped++;
continue;
}
let allValid = true;
for (let [packageName, bump] of parsed.packages) {
if (!validBumps.has(bump)) {
console.warn(
` ⚠️ Unknown bump type "${bump}" for "${packageName}" — skipping file\n`,
);
allValid = false;
break;
}
let dirName = packageNameToDirectoryName(packageName);
if (!dirName) {
console.warn(
` ⚠️ Could not resolve directory for package "${packageName}" — skipping file\n`,
);
allValid = false;
break;
}
let changesDir = path.join(packagesDir, dirName, ".changes");
if (!fs.existsSync(changesDir)) {
console.warn(
` ⚠️ .changes directory does not exist for "${packageName}" (${dirName}) — skipping file\n`,
);
allValid = false;
break;
}
}
if (!allValid) {
totalSkipped++;
continue;
}
// Write one change file per package entry
for (let [packageName, bump] of parsed.packages) {
let dirName = packageNameToDirectoryName(packageName)!;
let changesDir = path.join(packagesDir, dirName, ".changes");
let slug = slugify(baseName);
let destFileName = `${bump}.${slug}.md`;
let destPath = path.join(changesDir, destFileName);
// Avoid overwriting existing files by appending a counter
let counter = 1;
while (fs.existsSync(destPath)) {
destFileName = `${bump}.${slug}-${counter}.md`;
destPath = path.join(changesDir, destFileName);
counter++;
}
let destRelative = path.relative(repoRoot, destPath);
console.log(` ✅ ${packageName} → ${destRelative}`);
if (!dryRun) {
let link = getSourceLink(filePath);
let lines = parsed.description.trim().split("\n");
lines[0] += link;
let content = lines.join("\n") + "\n";
fs.writeFileSync(destPath, content, "utf-8");
}
totalCreated++;
}
// Delete the original changeset file
let fileRelative = path.relative(repoRoot, filePath);
console.log(` 🗑️ Deleting ${fileRelative}`);
if (!dryRun) {
fs.unlinkSync(filePath);
}
totalDeleted++;
console.log();
}
console.log(
`${dryRun ? "[DRY RUN] " : ""}Done: ${totalCreated} change file${totalCreated === 1 ? "" : "s"} created, ` +
`${totalDeleted} changeset file${totalDeleted === 1 ? "" : "s"} deleted, ` +
`${totalSkipped} skipped.`,
);
}
main().catch((error) => {
console.error("Error:", error.message);
process.exit(1);
});