-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathgithub.ts
More file actions
434 lines (386 loc) · 12.2 KB
/
Copy pathgithub.ts
File metadata and controls
434 lines (386 loc) · 12.2 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
/*
* Copyright (c) 2025 Bytedance, Inc. and its affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* GitHub utilities for creating releases
*/
import { execa } from 'execa';
import { logger } from './logger';
import { shouldIncludeCommitByScope } from './commit';
// Username mapping for commit authors to correct GitHub usernames
const USERNAME_MAP: Record<string, string> = {
chenhaoli: 'ulivz',
小健: 'cjraft',
};
/**
* Extract GitHub username from noreply email or apply manual mapping
*/
function resolveGitHubUsername(
authorName: string,
authorEmail: string,
): string {
// Extract from GitHub noreply email pattern: {id}+{username}@users.noreply.github.com
const emailMatch = authorEmail.match(
/^\d+\+([^@]+)@users\.noreply\.github\.com$/,
);
if (emailMatch) {
return emailMatch[1];
}
// Fallback to manual mapping
return USERNAME_MAP[authorName] || authorName;
}
/**
* GitHub release options
*/
export interface GitHubReleaseOptions {
version: string;
tagName: string;
cwd: string;
dryRun?: boolean;
}
/**
* Gets the previous tag for generating release notes
* Handles mixed tag formats (v1.0.0 and @sailors@1.0.0)
* Filters out canary releases
*/
export async function getPreviousTag(
tagName: string,
cwd: string,
): Promise<string | null> {
try {
// Get all tags sorted by creation date (chronological order, newest first)
const { stdout } = await execa('git', ['tag', '--sort=-creatordate'], {
cwd,
});
const allTags = stdout.trim().split('\n').filter(Boolean);
if (allTags.length === 0) {
return null;
}
// Filter out canary releases
const nonCanaryTags = allTags.filter((tag) => !tag.includes('canary'));
if (nonCanaryTags.length === 0) {
return null;
}
// Find the current tag in the filtered list
const currentIndex = nonCanaryTags.findIndex((tag) => tag === tagName);
if (currentIndex === -1) {
// If current tag not found, it might be a new tag
// Return the most recent non-canary tag (first in the list)
return nonCanaryTags[0] || null;
}
// Return the next tag (previous in chronological order)
if (currentIndex < nonCanaryTags.length - 1) {
return nonCanaryTags[currentIndex + 1];
}
return null;
} catch (error) {
logger.warn(`Failed to get previous tag: ${(error as Error).message}`);
return null;
}
}
/**
* Generates beautiful release notes using conventional-changelog format
*/
export async function generateReleaseNotes(
tagName: string,
previousTag: string | null,
cwd: string,
repoInfo?: { owner: string; repo: string },
filterScopes?: string[],
): Promise<string> {
try {
// Get commits between tags
const gitRange = previousTag ? `${previousTag}..${tagName}` : tagName;
const { stdout } = await execa(
'git',
['log', gitRange, '--pretty=format:%H|%s|%an|%ae', '--no-merges'],
{ cwd },
);
if (!stdout.trim()) {
return `## What's Changed\n\nNo changes found.`;
}
const commits = stdout
.trim()
.split('\n')
.map((line) => {
const [hash, subject, author, email] = line.split('|');
return { hash, subject, author, email };
});
// Group commits by type
const groups = {
feat: [] as typeof commits,
fix: [] as typeof commits,
docs: [] as typeof commits,
style: [] as typeof commits,
refactor: [] as typeof commits,
test: [] as typeof commits,
chore: [] as typeof commits,
other: [] as typeof commits,
};
commits.forEach((commit) => {
const match = commit.subject.match(/^(\w+)(\([^)]+\))?:\s*(.+)$/);
if (match) {
const [, type] = match;
// Apply scope filter if provided
if (!shouldIncludeCommitByScope(commit.subject, filterScopes)) {
return; // Skip this commit
}
if (type in groups) {
groups[type as keyof typeof groups].push(commit);
} else {
groups.other.push(commit);
}
} else {
groups.other.push(commit);
}
});
// Generate release notes
let releaseNotes = "## What's Changed\n\n";
// New Features
if (groups.feat.length > 0) {
releaseNotes += '### New Features 🎉\n\n';
groups.feat.forEach((commit) => {
const match = commit.subject.match(/^feat(\([^)]+\))?:\s*(.+)$/);
const description = match ? match[2] : commit.subject;
const scope = match?.[1] || '';
releaseNotes += `* feat${scope}: ${description} by @${resolveGitHubUsername(commit.author, commit.email)} in ${commit.hash.substring(0, 7)}\n`;
});
releaseNotes += '\n';
}
// Bug Fixes
if (groups.fix.length > 0) {
releaseNotes += '### Bug Fixes 🐛\n\n';
groups.fix.forEach((commit) => {
const match = commit.subject.match(/^fix(\([^)]+\))?:\s*(.+)$/);
const description = match ? match[2] : commit.subject;
const scope = match?.[1] || '';
releaseNotes += `* fix${scope}: ${description} by @${resolveGitHubUsername(commit.author, commit.email)} in ${commit.hash.substring(0, 7)}\n`;
});
releaseNotes += '\n';
}
// Documentation
if (groups.docs.length > 0) {
releaseNotes += '### Documentation 📚\n\n';
groups.docs.forEach((commit) => {
const match = commit.subject.match(/^docs(\([^)]+\))?:\s*(.+)$/);
const description = match ? match[2] : commit.subject;
const scope = match?.[1] || '';
releaseNotes += `* docs${scope}: ${description} by @${resolveGitHubUsername(commit.author, commit.email)} in ${commit.hash.substring(0, 7)}\n`;
});
releaseNotes += '\n';
}
// Other Changes
const otherCommits = [
...groups.style,
...groups.refactor,
...groups.test,
...groups.chore,
...groups.other,
];
if (otherCommits.length > 0) {
releaseNotes += '### Other Changes\n\n';
otherCommits.forEach((commit) => {
const match = commit.subject.match(/^(\w+)(\([^)]+\))?:\s*(.+)$/);
const type = match?.[1] || '';
const scope = match?.[2] || '';
const description = match ? match[3] : commit.subject;
releaseNotes += `* ${type}${scope}: ${description} by @${resolveGitHubUsername(commit.author, commit.email)} in ${commit.hash.substring(0, 7)}\n`;
});
}
// Add Full Changelog link if repository info is available
if (repoInfo) {
if (previousTag) {
// Extract version from tag (ensure v prefix for display)
const previousVersion = previousTag.startsWith('v')
? previousTag
: previousTag.startsWith('@')
? previousTag
: `v${previousTag}`;
const currentVersion = tagName.startsWith('v')
? tagName
: tagName.startsWith('@')
? tagName
: `v${tagName}`;
const changelogText = `${previousVersion}...${currentVersion}`;
releaseNotes += `\n**Full Changelog**: [${changelogText}](https://github.com/${repoInfo.owner}/${repoInfo.repo}/compare/${previousTag}...${tagName})`;
} else {
const currentVersion = tagName.startsWith('v')
? tagName
: tagName.startsWith('@')
? tagName
: `v${tagName}`;
releaseNotes += `\n**Full Changelog**: [${currentVersion}](https://github.com/${repoInfo.owner}/${repoInfo.repo}/commits/${tagName})`;
}
}
return releaseNotes;
} catch (error) {
logger.warn(
`Failed to generate release notes: ${(error as Error).message}`,
);
return `## What's Changed\n\nRelease ${tagName}`;
}
}
/**
* Gets repository URL from git remote
*/
export async function getRepositoryInfo(
cwd: string,
): Promise<{ owner: string; repo: string } | null> {
try {
const { stdout } = await execa(
'git',
['config', '--get', 'remote.origin.url'],
{ cwd },
);
const url = stdout.trim();
// Parse GitHub URL (both HTTPS and SSH)
// HTTPS: https://github.com/owner/repo.git
// SSH: git@github.com:owner/repo.git
const match = url.match(/github\.com[:\/]([^/]+)\/([^/]+?)(?:\.git)?$/);
if (!match) {
logger.warn('Could not parse GitHub repository URL');
return null;
}
const [, owner, repo] = match;
return { owner, repo };
} catch (error) {
logger.warn(`Failed to get repository info: ${(error as Error).message}`);
return null;
}
}
/**
* Creates a GitHub release using GitHub CLI with native release notes generation
*/
export async function createGitHubRelease(
options: GitHubReleaseOptions,
): Promise<void> {
const { version, tagName, cwd, dryRun = false } = options;
try {
// Check if GitHub CLI is available
try {
await execa('gh', ['--version'], { cwd });
} catch (error) {
throw new Error(
'GitHub CLI (gh) is not installed or not available in PATH. Please install it from https://cli.github.com/',
);
}
// Check if user is authenticated
try {
await execa('gh', ['auth', 'status'], { cwd });
} catch (error) {
throw new Error(
'Not authenticated with GitHub CLI. Please run "gh auth login" first.',
);
}
// Get repository info
const repoInfo = await getRepositoryInfo(cwd);
if (!repoInfo) {
throw new Error('Could not determine GitHub repository information');
}
// Determine if this is a prerelease
const isPrerelease = version.includes('-');
// Get previous tag for generating release notes
const previousTag = await getPreviousTag(tagName, cwd);
// Extract version from tag name for display purposes
const releaseTitle = tagName.startsWith('@')
? `v${tagName.split('@').pop()}`
: tagName.startsWith('v')
? tagName
: `v${tagName}`;
if (dryRun) {
logger.info(`[dry-run] Would create GitHub release:`);
logger.info(` Repository: ${repoInfo.owner}/${repoInfo.repo}`);
logger.info(` Tag: ${tagName}`);
logger.info(` Title: ${releaseTitle}`);
logger.info(` Prerelease: ${isPrerelease}`);
if (previousTag) {
logger.info(` Generate notes from: ${previousTag}`);
} else {
logger.info(` Generate notes from: repository start`);
}
// Generate and show release notes preview
logger.info(`\n[dry-run] Release notes preview:`);
logger.info(`${'='.repeat(50)}`);
const releaseNotes = await generateReleaseNotes(
tagName,
previousTag,
cwd,
repoInfo,
);
console.log(releaseNotes);
logger.info(`${'='.repeat(50)}`);
return;
}
// Check if release already exists
try {
await execa(
'gh',
[
'release',
'view',
tagName,
'--repo',
`${repoInfo.owner}/${repoInfo.repo}`,
],
{ cwd },
);
logger.warn(
`GitHub release for tag ${tagName} already exists, skipping creation`,
);
return;
} catch {
// Release doesn't exist, proceed with creation
}
// Generate beautiful release notes
const releaseNotes = await generateReleaseNotes(
tagName,
previousTag,
cwd,
repoInfo,
);
// Create the release with custom formatted notes
const releaseArgs = [
'release',
'create',
tagName,
'--repo',
`${repoInfo.owner}/${repoInfo.repo}`,
'--title',
releaseTitle,
'--notes',
releaseNotes,
];
if (isPrerelease) {
releaseArgs.push('--prerelease');
}
logger.info(`Creating GitHub release for ${tagName}...`);
await execa('gh', releaseArgs, { cwd, stdio: 'inherit' });
logger.success(`✅ Successfully created GitHub release: ${tagName}`);
// Get the release URL
try {
const { stdout } = await execa(
'gh',
[
'release',
'view',
tagName,
'--repo',
`${repoInfo.owner}/${repoInfo.repo}`,
'--json',
'url',
'--jq',
'.url',
],
{ cwd },
);
logger.info(`🔗 Release URL: ${stdout.trim()}`);
} catch {
// Ignore if we can't get the URL
}
} catch (error) {
throw new Error(
`Failed to create GitHub release: ${(error as Error).message}`,
);
}
}