├── .gitignore ├── .github ├── FUNDING.yml └── workflows │ └── release.yml ├── CONTRIBUTING.md ├── pnpm-workspace.yaml ├── eslint.config.js ├── cli.mjs ├── src ├── index.ts ├── parse.ts ├── utils.ts ├── generate.ts ├── config.ts ├── types.ts ├── git.ts ├── style │ ├── plain.ts │ └── markdown.ts ├── cli.ts └── github.ts ├── tsconfig.json ├── LICENSE ├── .vscode └── settings.json ├── package.json ├── README.md └── test └── git.test.ts /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [antfu] 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Please refer to https://github.com/antfu/contribute 2 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | onlyBuiltDependencies: 2 | - esbuild 3 | - unrs-resolver 4 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import antfu from '@antfu/eslint-config' 2 | 3 | export default antfu() 4 | -------------------------------------------------------------------------------- /cli.mjs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | // eslint-disable-next-line antfu/no-import-dist 3 | import './dist/cli.mjs' 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './config' 2 | export * from './generate' 3 | export * from './git' 4 | export * from './github' 5 | export * from './parse' 6 | export * from './style/markdown' 7 | export * from './types' 8 | -------------------------------------------------------------------------------- /src/parse.ts: -------------------------------------------------------------------------------- 1 | import type { GitCommit, RawGitCommit } from 'changelogen' 2 | import type { ChangelogenOptions } from './types' 3 | import { notNullish } from '@antfu/utils' 4 | import { parseGitCommit } from 'changelogen' 5 | 6 | export function parseCommits(commits: RawGitCommit[], config: ChangelogenOptions): GitCommit[] { 7 | return commits.map(commit => parseGitCommit(commit, config)).filter(notNullish) 8 | } 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2018", 4 | "lib": ["esnext"], 5 | "module": "esnext", 6 | "moduleResolution": "node", 7 | "resolveJsonModule": true, 8 | "strict": true, 9 | "strictNullChecks": true, 10 | "esModuleInterop": true, 11 | "skipDefaultLibCheck": true, 12 | "skipLibCheck": true 13 | }, 14 | "exclude": [ 15 | "node_modules", 16 | "dist" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | tags: 9 | - 'v*' 10 | 11 | jobs: 12 | release: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | with: 17 | fetch-depth: 0 18 | - name: Set node 19 | uses: actions/setup-node@v4 20 | with: 21 | registry-url: https://registry.npmjs.org/ 22 | node-version: lts/* 23 | 24 | - name: Setup 25 | run: npm i -g @antfu/ni 26 | 27 | - name: Install 28 | run: nci 29 | 30 | - run: npm start 31 | env: 32 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 33 | 34 | - run: npm publish 35 | env: 36 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 37 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | export const emojisRE = /([\u2700-\u27BF\uE000-\uF8FF\u2011-\u26FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|\uD83E[\uDD10-\uDDFF])/g 2 | 3 | export function groupBy(items: T[], key: string, groups: Record = {}) { 4 | for (const item of items) { 5 | const v = (item as any)[key] as string 6 | groups[v] = groups[v] || [] 7 | groups[v].push(item) 8 | } 9 | return groups 10 | } 11 | 12 | export function capitalize(str: string) { 13 | return str.charAt(0).toUpperCase() + str.slice(1) 14 | } 15 | 16 | export function join(array?: string[], glue = ', ', finalGlue = ' and '): string { 17 | if (!array || array.length === 0) 18 | return '' 19 | 20 | if (array.length === 1) 21 | return array[0] 22 | 23 | if (array.length === 2) 24 | return array.join(finalGlue) 25 | 26 | return `${array.slice(0, -1).join(glue)}${finalGlue}${array.slice(-1)}` 27 | } 28 | -------------------------------------------------------------------------------- /src/generate.ts: -------------------------------------------------------------------------------- 1 | import type { ChangelogOptions } from './types' 2 | import { getGitDiff } from 'changelogen' 3 | import { resolveConfig } from './config' 4 | import { resolveAuthors } from './github' 5 | import { parseCommits } from './parse' 6 | import { generateMarkdown } from './style/markdown' 7 | import { generatePlain } from './style/plain' 8 | 9 | export async function generate(options: ChangelogOptions) { 10 | const resolved = await resolveConfig(options) 11 | 12 | const rawCommits = await getGitDiff(resolved.from, resolved.to) 13 | const commits = parseCommits(rawCommits, resolved) 14 | if (resolved.contributors) 15 | await resolveAuthors(commits, resolved) 16 | 17 | let output: string 18 | 19 | switch (resolved.style) { 20 | case 'markdown': 21 | output = generateMarkdown(commits, resolved) 22 | break 23 | case 'plain': 24 | output = generatePlain(commits, resolved) 25 | break 26 | default: 27 | throw new Error(`Invalid style: ${resolved.style}`) 28 | } 29 | 30 | return { config: resolved, output, commits } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Anthony Fu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "Changelogen", 4 | "changelogithub" 5 | ], 6 | 7 | // Enable the flat config support 8 | "eslint.experimental.useFlatConfig": true, 9 | 10 | // Disable the default formatter 11 | "prettier.enable": false, 12 | "editor.formatOnSave": false, 13 | 14 | // Auto fix 15 | "editor.codeActionsOnSave": { 16 | "source.fixAll": "explicit", 17 | "source.organizeImports": "never" 18 | }, 19 | 20 | // Silent the stylistic rules in you IDE, but still auto fix them 21 | "eslint.rules.customizations": [ 22 | { "rule": "@stylistic/*", "severity": "off" }, 23 | { "rule": "*-indent", "severity": "off" }, 24 | { "rule": "*-spacing", "severity": "off" }, 25 | { "rule": "*-spaces", "severity": "off" }, 26 | { "rule": "*-order", "severity": "off" }, 27 | { "rule": "*-dangle", "severity": "off" }, 28 | { "rule": "*-newline", "severity": "off" }, 29 | { "rule": "*quotes", "severity": "off" }, 30 | { "rule": "*semi", "severity": "off" } 31 | ], 32 | 33 | "eslint.validate": [ 34 | "javascript", 35 | "javascriptreact", 36 | "typescript", 37 | "typescriptreact", 38 | "vue", 39 | "html", 40 | "markdown", 41 | "json", 42 | "jsonc", 43 | "yaml" 44 | ] 45 | } 46 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | import type { ChangelogOptions, ResolvedChangelogOptions } from './types' 2 | import { getCurrentGitBranch, getFirstGitCommit, getGitHubRepo, getLastMatchingTag, getSafeTagTemplate, isPrerelease } from './git' 3 | 4 | export function defineConfig(config: ChangelogOptions) { 5 | return config 6 | } 7 | 8 | const defaultConfig = { 9 | scopeMap: {}, 10 | types: { 11 | feat: { title: '🚀 Features' }, 12 | fix: { title: '🐞 Bug Fixes' }, 13 | perf: { title: '🏎 Performance' }, 14 | }, 15 | titles: { 16 | breakingChanges: '🚨 Breaking Changes', 17 | }, 18 | contributors: true, 19 | emoji: true, 20 | capitalize: true, 21 | group: true, 22 | tag: 'v%s', 23 | style: 'markdown', 24 | } satisfies ChangelogOptions 25 | 26 | export async function resolveConfig(options: ChangelogOptions) { 27 | const { loadConfig } = await import('c12') 28 | const config = await loadConfig({ 29 | name: 'changelogithub', 30 | defaults: defaultConfig, 31 | overrides: options, 32 | packageJson: 'changelogithub', 33 | }).then(r => r.config || defaultConfig) 34 | 35 | config.baseUrl = config.baseUrl ?? 'github.com' 36 | config.baseUrlApi = config.baseUrlApi ?? 'api.github.com' 37 | config.to = config.to || await getCurrentGitBranch() 38 | config.tagFilter = config.tagFilter ?? (() => true) 39 | config.tag = getSafeTagTemplate(config.tag ?? defaultConfig.tag) 40 | config.from = config.from || await getLastMatchingTag( 41 | config.to, 42 | config.tagFilter, 43 | config.tag, 44 | ) || await getFirstGitCommit() 45 | // @ts-expect-error backward compatibility 46 | config.repo = config.repo || config.github || await getGitHubRepo(config.baseUrl) 47 | // @ts-expect-error backward compatibility 48 | config.releaseRepo = config.releaseRepo || config.releaseGithub || config.repo 49 | config.prerelease = config.prerelease ?? isPrerelease(config.to) 50 | 51 | if (typeof config.repo !== 'string') 52 | throw new Error(`Invalid GitHub repository, expected a string but got ${JSON.stringify(config.repo)}`) 53 | 54 | return config as ResolvedChangelogOptions 55 | } 56 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "changelogithub", 3 | "type": "module", 4 | "version": "14.0.0", 5 | "packageManager": "pnpm@10.23.0", 6 | "description": "Generate changelog for GitHub.", 7 | "author": "Anthony Fu ", 8 | "license": "MIT", 9 | "funding": "https://github.com/sponsors/antfu", 10 | "homepage": "https://github.com/antfu/changelogithub#readme", 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/antfu/changelogithub.git" 14 | }, 15 | "bugs": "https://github.com/antfu/changelogithub/issues", 16 | "keywords": [ 17 | "github", 18 | "release", 19 | "releases", 20 | "conventional", 21 | "changelog", 22 | "log" 23 | ], 24 | "sideEffects": false, 25 | "exports": { 26 | ".": { 27 | "types": "./dist/index.d.ts", 28 | "import": "./dist/index.mjs", 29 | "require": "./dist/index.cjs" 30 | } 31 | }, 32 | "main": "./dist/index.mjs", 33 | "module": "./dist/index.mjs", 34 | "types": "./dist/index.d.ts", 35 | "bin": "./cli.mjs", 36 | "files": [ 37 | "*.mjs", 38 | "dist" 39 | ], 40 | "engines": { 41 | "node": ">=12.0.0" 42 | }, 43 | "scripts": { 44 | "build": "unbuild", 45 | "dev": "unbuild --stub", 46 | "test": "vitest", 47 | "lint": "eslint .", 48 | "prepublishOnly": "nr build", 49 | "release": "bumpp", 50 | "start": "nr dev && node cli.mjs", 51 | "typecheck": "tsc --noEmit" 52 | }, 53 | "dependencies": { 54 | "ansis": "^4.2.0", 55 | "c12": "^3.3.2", 56 | "cac": "^6.7.14", 57 | "changelogen": "0.5.7", 58 | "convert-gitmoji": "^0.1.5", 59 | "execa": "^9.6.0", 60 | "ofetch": "^1.5.1", 61 | "semver": "^7.7.3", 62 | "tinyglobby": "^0.2.15" 63 | }, 64 | "devDependencies": { 65 | "@antfu/eslint-config": "^6.2.0", 66 | "@antfu/utils": "^9.3.0", 67 | "@types/debug": "^4.1.12", 68 | "@types/fs-extra": "^11.0.4", 69 | "@types/minimist": "^1.2.5", 70 | "@types/semver": "^7.7.1", 71 | "bumpp": "^10.3.1", 72 | "eslint": "^9.39.1", 73 | "fs-extra": "^11.3.2", 74 | "typescript": "^5.9.3", 75 | "unbuild": "^3.6.1", 76 | "vitest": "^4.0.13" 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # changelogithub 2 | 3 | [![NPM version](https://img.shields.io/npm/v/changelogithub?color=a1b858&label=)](https://www.npmjs.com/package/changelogithub) 4 | 5 | Generate changelog for GitHub releases from [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), powered by [changelogen](https://github.com/unjs/changelogen). 6 | 7 | [👉 Changelog example](https://github.com/unocss/unocss/releases/tag/v0.39.0) 8 | 9 | ## Features 10 | 11 | - Support exclamation mark as breaking change, e.g. `chore!: drop node v10` 12 | - Grouped scope in changelog 13 | - Create the release note, or update the existing one 14 | - List contributors 15 | 16 | ## Usage 17 | 18 | In GitHub Actions: 19 | 20 | ```yml 21 | # .github/workflows/release.yml 22 | 23 | name: Release 24 | 25 | permissions: 26 | contents: write 27 | 28 | on: 29 | push: 30 | tags: 31 | - 'v*' 32 | 33 | jobs: 34 | release: 35 | runs-on: ubuntu-latest 36 | steps: 37 | - uses: actions/checkout@v4 38 | with: 39 | fetch-depth: 0 40 | 41 | - name: Set node 42 | uses: actions/setup-node@v4 43 | with: 44 | registry-url: https://registry.npmjs.org/ 45 | node-version: lts/* 46 | 47 | - run: npx changelogithub # or changelogithub@0.12 to ensure a stable result 48 | env: 49 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 50 | ``` 51 | 52 | It will be trigged whenever you push a tag to GitHub that starts with `v`. 53 | 54 | ## Configuration 55 | 56 | You can put a configuration file in the project root, named as `changelogithub.config.{json,ts,js,mjs,cjs}`, `.changelogithubrc` or use the `changelogithub` field in `package.json`. 57 | 58 | ## Preview Locally 59 | 60 | ```bash 61 | npx changelogithub --dry 62 | ``` 63 | 64 | ## Why? 65 | 66 | I used to use [`conventional-github-releaser`](https://github.com/conventional-changelog/releaser-tools/tree/master/packages/conventional-github-releaser) for almost all my projects. Until I found that it [does NOT support using exclamation marks for breaking changes](https://github.com/conventional-changelog/conventional-changelog/issues/648) - hiding those important breaking changes in the changelog without the awareness from maintainers. 67 | 68 | ## License 69 | 70 | [MIT](./LICENSE) License © 2022 [Anthony Fu](https://github.com/antfu) 71 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import type { ChangelogConfig, GitCommit, RepoConfig } from 'changelogen' 2 | 3 | export type ChangelogenOptions = ChangelogConfig 4 | 5 | export interface GitHubRepo { 6 | owner: string 7 | repo: string 8 | } 9 | 10 | export interface GitHubAuth { 11 | token: string 12 | url: string 13 | } 14 | 15 | export interface Commit extends GitCommit { 16 | resolvedAuthors?: AuthorInfo[] 17 | } 18 | 19 | export interface ChangelogOptions extends Partial { 20 | /** 21 | * Dry run. Skip releasing to GitHub. 22 | */ 23 | dry?: boolean 24 | /** 25 | * Whether to include contributors in release notes. 26 | * 27 | * @default true 28 | */ 29 | contributors?: boolean 30 | /** 31 | * Name of the release 32 | */ 33 | name?: string 34 | /** 35 | * Mark the release as a draft 36 | */ 37 | draft?: boolean 38 | /** 39 | * Mark the release as prerelease 40 | */ 41 | prerelease?: boolean 42 | /** 43 | * GitHub Token 44 | */ 45 | token?: string 46 | /** 47 | * Custom titles 48 | */ 49 | titles?: { 50 | breakingChanges?: string 51 | } 52 | /** 53 | * Capitalize commit messages 54 | * @default true 55 | */ 56 | capitalize?: boolean 57 | /** 58 | * Nest commit messages under their scopes 59 | * @default true 60 | */ 61 | group?: boolean | 'multiple' 62 | /** 63 | * Use emojis in section titles 64 | * @default true 65 | */ 66 | emoji?: boolean 67 | /** 68 | * Github base url 69 | * @default github.com 70 | */ 71 | baseUrl?: string 72 | /** 73 | * Github base API url 74 | * @default api.github.com 75 | */ 76 | baseUrlApi?: string 77 | 78 | /** 79 | * Filter tags 80 | */ 81 | tagFilter?: (tag: string) => boolean 82 | 83 | /** 84 | * Release repository, defaults to `repo` 85 | */ 86 | releaseRepo?: RepoConfig | string 87 | 88 | /** 89 | * Can be set to a custom tag string 90 | * Any `%s` placeholders in the tag string will be replaced 91 | * If the tag string does _not_ contain any `%s` placeholders, 92 | * then the version number will be appended to the tag. 93 | * 94 | * @default `v%s`. 95 | */ 96 | tag?: string 97 | 98 | /** 99 | * Files to upload as assets to the release 100 | * `--assets path1,path2` or `--assets path1 --assets path2` 101 | */ 102 | assets?: string[] | string 103 | 104 | /** 105 | * Style of the changelog 106 | * @default 'markdown' 107 | */ 108 | style?: 'markdown' | 'plain' 109 | } 110 | 111 | export type ResolvedChangelogOptions = Required 112 | 113 | export interface AuthorInfo { 114 | commits: string[] 115 | login?: string 116 | email: string 117 | name: string 118 | } 119 | -------------------------------------------------------------------------------- /src/git.ts: -------------------------------------------------------------------------------- 1 | import semver from 'semver' 2 | 3 | export async function getGitHubRepo(baseUrl: string) { 4 | const url = await execCommand('git', ['config', '--get', 'remote.origin.url']) 5 | const escapedBaseUrl = baseUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') 6 | const regex = new RegExp(`${escapedBaseUrl}[\/:]([\\w\\d._-]+?)\\/([\\w\\d._-]+?)(\\.git)?$`, 'i') 7 | const match = regex.exec(url) 8 | if (!match) 9 | throw new Error(`Can not parse GitHub repo from url ${url}`) 10 | return `${match[1]}/${match[2]}` 11 | } 12 | 13 | export async function getCurrentGitBranch() { 14 | return await execCommand('git', ['tag', '--points-at', 'HEAD']) || await execCommand('git', ['rev-parse', '--abbrev-ref', 'HEAD']) 15 | } 16 | 17 | export async function isRepoShallow() { 18 | return (await execCommand('git', ['rev-parse', '--is-shallow-repository'])).trim() === 'true' 19 | } 20 | 21 | export function getSafeTagTemplate(template: string) { 22 | return template.includes('%s') ? template : `${template}%s` 23 | } 24 | 25 | function getVersionString(template: string, tag: string) { 26 | const pattern = template.replace(/%s/g, '(.+)') 27 | const regex = new RegExp(`^${pattern}$`) 28 | const match = regex.exec(tag) 29 | return match ? match[1] : tag 30 | } 31 | 32 | export async function getGitTags() { 33 | const output = await execCommand('git', [ 34 | 'log', 35 | '--simplify-by-decoration', 36 | '--pretty=format:"%d"', 37 | ]) 38 | 39 | const tagRegex = /tag: ([^,)]+)/g 40 | const tagList: string[] = [] 41 | let match 42 | 43 | while (match !== null) { 44 | const tag = match?.[1].trim() 45 | if (tag) { 46 | tagList.push(tag) 47 | } 48 | match = tagRegex.exec(output) 49 | } 50 | 51 | return tagList 52 | } 53 | 54 | export async function getLastMatchingTag( 55 | inputTag: string, 56 | tagFilter: (tag: string) => boolean, 57 | tagTemplate: string, 58 | ) { 59 | const inputVersionString = getVersionString(tagTemplate, inputTag) 60 | const isVersion = semver.valid(inputVersionString) !== null 61 | const isPrerelease = semver.prerelease(inputVersionString) !== null 62 | const tags = await getGitTags() 63 | const filteredTags = tags.filter(tagFilter) 64 | 65 | let tag: string | undefined 66 | // Doing a stable release, find the last stable release to compare with 67 | if (!isPrerelease && isVersion) { 68 | tag = filteredTags.find((tag) => { 69 | const versionString = getVersionString(tagTemplate, tag) 70 | 71 | return versionString !== inputVersionString 72 | && semver.valid(versionString) !== null 73 | && semver.prerelease(versionString) === null 74 | }) 75 | } 76 | 77 | // Fallback to the last tag, that are not the input tag 78 | tag ||= filteredTags.find(tag => tag !== inputTag) 79 | return tag 80 | } 81 | 82 | export async function isRefGitTag(to: string) { 83 | const { execa } = await import('execa') 84 | try { 85 | await execa('git', ['show-ref', '--verify', `refs/tags/${to}`], { reject: true }) 86 | } 87 | catch { 88 | return false 89 | } 90 | } 91 | 92 | export async function getFirstGitCommit() { 93 | return await execCommand('git', ['rev-list', '--max-parents=0', 'HEAD']) 94 | } 95 | 96 | export function isPrerelease(version: string) { 97 | return !/^[^.]*(?:\.[\d.]*|\d)$/.test(version) 98 | } 99 | 100 | async function execCommand(cmd: string, args: string[]) { 101 | const { execa } = await import('execa') 102 | const res = await execa(cmd, args) 103 | return res.stdout.trim() 104 | } 105 | -------------------------------------------------------------------------------- /src/style/plain.ts: -------------------------------------------------------------------------------- 1 | import type { Reference } from 'changelogen' 2 | import type { Commit, ResolvedChangelogOptions } from '../types' 3 | import { partition } from '@antfu/utils' 4 | import { capitalize, emojisRE, groupBy, join } from '../utils' 5 | 6 | function formatReferences(references: Reference[], baseUrl: string, github: string, type: 'issues' | 'hash'): string { 7 | const refs = references 8 | .filter((i) => { 9 | if (type === 'issues') 10 | return i.type === 'issue' || i.type === 'pull-request' 11 | return i.type === 'hash' 12 | }) 13 | .map((ref) => { 14 | if (!github) 15 | return ref.value 16 | if (ref.type === 'pull-request' || ref.type === 'issue') 17 | return `#${ref.value.slice(1)}` 18 | return `(${ref.value.slice(0, 7)})` 19 | }) 20 | 21 | const referencesString = join(refs).trim() 22 | 23 | if (type === 'issues') 24 | return referencesString && `in ${referencesString}` 25 | return referencesString 26 | } 27 | 28 | function formatLine(commit: Commit, options: ResolvedChangelogOptions) { 29 | const prRefs = formatReferences(commit.references, options.baseUrl, options.repo as string, 'issues') 30 | const hashRefs = formatReferences(commit.references, options.baseUrl, options.repo as string, 'hash') 31 | 32 | let authors = join([...new Set(commit.resolvedAuthors?.map(i => i.login ? `@${i.login}` : i.name))])?.trim() 33 | if (authors) 34 | authors = `by ${authors}` 35 | 36 | let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ') 37 | 38 | if (refs) 39 | refs = ` - ${refs}` 40 | 41 | const description = options.capitalize ? capitalize(commit.description) : commit.description 42 | 43 | return [description, refs].filter(i => i?.trim()).join(' ') 44 | } 45 | 46 | function formatTitle(name: string) { 47 | return name.replace(emojisRE, '').trim() 48 | } 49 | 50 | function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { 51 | if (!commits.length) 52 | return [] 53 | 54 | const lines: string[] = [ 55 | '', 56 | formatTitle(sectionName), 57 | '', 58 | ] 59 | 60 | const scopes = groupBy(commits, 'scope') 61 | let useScopeGroup = options.group 62 | 63 | // group scopes only when one of the scope have multiple commits 64 | if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) 65 | useScopeGroup = false 66 | 67 | Object.keys(scopes).sort().forEach((scope) => { 68 | let padding = '' 69 | let prefix = '' 70 | const scopeText = options.scopeMap[scope] || scope 71 | if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { 72 | lines.push(`- ${scopeText}:`) 73 | padding = ' ' 74 | } 75 | else if (scope) { 76 | prefix = `${scopeText}: ` 77 | } 78 | 79 | lines.push(...scopes[scope] 80 | .reverse() 81 | .map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`), 82 | ) 83 | }) 84 | 85 | return lines 86 | } 87 | 88 | export function generatePlain(commits: Commit[], options: ResolvedChangelogOptions) { 89 | const lines: string[] = [] 90 | 91 | const [breaking, changes] = partition(commits, c => c.isBreaking) 92 | 93 | const group = groupBy(changes, 'type') 94 | 95 | lines.push( 96 | ...formatSection(breaking, options.titles.breakingChanges!, options), 97 | ) 98 | 99 | for (const type of Object.keys(options.types)) { 100 | const items = group[type] || [] 101 | lines.push( 102 | ...formatSection(items, options.types[type].title, options), 103 | ) 104 | } 105 | 106 | if (!lines.length) 107 | lines.push('No significant changes') 108 | 109 | const url = `https://${options.baseUrl}/${options.repo}/compare/${options.from}...${options.to}` 110 | 111 | lines.push('', `View changes on GitHub: ${url}`) 112 | 113 | return lines.join('\n').trim() 114 | } 115 | -------------------------------------------------------------------------------- /src/style/markdown.ts: -------------------------------------------------------------------------------- 1 | import type { Reference } from 'changelogen' 2 | import type { Commit, ResolvedChangelogOptions } from '../types' 3 | import { partition } from '@antfu/utils' 4 | import { convert } from 'convert-gitmoji' 5 | import { capitalize, emojisRE, groupBy, join } from '../utils' 6 | 7 | function formatReferences(references: Reference[], baseUrl: string, github: string, type: 'issues' | 'hash'): string { 8 | const refs = references 9 | .filter((i) => { 10 | if (type === 'issues') 11 | return i.type === 'issue' || i.type === 'pull-request' 12 | return i.type === 'hash' 13 | }) 14 | .map((ref) => { 15 | if (!github) 16 | return ref.value 17 | if (ref.type === 'pull-request' || ref.type === 'issue') 18 | return `https://${baseUrl}/${github}/issues/${ref.value.slice(1)}` 19 | return `[(${ref.value.slice(0, 5)})](https://${baseUrl}/${github}/commit/${ref.value})` 20 | }) 21 | 22 | const referencesString = join(refs).trim() 23 | 24 | if (type === 'issues') 25 | return referencesString && `in ${referencesString}` 26 | return referencesString 27 | } 28 | 29 | function formatLine(commit: Commit, options: ResolvedChangelogOptions) { 30 | const prRefs = formatReferences(commit.references, options.baseUrl, options.repo as string, 'issues') 31 | const hashRefs = formatReferences(commit.references, options.baseUrl, options.repo as string, 'hash') 32 | 33 | let authors = join([...new Set(commit.resolvedAuthors?.map(i => i.login ? `@${i.login}` : `**${i.name}**`))])?.trim() 34 | if (authors) 35 | authors = `by ${authors}` 36 | 37 | let refs = [authors, prRefs, hashRefs].filter(i => i?.trim()).join(' ') 38 | 39 | if (refs) 40 | refs = ` -  ${refs}` 41 | 42 | const description = options.capitalize ? capitalize(commit.description) : commit.description 43 | 44 | return [description, refs].filter(i => i?.trim()).join(' ') 45 | } 46 | 47 | function formatTitle(name: string, options: ResolvedChangelogOptions) { 48 | if (!options.emoji) 49 | name = name.replace(emojisRE, '') 50 | 51 | return `###    ${name.trim()}` 52 | } 53 | 54 | function formatSection(commits: Commit[], sectionName: string, options: ResolvedChangelogOptions) { 55 | if (!commits.length) 56 | return [] 57 | 58 | const lines: string[] = [ 59 | '', 60 | formatTitle(sectionName, options), 61 | '', 62 | ] 63 | 64 | const scopes = groupBy(commits, 'scope') 65 | let useScopeGroup = options.group 66 | 67 | // group scopes only when one of the scope have multiple commits 68 | if (!Object.entries(scopes).some(([k, v]) => k && v.length > 1)) 69 | useScopeGroup = false 70 | 71 | Object.keys(scopes).sort().forEach((scope) => { 72 | let padding = '' 73 | let prefix = '' 74 | const scopeText = `**${options.scopeMap[scope] || scope}**` 75 | if (scope && (useScopeGroup === true || (useScopeGroup === 'multiple' && scopes[scope].length > 1))) { 76 | lines.push(`- ${scopeText}:`) 77 | padding = ' ' 78 | } 79 | else if (scope) { 80 | prefix = `${scopeText}: ` 81 | } 82 | 83 | lines.push(...scopes[scope] 84 | .reverse() 85 | .map(commit => `${padding}- ${prefix}${formatLine(commit, options)}`), 86 | ) 87 | }) 88 | 89 | return lines 90 | } 91 | 92 | export function generateMarkdown(commits: Commit[], options: ResolvedChangelogOptions) { 93 | const lines: string[] = [] 94 | 95 | const [breaking, changes] = partition(commits, c => c.isBreaking) 96 | 97 | const group = groupBy(changes, 'type') 98 | 99 | lines.push( 100 | ...formatSection(breaking, options.titles.breakingChanges!, options), 101 | ) 102 | 103 | for (const type of Object.keys(options.types)) { 104 | const items = group[type] || [] 105 | lines.push( 106 | ...formatSection(items, options.types[type].title, options), 107 | ) 108 | } 109 | 110 | if (!lines.length) 111 | lines.push('*No significant changes*') 112 | 113 | const url = `https://${options.baseUrl}/${options.repo}/compare/${options.from}...${options.to}` 114 | 115 | lines.push('', `#####     [View changes on GitHub](${url})`) 116 | 117 | return convert(lines.join('\n').trim(), true) 118 | } 119 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import fs from 'node:fs/promises' 4 | import process from 'node:process' 5 | import { blue, bold, cyan, dim, red, yellow } from 'ansis' 6 | import cac from 'cac' 7 | import { execa } from 'execa' 8 | import { version } from '../package.json' 9 | import { uploadAssets } from './github' 10 | import { generate, hasTagOnGitHub, isRepoShallow, sendRelease } from './index' 11 | 12 | const cli = cac('changelogithub') 13 | 14 | cli 15 | .version(version) 16 | .option('-t, --token ', 'GitHub Token') 17 | .option('--from ', 'From tag') 18 | .option('--to ', 'To tag') 19 | .option('--github ', 'GitHub Repository, e.g. antfu/changelogithub') 20 | .option('--release-github ', 'Release GitHub Repository, defaults to `github`') 21 | .option('--name ', 'Name of the release') 22 | .option('--contributors', 'Show contributors section') 23 | .option('--prerelease', 'Mark release as prerelease') 24 | .option('-d, --draft', 'Mark release as draft') 25 | .option('--output ', 'Output to file instead of sending to GitHub') 26 | .option('--capitalize', 'Should capitalize for each comment message') 27 | .option('--emoji', 'Use emojis in section titles') 28 | .option('--group', 'Nest commit messages under their scopes') 29 | .option('--dry', 'Dry run') 30 | .option('--assets ', 'Files to upload as assets to the release. Use quotes to prevent shell glob expansion, e.g., "--assets \'dist/*.js\'"') 31 | .option('--style