@reelout/core 0.1.1 → 0.4.0

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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/dist/analyzer.js +33 -0
  3. package/dist/analyzer.js.map +1 -0
  4. package/dist/builder.js +64 -0
  5. package/dist/builder.js.map +1 -0
  6. package/dist/changelog.js +63 -0
  7. package/dist/changelog.js.map +1 -0
  8. package/dist/formatError-BXNdyRfu.js +23 -0
  9. package/dist/formatError-BXNdyRfu.js.map +1 -0
  10. package/dist/index.js +199 -1
  11. package/dist/index.js.map +1 -0
  12. package/dist/types-la_KkjCS.js +1 -0
  13. package/dist/types.js +2 -0
  14. package/dist/workflow-BRMp4uB6.js +2736 -0
  15. package/dist/workflow-BRMp4uB6.js.map +1 -0
  16. package/package.json +35 -6
  17. package/src/analyzer.ts +59 -0
  18. package/src/builder.ts +116 -0
  19. package/src/cache/TTLCache.ts +100 -0
  20. package/src/cache/index.ts +4 -0
  21. package/src/changelog.ts +107 -0
  22. package/src/config/const.ts +104 -0
  23. package/src/config/createPlugin.ts +41 -0
  24. package/src/config/findReleaseRule.ts +26 -0
  25. package/src/config/index.ts +15 -0
  26. package/src/config/isSemVer.ts +31 -0
  27. package/src/config/isSemVerGitTag.ts +25 -0
  28. package/src/config/normalizeCommitFilter.ts +37 -0
  29. package/src/config/normalizeReleaseRule.ts +66 -0
  30. package/src/config/normalizeWorkspace.ts +34 -0
  31. package/src/config/resolvePlugin.ts +57 -0
  32. package/src/config/resolveReleaseChannel.ts +47 -0
  33. package/src/config/resolveVersionQualifier.ts +53 -0
  34. package/src/config/sanitizePrereleaseLabel.ts +18 -0
  35. package/src/git/branch/getCurrentGitBranch.ts +18 -0
  36. package/src/git/branch/index.ts +4 -0
  37. package/src/git/commit/createGitCommit.ts +29 -0
  38. package/src/git/commit/extractMentions.ts +34 -0
  39. package/src/git/commit/getCurrentGitCommit.ts +19 -0
  40. package/src/git/commit/getParsedGitCommit.ts +49 -0
  41. package/src/git/commit/index.ts +9 -0
  42. package/src/git/commit/parseGitCommit.ts +114 -0
  43. package/src/git/commit/parseGitPrettyFormat.ts +76 -0
  44. package/src/git/history/countGitHistory.ts +28 -0
  45. package/src/git/history/expandGitHistory.ts +112 -0
  46. package/src/git/history/index.ts +9 -0
  47. package/src/git/history/mergeGitHistory.ts +76 -0
  48. package/src/git/history/restoreFullGitHistory.ts +19 -0
  49. package/src/git/history/showGitHistory.ts +80 -0
  50. package/src/git/history/showParsedGitHistory.ts +28 -0
  51. package/src/git/index.ts +9 -0
  52. package/src/git/repository/ensureGitUserConfig.ts +50 -0
  53. package/src/git/repository/getGitConfigValue.ts +27 -0
  54. package/src/git/repository/getGitRemote.ts +20 -0
  55. package/src/git/repository/index.ts +10 -0
  56. package/src/git/repository/isGitShallowRepository.ts +21 -0
  57. package/src/git/repository/pushGitChanges.ts +26 -0
  58. package/src/git/repository/resolveGitRepository.ts +40 -0
  59. package/src/git/repository/withShallowLock.ts +62 -0
  60. package/src/git/revision/detectGitRelationship.ts +43 -0
  61. package/src/git/revision/index.ts +7 -0
  62. package/src/git/revision/isGitAncestor.ts +33 -0
  63. package/src/git/revision/readGitFile.ts +29 -0
  64. package/src/git/revision/resolveGitRevision.ts +23 -0
  65. package/src/git/tag/createGitTag.ts +25 -0
  66. package/src/git/tag/deleteGitTag.ts +17 -0
  67. package/src/git/tag/ensureGitTag.ts +63 -0
  68. package/src/git/tag/generateGitTagName.ts +43 -0
  69. package/src/git/tag/getCurrentGitTag.ts +23 -0
  70. package/src/git/tag/getGitTagMessage.ts +35 -0
  71. package/src/git/tag/getLatestGitTag.ts +22 -0
  72. package/src/git/tag/index.ts +13 -0
  73. package/src/git/tag/isGitTagConnected.ts +33 -0
  74. package/src/git/tag/isGitTagPointed.ts +38 -0
  75. package/src/git/tag/isGitTagPresent.ts +17 -0
  76. package/src/index.ts +9 -2
  77. package/src/plugin/HookManager.ts +128 -0
  78. package/src/plugin/index.ts +4 -0
  79. package/src/types.ts +259 -0
  80. package/src/util/buildTrailerPattern.ts +20 -0
  81. package/src/util/compact.ts +14 -0
  82. package/src/util/execCommand.ts +196 -0
  83. package/src/util/execGit.ts +27 -0
  84. package/src/util/formatError.ts +21 -0
  85. package/src/util/formatFile.ts +41 -0
  86. package/src/util/index.ts +18 -0
  87. package/src/util/interpolate.ts +141 -0
  88. package/src/util/isCI.ts +18 -0
  89. package/src/util/isClass.ts +34 -0
  90. package/src/util/isDefined.ts +12 -0
  91. package/src/util/isMatch.ts +43 -0
  92. package/src/util/isTruthyString.ts +19 -0
  93. package/src/util/readJson.ts +47 -0
  94. package/src/util/unique.ts +26 -0
  95. package/src/util/writeJson.ts +28 -0
  96. package/src/workflow/analysis/deriveChangeReleases.ts +76 -0
  97. package/src/workflow/analysis/deriveTransitionReleases.ts +134 -0
  98. package/src/workflow/analysis/index.ts +10 -0
  99. package/src/workflow/analysis/isCommitForPackage.ts +23 -0
  100. package/src/workflow/analysis/promotePrereleaseVersions.ts +51 -0
  101. package/src/workflow/analysis/propagateDependencyUpdates.ts +71 -0
  102. package/src/workflow/analysis/sliceUnreleased.ts +36 -0
  103. package/src/workflow/analysis/streamPackageCommits.ts +34 -0
  104. package/src/workflow/changelog/buildChangelog.ts +79 -0
  105. package/src/workflow/changelog/buildReleaseNotes.ts +50 -0
  106. package/src/workflow/changelog/conventional-changelog-conventionalcommits.d.ts +7 -0
  107. package/src/workflow/changelog/extractLatestVersion.ts +22 -0
  108. package/src/workflow/changelog/extractPlainText.ts +38 -0
  109. package/src/workflow/changelog/extractPreviousVersion.ts +77 -0
  110. package/src/workflow/changelog/extractSemVer.ts +33 -0
  111. package/src/workflow/changelog/index.ts +12 -0
  112. package/src/workflow/changelog/iterateChangelogVersions.ts +70 -0
  113. package/src/workflow/changelog/prependChangelog.ts +59 -0
  114. package/src/workflow/changelog/writeChangelog.ts +27 -0
  115. package/src/workflow/committing/generateReleaseCommitMessage.ts +121 -0
  116. package/src/workflow/committing/index.ts +5 -0
  117. package/src/workflow/committing/isReleaseCommit.ts +56 -0
  118. package/src/workflow/discovery/buildDependencyGraph.ts +43 -0
  119. package/src/workflow/discovery/discoverPackageTag.ts +98 -0
  120. package/src/workflow/discovery/index.ts +9 -0
  121. package/src/workflow/discovery/resolvePackageStableTag.ts +88 -0
  122. package/src/workflow/discovery/resolvePackageTag.ts +45 -0
  123. package/src/workflow/discovery/sortPackages.ts +75 -0
  124. package/src/workflow/discovery/verifyPackageTag.ts +49 -0
  125. package/src/workflow/executeReleaseWorkflow.ts +130 -0
  126. package/src/workflow/index.ts +10 -0
  127. package/src/workflow/report/generateReleaseReport.ts +54 -0
  128. package/src/workflow/report/index.ts +5 -0
  129. package/src/workflow/report/printReleaseReport.ts +97 -0
  130. package/src/workflow/versioning/bumpVersion.ts +76 -0
  131. package/src/workflow/versioning/deriveReleaseType.ts +33 -0
  132. package/src/workflow/versioning/determineReleaseType.ts +35 -0
  133. package/src/workflow/versioning/extractVersionQualifier.ts +29 -0
  134. package/src/workflow/versioning/index.ts +10 -0
  135. package/src/workflow/versioning/isSameReleaseCycle.ts +36 -0
  136. package/src/workflow/versioning/isStableVersion.ts +31 -0
  137. package/src/workflow/versioning/pickPriorityReleaseType.ts +27 -0
@@ -0,0 +1,34 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { Workspace } from '#types'
5
+ import path from 'node:path'
6
+
7
+ /**
8
+ * Normalize and validate workspace configuration for a repository.
9
+ *
10
+ * Resolves the workspace entry directory relative to `cwd` and normalizes
11
+ * the path representation. Returns a workspace object with normalized `entry`
12
+ * and optional workspace members.
13
+ *
14
+ * @param cwd Repository working directory
15
+ * @param workspace Partial workspace configuration (optional)
16
+ * @returns Normalized workspace object
17
+ */
18
+ export function normalizeWorkspace(
19
+ cwd: string,
20
+ workspace?: {
21
+ entry?: string | null | undefined
22
+ members?: readonly string[] | null | undefined
23
+ }
24
+ ): Workspace {
25
+ let entry = workspace?.entry || '.'
26
+ const members = workspace?.members ?? null
27
+
28
+ entry = path.normalize(path.relative(cwd, path.resolve(cwd, entry)))
29
+
30
+ return {
31
+ entry,
32
+ members,
33
+ }
34
+ }
@@ -0,0 +1,57 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type {
5
+ ReleasePlugin,
6
+ ReleasePluginDefinition,
7
+ ReleasePluginFactory,
8
+ ReleasePluginTuple,
9
+ } from '#types'
10
+ import { createRequire } from 'node:module'
11
+ import { pathToFileURL } from 'node:url'
12
+
13
+ /**
14
+ * Resolve a release plugin definition into a factory tuple or plugin object.
15
+ *
16
+ * Handles string module specifiers by dynamically importing the package relative
17
+ * to `cwd`. Unwraps ES module default exports, array configurations containing
18
+ * options, function factories, and direct plugin objects.
19
+ *
20
+ * @param cwd The working directory path used to resolve string specifiers
21
+ * @param plugin The plugin name, path, tuple configuration, or plugin object
22
+ * @returns A factory tuple, plugin object, or null if resolution fails
23
+ */
24
+ export async function resolvePlugin(
25
+ cwd: string,
26
+ plugin: unknown
27
+ ): Promise<ReleasePluginDefinition | ReleasePluginTuple | null> {
28
+ let options: unknown
29
+
30
+ if (Array.isArray(plugin)) {
31
+ ;[plugin, options] = plugin
32
+ }
33
+
34
+ if (typeof plugin === 'string') {
35
+ const require = createRequire(pathToFileURL(cwd))
36
+ plugin = await import(require.resolve(plugin))
37
+ }
38
+
39
+ if (plugin != null && typeof plugin === 'object' && 'default' in plugin) {
40
+ plugin = plugin.default
41
+ }
42
+
43
+ if (typeof plugin === 'function') {
44
+ return [plugin as ReleasePluginFactory, options]
45
+ }
46
+
47
+ if (
48
+ plugin != null &&
49
+ typeof plugin === 'object' &&
50
+ Object.hasOwn(plugin, 'name') &&
51
+ typeof (plugin as ReleasePlugin).name === 'string'
52
+ ) {
53
+ return plugin as ReleasePlugin
54
+ }
55
+
56
+ return null
57
+ }
@@ -0,0 +1,47 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { GitRef, ResolvedReleaseRule } from '#types'
5
+ import { interpolate } from '#util'
6
+ import { sanitizePrereleaseLabel } from './sanitizePrereleaseLabel'
7
+
8
+ export interface ResolveReleaseChannelOptions {
9
+ ref: GitRef
10
+ rule: ResolvedReleaseRule | undefined
11
+ templateParams: Record<string, unknown>
12
+ channel: boolean | string | undefined
13
+ }
14
+
15
+ /**
16
+ * Resolve the release channel for a release context.
17
+ *
18
+ * Uses the release rule when `channel` is `boolean` or omitted. Sanitizes the
19
+ * reference name when enabling default channel resolution and interpolates
20
+ * `templateParams` into the result.
21
+ *
22
+ * @param options Options for resolving the release channel
23
+ * @returns Resolved release channel string or `undefined`
24
+ */
25
+ export function resolveReleaseChannel(
26
+ options: ResolveReleaseChannelOptions
27
+ ): string | undefined {
28
+ const { ref, rule, templateParams } = options
29
+ let { channel } = options
30
+ let resolved: string | undefined
31
+
32
+ if (channel === true || channel == null) {
33
+ channel = rule?.releaseChannel ?? channel
34
+ }
35
+
36
+ if (typeof channel === 'string') {
37
+ resolved = channel
38
+ } else if (channel) {
39
+ resolved = sanitizePrereleaseLabel(ref.name)
40
+ }
41
+
42
+ if (typeof resolved === 'string') {
43
+ resolved = interpolate(resolved, templateParams)
44
+ }
45
+
46
+ return resolved
47
+ }
@@ -0,0 +1,53 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { ResolvedReleaseRule } from '#types'
5
+ import { interpolate } from '#util'
6
+ import { isSemVer } from './isSemVer'
7
+
8
+ export interface ResolveVersionQualifierOptions {
9
+ rule: ResolvedReleaseRule | undefined
10
+ templateParams: Record<string, unknown>
11
+ qualifier: boolean | string | undefined
12
+ }
13
+
14
+ /**
15
+ * Resolve the version qualifier for a release context.
16
+ *
17
+ * Uses the release rule when `qualifier` is `boolean` or omitted. Interpolates
18
+ * `templateParams` into `qualifier` and validates that the result forms a
19
+ * valid SemVer prerelease identifier.
20
+ *
21
+ * @param options Options for resolving the version qualifier
22
+ * @returns Resolved version qualifier string or `undefined`
23
+ * @throws If the resolved string is not a valid SemVer prerelease identifier
24
+ */
25
+ export function resolveVersionQualifier(
26
+ options: ResolveVersionQualifierOptions
27
+ ): string | undefined {
28
+ const { rule, templateParams } = options
29
+ let { qualifier } = options
30
+ let resolved: string | undefined
31
+
32
+ if (qualifier === true || qualifier == null) {
33
+ qualifier = rule?.versionQualifier ?? qualifier
34
+ }
35
+
36
+ if (typeof qualifier === 'string') {
37
+ resolved = qualifier
38
+ } else if (qualifier) {
39
+ resolved = ''
40
+ }
41
+
42
+ if (typeof resolved === 'string') {
43
+ resolved = interpolate(resolved, templateParams)
44
+ }
45
+
46
+ if (resolved && !isSemVer(`1.0.0-${resolved}.1`)) {
47
+ throw new Error(
48
+ `The resolved version qualifier "${resolved}" is not a valid SemVer prerelease identifier.`
49
+ )
50
+ }
51
+
52
+ return resolved
53
+ }
@@ -0,0 +1,18 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ /**
5
+ * Sanitize a string into a safe, SemVer-compliant prerelease label.
6
+ *
7
+ * Replaces sequences of non-alphanumeric characters with a single hyphen and
8
+ * removes leading or trailing hyphens.
9
+ *
10
+ * @param label Raw string to sanitize
11
+ * @returns Safe SemVer prerelease label
12
+ */
13
+ export function sanitizePrereleaseLabel(label: string): string {
14
+ return label
15
+ .replace(/[^a-zA-Z0-9]+/g, '-')
16
+ .replace(/-+/g, '-')
17
+ .replace(/^-+|-+$/g, '')
18
+ }
@@ -0,0 +1,18 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Get the current Git branch name.
8
+ *
9
+ * Uses `execGit` to run `git symbolic-ref -q --short HEAD` in the provided
10
+ * working directory and trims the result. Returns an empty string when the
11
+ * repository is in a detached HEAD state.
12
+ *
13
+ * @param cwd The working directory to run the Git command in
14
+ * @returns The current branch name as a string
15
+ */
16
+ export async function getCurrentGitBranch(cwd: string): Promise<string> {
17
+ return (await execGit(cwd, ['symbolic-ref', '-q', '--short', 'HEAD'])).trim()
18
+ }
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ export * from './getCurrentGitBranch'
@@ -0,0 +1,29 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Stage all changes and create a git commit with the specified message.
8
+ *
9
+ * Validates the commit message and working directory status before staging
10
+ * all changes and executing the commit command.
11
+ *
12
+ * @param cwd The target directory path for executing git commands
13
+ * @param message The message to associate with the commit
14
+ * @returns A promise that resolves when the operation completes
15
+ */
16
+ export async function createGitCommit(
17
+ cwd: string,
18
+ message: string | null | undefined
19
+ ): Promise<void> {
20
+ if (!message) return
21
+
22
+ await execGit(cwd, ['add', '.'])
23
+
24
+ const stdout = (await execGit(cwd, ['status', '--porcelain'])).trim()
25
+
26
+ if (!stdout) return
27
+
28
+ await execGit(cwd, ['commit', '--message', message])
29
+ }
@@ -0,0 +1,34 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ const ALPHANUMERIC = '[a-zA-Z0-9]'
5
+ const SEPARATOR = '[-_]'
6
+ const USERNAME = `${ALPHANUMERIC}+(?:${SEPARATOR}+${ALPHANUMERIC}+)*`
7
+ const EMAIL_LOCAL = '[a-zA-Z0-9._%+-]'
8
+ const DOMAIN_SUFFIX = '[a-zA-Z0-9.-]*\\.[a-zA-Z]{2,}'
9
+ const SCOPED_PACKAGE_SPEC_SUFFIX = `/${USERNAME}@[0-9]+\\.[0-9]+\\.[0-9]+`
10
+
11
+ /**
12
+ * Extract unique mention handles from the input text string.
13
+ *
14
+ * Evaluates `text` against boundary rules to isolate valid handles while
15
+ * excluding email addresses, domain names, and scoped package specs, then
16
+ * de-duplicates the resulting handles.
17
+ *
18
+ * @param text The input string to parse for mentions
19
+ * @returns An array of unique mention handles
20
+ */
21
+ export function extractMentions(text: string): string[] {
22
+ if (!text) return []
23
+
24
+ const regex = new RegExp(
25
+ `(?<!${EMAIL_LOCAL})@(${USERNAME})\\b(?!${SEPARATOR}|${DOMAIN_SUFFIX}|${SCOPED_PACKAGE_SPEC_SUFFIX})`,
26
+ 'g'
27
+ )
28
+
29
+ const matches = text.matchAll(regex)
30
+
31
+ const mentions = new Set(matches.map((match) => match[1] as string))
32
+
33
+ return Array.from(mentions)
34
+ }
@@ -0,0 +1,19 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type { GitCommit } from '#types'
5
+ import { getParsedGitCommit } from './getParsedGitCommit'
6
+
7
+ /**
8
+ * Resolve the current `HEAD` commit in the repository.
9
+ *
10
+ * @param cwd Repository working directory path
11
+ * @param markers Optional array of custom trailer marker strings
12
+ * @returns Parsed commit object for the current `HEAD` commit
13
+ */
14
+ export function getCurrentGitCommit(
15
+ cwd: string,
16
+ markers: readonly string[] = []
17
+ ): Promise<GitCommit> {
18
+ return getParsedGitCommit(cwd, 'HEAD', markers)
19
+ }
@@ -0,0 +1,49 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { TTLCache } from '#cache'
5
+ import type { GitCommit } from '#types'
6
+ import { execGit } from '#util'
7
+ import { parseGitCommit } from './parseGitCommit'
8
+ import { GIT_PRETTY_FORMAT, parseGitPrettyFormat } from './parseGitPrettyFormat'
9
+
10
+ const cache = new TTLCache<string, GitCommit>()
11
+
12
+ /**
13
+ * Retrieve and parse a git commit by its reference.
14
+ *
15
+ * Fetches the raw git log entry for the specified `ref`, checking the local cache
16
+ * prior to parsing missing entries.
17
+ *
18
+ * @param cwd Current working directory path
19
+ * @param ref Git reference to fetch
20
+ * @param markers Optional array of custom trailer marker strings
21
+ * @returns Structured commit object
22
+ */
23
+ export async function getParsedGitCommit(
24
+ cwd: string,
25
+ ref: string,
26
+ markers: readonly string[] = []
27
+ ): Promise<GitCommit> {
28
+ const stdout = await execGit(cwd, [
29
+ 'log',
30
+ '-1',
31
+ ref,
32
+ '--name-only',
33
+ `--pretty=format:${GIT_PRETTY_FORMAT}`,
34
+ ])
35
+
36
+ const entry = parseGitPrettyFormat(stdout)
37
+
38
+ const key = `${entry.hash}:${entry.parent}:${markers}`
39
+
40
+ const cached = cache.get(key)
41
+
42
+ if (cached) return cached
43
+
44
+ const parsed = await parseGitCommit(entry, markers)
45
+
46
+ cache.set(key, parsed)
47
+
48
+ return parsed
49
+ }
@@ -0,0 +1,9 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ export * from './createGitCommit'
5
+ export * from './extractMentions'
6
+ export * from './getCurrentGitCommit'
7
+ export * from './getParsedGitCommit'
8
+ export * from './parseGitCommit'
9
+ export * from './parseGitPrettyFormat'
@@ -0,0 +1,114 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import type {
5
+ GitCommit,
6
+ GitCommitNote,
7
+ GitCommitTrailer,
8
+ GitCommitType,
9
+ } from '#types'
10
+ import type { CommitBase } from 'conventional-commits-parser'
11
+ import { CommitParser } from 'conventional-commits-parser'
12
+ import { buildTrailerPattern } from '../../util/buildTrailerPattern'
13
+ import { extractMentions } from './extractMentions'
14
+
15
+ export interface GitLogEntry {
16
+ hash: string
17
+ parent: string[]
18
+ authorDate: string
19
+ committerDate: string
20
+ subject: string
21
+ body: string
22
+ files: string[]
23
+ }
24
+
25
+ interface Commit extends CommitBase {
26
+ type: GitCommitType | null
27
+ scope: string | null
28
+ subject: string
29
+ header: string
30
+ body: string | null
31
+ footer: string | null
32
+ }
33
+
34
+ const BREAKING_HEADER_REGEX = /^([\w-]+)(?:\(([^)]+)\))?!: (.*)$/
35
+
36
+ const BREAKING_MARKERS: readonly string[] = [
37
+ 'BREAKING CHANGE',
38
+ 'BREAKING-CHANGE',
39
+ ]
40
+
41
+ /**
42
+ * Parse a git log entry into a structured commit object.
43
+ *
44
+ * Combines the commit subject and body, extracts conventional commit metadata
45
+ * using custom trailer markers and breaking header patterns, and normalizes
46
+ * dates to ISO format strings.
47
+ *
48
+ * @param entry The raw git log entry to parse
49
+ * @param markers Optional array of custom trailer marker strings
50
+ * @returns A structured commit object containing parsed details, notes, and mentions
51
+ */
52
+ export async function parseGitCommit(
53
+ entry: GitLogEntry,
54
+ markers: readonly string[] = []
55
+ ): Promise<GitCommit> {
56
+ const message = [entry.subject, entry.body].filter(Boolean).join('\n\n')
57
+
58
+ const parser = new CommitParser({
59
+ breakingHeaderPattern: BREAKING_HEADER_REGEX,
60
+ noteKeywords: [],
61
+ notesPattern: () => buildTrailerPattern(BREAKING_MARKERS.concat(markers)),
62
+ })
63
+
64
+ const commit = parser.parse(message) as CommitBase as Commit
65
+
66
+ const notes: GitCommitNote[] = []
67
+
68
+ const trailers: GitCommitTrailer[] = []
69
+
70
+ for (const note of commit.notes) {
71
+ if (BREAKING_MARKERS.includes(note.title.toUpperCase())) {
72
+ notes.push(note)
73
+ }
74
+
75
+ trailers.push({
76
+ key: note.title,
77
+ value: note.text,
78
+ })
79
+ }
80
+
81
+ if (notes.length === 0 && BREAKING_HEADER_REGEX.test(commit.header)) {
82
+ const note: GitCommitNote = {
83
+ title: 'BREAKING CHANGE',
84
+ text: commit.subject,
85
+ }
86
+
87
+ notes.push(note)
88
+
89
+ trailers.push({
90
+ key: note.title,
91
+ value: note.text,
92
+ })
93
+ }
94
+
95
+ const mentions = extractMentions(message)
96
+
97
+ return {
98
+ ...commit,
99
+ hash: entry.hash,
100
+ parent: entry.parent,
101
+ authorDate: new Date(entry.authorDate).toISOString(),
102
+ committerDate: new Date(entry.committerDate).toISOString(),
103
+ type: commit.type?.toLowerCase() || null,
104
+ scope: commit.scope || null,
105
+ subject: commit.subject || null,
106
+ header: commit.header,
107
+ body: commit.body,
108
+ footer: commit.footer,
109
+ notes,
110
+ mentions,
111
+ trailers,
112
+ files: entry.files,
113
+ }
114
+ }
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { colors } from 'consola/utils'
5
+ import type { GitLogEntry } from './parseGitCommit'
6
+
7
+ /**
8
+ * Field separator used in the git pretty format to produce a single-line
9
+ *, machine-parseable record.
10
+ */
11
+ export const GIT_PRETTY_FIELD_SEPARATOR = '\x1f'
12
+
13
+ /**
14
+ * Pretty format string passed to `git log --pretty=format:`. Produces seven
15
+ * fields separated by `GIT_PRETTY_FIELD_SEPARATOR`:
16
+ * hash, parents, author date, committer date, subject, body, files.
17
+ */
18
+ export const GIT_PRETTY_FORMAT = [
19
+ '%H',
20
+ '%P',
21
+ '%aI',
22
+ '%cI',
23
+ '%s',
24
+ '%b',
25
+ '',
26
+ ].join(GIT_PRETTY_FIELD_SEPARATOR)
27
+
28
+ /**
29
+ * Parse a single line produced by `git log --pretty=format:${GIT_PRETTY_FORMAT}`.
30
+ *
31
+ * The input is expected to contain seven fields separated by
32
+ * `GIT_PRETTY_FIELD_SEPARATOR`:
33
+ * 1. `hash` (commit hash)
34
+ * 2. `parent` (space-separated parent hashes)
35
+ * 3. `authorDate` (ISO 8601)
36
+ * 4. `committerDate` (ISO 8601)
37
+ * 5. `subject`
38
+ * 6. `body`
39
+ * 7. `files` (newline-separated list)
40
+ *
41
+ * The function trims fields, converts parent hashes into an array, normalizes
42
+ * dates to ISO strings, and splits `files` into an array. Missing optional
43
+ * fields are normalized to sensible defaults.
44
+ *
45
+ * @param raw Raw pretty-format string produced by git
46
+ * @returns Parsed `GitLogEntry` with `hash`, `parent`, `authorDate`, `committerDate`, `subject`, `body`, and `files`
47
+ * @throws If required fields (hash, authorDate, committerDate, subject) are missing or malformed
48
+ */
49
+ export function parseGitPrettyFormat(raw: string): GitLogEntry {
50
+ let [hash, parentHashes, authorDate, committerDate, subject, body, files] =
51
+ raw.split(GIT_PRETTY_FIELD_SEPARATOR)
52
+
53
+ hash = hash?.trim()
54
+ parentHashes = parentHashes?.trim()
55
+ authorDate = authorDate?.trim()
56
+ committerDate = committerDate?.trim()
57
+ subject = subject?.trim()
58
+ body = body?.trim()
59
+ files = files?.trim()
60
+
61
+ if (!hash || !authorDate || !committerDate || typeof subject !== 'string') {
62
+ throw new Error(
63
+ `The input "${colors.bold(raw)}" is not in the expected pretty format.`
64
+ )
65
+ }
66
+
67
+ return {
68
+ hash,
69
+ parent: parentHashes ? parentHashes.split(/\s+/) : [],
70
+ authorDate: new Date(authorDate).toISOString(),
71
+ committerDate: new Date(committerDate).toISOString(),
72
+ subject,
73
+ body: body ?? '',
74
+ files: files ? files.split('\n') : [],
75
+ }
76
+ }
@@ -0,0 +1,28 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2026 Fai
3
+
4
+ import { execGit } from '#util'
5
+
6
+ /**
7
+ * Count mainline commits reachable from a given reference.
8
+ *
9
+ * Uses `git rev-list --count --first-parent` to calculate the length of the
10
+ * primary history trunk, excluding commits introduced by side-branch merges.
11
+ *
12
+ * @param cwd Repository working directory
13
+ * @param ref Commit reference to count from (defaults to `HEAD`)
14
+ * @returns Number of commits along the primary branch line up to `ref`
15
+ */
16
+ export async function countGitHistory(
17
+ cwd: string,
18
+ ref: string = 'HEAD'
19
+ ): Promise<number> {
20
+ const stdout = await execGit(cwd, [
21
+ 'rev-list',
22
+ '--count',
23
+ '--first-parent',
24
+ ref,
25
+ ])
26
+
27
+ return Number.parseInt(stdout.trim(), 10)
28
+ }