-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathbump-version.ts
More file actions
466 lines (391 loc) · 13.5 KB
/
bump-version.ts
File metadata and controls
466 lines (391 loc) · 13.5 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
#!/usr/bin/env npx tsx
/**
* Version bump script for AgentCore CLI
*
* Usage:
* npx tsx scripts/bump-version.ts <bump_type> [options]
*
* Arguments:
* bump_type: major | minor | patch | prerelease | preview | preview-major
*
* Options:
* --changelog <text> Custom changelog entry
* --prerelease-tag <tag> Prerelease identifier (default: beta)
* --dry-run Show what would be done without making changes
*
* Preview bumps (internal format):
* - 0.3.0 -> 0.3.0-preview.1.0
* - 0.3.0-preview.1.0 -> 0.3.0-preview.1.1 (preview)
* - 0.3.0-preview.1.0 -> 0.3.0-preview.2.0 (preview-major)
*/
import { execSync } from 'child_process';
import { existsSync, readFileSync, writeFileSync } from 'fs';
// ===========================
// Types
// ===========================
type BumpType = 'major' | 'minor' | 'patch' | 'prerelease' | 'preview' | 'preview-major';
interface ParsedVersion {
major: number;
minor: number;
patch: number;
prerelease?: string;
prereleaseNum?: number;
// For preview format: X.Y.Z-previewN.M
previewMajor?: number;
previewMinor?: number;
}
interface PackageJson {
version: string;
[key: string]: unknown;
}
interface PackageLockJson {
version: string;
packages?: {
''?: { version: string };
[key: string]: unknown;
};
[key: string]: unknown;
}
// ===========================
// Version Parsing & Bumping
// ===========================
function parseVersion(version: string): ParsedVersion {
// First try to match preview format: X.Y.Z-preview.N.M (e.g., 0.3.0-preview.1.0)
const previewMatch = /^(\d+)\.(\d+)\.(\d+)-preview\.(\d+)\.(\d+)$/.exec(version);
if (previewMatch) {
return {
major: parseInt(previewMatch[1]!, 10),
minor: parseInt(previewMatch[2]!, 10),
patch: parseInt(previewMatch[3]!, 10),
previewMajor: parseInt(previewMatch[4]!, 10),
previewMinor: parseInt(previewMatch[5]!, 10),
};
}
// Match standard versions like: 1.2.3, 1.2.3-beta.1, 1.2.3-rc.0
const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-zA-Z]+)\.(\d+))?$/.exec(version);
if (!match) {
throw new Error(`Invalid version format: ${version}`);
}
return {
major: parseInt(match[1]!, 10),
minor: parseInt(match[2]!, 10),
patch: parseInt(match[3]!, 10),
prerelease: match[4],
prereleaseNum: match[5] ? parseInt(match[5], 10) : undefined,
};
}
function formatVersion(parsed: ParsedVersion): string {
const base = `${parsed.major}.${parsed.minor}.${parsed.patch}`;
// Handle preview format: X.Y.Z-preview.N.M
if (parsed.previewMajor !== undefined && parsed.previewMinor !== undefined) {
return `${base}-preview.${parsed.previewMajor}.${parsed.previewMinor}`;
}
// Handle standard prerelease format: X.Y.Z-tag.N
if (parsed.prerelease !== undefined && parsed.prereleaseNum !== undefined) {
return `${base}-${parsed.prerelease}.${parsed.prereleaseNum}`;
}
return base;
}
function bumpVersion(current: string, bumpType: BumpType, prereleaseTag = 'beta'): string {
const parsed = parseVersion(current);
switch (bumpType) {
case 'major':
return formatVersion({
major: parsed.major + 1,
minor: 0,
patch: 0,
});
case 'minor':
return formatVersion({
major: parsed.major,
minor: parsed.minor + 1,
patch: 0,
});
case 'patch':
// If currently a prerelease or preview, just remove the suffix
if (parsed.prerelease || parsed.previewMajor !== undefined) {
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.patch,
});
}
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.patch + 1,
});
case 'prerelease':
// If already a prerelease with same tag, increment the number
if (parsed.prerelease === prereleaseTag && parsed.prereleaseNum !== undefined) {
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.patch,
prerelease: prereleaseTag,
prereleaseNum: parsed.prereleaseNum + 1,
});
}
// Otherwise, bump patch and start new prerelease
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.prerelease ? parsed.patch : parsed.patch + 1,
prerelease: prereleaseTag,
prereleaseNum: 0,
});
case 'preview':
// Handle preview format: X.Y.Z-previewN.M
// If already a preview, increment the minor preview number
if (parsed.previewMajor !== undefined && parsed.previewMinor !== undefined) {
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.patch,
previewMajor: parsed.previewMajor,
previewMinor: parsed.previewMinor + 1,
});
}
// Otherwise, start at preview.1.0
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.patch,
previewMajor: 1,
previewMinor: 0,
});
case 'preview-major':
// Increment the major preview number and reset minor to 0
if (parsed.previewMajor !== undefined && parsed.previewMinor !== undefined) {
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.patch,
previewMajor: parsed.previewMajor + 1,
previewMinor: 0,
});
}
// Otherwise, start at preview.1.0
return formatVersion({
major: parsed.major,
minor: parsed.minor,
patch: parsed.patch,
previewMajor: 1,
previewMinor: 0,
});
default: {
const exhaustiveCheck: never = bumpType;
throw new Error(`Unknown bump type: ${exhaustiveCheck as string}`);
}
}
}
// ===========================
// File Operations
// ===========================
function getCurrentVersion(): string {
const packageJson = JSON.parse(readFileSync('package.json', 'utf-8')) as PackageJson;
return packageJson.version;
}
function updatePackageJson(newVersion: string): void {
const packageJson = JSON.parse(readFileSync('package.json', 'utf-8')) as PackageJson;
packageJson.version = newVersion;
writeFileSync('package.json', JSON.stringify(packageJson, null, 2) + '\n');
console.log('✓ Updated package.json');
}
function updatePackageLockJson(newVersion: string): void {
if (!existsSync('package-lock.json')) {
return;
}
const packageLock = JSON.parse(readFileSync('package-lock.json', 'utf-8')) as PackageLockJson;
packageLock.version = newVersion;
// Also update the root package in packages
if (packageLock.packages?.['']) {
packageLock.packages[''].version = newVersion;
}
writeFileSync('package-lock.json', JSON.stringify(packageLock, null, 2) + '\n');
console.log('✓ Updated package-lock.json');
}
// ===========================
// Git Log & Changelog
// ===========================
function getGitLog(sinceTag?: string): string {
try {
let cmd = 'git log --pretty=format:"- %s (%h)"';
if (sinceTag) {
cmd += ` ${sinceTag}..HEAD`;
} else {
// Try to get the last tag
try {
const lastTag = execSync('git describe --tags --abbrev=0', { encoding: 'utf-8' }).trim();
cmd += ` ${lastTag}..HEAD`;
} catch {
// No tags exist, get last 20 commits
cmd += ' -n 20';
}
}
return execSync(cmd, { encoding: 'utf-8' });
} catch {
return '';
}
}
interface CategorizedChanges {
features: string[];
fixes: string[];
docs: string[];
other: string[];
}
function categorizeCommits(gitLog: string): CategorizedChanges {
const result: CategorizedChanges = {
features: [],
fixes: [],
docs: [],
other: [],
};
for (const line of gitLog.split('\n')) {
const trimmed = line.trim();
if (!trimmed?.startsWith('-')) continue;
const msg = trimmed.slice(2).trim();
if (msg.startsWith('feat:') || msg.startsWith('feature:')) {
result.features.push(msg);
} else if (msg.startsWith('fix:') || msg.startsWith('bugfix:')) {
result.fixes.push(msg);
} else if (msg.startsWith('docs:') || msg.startsWith('doc:')) {
result.docs.push(msg);
} else {
result.other.push(msg);
}
}
return result;
}
function formatChangelog(changes: CategorizedChanges): string {
const sections: string[] = [];
if (changes.features.length > 0) {
sections.push('### Added\n' + changes.features.map(m => `- ${m}`).join('\n'));
}
if (changes.fixes.length > 0) {
sections.push('### Fixed\n' + changes.fixes.map(m => `- ${m}`).join('\n'));
}
if (changes.docs.length > 0) {
sections.push('### Documentation\n' + changes.docs.map(m => `- ${m}`).join('\n'));
}
if (changes.other.length > 0) {
sections.push('### Other Changes\n' + changes.other.map(m => `- ${m}`).join('\n'));
}
return sections.join('\n\n');
}
function updateChangelog(newVersion: string, customChanges?: string): void {
const changelogPath = 'CHANGELOG.md';
const date = new Date().toISOString().split('T')[0];
// Build the new entry
let entryContent = '';
if (customChanges) {
entryContent = `### Changes\n\n${customChanges}`;
} else {
console.log('\n⚠️ No changelog provided. Auto-generating from commits.');
console.log('💡 Tip: Use --changelog to provide meaningful release notes');
const gitLog = getGitLog();
if (gitLog) {
const categorized = categorizeCommits(gitLog);
const formatted = formatChangelog(categorized);
entryContent = formatted || `### Changes\n\n${gitLog}`;
}
}
const entry = `## [${newVersion}] - ${date}\n\n${entryContent}`;
let content: string;
if (existsSync(changelogPath)) {
content = readFileSync(changelogPath, 'utf-8');
// Find where to insert (after # Changelog header line)
const lines = content.split('\n');
const headerIndex = lines.findIndex(line => line.startsWith('# Changelog'));
if (headerIndex !== -1) {
// Find the next ## or end of preamble (first non-empty line after a blank line)
let insertAt = headerIndex + 1;
// Skip blank lines and description text until we hit an existing ## or end
while (insertAt < lines.length && !lines[insertAt]?.startsWith('## ')) {
insertAt++;
}
// Insert the new entry
lines.splice(insertAt, 0, '', entry, '');
content = lines.join('\n');
} else {
// No header found, prepend everything
content = `# Changelog\n\n${entry}\n\n${content}`;
}
} else {
content = `# Changelog\n\nAll notable changes to this project will be documented in this file.\n\n${entry}\n`;
}
// Clean up multiple consecutive blank lines
content = content.replace(/\n{3,}/g, '\n\n');
// Ensure single trailing newline
content = content.trimEnd() + '\n';
writeFileSync(changelogPath, content);
console.log('✓ Updated CHANGELOG.md');
}
// ===========================
// CLI
// ===========================
function parseArgs(): { bumpType: BumpType; changelog?: string; prereleaseTag: string; dryRun: boolean } {
const args = process.argv.slice(2);
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
console.log(`
Usage: npx tsx scripts/bump-version.ts <bump_type> [options]
Arguments:
bump_type: major | minor | patch | prerelease | preview | preview-major
Options:
--changelog <text> Custom changelog entry
--prerelease-tag <tag> Prerelease identifier (default: beta)
--dry-run Show what would be done without making changes
--help, -h Show this help message
Preview bumps:
- 0.3.0 -> 0.3.0-preview.1.0
- 0.3.0-preview.1.0 -> 0.3.0-preview.1.1 (preview)
- 0.3.0-preview.1.0 -> 0.3.0-preview.2.0 (preview-major)
`);
process.exit(0);
}
const bumpType = args[0] as BumpType;
if (!['major', 'minor', 'patch', 'prerelease', 'preview', 'preview-major'].includes(bumpType)) {
console.error(
`Error: Invalid bump type '${bumpType}'. Must be one of: major, minor, patch, prerelease, preview, preview-major`
);
process.exit(1);
}
let changelog: string | undefined;
let prereleaseTag = 'beta';
let dryRun = false;
for (let i = 1; i < args.length; i++) {
if (args[i] === '--changelog' && args[i + 1]) {
changelog = args[++i];
} else if (args[i] === '--prerelease-tag' && args[i + 1]) {
prereleaseTag = args[++i]!;
} else if (args[i] === '--dry-run') {
dryRun = true;
}
}
return { bumpType, changelog, prereleaseTag, dryRun };
}
function main(): void {
const { bumpType, changelog, prereleaseTag, dryRun } = parseArgs();
try {
const currentVersion = getCurrentVersion();
const newVersion = bumpVersion(currentVersion, bumpType, prereleaseTag);
console.log(`Current version: ${currentVersion}`);
console.log(`New version: ${newVersion}`);
if (dryRun) {
console.log('\nDry run - no changes made');
return;
}
updatePackageJson(newVersion);
updatePackageLockJson(newVersion);
updateChangelog(newVersion, changelog);
console.log(`\n✓ Version bumped from ${currentVersion} to ${newVersion}`);
console.log('\nNext steps:');
console.log('1. Review changes: git diff');
console.log(`2. Commit: git add -A && git commit -m 'chore: bump version to ${newVersion}'`);
console.log('3. Create PR or push to trigger release workflow');
} catch (error) {
console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}
}
main();