changelogithub

repository·main·Indexed 21 days ago

https://github.com/antfu/changelogithub

A tool for generating or updating GitHub release notes using Conventional Commits. Designed for CI/CD pipelines and GitHub Actions, it supports breaking change detection, grouped scopes, contributor listing, and asset uploads. It provides a CLI and a programmatic API including functions like generate(), sendRelease(), and uploadAssets() to automate the release documentation process.

Tokens
6K
Snippets
18
Records
20
Agent score
75%

What's inside changelogithub

  1. Overview of changelogithub features

    main

    changelogithub generates changelogs for GitHub releases based on Conventional Commits. Key features include:

    • Breaking Change Support: Recognizes the exclamation mark syntax (e.g., chore!: description) to highlight breaking changes.
    • Grouped Scopes: Organizes changes by their scope in the changelog.
    • Release Management: Can either create a new release note or update an existing one.
    • Contributor Listing: Automatically lists contributors in the release notes.
  2. Use changelogithub in GitHub Actions

    main

    To automatically generate or update release notes for GitHub releases, use changelogithub within a GitHub Action workflow. The workflow should trigger on tag pushes (e.g., v*) and requires contents: write permissions. You must provide a GITHUB_TOKEN via environment variables. It is recommended to use npx changelogithub to run the tool.

    # .github/workflows/release.yml
    
    name: Release
    
    permissions:
      contents: write
    
    on:
      push:
        tags:
          - 'v*'
    
    jobs:
      release:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v6
            with:
              fetch-depth: 0
    
          - name: Set node
            uses: actions/setup-node@v6
            with:
              registry-url: https://registry.npmjs.org/
              node-version: lts/*
    
          - run: npx changelogithub # or changelogithub@0.12 to ensure a stable result
            env:
              GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
  3. Define custom tag patterns with the tag option

    main

    The tag option allows you to define how the release tag is formatted.

    • If you include the %s placeholder, the version number will be inserted at that position.
    • If you do not include %s, the version number will be automatically appended to your string.

    Default value is v%s.

    // Example 1: Using placeholder
    // Resulting tag: 'release-1.2.3'
    const options1: ChangelogOptions = { tag: 'release-%s' };
    
    // Example 2: No placeholder (appends version)
    // Resulting tag: 'production-1.2.3'
    const options2: ChangelogOptions = { tag: 'production-' };
  4. Configure changelogithub

    main

    You can customize the behavior of changelogithub by providing a configuration file. The tool looks for configuration in the following locations:

    • A file named changelogithub.config.{json,ts,js,mjs,cjs} in the project root.
    • A .changelogithubrc file.
    • A changelogithub field within your package.json.
  5. Install and use @antfu/eslint-config

    main

    To use the default ESLint configuration provided by this package, import the antfu function from @antfu/eslint-config and export it in your eslint.config.js file. By default, calling antfu() without arguments applies the standard configuration settings.

    import antfu from '@antfu/eslint-config'
    
    export default antfu()
  6. Configure changelogithub with ChangelogOptions

    main

    The ChangelogOptions interface defines the configuration available for generating changelogs and creating GitHub releases. It extends the base ChangelogenOptions (from the changelogen package) with specific settings for GitHub integration and release formatting.

    Key configuration categories include:

    • Release Metadata: Control the release name, whether it is a draft, or if it is a prerelease.
    • Formatting: Customize how commits appear using capitalize (boolean), group (boolean or 'multiple'), emoji (boolean), and titles (e.g., custom breakingChanges title).
    • GitHub Integration: Provide a token for authentication, specify a baseUrl or baseUrlApi, and define which repository to release to via releaseRepo.
    • Tagging: Customize the release tag using the tag option. Use %s as a placeholder for the version number (e.g., release-%s). If no %s is provided, the version is appended to the string (default: v%s).
    • Filtering: Use tagFilter to filter tags by name or commitFilterByPaths to restrict commits to specific directories.
    const options: ChangelogOptions = {
      dry: true,
      contributors: true,
      capitalize: true,
      group: 'multiple',
      emoji: true,
      tag: 'v%s',
      titles: {
        breakingChanges: '🚨 Breaking Changes'
      },
      assets: ['dist/bundle.js', 'CHANGELOG.md'],
      commitFilterByPaths: ['packages/core']
    };
  7. Configure tsdown for changelogithub

    main

    The changelogithub project uses tsdown for its build configuration. The configuration defines entry points for the library and CLI, enables declaration file generation, and manages dependency bundling.

    Key configuration options used:

    • entry: An array of file paths serving as the build entry points (e.g., src/index.ts for the library and src/cli.ts for the CLI).
    • dts: A boolean that, when set to true, enables the generation of TypeScript declaration files.
    • exports: A boolean that enables the generation of package exports.
    • deps.onlyBundle: An array of dependency names that should be bundled into the output.
    import { defineConfig } from 'tsdown'
    
    export default defineConfig({
      entry: [
        'src/index.ts',
        'src/cli.ts',
      ],
      dts: true,
      exports: true,
      deps: {
        onlyBundle: [
          '@antfu/utils',
        ],
      },
    })
  8. Preview changelog changes locally

    main

    To see what changes changelogithub would make without actually updating the GitHub release, run the command with the --dry flag. This is useful for verifying the output before committing to a release workflow.

    npx changelogithub --dry
  9. Configure changelogithub using defineConfig()

    main

    Use the defineConfig helper to provide a type-safe configuration object for changelogithub. This is useful for ensuring your configuration adheres to the ChangelogOptions type when used in scripts or configuration files.

    import { defineConfig } from 'changelogithub'
    
    export default defineConfig({
      // your configuration here
    })
  10. Resolve GitHub author logins with resolveAuthors()

    main

    The resolveAuthors function takes an array of Commit objects and attempts to map commit authors to their GitHub login usernames. This is useful for generating release notes that link to user profiles.

    Process:

    1. It filters out bot authors (e.g., [bot], dependabot, (bot)).
    2. It aggregates authors by email to avoid redundant API calls.
    3. For each unique author, it calls resolveAuthorInfo to find their GitHub login via:
      • Searching GitHub users by email.
      • Falling back to looking up the author of the first associated commit if the email search fails.
    4. It returns a sorted list of unique, resolved authors.

    Note: A valid token in options is required for GitHub API searches to work.

    import { resolveAuthors } from './github'
    import type { Commit, ChangelogOptions } from './types'
    
    const commits: Commit[] = [
      // ... your commit data
    ]
    
    const options: ChangelogOptions = {
      token: 'YOUR_GITHUB_TOKEN',
      // ... other options
    }
    
    const authors = await resolveAuthors(commits, options)
  11. Generate changelogs in Markdown format

    main

    The generateMarkdown function is the primary entrypoint for converting a list of commits into a formatted Markdown changelog. It organizes commits into sections based on their type (e.g., features, fixes) and handles breaking changes separately.

    Key behaviors:

    • Breaking Changes: Commits marked as isBreaking are placed in a dedicated section using the title provided in options.titles.breakingChanges.
    • Type Grouping: Commits are grouped by their type according to the mapping defined in options.types.
    • Scope Grouping: If options.group is enabled, commits are grouped by their scope. The logic automatically detects if scope grouping is necessary based on whether any scope contains multiple commits.
    • GitHub Integration: If options.repo and options.baseUrl are provided, it generates a "View changes on GitHub" link at the bottom of the changelog.
    • Gitmoji Support: The output is processed through convert-gitmoji to ensure emojis are correctly rendered in the Markdown output.

    To use this, you must provide an array of Commit objects and a ResolvedChangelogOptions configuration object.

    import { generateMarkdown } from './src/style/markdown'
    
    const commits = [...] // Array of Commit objects
    const options = {
      baseUrl: 'github.com/antfu',
      repo: 'antfu/changelogithub',
      from: 'v14.0.0',
      to: 'v15.0.0',
      capitalize: true,
      emoji: true,
      group: 'multiple', // or true, or false
      scopeMap: { 'core': 'Core Engine' },
      types: {
        feat: { title: 'Features' },
        fix: { title: 'Bug Fixes' }
      },
      titles: {
        breakingChanges: 'Breaking Changes'
      }
    }
    
    const markdown = generateMarkdown(commits, options)
  12. Upload release assets with uploadAssets()

    main

    The uploadAssets function uploads files to an existing GitHub release. It supports both direct file paths and glob patterns.

    Parameters:

    • options: ChangelogOptions containing baseUrlApi, releaseRepo, to, and token.
    • assets: A string (comma-separated paths) or an array of strings (paths or glob patterns).
    • releaseResponse (optional): The response object from a previous sendRelease call. If not provided, the function will attempt to fetch the release details from GitHub using options.to.

    Features:

    • Glob Expansion: Supports patterns like dist/*.zip. If a pattern matches files, they are uploaded; if not, the pattern is treated as a literal path.
    • Automatic URL Construction: Handles the GitHub upload_url replacement for the file name.
    • Content Type: Files are uploaded with application/octet-stream.
    import { uploadAssets } from './github'
    
    // Using glob patterns
    await uploadAssets(
      {
        baseUrlApi: 'api.github.com',
        releaseRepo: 'owner/repo',
        to: 'v1.0.0',
        token: 'YOUR_GITHUB_TOKEN',
      },
      ['dist/*.tar.gz', 'assets/logo.png']
    )