@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/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-changelog",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "version": "2.4.1",
5
+ "description": "Generates a release's changelog from its conventional commits and publishes it as a Forgejo release.",
6
+ "author": "Kaynooo <contact@kaynooo.fr>",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/Kayno0o/cli/tree/main/packages/changelog#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Kayno0o/cli.git",
12
+ "directory": "packages/changelog"
13
+ },
14
+ "bugs": "https://github.com/Kayno0o/cli/issues",
15
+ "keywords": ["forgejo", "gitea", "release", "changelog", "conventional-commits"],
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": "./src/index.ts"
19
+ },
20
+ "bin": {
21
+ "changelog": "./dist/cli.js"
22
+ },
23
+ "files": ["dist", "src"],
24
+ "engines": {
25
+ "bun": ">=1.4.3"
26
+ },
27
+ "scripts": {
28
+ "build": "$npm_execpath build src/cli.ts --target bun --outdir dist && $npm_execpath ../../scripts/shell-shebang.ts",
29
+ "changelog": "$npm_execpath src/cli.ts"
30
+ },
31
+ "dependencies": {
32
+ "@kaynooo/cli-kit": "0.48.0",
33
+ "@kaynooo/utils": "3.1.0"
34
+ }
35
+ }
@@ -0,0 +1,150 @@
1
+ import { $ } from 'bun'
2
+
3
+ // Types and logic inlined from `changelogen` (MIT) to avoid pulling in its
4
+ // transitive dependency tree — only `getGitDiff` and `parseGitCommit` are used.
5
+
6
+ export type SemverBumpType = 'major' | 'premajor' | 'minor' | 'preminor' | 'patch' | 'prepatch' | 'prerelease'
7
+
8
+ export type RepoProvider = 'github' | 'gitlab' | 'bitbucket'
9
+
10
+ export interface ChangelogConfig {
11
+ cwd: string
12
+ types: Record<string, { title: string, semver?: SemverBumpType, folded?: boolean } | boolean>
13
+ scopeMap: Record<string, string>
14
+ repo?: string
15
+ tokens: Partial<Record<RepoProvider, string>>
16
+ from: string
17
+ to: string
18
+ newVersion?: string
19
+ signTags?: boolean
20
+ output: string | boolean
21
+ publish: {
22
+ args?: string[]
23
+ tag?: string
24
+ private?: boolean
25
+ }
26
+ templates: {
27
+ commitMessage?: string
28
+ tagMessage?: string
29
+ tagBody?: string
30
+ }
31
+ noAuthors: boolean
32
+ excludeAuthors: string[]
33
+ hideAuthorEmail?: boolean
34
+ }
35
+
36
+ export interface GitCommitAuthor {
37
+ name: string
38
+ email: string
39
+ }
40
+
41
+ export interface RawGitCommit {
42
+ message: string
43
+ body: string
44
+ shortHash: string
45
+ author: GitCommitAuthor
46
+ }
47
+
48
+ export interface Reference {
49
+ type: 'hash' | 'issue' | 'pull-request'
50
+ value: string
51
+ title?: string
52
+ }
53
+
54
+ export interface GitCommit extends RawGitCommit {
55
+ description: string
56
+ type: string
57
+ scope: string
58
+ references: Reference[]
59
+ authors: GitCommitAuthor[]
60
+ isBreaking: boolean
61
+ // The migration note of a BREAKING CHANGE footer, when it has one.
62
+ breakingNote?: string
63
+ }
64
+
65
+ const ConventionalCommitRegex = /^(?::.+:|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFF]|[\u2600-\u2B55])? *(?<type>[a-z]+)(?:\((?<scope>[^()\n]+)\))?(?<breaking>!)?: (?<description>.+)/i
66
+ const CoAuthoredByRegex = /co-authored-by:\s*(?<name>\S[^<]*)<(?<email>[^>]+)>/gi
67
+ const PullRequestRE = /\([ a-z]*(#\d+)\s*\)/g
68
+ const IssueRE = /(#\d+)/g
69
+ // The footer is uppercase by the Conventional Commits spec; its note runs on over the lines up to a blank one or the next trailer.
70
+ const BreakingBodyRE = /^BREAKING[ -]CHANGE:[ \t]*(.*(?:\n(?![ \t]*$|[\w-]+(?:: | #)).+)*)/m
71
+ const TicketLineRE = /^(#\d+) - (.+)$/gm
72
+
73
+ export async function getGitDiff(from: string | undefined, to = 'HEAD', firstParent = false): Promise<RawGitCommit[]> {
74
+ const range = `${from !== undefined && from !== '' ? `${from}..` : ''}${to}`
75
+ const pretty = '%x1e%s%x00%h%x00%an%x00%ae%x00%b'
76
+ const flags = firstParent ? ['--first-parent'] : []
77
+ const output = await $`git --no-pager log ${range} ${flags} --pretty=${pretty}`.quiet().text()
78
+
79
+ return output
80
+ .split('\x1E')
81
+ .slice(1)
82
+ .map((record) => {
83
+ const [message = '', shortHash = '', authorName = '', authorEmail = '', body = ''] = record.split('\0')
84
+
85
+ return {
86
+ message,
87
+ shortHash,
88
+ author: { name: authorName, email: authorEmail },
89
+ body: body.trim(),
90
+ }
91
+ })
92
+ }
93
+
94
+ export function parseGitCommit(commit: RawGitCommit, config: ChangelogConfig): GitCommit | null {
95
+ const match = commit.message.match(ConventionalCommitRegex)
96
+
97
+ if (!match?.groups)
98
+ return null
99
+
100
+ // Conventional Commits types are not case-sensitive, and the notes group them by their lower-case name.
101
+ const type = (match.groups.type ?? '').toLowerCase()
102
+ const breakingBody = BreakingBodyRE.exec(commit.body)
103
+ const breakingNote = breakingBody?.[1]?.replaceAll(/\s+/g, ' ').trim()
104
+ const rawScope = match.groups.scope ?? ''
105
+ // Mapped here once, so the renderers print commit.scope as it is; an own key only, as `constructor` is no mapping.
106
+ const scope = Object.hasOwn(config.scopeMap, rawScope) ? config.scopeMap[rawScope]! : rawScope
107
+ const isBreaking = match.groups.breaking !== undefined || breakingBody !== null
108
+ let description = match.groups.description ?? ''
109
+ const references: Reference[] = []
110
+
111
+ for (const m of description.matchAll(PullRequestRE))
112
+ references.push({ type: 'pull-request', value: m[1]! })
113
+
114
+ for (const m of description.matchAll(IssueRE)) {
115
+ if (!references.some(i => i.value === m[1]))
116
+ references.push({ type: 'issue', value: m[1]! })
117
+ }
118
+
119
+ for (const m of commit.body.matchAll(TicketLineRE)) {
120
+ const known = references.find(i => i.value === m[1])
121
+
122
+ if (known)
123
+ known.title = m[2]!.trim()
124
+ else
125
+ references.push({ type: 'issue', value: m[1]!, title: m[2]!.trim() })
126
+ }
127
+
128
+ references.push({ value: commit.shortHash, type: 'hash' })
129
+ description = description.replace(PullRequestRE, '').trim()
130
+
131
+ const authors: GitCommitAuthor[] = [commit.author]
132
+
133
+ for (const m of commit.body.matchAll(CoAuthoredByRegex)) {
134
+ authors.push({
135
+ name: (m.groups?.name ?? '').trim(),
136
+ email: (m.groups?.email ?? '').trim(),
137
+ })
138
+ }
139
+
140
+ return {
141
+ ...commit,
142
+ authors,
143
+ description,
144
+ type,
145
+ scope,
146
+ references,
147
+ isBreaking,
148
+ ...(breakingNote === undefined || breakingNote === '' ? {} : { breakingNote }),
149
+ }
150
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,298 @@
1
+ #!/usr/bin/env -S bun --config=/dev/null
2
+
3
+ import type { ExitRow } from '@kaynooo/cli-kit'
4
+ import type { ResolvedChangelogOptions } from './types'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import { Exit, fail, parse, printJson, role, runCli } from '@kaynooo/cli-kit'
8
+ import { confirm } from '@kaynooo/cli-kit/prompt'
9
+ import { sendDiscordWebhook } from '@kaynooo/utils/discord'
10
+ import { version } from '../package.json'
11
+ import { aliasFlags, shared, shouldAskNote, toOptions, undoFlags, withToken } from './flags'
12
+ import { deleteRelease, deleteRemoteTag, getRelease, hasRemoteTag, uploadAssets } from './gitea'
13
+ import { deleteLocalTag, deleteRemoteGitTag, forgeName, generate, getCommitSubject, getGiteaRepo, getGitTags, getHeadCommit, getTagCommit, hasRemoteGitTag, hasTagOnGitea, isRefGitTag, isRepoShallow, resolveConfig, sendRelease, softResetLastCommit } from './index'
14
+ import { err, out, stdoutToStderr } from './ui'
15
+
16
+ type Report = Record<string, unknown>
17
+
18
+ // Runs a command under --json: its logging goes to stderr and the report it hands over is printed as the only thing on stdout.
19
+ async function reporting(argv: string[], run: (argv: string[], report: (value: Report) => unknown) => Promise<number>): Promise<number> {
20
+ const end = argv.indexOf('--')
21
+ const json = (end === -1 ? argv : argv.slice(0, end)).includes('--json')
22
+ const reports: Report[] = []
23
+ const code = await stdoutToStderr(json, async () => run(argv, value => reports.push(value)))
24
+
25
+ if (json && reports[0] !== undefined)
26
+ printJson(reports[0])
27
+
28
+ return code
29
+ }
30
+
31
+ // An unexpected error ends as a shared `error: changelog <command>: message`, its stack shown only under --debug.
32
+ function failed(e: unknown, debug: boolean | undefined): never {
33
+ if (e instanceof Exit)
34
+ throw e
35
+
36
+ if (debug === true && e instanceof Error && e.stack !== undefined)
37
+ console.error(err().dim(e.stack.split('\n').slice(1).join('\n')))
38
+
39
+ return fail(e instanceof Error ? e.message : String(e), 1)
40
+ }
41
+
42
+ async function ask(question: string) {
43
+ return await confirm(question, { default: false, hint: 'pass --yes to skip the questions' }) === true
44
+ }
45
+
46
+ // The new-release page of Forgejo and GitHub only reads `tag` reliably, so the notes go to a file to paste instead of into the link.
47
+ async function printManualRelease(config: ResolvedChangelogOptions, md: string, heading: string) {
48
+ const file = join(tmpdir(), `changelog-${config.to.replaceAll('/', '-')}.md`)
49
+
50
+ await Bun.write(file, md)
51
+ console.log()
52
+ console.error(err().yellow(heading))
53
+ console.error(err().yellow(` https://${config.baseUrl}/${config.releaseRepo}/releases/new?tag=${encodeURIComponent(config.to)}`))
54
+ console.error(err().yellow(` pasting the notes saved to ${file}`))
55
+ console.log()
56
+ }
57
+
58
+ const RELEASE_EXITS: ExitRow[] = [[0, 'it released, wrote --output or showed --dry-run'], [1, 'the release could not be made (no token, the tag not on the forge, a shallow clone, an API error), an asset upload or the Discord post failed'], [2, 'a usage error']]
59
+
60
+ async function release(argv: string[], report: (value: Report) => unknown) {
61
+ const parsed = parse(argv, `usage: changelog release [options]
62
+
63
+ --json prints {command, status (released, dry-run or saved), from, to, commits, notes, url, output, assetsFailed, discord (posted, failed or null)} on stdout and the progress on stderr; a failure is {error} on stderr.`, shared, { allowNegative: true, positionals: [], exits: RELEASE_EXITS })
64
+
65
+ const options = withToken(toOptions(parsed.values))
66
+ let generated: { config: ResolvedChangelogOptions, md: string } | undefined
67
+ let code = 0
68
+
69
+ try {
70
+ console.log()
71
+ console.log(out().dim(`changelog v${version}`))
72
+
73
+ const { config, md, discord, commits } = await generate(options)
74
+ const result = { command: 'release', status: 'released', from: config.from, to: config.to, commits: commits.length, notes: md, url: null as string | null, output: null as string | null, assetsFailed: 0, discord: null as string | null }
75
+
76
+ generated = { config, md }
77
+
78
+ console.log(role('accent', process.stdout)(config.from) + out().dim(' -> ') + role('path', process.stdout)(config.to) + out().dim(` (${commits.length} commits)`))
79
+ console.log(out().dim('--------------'))
80
+ console.log()
81
+ console.log(md.replace(/&nbsp;/g, ''))
82
+ console.log()
83
+ console.log(out().dim('--------------'))
84
+
85
+ if (config.dry) {
86
+ console.log(out().yellow(config.discordWebhook ? 'Dry run. Release and Discord post skipped.' : 'Dry run. Release skipped.'))
87
+ await printManualRelease(config, md, 'Create it manually at')
88
+ report({ ...result, status: 'dry-run' })
89
+
90
+ return 0
91
+ }
92
+
93
+ if (typeof config.output === 'string') {
94
+ await Bun.write(config.output, md)
95
+ console.log(out().yellow(`Saved to ${config.output}`))
96
+ report({ ...result, status: 'saved', output: config.output })
97
+
98
+ return 0
99
+ }
100
+
101
+ if (!config.token) {
102
+ await printManualRelease(config, md, 'Create it manually at')
103
+ fail(`no ${forgeName(config)} token found, pass --token or set GITHUB_TOKEN${config.provider === 'github' ? ', or log in with gh auth login' : ''}, release skipped`, 1)
104
+ }
105
+
106
+ if (!await hasTagOnGitea(config.to, config)) {
107
+ await printManualRelease(config, md, 'Create it manually at')
108
+ fail(`the ref "${config.to}" is not available as a tag on ${forgeName(config)}, release skipped`, 1)
109
+ }
110
+
111
+ if (!commits.length && await isRepoShallow()) {
112
+ await printManualRelease(config, md, 'Create it manually at')
113
+ fail('the repo seems to be cloned shallowly, which makes changelog fail to generate, specify `fetch-depth: 0` in your CI config', 1)
114
+ }
115
+
116
+ result.url = await sendRelease(config, md)
117
+
118
+ if (config.assets?.length) {
119
+ result.assetsFailed = await uploadAssets(config, config.assets)
120
+
121
+ if (result.assetsFailed > 0)
122
+ code = 1
123
+ }
124
+
125
+ if (config.discordWebhook) {
126
+ try {
127
+ await sendDiscordWebhook(config.discordWebhook, discord)
128
+ console.log(out().green('Posted to Discord'))
129
+ result.discord = 'posted'
130
+ }
131
+ catch (e) {
132
+ console.error(err().red(`Released, but the Discord post failed: ${String(e)}`))
133
+ result.discord = 'failed'
134
+ code = 1
135
+ }
136
+ }
137
+
138
+ report(result)
139
+
140
+ return code
141
+ }
142
+ catch (e) {
143
+ if (generated && !(e instanceof Exit))
144
+ await printManualRelease(generated.config, generated.md, 'Failed to create the release. Create it manually at')
145
+
146
+ return failed(e, parsed.values.debug)
147
+ }
148
+ }
149
+
150
+ const UNDO_EXITS: ExitRow[] = [[0, 'it undid it, had nothing to undo, ran --dry-run or the question was declined'], [1, 'a step fails'], [2, 'a usage error']]
151
+
152
+ async function undo(argv: string[], report: (value: Report) => unknown) {
153
+ const { values: args, positionals } = parse(argv, `usage: changelog undo [tag] [options]
154
+
155
+ --json prints {command, status (undone, nothing, dry-run or declined), tag, releaseNote, remoteTag, localTag, commitReset: {hash, subject} or null} on stdout and the progress on stderr, each flag true when that step is (or, on a dry run, would be) taken. It asks no question: the release note is deleted with --note only, and anything to remove needs --yes or --dry-run (exit 2 otherwise).`, undoFlags, { positionals: ['[tag]'], exits: UNDO_EXITS })
156
+ const json = args.json === true
157
+ let tag = positionals[0]
158
+ const options = withToken(toOptions(args))
159
+
160
+ try {
161
+ console.log()
162
+ console.log(out().dim(`changelog v${version}`))
163
+
164
+ if (tag === undefined || tag === '') {
165
+ tag = (await getGitTags())[0]
166
+
167
+ if (tag === undefined) {
168
+ console.log(out().yellow('No tags found, nothing to undo.'))
169
+ report({ command: 'undo', status: 'nothing', tag: null, releaseNote: false, remoteTag: false, localTag: false, commitReset: null })
170
+
171
+ return 0
172
+ }
173
+
174
+ console.log(out().yellow(`No tag specified, using the latest tag "${out().bold(tag)}".`))
175
+ }
176
+
177
+ const config = await resolveConfig({ ...options, to: tag })
178
+
179
+ // Prefer plain git for the origin repo so remote tags are handled without
180
+ // relying on an API token; only fall back to the API for a distinct
181
+ // release repository.
182
+ let originRepo: string | undefined
183
+
184
+ try {
185
+ originRepo = await getGiteaRepo()
186
+ }
187
+ catch {}
188
+ const remoteViaGit = Boolean(originRepo) && String(config.releaseRepo) === originRepo
189
+
190
+ const release = config.token ? await getRelease(config, tag) : null
191
+ const remoteTag = remoteViaGit
192
+ ? await hasRemoteGitTag(tag)
193
+ : Boolean(config.token) && await hasRemoteTag(config, tag)
194
+ const localTag = await isRefGitTag(tag)
195
+
196
+ // Only reset the bump commit when the tag actually points at HEAD,
197
+ // otherwise we'd drop an unrelated commit.
198
+ let commitToReset: { hash: string, subject: string } | undefined
199
+
200
+ if (localTag && await getTagCommit(tag) === await getHeadCommit()) {
201
+ commitToReset = { hash: await getHeadCommit(), subject: await getCommitSubject('HEAD') }
202
+ }
203
+
204
+ // Deleting the release note is opt-in: --note forces it, --yes and --dry-run skip the question, otherwise it defaults to "no".
205
+ const deleteNote = release !== null && (args.note === true || (!json && shouldAskNote({ release, note: args.note, yes: args.yes, dry: args['dry-run'] }) && await ask(`Also delete the ${forgeName(config)} release note "${release.name || tag}"?`)))
206
+
207
+ const actions: string[] = []
208
+
209
+ if (deleteNote)
210
+ actions.push(`${out().red('release note')} ${tag}`)
211
+
212
+ if (remoteTag)
213
+ actions.push(`${out().red('remote tag')} ${tag}`)
214
+
215
+ if (localTag)
216
+ actions.push(`${out().red('local tag')} ${tag}`)
217
+
218
+ if (commitToReset)
219
+ actions.push(`${out().red('commit')} reset --soft (${commitToReset.hash.slice(0, 7)} "${commitToReset.subject}")`)
220
+ else if (localTag)
221
+ actions.push(out().dim(`commit skipped (${tag} is not HEAD)`))
222
+
223
+ const result = { command: 'undo', status: 'undone', tag, releaseNote: deleteNote, remoteTag, localTag, commitReset: commitToReset === undefined ? null : { hash: commitToReset.hash, subject: commitToReset.subject } }
224
+
225
+ if (!actions.length) {
226
+ console.log(out().yellow(`Nothing to undo for "${tag}".`))
227
+ report({ ...result, status: 'nothing' })
228
+
229
+ return 0
230
+ }
231
+
232
+ if (json && args.yes !== true && args['dry-run'] !== true)
233
+ fail('--json asks no question, so removing needs --yes (or --dry-run to preview)')
234
+
235
+ console.log()
236
+ console.log(`About to remove on ${out().bold(String(config.releaseRepo))}:`)
237
+ for (const action of actions)
238
+ console.log(` - ${action}`)
239
+ console.log()
240
+
241
+ if (args['dry-run']) {
242
+ console.log(out().yellow('Dry run. Nothing removed.'))
243
+ report({ ...result, status: 'dry-run' })
244
+
245
+ return 0
246
+ }
247
+
248
+ if (!args.yes && !await ask('Proceed?')) {
249
+ console.log(out().yellow('Aborted.'))
250
+ report({ ...result, status: 'declined', releaseNote: false, remoteTag: false, localTag: false, commitReset: null })
251
+
252
+ return 0
253
+ }
254
+
255
+ if (deleteNote) {
256
+ await deleteRelease(config, release.id)
257
+ console.log(out().green(`Deleted release note ${tag}`))
258
+ }
259
+
260
+ if (remoteTag) {
261
+ if (remoteViaGit)
262
+ await deleteRemoteGitTag(tag)
263
+ else
264
+ await deleteRemoteTag(config, tag)
265
+
266
+ console.log(out().green(`Deleted remote tag ${tag}`))
267
+ }
268
+
269
+ if (localTag) {
270
+ await deleteLocalTag(tag)
271
+ console.log(out().green(`Deleted local tag ${tag}`))
272
+ }
273
+
274
+ if (commitToReset) {
275
+ await softResetLastCommit()
276
+ console.log(out().green(`Reset commit ${commitToReset.hash.slice(0, 7)} (changes kept in working tree)`))
277
+ }
278
+
279
+ report(result)
280
+
281
+ return 0
282
+ }
283
+ catch (e) {
284
+ return failed(e, args.debug)
285
+ }
286
+ }
287
+
288
+ process.exitCode = await runCli({
289
+ name: 'changelog',
290
+ about: 'generate the release notes and publish them',
291
+ replaces: 'writing the release notes by hand and posting them through the Forgejo or GitHub UI',
292
+ examples: [['changelog --dry-run', 'the notes since the last tag, nothing published'], ['changelog undo v1.2.0 --dry-run', 'what undoing that release would remove']],
293
+ commands: {
294
+ release: { summary: 'generate the release notes and publish them (the default)', run: async argv => reporting(aliasFlags(argv), release) },
295
+ undo: { summary: 'undo a release: delete the remote/local tag and reset the bump commit', run: async argv => reporting(aliasFlags(argv), undo) },
296
+ },
297
+ defaultCommand: 'release',
298
+ })
package/src/config.ts ADDED
@@ -0,0 +1,147 @@
1
+ import type { ChangelogOptions, ResolvedChangelogOptions } from './types'
2
+ import { join } from 'node:path'
3
+ import { configuredForge } from '@kaynooo/cli-kit'
4
+ import { $ } from 'bun'
5
+ import { getCurrentGitBranch, getFirstGitCommit, getGiteaRepo, getLastMatchingTag, getOriginHost, getSafeTagTemplate, isPrerelease } from './git'
6
+
7
+ const GITHUB = 'github.com'
8
+
9
+ export function defineConfig(config: ChangelogOptions) {
10
+ return config
11
+ }
12
+
13
+ // The forge's name in messages.
14
+ export function forgeName(config: ChangelogOptions): string {
15
+ return config.provider === 'github' ? 'GitHub' : 'Forgejo'
16
+ }
17
+
18
+ const configFiles = ['ts', 'mts', 'js', 'mjs', 'json'].map(ext => `changelog.config.${ext}`)
19
+
20
+ const defaultConfig = {
21
+ scopeMap: {},
22
+ types: {
23
+ feat: { title: '✨ New' },
24
+ fix: { title: '🔧 Fixed' },
25
+ perf: { title: '⚡ Faster' },
26
+ refactor: { title: 'refactor', folded: true },
27
+ docs: { title: 'docs', folded: true },
28
+ build: { title: 'build', folded: true },
29
+ types: { title: 'types', folded: true },
30
+ test: { title: 'test', folded: true },
31
+ style: { title: 'style', folded: true },
32
+ ci: { title: 'ci', folded: true },
33
+ },
34
+ titles: {
35
+ breakingChanges: '⚠️ Breaking',
36
+ highlights: '🌟 Highlights',
37
+ maintenance: '🧹 Maintenance',
38
+ },
39
+ contributors: true,
40
+ capitalize: true,
41
+ group: true,
42
+ emoji: true,
43
+ firstParent: false,
44
+ tag: 'v%s',
45
+ } satisfies ChangelogOptions
46
+
47
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
48
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
49
+ }
50
+
51
+ // Later layers win; plain objects merge key by key, anything else (arrays, functions) is replaced, and an undefined value never overrides.
52
+ function mergeLayers(...layers: object[]): Record<string, unknown> {
53
+ const merged: Record<string, unknown> = {}
54
+
55
+ for (const layer of layers) {
56
+ for (const [key, value] of Object.entries(layer)) {
57
+ if (value === undefined)
58
+ continue
59
+
60
+ merged[key] = isPlainObject(value) && isPlainObject(merged[key]) ? mergeLayers(merged[key], value) : value
61
+ }
62
+ }
63
+
64
+ return merged
65
+ }
66
+
67
+ async function loadConfigFile(cwd: string): Promise<ChangelogOptions> {
68
+ for (const name of configFiles) {
69
+ const path = join(cwd, name)
70
+
71
+ if (await Bun.file(path).exists())
72
+ return (await import(path) as { default?: ChangelogOptions }).default ?? {}
73
+ }
74
+
75
+ return {}
76
+ }
77
+
78
+ // gh's own login, for a GitHub release given no token; undefined without gh or a login.
79
+ async function ghToken(): Promise<string | undefined> {
80
+ if (Bun.which('gh') === null)
81
+ return undefined
82
+
83
+ const answer = await $`gh auth token`.quiet().nothrow()
84
+
85
+ return answer.exitCode === 0 && answer.text().trim() !== '' ? answer.text().trim() : undefined
86
+ }
87
+
88
+ async function loadPackageConfig(cwd: string): Promise<ChangelogOptions> {
89
+ const file = Bun.file(join(cwd, 'package.json'))
90
+
91
+ return !await file.exists() ? {} : (await file.json() as { changelog?: ChangelogOptions }).changelog ?? {}
92
+ }
93
+
94
+ // Layers, lowest first: defaults, the package.json `changelog` field, `changelog.config.*`, then the options passed in.
95
+ export async function loadConfig(options: ChangelogOptions, cwd = process.cwd()): Promise<ChangelogOptions> {
96
+ const [packageConfig, fileConfig] = await Promise.all([loadPackageConfig(cwd), loadConfigFile(cwd)])
97
+
98
+ return mergeLayers(defaultConfig, packageConfig, fileConfig, options)
99
+ }
100
+
101
+ export async function resolveConfig(options: ChangelogOptions) {
102
+ const config = await loadConfig(options)
103
+
104
+ // origin may be the forge's private address, while the links want the public one config.json names.
105
+ const origin = config.baseUrl === undefined ? await getOriginHost() : undefined
106
+
107
+ const baseUrl = config.baseUrl ?? (origin === GITHUB ? origin : configuredForge()?.host ?? origin)
108
+
109
+ if (baseUrl === undefined || baseUrl === '')
110
+ throw new Error('no forge to link the notes to: set baseUrl in the changelog config, forge in ~/.config/kaynooo-cli/config.json, or an origin remote')
111
+
112
+ config.baseUrl = baseUrl
113
+ config.provider ??= baseUrl === GITHUB ? 'github' : 'gitea'
114
+ config.baseUrlApi ??= config.provider === 'github' ? 'api.github.com' : `${baseUrl}/api/v1`
115
+
116
+ const token = config.provider === 'github' && (config.token ?? '') === '' ? await ghToken() : undefined
117
+
118
+ if (token !== undefined)
119
+ config.token = token
120
+
121
+ config.to ||= await getCurrentGitBranch()
122
+ config.tagFilter ??= () => true
123
+ config.tag = getSafeTagTemplate(config.tag ?? defaultConfig.tag)
124
+ config.rollup ??= {}
125
+ // Worked out here alone, so a config file setting it never drops a given from.
126
+ config.fromRoot = false
127
+
128
+ if (config.from === undefined || config.from === '') {
129
+ const tag = await getLastMatchingTag(config.to, config.tagFilter, config.tag, config.rollup, config.firstParent)
130
+
131
+ config.fromRoot = tag === undefined
132
+ config.from = tag ?? await getFirstGitCommit(config.firstParent, config.to)
133
+ }
134
+
135
+ // The option names it had before Forgejo, still read from older configs.
136
+ const legacy = config as ChangelogOptions & { gitea?: string, releaseGithub?: string }
137
+
138
+ config.repo ||= legacy.gitea ?? await getGiteaRepo()
139
+ config.releaseRepo ||= legacy.releaseGithub ?? config.repo
140
+ config.prerelease ??= isPrerelease(config.to)
141
+ config.discordWebhook ??= process.env.DISCORD_WEBHOOK ?? ''
142
+
143
+ if (typeof config.repo !== 'string')
144
+ throw new TypeError(`Invalid repository, expected a string but got ${JSON.stringify(config.repo)}`)
145
+
146
+ return config as ResolvedChangelogOptions
147
+ }