@kaynooo/cli-changelog 0.0.0-stage → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +212 -2
- package/dist/cli.js +3038 -0
- package/package.json +33 -4
- package/src/changelog.ts +150 -0
- package/src/cli.ts +298 -0
- package/src/config.ts +147 -0
- package/src/discord.ts +158 -0
- package/src/flags.ts +92 -0
- package/src/generate.ts +23 -0
- package/src/git.ts +166 -0
- package/src/gitea.ts +326 -0
- package/src/highlights.ts +142 -0
- package/src/index.ts +9 -0
- package/src/markdown.ts +199 -0
- package/src/parse.ts +8 -0
- package/src/types.ts +185 -0
- package/src/ui.ts +20 -0
package/src/gitea.ts
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import type { AuthorInfo, ChangelogOptions, Commit } from './types'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { err, out } from './ui'
|
|
4
|
+
|
|
5
|
+
const REQUEST_MS = 60_000
|
|
6
|
+
|
|
7
|
+
interface GiteaRelease {
|
|
8
|
+
id: number
|
|
9
|
+
name: string
|
|
10
|
+
url: string
|
|
11
|
+
html_url: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface GiteaCommit {
|
|
15
|
+
// GitHub leaves it null for an email no account claims.
|
|
16
|
+
author: { login: string, avatar_url: string } | null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function onGithub(options: ChangelogOptions): boolean {
|
|
20
|
+
return options.provider === 'github'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// GitHub reads a tag as a git ref, under `ref` to read and `refs` to delete; Forgejo has a tags endpoint.
|
|
24
|
+
function tagPath(options: ChangelogOptions, repo: string | undefined, tag: string, write = false): string {
|
|
25
|
+
return onGithub(options) ? `repos/${repo}/git/${write ? 'refs' : 'ref'}/tags/${encodeURIComponent(tag)}` : `repos/${repo}/tags/${encodeURIComponent(tag)}`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function request(url: string, init?: RequestInit) {
|
|
29
|
+
const res = await fetch(url, { ...init, signal: AbortSignal.timeout(REQUEST_MS) })
|
|
30
|
+
|
|
31
|
+
if (!res.ok)
|
|
32
|
+
throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`)
|
|
33
|
+
|
|
34
|
+
return res
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function api<T = unknown>(url: string, init?: RequestInit): Promise<T> {
|
|
38
|
+
return await (await request(url, init)).json() as T
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function sendRelease(
|
|
42
|
+
options: ChangelogOptions,
|
|
43
|
+
content: string,
|
|
44
|
+
) {
|
|
45
|
+
const headers = getHeaders(options)
|
|
46
|
+
let url = `https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases`
|
|
47
|
+
let method = 'POST'
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const exists = await api<GiteaRelease>(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to ?? '')}`, {
|
|
51
|
+
headers,
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
if (exists.url) {
|
|
55
|
+
url = exists.url
|
|
56
|
+
method = 'PATCH'
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const body = {
|
|
63
|
+
body: content,
|
|
64
|
+
draft: options.draft || false,
|
|
65
|
+
name: options.name ?? options.to,
|
|
66
|
+
prerelease: options.prerelease,
|
|
67
|
+
tag_name: options.to,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
console.log(out().cyan(method === 'POST'
|
|
71
|
+
? 'Creating release notes...'
|
|
72
|
+
: 'Updating release notes...'),
|
|
73
|
+
)
|
|
74
|
+
const res = await api<GiteaRelease>(url, {
|
|
75
|
+
method,
|
|
76
|
+
body: JSON.stringify(body),
|
|
77
|
+
headers: { ...headers, 'content-type': 'application/json' },
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
console.log(out().green(`Released on ${res.html_url}`))
|
|
81
|
+
|
|
82
|
+
return res.html_url
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export async function getRelease(options: ChangelogOptions, tag: string) {
|
|
86
|
+
try {
|
|
87
|
+
return await api<GiteaRelease>(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(tag)}`, {
|
|
88
|
+
headers: getHeaders(options),
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function deleteRelease(options: ChangelogOptions, releaseId: number) {
|
|
97
|
+
await request(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/${releaseId}`, {
|
|
98
|
+
method: 'DELETE',
|
|
99
|
+
headers: getHeaders(options),
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function hasRemoteTag(options: ChangelogOptions, tag: string) {
|
|
104
|
+
try {
|
|
105
|
+
await api(`https://${options.baseUrlApi}/${tagPath(options, options.releaseRepo, tag)}`, {
|
|
106
|
+
headers: getHeaders(options),
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
return true
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return false
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function deleteRemoteTag(options: ChangelogOptions, tag: string) {
|
|
117
|
+
await request(`https://${options.baseUrlApi}/${tagPath(options, options.releaseRepo, tag, true)}`, {
|
|
118
|
+
method: 'DELETE',
|
|
119
|
+
headers: getHeaders(options),
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function getHeaders(options: ChangelogOptions): Record<string, string> {
|
|
124
|
+
if (onGithub(options))
|
|
125
|
+
return { 'accept': 'application/vnd.github+json', 'authorization': `Bearer ${options.token}`, 'x-github-api-version': '2022-11-28' }
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
accept: 'application/vnd.gitea.v3+json',
|
|
129
|
+
authorization: `token ${options.token}`,
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const excludeAuthors = [
|
|
134
|
+
/\[bot\]/i,
|
|
135
|
+
/dependabot/i,
|
|
136
|
+
/\(bot\)/i,
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
export async function resolveAuthorInfo(options: ChangelogOptions, info: AuthorInfo) {
|
|
140
|
+
if ((info.login ?? '') !== '')
|
|
141
|
+
return info
|
|
142
|
+
|
|
143
|
+
// token not provided, skip gitea resolving
|
|
144
|
+
if ((options.token ?? '') === '')
|
|
145
|
+
return info
|
|
146
|
+
|
|
147
|
+
// A commit names its author's account exactly, so only an author with no commit of their own, a co-author, is searched by email.
|
|
148
|
+
if (info.commits.length) {
|
|
149
|
+
try {
|
|
150
|
+
const data = await api<GiteaCommit>(`https://${options.baseUrlApi}/repos/${options.repo}/${onGithub(options) ? 'commits' : 'git/commits'}/${info.commits[0]}`, {
|
|
151
|
+
headers: getHeaders(options),
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
if (data.author !== null) {
|
|
155
|
+
info.login = data.author.login
|
|
156
|
+
info.avatar = data.author.avatar_url
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
catch {}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// GitHub's user search shows no email to match exactly, so a co-author stays a name there.
|
|
163
|
+
if ((info.login ?? '') !== '' || onGithub(options))
|
|
164
|
+
return info
|
|
165
|
+
|
|
166
|
+
try {
|
|
167
|
+
// Forgejo matches the keyword inside a public email only, so the account whose email is exactly this one is picked.
|
|
168
|
+
const data = await api<{ data: { login: string, email: string, avatar_url?: string }[] }>(`https://${options.baseUrlApi}/users/search?q=${encodeURIComponent(info.email)}`, {
|
|
169
|
+
headers: getHeaders(options),
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
const user = data.data.find(user => user.email.toLowerCase() === info.email.toLowerCase())
|
|
173
|
+
|
|
174
|
+
if (user !== undefined) {
|
|
175
|
+
info.login = user.login
|
|
176
|
+
|
|
177
|
+
if (user.avatar_url !== undefined)
|
|
178
|
+
info.avatar = user.avatar_url
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
catch {}
|
|
182
|
+
|
|
183
|
+
return info
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function resolveAuthors(commits: Commit[], options: ChangelogOptions) {
|
|
187
|
+
const map = new Map<string, AuthorInfo>()
|
|
188
|
+
|
|
189
|
+
for (const commit of commits) {
|
|
190
|
+
for (const [idx, author] of commit.authors.entries()) {
|
|
191
|
+
if (!author.email || !author.name || excludeAuthors.some(re => re.test(author.name)))
|
|
192
|
+
continue
|
|
193
|
+
|
|
194
|
+
if (!map.has(author.email))
|
|
195
|
+
map.set(author.email, { commits: [], name: author.name, email: author.email })
|
|
196
|
+
|
|
197
|
+
// record commits only for the first author
|
|
198
|
+
if (idx === 0)
|
|
199
|
+
map.get(author.email)!.commits.push(commit.shortHash)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const authors = Array.from(map.values())
|
|
204
|
+
const resolved = await Promise.all(authors.map(async info => resolveAuthorInfo(options, info)))
|
|
205
|
+
|
|
206
|
+
const loginSet = new Set<string>()
|
|
207
|
+
const nameSet = new Set<string>()
|
|
208
|
+
|
|
209
|
+
return resolved
|
|
210
|
+
.sort((a, b) => (a.login ?? a.name).localeCompare(b.login ?? b.name))
|
|
211
|
+
.filter((i) => {
|
|
212
|
+
if (i.login !== undefined && loginSet.has(i.login))
|
|
213
|
+
return false
|
|
214
|
+
|
|
215
|
+
if (i.login !== undefined) {
|
|
216
|
+
loginSet.add(i.login)
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
if (nameSet.has(i.name))
|
|
220
|
+
return false
|
|
221
|
+
|
|
222
|
+
nameSet.add(i.name)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return true
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export async function hasTagOnGitea(tag: string, options: ChangelogOptions) {
|
|
230
|
+
try {
|
|
231
|
+
const url = `https://${options.baseUrlApi}/${tagPath(options, options.repo, tag)}`
|
|
232
|
+
|
|
233
|
+
console.log(`checking if tag exists on ${url}`)
|
|
234
|
+
await api(url, {
|
|
235
|
+
headers: getHeaders(options),
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
return true
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
return false
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Returns how many assets could not be uploaded.
|
|
246
|
+
export async function uploadAssets(options: ChangelogOptions, assets: string | string[]): Promise<number> {
|
|
247
|
+
const headers = getHeaders(options)
|
|
248
|
+
let assetList: string[] = []
|
|
249
|
+
|
|
250
|
+
if (typeof assets === 'string') {
|
|
251
|
+
assetList = assets.split(',').map(s => s.trim()).filter(Boolean)
|
|
252
|
+
}
|
|
253
|
+
else if (Array.isArray(assets)) {
|
|
254
|
+
assetList = assets.flatMap(item =>
|
|
255
|
+
typeof item === 'string' ? item.split(',').map(s => s.trim()) : [],
|
|
256
|
+
).filter(Boolean)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Expand glob patterns to actual file paths
|
|
260
|
+
const expandedAssets: string[] = []
|
|
261
|
+
|
|
262
|
+
for (const pattern of assetList) {
|
|
263
|
+
try {
|
|
264
|
+
// Use the pattern directly without shell expansion
|
|
265
|
+
const glob = new Bun.Glob(pattern)
|
|
266
|
+
const matches = Array.from(glob.scanSync())
|
|
267
|
+
|
|
268
|
+
if (matches.length) {
|
|
269
|
+
expandedAssets.push(...matches)
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
// If no matches found, treat as literal path
|
|
273
|
+
expandedAssets.push(pattern)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
console.error(err().red(`Failed to process glob pattern "${pattern}": ${String(error)}`))
|
|
278
|
+
// Keep the original pattern as fallback
|
|
279
|
+
expandedAssets.push(pattern)
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Get the release by tag to obtain its id
|
|
284
|
+
const release = await api<GiteaRelease>(`https://${options.baseUrlApi}/repos/${options.releaseRepo}/releases/tags/${encodeURIComponent(options.to ?? '')}`, {
|
|
285
|
+
headers,
|
|
286
|
+
})
|
|
287
|
+
let failed = 0
|
|
288
|
+
|
|
289
|
+
for (const asset of expandedAssets) {
|
|
290
|
+
const filePath = path.resolve(asset)
|
|
291
|
+
const file = Bun.file(filePath)
|
|
292
|
+
|
|
293
|
+
if (!await file.exists()) {
|
|
294
|
+
console.error(err().red(`Failed to read file ${filePath}: file does not exist`))
|
|
295
|
+
failed++
|
|
296
|
+
|
|
297
|
+
continue
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const fileName = path.basename(filePath)
|
|
301
|
+
const assetsPath = `repos/${options.releaseRepo}/releases/${release.id}/assets?name=${encodeURIComponent(fileName)}`
|
|
302
|
+
|
|
303
|
+
console.log(out().cyan(`Uploading ${fileName}...`))
|
|
304
|
+
|
|
305
|
+
try {
|
|
306
|
+
if (onGithub(options)) {
|
|
307
|
+
await request(`https://uploads.github.com/${assetsPath}`, { method: 'POST', headers: { ...headers, 'content-type': 'application/octet-stream' }, body: file })
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
// Forgejo expects multipart/form-data with an `attachment` field
|
|
311
|
+
const form = new FormData()
|
|
312
|
+
|
|
313
|
+
form.append('attachment', file, fileName)
|
|
314
|
+
await request(`https://${options.baseUrlApi}/${assetsPath}`, { method: 'POST', headers, body: form })
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
console.log(out().green(`Uploaded ${fileName} successfully.`))
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
console.error(err().red(`Failed to upload ${fileName}: ${String(error)}`))
|
|
321
|
+
failed++
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return failed
|
|
326
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { ChangelogOptions, LinkMap, ResolvedChangelogOptions } from './types'
|
|
2
|
+
import { isAbsolute, join } from 'node:path'
|
|
3
|
+
import { getVersionString } from './git'
|
|
4
|
+
|
|
5
|
+
export interface Highlights {
|
|
6
|
+
// The version's section, headings demoted to sit under the highlights title and links made absolute.
|
|
7
|
+
lines: string[]
|
|
8
|
+
// The page, at the version's heading.
|
|
9
|
+
link: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const fenceRE = /^\s*(`{3,}|~{3,})/
|
|
13
|
+
const headingRE = /^(#{1,6})(\s.*)$/
|
|
14
|
+
const schemeRE = /^[a-z][a-z\d+.-]*:/i
|
|
15
|
+
// A target may hold balanced parentheses, as CommonMark allows: `/wiki/Foo_(bar)`.
|
|
16
|
+
const inlineLinkRE = /(\]\(\s*<?)((?:[^\s<>()]|\([^\s<>()]*\))+)/g
|
|
17
|
+
const definitionRE = /^(\s{0,3}\[[^\]]+\]:\s*<?)([^\s<>]+)(>?(?:\s.*)?)$/
|
|
18
|
+
const newlineRE = /\r?\n/
|
|
19
|
+
const codeSpanRE = /(`+)[\s\S]*?\1/
|
|
20
|
+
|
|
21
|
+
// The same slug GitHub and Bun.markdown give a heading: `1.44.0` is `#1440`.
|
|
22
|
+
export function headingAnchor(text: string) {
|
|
23
|
+
return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The page a target names, as `link` maps it, then made absolute against the page.
|
|
27
|
+
function resolveTarget(written: string, base: string, link?: LinkMap) {
|
|
28
|
+
const target = link?.(written) ?? written
|
|
29
|
+
|
|
30
|
+
if (schemeRE.test(target) || target.startsWith('//'))
|
|
31
|
+
return target
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
return new URL(target, base).href
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return target
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Makes each link of a line absolute against the page, leaving code spans as written.
|
|
42
|
+
export function resolveLinks(line: string, base: string, link?: LinkMap) {
|
|
43
|
+
const definition = definitionRE.exec(line)
|
|
44
|
+
|
|
45
|
+
if (definition)
|
|
46
|
+
return `${definition[1]}${resolveTarget(definition[2]!, base, link)}${definition[3]}`
|
|
47
|
+
|
|
48
|
+
let rest = line
|
|
49
|
+
let out = ''
|
|
50
|
+
|
|
51
|
+
while (rest) {
|
|
52
|
+
const code = codeSpanRE.exec(rest)
|
|
53
|
+
const text = code ? rest.slice(0, code.index) : rest
|
|
54
|
+
|
|
55
|
+
out += text.replace(inlineLinkRE, (_, open: string, target: string) => `${open}${resolveTarget(target, base, link)}`)
|
|
56
|
+
|
|
57
|
+
if (!code)
|
|
58
|
+
break
|
|
59
|
+
|
|
60
|
+
out += code[0]
|
|
61
|
+
rest = rest.slice(code.index + code[0].length)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return out
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function withoutAnchor(url: string) {
|
|
68
|
+
const hash = url.indexOf('#')
|
|
69
|
+
|
|
70
|
+
return hash === -1 ? url : url.slice(0, hash)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function withoutFrontmatter(lines: string[]) {
|
|
74
|
+
if (lines[0]?.trim() !== '---')
|
|
75
|
+
return lines
|
|
76
|
+
|
|
77
|
+
const end = lines.findIndex((line, index) => index > 0 && line.trim() === '---')
|
|
78
|
+
|
|
79
|
+
return end === -1 ? lines : lines.slice(end + 1)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// The lines under `## <version>`, up to the next `## ` heading outside a code fence; a heading under it is demoted one level, below the `###` highlights title.
|
|
83
|
+
export function parseHighlights(source: string, version: string, url: string, link?: LinkMap): Highlights | undefined {
|
|
84
|
+
const lines = withoutFrontmatter(source.split(newlineRE))
|
|
85
|
+
const section: string[] = []
|
|
86
|
+
let fence: string | undefined
|
|
87
|
+
let inside = false
|
|
88
|
+
|
|
89
|
+
for (const line of lines) {
|
|
90
|
+
const marker = fenceRE.exec(line)?.[1]
|
|
91
|
+
|
|
92
|
+
if (fence === undefined && marker === undefined) {
|
|
93
|
+
const heading = headingRE.exec(line)
|
|
94
|
+
|
|
95
|
+
if (heading?.[1] === '##') {
|
|
96
|
+
if (inside)
|
|
97
|
+
break
|
|
98
|
+
|
|
99
|
+
inside = heading[2]!.trim() === version
|
|
100
|
+
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (inside && heading) {
|
|
105
|
+
section.push(`${'#'.repeat(Math.min(heading[1]!.length + 1, 6))}${heading[2]}`)
|
|
106
|
+
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (marker !== undefined)
|
|
112
|
+
fence = fence !== undefined && marker.startsWith(fence) ? undefined : fence ?? marker
|
|
113
|
+
|
|
114
|
+
if (inside)
|
|
115
|
+
section.push(fence !== undefined || marker !== undefined ? line : resolveLinks(line, url, link))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
while (section.length && !section[0]!.trim())
|
|
119
|
+
section.shift()
|
|
120
|
+
|
|
121
|
+
while (section.length && !section.at(-1)!.trim())
|
|
122
|
+
section.pop()
|
|
123
|
+
|
|
124
|
+
return !section.length ? undefined : { lines: section, link: `${withoutAnchor(url)}#${headingAnchor(version)}` }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The `highlights.file` section of the version being released, or nothing without the option, the file or a section for it.
|
|
128
|
+
export async function readHighlights(options: ResolvedChangelogOptions, cwd = process.cwd()): Promise<Highlights | undefined> {
|
|
129
|
+
// Resolved options type every key as set, but highlights stays unset without the option.
|
|
130
|
+
const highlights = options.highlights as ChangelogOptions['highlights']
|
|
131
|
+
|
|
132
|
+
if (highlights === undefined)
|
|
133
|
+
return undefined
|
|
134
|
+
|
|
135
|
+
const { file, url, link } = highlights
|
|
136
|
+
const source = Bun.file(isAbsolute(file) ? file : join(cwd, file))
|
|
137
|
+
|
|
138
|
+
if (!await source.exists())
|
|
139
|
+
return undefined
|
|
140
|
+
|
|
141
|
+
return parseHighlights(await source.text(), getVersionString(options.tag, options.to), url, link)
|
|
142
|
+
}
|
package/src/index.ts
ADDED
package/src/markdown.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import type { Reference } from './changelog'
|
|
2
|
+
import type { Highlights } from './highlights'
|
|
3
|
+
import type { AuthorInfo, Commit, ResolvedChangelogOptions } from './types'
|
|
4
|
+
import { groupBy } from '@kaynooo/utils/array'
|
|
5
|
+
import { capitalize } from '@kaynooo/utils/text'
|
|
6
|
+
|
|
7
|
+
const emojiRE = /\p{Extended_Pictographic}\uFE0F?/gu
|
|
8
|
+
const fullHashRE = /^[\da-f]{40}$/
|
|
9
|
+
// A first word that reads as an identifier, a path or a code span: camelCase, a dot, underscore, slash or digit in it, or a backtick.
|
|
10
|
+
const IDENTIFIER_START = /^(?:`|[a-z]+[A-Z]|\S*\d|\S*[._/]\w)/
|
|
11
|
+
|
|
12
|
+
export interface Section {
|
|
13
|
+
title: string
|
|
14
|
+
commits: Commit[]
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface GroupedCommits {
|
|
18
|
+
sections: Section[]
|
|
19
|
+
folded: Section[]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Breaking commits lead whatever their type, and the types marked `folded` are kept apart for the maintenance block.
|
|
23
|
+
export function groupCommits(commits: Commit[], options: ResolvedChangelogOptions): GroupedCommits {
|
|
24
|
+
const breaking = commits.filter(c => c.isBreaking)
|
|
25
|
+
const byType = groupBy(commits.filter(c => !c.isBreaking), c => c.type)
|
|
26
|
+
const sections: Section[] = breaking.length ? [{ title: options.titles.breakingChanges!, commits: breaking }] : []
|
|
27
|
+
const folded: Section[] = []
|
|
28
|
+
|
|
29
|
+
for (const [type, config] of Object.entries(options.types)) {
|
|
30
|
+
const typed = byType[type] ?? []
|
|
31
|
+
|
|
32
|
+
if (typeof config === 'boolean' || typed.length === 0)
|
|
33
|
+
continue
|
|
34
|
+
|
|
35
|
+
const target = config.folded === true ? folded : sections
|
|
36
|
+
|
|
37
|
+
target.push({ title: config.title, commits: typed })
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return { sections, folded }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function formatTitle(title: string, options: ResolvedChangelogOptions) {
|
|
44
|
+
return (options.emoji ? title : title.replace(emojiRE, '')).trim()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// A range starting at the first commit names it by its full hash, too long to read.
|
|
48
|
+
export function shortRef(ref: string) {
|
|
49
|
+
return fullHashRE.test(ref) ? ref.slice(0, 7) : ref
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function repoUrl(options: ResolvedChangelogOptions) {
|
|
53
|
+
return `https://${options.baseUrl}/${options.repo}`
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function compareUrl(options: ResolvedChangelogOptions) {
|
|
57
|
+
return `${repoUrl(options)}/compare/${options.from}...${options.to}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function releaseUrl(options: ResolvedChangelogOptions) {
|
|
61
|
+
return `https://${options.baseUrl}/${options.releaseRepo}/releases/tag/${encodeURIComponent(options.to)}`
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function userUrl(login: string, options: ResolvedChangelogOptions) {
|
|
65
|
+
return `https://${options.baseUrl}/${login}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function formatIssue(ref: Reference, options: ResolvedChangelogOptions, withTitle: boolean) {
|
|
69
|
+
const text = withTitle && ref.title !== undefined ? `${ref.value} ${ref.title}` : ref.value
|
|
70
|
+
|
|
71
|
+
return `[${text}](${repoUrl(options)}/issues/${ref.value.slice(1)})`
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Capitalizes a plain first word, and leaves an identifier such as `getUser`, `foo.ts` or `a/b` as written.
|
|
75
|
+
function capitalized(description: string): string {
|
|
76
|
+
return IDENTIFIER_START.test(description) ? description : capitalize(description)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// One commit as `description · hash · issues`; Discord has no hover card on issue links, so it asks for their titles inline.
|
|
80
|
+
export function formatLine(commit: Commit, options: ResolvedChangelogOptions, prefix = '', issueTitles = false) {
|
|
81
|
+
const description = options.capitalize ? capitalized(commit.description) : commit.description
|
|
82
|
+
const hash = `[\`${commit.shortHash.slice(0, 7)}\`](${repoUrl(options)}/commit/${commit.shortHash})`
|
|
83
|
+
const issues = commit.references
|
|
84
|
+
.filter(ref => ref.type !== 'hash')
|
|
85
|
+
.map(ref => formatIssue(ref, options, issueTitles))
|
|
86
|
+
|
|
87
|
+
return [`${prefix}${description}`, hash, ...issues].join(' · ')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function foldedPrefix(commit: Commit) {
|
|
91
|
+
return `**${commit.scope ? `${commit.type}(${commit.scope})` : commit.type}**: `
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function foldedCounts(folded: Section[], options: ResolvedChangelogOptions) {
|
|
95
|
+
return folded.map(section => `${section.commits.length} ${formatTitle(section.title, options)}`).join(', ')
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function formatAuthors(contributors: AuthorInfo[], options: ResolvedChangelogOptions) {
|
|
99
|
+
return join(contributors.map(c => c.login !== undefined ? `[@${c.login}](${userUrl(c.login, options)})` : `**${c.name}**`))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function summaryLabel(title: string) {
|
|
103
|
+
return title.replace(emojiRE, '').trim().toLowerCase()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function formatSummary({ sections, folded }: GroupedCommits, contributors: AuthorInfo[], options: ResolvedChangelogOptions) {
|
|
107
|
+
const counts = sections.map(section => `${section.commits.length} ${summaryLabel(section.title)}`)
|
|
108
|
+
|
|
109
|
+
if (folded.length) {
|
|
110
|
+
const total = folded.reduce((sum, section) => sum + section.commits.length, 0)
|
|
111
|
+
|
|
112
|
+
counts.push(`${total} ${summaryLabel(options.titles.maintenance!)}`)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const authors = formatAuthors(contributors, options)
|
|
116
|
+
const parts = [
|
|
117
|
+
counts.length ? `**${counts.join(' · ')}**` : '',
|
|
118
|
+
authors && `by ${authors}`,
|
|
119
|
+
`\`${shortRef(options.from)}\` → \`${shortRef(options.to)}\``,
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
return `> ${parts.filter(Boolean).join(' · ')}`
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function formatSection(section: Section, options: ResolvedChangelogOptions) {
|
|
126
|
+
const lines = ['', `### ${formatTitle(section.title, options)}`, '']
|
|
127
|
+
const scopes = groupBy(section.commits, c => c.scope)
|
|
128
|
+
|
|
129
|
+
// Nesting under scopes only pays off when one of them holds several commits.
|
|
130
|
+
const nestable = Object.entries(scopes).some(([scope, commits]) => scope !== '' && commits.length > 1)
|
|
131
|
+
|
|
132
|
+
for (const [scope, commits] of Object.entries(scopes).sort(([a], [b]) => a.localeCompare(b))) {
|
|
133
|
+
const scopeText = `**${scope}**`
|
|
134
|
+
const nested = nestable && scope !== '' && (options.group === true || (options.group === 'multiple' && commits.length > 1))
|
|
135
|
+
const prefix = scope !== '' && !nested ? `${scopeText}: ` : ''
|
|
136
|
+
const padding = nested ? ' ' : ''
|
|
137
|
+
|
|
138
|
+
if (nested)
|
|
139
|
+
lines.push(`- ${scopeText}:`)
|
|
140
|
+
|
|
141
|
+
for (const commit of commits.toReversed()) {
|
|
142
|
+
lines.push(`${padding}- ${formatLine(commit, options, prefix)}`)
|
|
143
|
+
|
|
144
|
+
if (commit.breakingNote !== undefined)
|
|
145
|
+
lines.push(`${padding} - ${commit.breakingNote}`)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return lines
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function formatAvatars(contributors: AuthorInfo[], options: ResolvedChangelogOptions) {
|
|
153
|
+
return contributors
|
|
154
|
+
.filter(c => c.login !== undefined && c.avatar !== undefined)
|
|
155
|
+
.map(c => `<a href="${userUrl(c.login!, options)}"><img src="${c.avatar}" width="28" height="28" alt="@${c.login}"></a>`)
|
|
156
|
+
.join(' ')
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions, contributors: AuthorInfo[] = [], highlights?: Highlights) {
|
|
160
|
+
const grouped = groupCommits(commits, options)
|
|
161
|
+
const { sections, folded } = grouped
|
|
162
|
+
const lines = [formatSummary(grouped, contributors, options)]
|
|
163
|
+
|
|
164
|
+
if (highlights)
|
|
165
|
+
lines.push('', `### ${formatTitle(options.titles.highlights!, options)}`, '', ...highlights.lines, '', `[Read more](${highlights.link})`)
|
|
166
|
+
|
|
167
|
+
for (const section of sections)
|
|
168
|
+
lines.push(...formatSection(section, options))
|
|
169
|
+
|
|
170
|
+
if (folded.length) {
|
|
171
|
+
lines.push(
|
|
172
|
+
'',
|
|
173
|
+
'<details>',
|
|
174
|
+
`<summary><b>${formatTitle(options.titles.maintenance!, options)}</b> · ${foldedCounts(folded, options)}</summary>`,
|
|
175
|
+
'',
|
|
176
|
+
...folded.flatMap(section => section.commits.toReversed().map(commit => `- ${formatLine(commit, options, foldedPrefix(commit))}`)),
|
|
177
|
+
'',
|
|
178
|
+
'</details>',
|
|
179
|
+
)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (!sections.length && !folded.length)
|
|
183
|
+
lines.push('', '*No significant changes*')
|
|
184
|
+
|
|
185
|
+
lines.push('', '---', '')
|
|
186
|
+
|
|
187
|
+
const avatars = formatAvatars(contributors, options)
|
|
188
|
+
|
|
189
|
+
if (avatars)
|
|
190
|
+
lines.push(avatars, '')
|
|
191
|
+
|
|
192
|
+
lines.push(`<sub>[Full diff \`${shortRef(options.from)}...${shortRef(options.to)}\`](${compareUrl(options)}) · generated by cli-changelog</sub>`)
|
|
193
|
+
|
|
194
|
+
return lines.join('\n')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function join(array: string[], glue = ', ', finalGlue = ' and '): string {
|
|
198
|
+
return array.length <= 2 ? array.join(finalGlue) : `${array.slice(0, -1).join(glue)}${finalGlue}${array.at(-1)}`
|
|
199
|
+
}
|
package/src/parse.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { GitCommit, RawGitCommit } from './changelog'
|
|
2
|
+
import type { ChangelogenOptions } from './types'
|
|
3
|
+
import { notNullish } from '@kaynooo/utils/array'
|
|
4
|
+
import { parseGitCommit } from './changelog'
|
|
5
|
+
|
|
6
|
+
export function parseCommits(commits: RawGitCommit[], config: ChangelogenOptions): GitCommit[] {
|
|
7
|
+
return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish)
|
|
8
|
+
}
|