### Changelogen Quick Start Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/index.md This snippet demonstrates the core workflow of Changelogen, including loading configuration, getting git diffs, parsing commits, generating Markdown, bumping versions, and publishing to npm. Ensure you have the 'changelogen' package installed and configured. ```typescript import { loadChangelogConfig, getGitDiff, parseCommits, generateMarkDown, bumpVersion, npmPublish } from 'changelogen'; // Load configuration const config = await loadChangelogConfig(process.cwd()); // Get commits between versions const rawCommits = await getGitDiff('v1.0.0', 'v2.0.0'); const commits = parseCommits(rawCommits, config); // Generate changelog const markdown = await generateMarkDown(commits, config); console.log(markdown); // Bump version const newVersion = await bumpVersion(commits, config); console.log(`Bumped to ${newVersion}`); // Publish to npm await npmPublish(config); ``` -------------------------------- ### package.json Configuration Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/config.md Example of configuring Changelogen within the `package.json` file. Suitable for project-specific settings. ```json { "name": "my-package", "changelog": { "types": { "feat": { "title": "Features" } } } } ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/config.md Example of a changelog configuration using a JSON file. Useful for defining custom types and scope mappings. ```json { "types": { "feat": { "title": "✨ Features", "semver": "minor" }, "fix": { "title": "🐛 Fixes", "semver": "patch" } }, "scopeMap": { "api": "API", "ui": "User Interface" }, "noAuthors": false, "output": "CHANGELOG.md" } ``` -------------------------------- ### Sync GitHub Release Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Demonstrates using `syncGithubRelease` with and without authentication. The example shows how to handle the different statuses ('created', 'updated', 'manual') and access the release ID or manual creation URL. ```typescript import { syncGithubRelease } from 'changelogen'; // With authentication const result = await syncGithubRelease(config, { version: '2.0.0', body: '## Features\n- Feature 1\n- Feature 2' }); if (result.status === 'created') { console.log('Release created:', result.id); } else if (result.status === 'updated') { console.log('Release updated:', result.id); } else { console.log('Manual release:', result.url); // URL: https://github.com/user/repo/releases/new?tag=v2.0.0&title=v2.0.0&body=... } // Without authentication // result.status === 'manual' // result.url contains URL to create release manually in browser ``` -------------------------------- ### TypeScript Configuration Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/config.md Example of a changelog configuration using a TypeScript file with `defineConfig`. Allows for programmatic configuration and type safety. ```typescript import { defineConfig } from 'changelogen'; export default defineConfig({ types: { feat: { title: '🚀 Features', semver: 'minor' } }, excludeAuthors: ['bot@example.com'] }); ``` -------------------------------- ### Update GitHub Release Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Example demonstrating how to update an existing GitHub release by first fetching it using `getGithubReleaseByTag` and then calling `updateGithubRelease` with the retrieved ID and updated body. ```typescript import { updateGithubRelease, getGithubReleaseByTag } from 'changelogen'; const existing = await getGithubReleaseByTag(config, 'v2.0.0'); const updated = await updateGithubRelease(config, existing.id, { tag_name: 'v2.0.0', body: 'Updated changelog body' }); ``` -------------------------------- ### 0.x.y Version Bumping Examples Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/semver.md Illustrates semver bumping for versions starting with 0.x.y, where the second number is treated as the major version. ```typescript // Current: 0.0.5 feat → 0.1.0 (not 1.0.0) fix → 0.0.6 (not 0.1.0) breaking → 0.1.0 (not 1.0.0) ``` -------------------------------- ### 0.0.x Version Bumping Examples Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/semver.md Shows semver bumping for versions starting with 0.0.x, where the third number is treated as the major version. ```typescript // Current: 0.0.5 feat → 0.0.6 (not 0.1.0) fix → 0.0.6 (not 0.0.6) breaking → 0.1.0 ``` -------------------------------- ### Generate GitHub New Release URL Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Example of using `githubNewReleaseURL` to obtain a URL for manual GitHub release creation. The generated URL can be used to open a new release form in the browser with pre-populated details. ```typescript import { githubNewReleaseURL } from 'changelogen'; const url = githubNewReleaseURL(config, { version: '2.0.0', body: 'Release notes' }); // URL: https://github.com/user/repo/releases/new?tag=v2.0.0&title=v2.0.0&body=... ``` -------------------------------- ### Bitbucket Link Formatting Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/markdown.md Examples of how issue, pull request, and commit links are formatted for Bitbucket repositories. ```markdown [#123](https://bitbucket.org/user/repo/issues/123) [#456](https://bitbucket.org/user/repo/pull-requests/456) [abc1234](https://bitbucket.org/user/repo/commit/abc1234) ``` -------------------------------- ### Example Markdown Output Structure Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/markdown.md Illustrates the standard structure of the generated markdown, including version headers, commit details, and contributor information. ```markdown ## [version or range] [compare changes link] ### [Type Title] - **scope:** description ([references]) ### ❤️ Contributors - Author Name ([@username](https://github.com/username)) ``` -------------------------------- ### TypeScript Configuration (changelog.config.ts) Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Configuration for Changelogen using TypeScript. This example demonstrates defining types, scope mapping, and output file using the `defineConfig` helper. ```typescript import { defineConfig } from 'changelogen'; export default defineConfig({ types: { feat: { title: '✨ Features', semver: 'minor' }, fix: { title: '🐛 Fixes', semver: 'patch' }, }, scopeMap: { api: 'API', cli: 'CLI', }, output: 'CHANGELOG.md', noAuthors: false, }); ``` -------------------------------- ### Example Valid Commit: Feature with Co-Authored-By Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Illustrates a valid conventional commit for a new feature, including a scope, description, body, and co-authored-by footer. ```markdown feat(api): add user authentication endpoint This adds OAuth2 support to the API. Fixes #123 Co-Authored-By: Alice ``` -------------------------------- ### Complete Configuration (changelog.config.json) Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md An extensive configuration example for Changelogen in JSON format. It includes type definitions, scope mapping, repository details, output file, author exclusion, and custom templates. ```json { "types": { "feat": { "title": "🚀 Features", "semver": "minor" }, "fix": { "title": "🐛 Bug Fixes", "semver": "patch" }, "docs": { "title": "📚 Documentation", "semver": "patch" }, "chore": { "title": "🔧 Maintenance" } }, "scopeMap": { "api": "API", "cli": "CLI", "ui": "User Interface" }, "repo": "user/my-project", "output": "CHANGELOG.md", "noAuthors": false, "excludeAuthors": ["dependabot"], "publish": { "tag": "latest" }, "templates": { "commitMessage": "chore(release): v{{newVersion}}", "tagMessage": "v{{newVersion}}" } } ``` -------------------------------- ### Resolve GitHub Token Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Example of using `resolveGithubToken` to obtain a GitHub token. If a token is found, it's assigned to the `config.tokens.github` property for subsequent API operations. ```typescript import { resolveGithubToken } from 'changelogen'; const token = await resolveGithubToken(config); if (token) { config.tokens.github = token; } ``` -------------------------------- ### GitLab Link Formatting Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/markdown.md Examples of how issue, merge request, and commit links are formatted for GitLab repositories. ```markdown [#123](https://gitlab.com/user/repo/issues/123) [!456](https://gitlab.com/user/repo/merge_requests/456) [abc1234](https://gitlab.com/user/repo/commit/abc1234) ``` -------------------------------- ### Common Git Commands Integration Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/exec.md Shows examples of using `execCommand` to perform various common git operations like retrieving tags, branches, status, logs, and remote URLs. ```typescript // Get latest tag execCommand('git describe --tags --abbrev=0', cwd); // Get current branch execCommand('git rev-parse --abbrev-ref HEAD', cwd); // Get tag at HEAD execCommand('git tag --points-at HEAD', cwd); // Get git status execCommand('git status --porcelain', cwd); // Get commit log execCommand( 'git --no-pager log "from...to" --pretty="----%n%s|%h|%an|%ae%n%b" --name-status', cwd ); // Get remote URL execCommand('git --work-tree="${cwd}" remote get-url "origin"', cwd); ``` -------------------------------- ### 0.0.x Versioning Behavior Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md For versions starting with '0.0.', the third number is treated as the major version. ```text 0.0.x Versions For versions starting with "0.0.", the third number is treated as the major version. ``` -------------------------------- ### Get Release by Tag Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Retrieves a specific release identified by its tag. ```APIDOC ## GET /repos/{owner}/{repo}/releases/tags/{tag} ### Description Get a specific release by its tag. ### Method GET ### Endpoint /repos/{owner}/{repo}/releases/tags/{tag} ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **tag** (string) - Required - The tag of the release to retrieve. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **release** (object) - The release object corresponding to the tag. #### Response Example (Example response structure not provided in source) ``` -------------------------------- ### .changelogrc (YAML) Configuration Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Configuration for Changelogen using a YAML file (`.changelogrc`). This example shows how to define commit types, scope mapping, and output settings. ```yaml types: feat: title: "Features" semver: "minor" fix: title: "Fixes" semver: "patch" scopeMap: api: "API" cli: "CLI" output: "CHANGELOG.md" noAuthors: false ``` -------------------------------- ### GitHub Link Formatting Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/markdown.md Examples of how issue, pull request, and commit links are formatted for GitHub repositories. ```markdown [#123](https://github.com/user/repo/issues/123) [#456](https://github.com/user/repo/pull/456) [abc1234](https://github.com/user/repo/commit/abc1234) ``` -------------------------------- ### Load Changelog Configuration Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/config.md Loads and resolves changelog configuration from disk, applying overrides and resolving git references. Use this to get a fully configured changelog object. ```typescript import { loadChangelogConfig } from 'changelogen'; const config = await loadChangelogConfig(process.cwd(), { from: 'v1.0.0', to: 'HEAD' }); ``` -------------------------------- ### Conventional Commits Specification Example Source: https://github.com/unjs/changelogen/blob/main/_autodocs/README.md This illustrates the standard format for conventional commits, including type, scope, breaking change indicator, description, and optional body/footers. ```markdown type(scope)!: description Optional body and footers ``` -------------------------------- ### Example Valid Commit: Breaking Change Fix Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Demonstrates a valid conventional commit for a fix that includes a breaking change, indicated by '!' and a BREAKING CHANGE footer. ```markdown fix!: remove deprecated config option BREAKING CHANGE: The `oldConfig` option has been removed. ``` -------------------------------- ### getGitDiff Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Gets all commits between two git references. It takes starting and ending references, and an optional working directory. ```APIDOC ## getGitDiff ### Description Gets all commits between two git references. ### Method `async` ### Signature `getGitDiff(from: string | undefined, to = "HEAD", cwd?: string): Promise` ### Parameters #### Path Parameters - **from** (string | undefined) - Required - Starting commit reference (or undefined for initial commit) - **to** (string) - Optional - Ending commit reference (defaults to "HEAD") - **cwd** (string) - Optional - Working directory ### Returns Promise — Array of parsed raw commits ### Behavior - Uses `git log` with pretty format to extract commits - If `from` is undefined, returns commits up to `to` from the beginning - If `from` is provided, returns commits in the range `from...to` (3-dot range) - Parses commit message, body, author name, author email, and short hash ### Example ```typescript import { getGitDiff } from 'changelogen'; const commits = await getGitDiff('v1.0.0', 'v2.0.0'); console.log(commits.length); // number of commits between versions // Get all commits from initial commit to v2.0.0 const allCommits = await getGitDiff(undefined, 'v2.0.0'); ``` ``` -------------------------------- ### Publishing Workflow with Changelog Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/package.md Illustrates the full release and publish workflow using changelogen. This includes loading configuration, generating a changelog, bumping the version, and publishing to npm. ```typescript import { loadChangelogConfig, bumpVersion, npmPublish } from 'changelogen'; const config = await loadChangelogConfig(process.cwd()); // ... generate changelog and bump version ... // Configure publish options config.publish.tag = 'latest'; // Publish to npm await npmPublish(config); ``` -------------------------------- ### Generate Changelog and Display Source: https://github.com/unjs/changelogen/blob/main/_autodocs/index.md Loads configuration, parses git commits, generates markdown, and prints it to the console. Ensure git history is available. ```typescript const config = await loadChangelogConfig(process.cwd()); const commits = parseCommits( await getGitDiff(config.from, config.to), config ); const markdown = await generateMarkDown(commits, config); console.log(markdown); ``` -------------------------------- ### Create Beta Prerelease Version Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/semver.md Shows how to create a beta prerelease version using the bumpVersion function with the 'prerelease' type and 'beta' preid. ```typescript // Create beta prerelease const beta = await bumpVersion(commits, config, { type: 'prerelease', preid: 'beta' }); // Result: 1.0.1-beta.0 (current version with beta tag) ``` -------------------------------- ### getCurrentGitStatus Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Gets the status of the working directory. It can optionally take a working directory as an argument. ```APIDOC ## getCurrentGitStatus ### Description Gets the status of the working directory. ### Method `async` ### Signature `getCurrentGitStatus(cwd?: string): Promise` ### Parameters #### Path Parameters - **cwd** (string) - Optional - Working directory ### Returns Promise — Porcelain format status output (empty if clean) ### Example ```typescript import { getCurrentGitStatus } from 'changelogen'; const status = await getCurrentGitStatus(); if (status) { console.log('Working directory has uncommitted changes'); } ``` ``` -------------------------------- ### getCurrentGitBranch Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Gets the current git branch name. It can optionally take a working directory as an argument. ```APIDOC ## getCurrentGitBranch ### Description Gets the current git branch name. ### Method `sync` ### Signature `getCurrentGitBranch(cwd?: string): string` ### Parameters #### Path Parameters - **cwd** (string) - Optional - Working directory ### Returns string — Current branch name ### Example ```typescript import { getCurrentGitBranch } from 'changelogen'; const branch = getCurrentGitBranch(); console.log(branch); // "main" ``` ``` -------------------------------- ### Changelogen CLI Basic Usage Source: https://github.com/unjs/changelogen/blob/main/README.md The general command structure for using the changelogen CLI with optional arguments and directory specification. ```sh npx changelogen@latest [...args] [--dir ] ``` -------------------------------- ### getLastGitTag Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Gets the most recent git tag in the repository. It can optionally take a working directory as an argument. ```APIDOC ## getLastGitTag ### Description Gets the most recent git tag in the repository. ### Method `async` ### Signature `getLastGitTag(cwd?: string): Promise` ### Parameters #### Path Parameters - **cwd** (string) - Optional - Working directory (defaults to current directory) ### Returns Promise — Latest git tag or undefined if none exist ### Example ```typescript import { getLastGitTag } from 'changelogen'; const lastTag = await getLastGitTag('/path/to/repo'); console.log(lastTag); // "v1.2.3" ``` ``` -------------------------------- ### Version Bumping Workflow with Changelog Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/package.md Demonstrates a typical version update workflow using changelogen. It loads configuration, fetches git diffs, parses commits, and bumps the version in package.json. ```typescript import { loadChangelogConfig, getGitDiff, parseCommits, bumpVersion } from 'changelogen'; const config = await loadChangelogConfig(process.cwd()); const rawCommits = await getGitDiff('v1.0.0', 'HEAD'); const commits = parseCommits(rawCommits, config); // Bumps version in package.json and updates config.newVersion const newVersion = await bumpVersion(commits, config); if (newVersion) { console.log(`Bumped to ${newVersion}`); } ``` -------------------------------- ### Create Alpha Prerelease Version Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/semver.md Demonstrates creating an alpha prerelease version using the bumpVersion function with the 'preminor' type and 'alpha' preid. ```typescript // Create alpha prerelease const alpha = await bumpVersion(commits, config, { type: 'preminor', preid: 'alpha' }); // Result: 1.1.0-alpha.0, 1.1.0-alpha.1, etc. ``` -------------------------------- ### getGitRemoteURL Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Gets the URL of a git remote. Requires the working directory and optionally takes a remote name. ```APIDOC ## getGitRemoteURL ### Description Gets the URL of a git remote. ### Method `sync` ### Signature `getGitRemoteURL(cwd: string, remote = "origin"): string` ### Parameters #### Path Parameters - **cwd** (string) - Required - Working directory - **remote** (string) - Optional - Remote name (defaults to "origin") ### Returns string — Remote URL (SSH or HTTPS format) ### Example ```typescript import { getGitRemoteURL } from 'changelogen'; const url = getGitRemoteURL('/path/to/repo'); console.log(url); // "https://github.com/user/repo.git" ``` ``` -------------------------------- ### getCurrentGitTag Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Gets the tag that points to the current HEAD commit, if any. It can optionally take a working directory as an argument. ```APIDOC ## getCurrentGitTag ### Description Gets the tag that points to the current HEAD commit, if any. ### Method `sync` ### Signature `getCurrentGitTag(cwd?: string): string` ### Parameters #### Path Parameters - **cwd** (string) - Optional - Working directory ### Returns string — Tag name pointing at HEAD, or empty string ### Example ```typescript import { getCurrentGitTag } from 'changelogen'; const tag = getCurrentGitTag(); console.log(tag); // "v2.0.0" or "" ``` ``` -------------------------------- ### npmPublish Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/package.md Publishes the package to the npm registry. It constructs the npm publish command with configuration options, checks the private field in package.json, adds appropriate flags like `--access public` or `--provenance`, and executes the command in the specified cwd. ```APIDOC ## npmPublish ### Description Publishes the package to npm registry. ### Method ```typescript async function npmPublish(config: ChangelogConfig): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (ChangelogConfig) - Required - Configuration with publish settings ### Request Example ```typescript import { npmPublish } from 'changelogen'; const config = await loadChangelogConfig(process.cwd()); // Configure publish options config.publish.tag = 'next'; config.publish.args = ['--dry-run']; const output = await npmPublish(config); console.log(output); ``` ### Response #### Success Response - **string**: npm publish command output ### Requires - npm CLI installed and in PATH - `.npmrc` or environment variables for authentication (NPM_TOKEN) - Package to be registered on npm registry (for updates) ### Throws If npm publish fails ``` -------------------------------- ### getGithubReleaseByTag Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Gets a specific release by tag name. Retrieves a single GitHub release based on its Git tag. ```APIDOC ## getGithubReleaseByTag ### Description Gets a specific release by tag name. ### Function Signature ```typescript async function getGithubReleaseByTag( config: ResolvedChangelogConfig, tag: string ): Promise ``` ### Parameters #### Path Parameters - **config** (ResolvedChangelogConfig) - Required - Configuration with repo and token - **tag** (string) - Required - Git tag name (e.g., "v1.0.0") ### Returns - **Promise** — GitHub release object ### Example ```typescript import { getGithubReleaseByTag } from 'changelogen'; const release = await getGithubReleaseByTag(config, 'v1.0.0'); console.log(release.body); ``` ### Throws - If release not found or API request fails ``` -------------------------------- ### Minimal Configuration (changelog.config.json) Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md A basic configuration file for Changelogen using JSON. It defines custom commit types and their semantic versioning impact. ```json { "types": { "feat": { "title": "Features", "semver": "minor" }, "fix": { "title": "Fixes", "semver": "patch" } } } ``` -------------------------------- ### Set GitHub Token via Environment Variable Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Use this method to authenticate with GitHub by setting the GITHUB_TOKEN environment variable before running the changelogen command. ```bash export GITHUB_TOKEN="ghp_..." changelogen gh release ``` -------------------------------- ### getCurrentGitRef Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Gets the current git reference (tag if on a tagged commit, otherwise branch name). It can optionally take a working directory as an argument. ```APIDOC ## getCurrentGitRef ### Description Gets the current git reference (tag if on a tagged commit, otherwise branch name). ### Method `sync` ### Signature `getCurrentGitRef(cwd?: string): string` ### Parameters #### Path Parameters - **cwd** (string) - Optional - Working directory ### Returns string — Current git reference ### Example ```typescript import { getCurrentGitRef } from 'changelogen'; const ref = getCurrentGitRef(); console.log(ref); // "v2.0.0" or "main" ``` ``` -------------------------------- ### Parse Repository URL to Config Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/repo.md Parses various repository URL formats (HTTPS, SSH, shorthand) and shorthands into a structured configuration object. Assumes GitHub for shorthand inputs without a domain. Returns partial configuration for invalid inputs. ```typescript import { getRepoConfig } from 'changelogen'; // HTTPS URL getRepoConfig('https://github.com/user/repo.git'); // Returns: { provider: 'github', repo: 'user/repo', domain: 'github.com' } // SSH URL getRepoConfig('git@github.com:user/repo.git'); // Returns: { provider: 'github', repo: 'user/repo', domain: 'github.com' } // Shorthand getRepoConfig('user/repo'); // Returns: { provider: 'github', repo: 'user/repo', domain: 'github.com' } // GitLab getRepoConfig('https://gitlab.com/user/repo'); // Returns: { provider: 'gitlab', repo: 'user/repo', domain: 'gitlab.com' } // Bitbucket getRepoConfig('https://bitbucket.org/user/repo.git'); // Returns: { provider: 'bitbucket', repo: 'user/repo', domain: 'bitbucket.org' } // Invalid URL returns partial config getRepoConfig('invalid'); // Returns: { provider: undefined, repo: undefined, domain: undefined } ``` -------------------------------- ### Configuration APIs Source: https://github.com/unjs/changelogen/blob/main/_autodocs/index.md APIs for loading and resolving changelog configurations. ```APIDOC ## Configuration APIs ### Description Provides functions to load and resolve changelog configurations. ### Exports - `ChangelogConfig` - `ResolvedChangelogConfig` - `loadChangelogConfig` - `resolveChangelogConfig` ``` -------------------------------- ### Get Current Git Branch Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Retrieves the name of the current git branch. This is useful for identifying the active development line. The working directory can be specified. ```typescript import { getCurrentGitBranch } from 'changelogen'; const branch = getCurrentGitBranch(); console.log(branch); // "main" ``` -------------------------------- ### Get GitHub Repository Changelog Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Fetches the raw CHANGELOG.md file from the default branch of a GitHub repository. This function does not require authentication and fetches from raw.githubusercontent.com. ```typescript import { getGithubChangelog, parseChangelogMarkdown } from 'changelogen'; const markdown = await getGithubChangelog(config); const { releases } = parseChangelogMarkdown(markdown); ``` -------------------------------- ### Configure Repository Information Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Specify repository details like domain, owner/name, and provider. This can also be provided as a string or auto-detected. ```typescript { domain?: string; // github.com, gitlab.com, bitbucket.org, or custom repo?: string; // owner/name format provider?: RepoProvider; // "github" | "gitlab" | "bitbucket" token?: string; // (Deprecated, use tokens instead) } ``` -------------------------------- ### execCommand Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/exec.md Executes a shell command synchronously and returns its trimmed output. Throws an error if the command fails. ```APIDOC ## execCommand ### Description Executes a shell command synchronously in the specified directory and returns the trimmed standard output. ### Signature ```typescript function execCommand(cmd: string, cwd?: string): string ``` ### Parameters #### Path Parameters - **cmd** (string) - Required - Shell command to execute - **cwd** (string) - Optional - Working directory for command execution ### Returns - **string** - Trimmed command output (stdout) ### Behavior - Executes command synchronously using Node.js `child_process.execSync`. - Uses UTF-8 encoding. - Trims whitespace from output. - Inherits current process environment. - Throws if command exits with a non-zero status code. ### Example ```typescript import { execCommand } from 'changelogen'; // Get latest git tag const tag = execCommand('git describe --tags --abbrev=0', '/path/to/repo'); console.log(tag); // "v1.2.3" // Get current branch const branch = execCommand('git rev-parse --abbrev-ref HEAD'); console.log(branch); // "main" // List files const files = execCommand('ls -la /path/to/dir'); console.log(files); ``` ### Output Trimming Example ```typescript const output = execCommand('echo " hello "'); console.log(output); // "hello" (whitespace trimmed) ``` ### Error Handling Example ```typescript try { execCommand('git tag --nonexistent-flag'); } catch (error) { console.error('Command failed'); } ``` ``` -------------------------------- ### Authenticate GitHub CLI Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Log in using the GitHub CLI; Changelogen will automatically use the credentials stored in `~/.config/gh/hosts.yml`. ```bash gh auth login # Automatically uses ~/.config/gh/hosts.yml ``` -------------------------------- ### Get Current Git Status Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Retrieves the status of the working directory in porcelain format. An empty string indicates a clean working directory. This is an asynchronous operation. ```typescript import { getCurrentGitStatus } from 'changelogen'; const status = await getCurrentGitStatus(); if (status) { console.log('Working directory has uncommitted changes'); } ``` -------------------------------- ### Sync Release to GitHub Source: https://github.com/unjs/changelogen/blob/main/_autodocs/index.md Parses the CHANGELOG.md file and syncs each release entry to GitHub. Ensure CHANGELOG.md exists and is correctly formatted. ```typescript const config = await loadChangelogConfig(process.cwd()); const { releases } = parseChangelogMarkdown( readFileSync('CHANGELOG.md', 'utf-8') ); for (const release of releases) { const result = await syncGithubRelease(config, release); console.log(`${release.version}: ${result.status}`); } ``` -------------------------------- ### Get Git Remote URL Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Retrieves the URL of a specified git remote, defaulting to 'origin'. Requires the working directory of the repository. The URL can be in SSH or HTTPS format. ```typescript import { getGitRemoteURL } from 'changelogen'; const url = getGitRemoteURL('/path/to/repo'); console.log(url); // "https://github.com/user/repo.git" ``` -------------------------------- ### listGithubReleases Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Lists all releases for a repository. Fetches releases from GitHub API with pagination (per_page=100). Requires valid GitHub token in config.tokens.github. Only works for GitHub repositories. ```APIDOC ## listGithubReleases ### Description Lists all releases for a repository. ### Function Signature ```typescript async function listGithubReleases( config: ResolvedChangelogConfig ): Promise ``` ### Parameters #### Path Parameters - **config** (ResolvedChangelogConfig) - Required - Configuration with repo and token ### Returns - **Promise** — Array of GitHub releases ### Behavior - Fetches releases from GitHub API with pagination (per_page=100) - Requires valid GitHub token in config.tokens.github - Only works for GitHub repositories ### Example ```typescript import { listGithubReleases, loadChangelogConfig } from 'changelogen'; const config = await loadChangelogConfig(process.cwd()); const releases = await listGithubReleases(config); console.log(releases.map(r => r.tag_name)); // Output: ["v2.0.0", "v1.5.0", "v1.0.0"] ``` ### Throws - If API request fails or repo is not GitHub ``` -------------------------------- ### Get Specific GitHub Release by Tag Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Retrieves a specific GitHub release using its tag name. Throws an error if the release is not found or if the API request fails. ```typescript import { getGithubReleaseByTag } from 'changelogen'; const release = await getGithubReleaseByTag(config, 'v1.0.0'); console.log(release.body); ``` -------------------------------- ### loadChangelogConfig Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/config.md Loads and resolves changelog configuration from disk, applying overrides and resolving git references. ```APIDOC ## loadChangelogConfig ### Description Loads and resolves changelog configuration from disk. ### Signature ```typescript async function loadChangelogConfig(cwd: string, overrides?: Partial): Promise ``` ### Parameters #### Path Parameters - **cwd** (string) - Required - Directory to load configuration from - **overrides** (Partial) - Optional - Configuration overrides to apply ### Returns Promise — Fully resolved configuration with defaults applied ### Behavior - Loads .env files from the cwd directory - Searches for configuration in: `changelog.config.{ts,js,mjs,cjs}`, `changelog.config.json`, `.changelogrc`, or `package.json` changelog field - Applies provided overrides - Resolves `from` and `to` from git if not specified - Resolves output file path relative to cwd - Resolves repository configuration from package.json or git remote ### Example ```typescript import { loadChangelogConfig } from 'changelogen'; const config = await loadChangelogConfig(process.cwd(), { from: 'v1.0.0', to: 'HEAD' }); ``` ### Throws If configuration loading fails or git operations fail ``` -------------------------------- ### 0.x.y Versioning Behavior Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md For versions starting with '0.', the second number is treated as the major version. A major change increments this number, while a minor change increments the third number. ```text 0.1.0 + major change → 0.2.0 (not 1.0.0) 0.1.0 + minor change → 0.1.1 (not 0.2.0) ``` -------------------------------- ### Specify Working Directory for Command Execution Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/exec.md Demonstrates how to execute commands in a specific directory using the `cwd` parameter, and shows that it defaults to the current process directory if omitted. ```typescript // Uses specified directory execCommand('pwd', '/some/directory'); // Output: /some/directory // Uses current process directory if not specified execCommand('pwd'); // Output: current working directory ``` -------------------------------- ### Get Current Git Reference Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Retrieves the current git reference, which is either the tag name if HEAD is on a tagged commit, or the branch name otherwise. The working directory can be specified. ```typescript import { getCurrentGitRef } from 'changelogen'; const ref = getCurrentGitRef(); console.log(ref); // "v2.0.0" or "main" ``` -------------------------------- ### Bump Version and Create Release Source: https://github.com/unjs/changelogen/blob/main/_autodocs/index.md Generates a changelog, bumps the version, writes the changelog to a file, and creates a git commit and tag. Requires git commands to be executable. ```typescript const config = await loadChangelogConfig(process.cwd()); const commits = parseCommits( await getGitDiff(config.from, config.to), config ); // Bump version const newVersion = await bumpVersion(commits, config); // Generate and write changelog const markdown = await generateMarkDown(commits, config); await writeFile('CHANGELOG.md', markdown); // Create git commit and tag execCommand(`git add package.json CHANGELOG.md`, config.cwd); execCommand(`git commit -m "chore(release): v${newVersion}"`, config.cwd); execCommand(`git tag -a v${newVersion} -m "v${newVersion}"`, config.cwd); ``` -------------------------------- ### Changelogen Module Map Source: https://github.com/unjs/changelogen/blob/main/_autodocs/index.md Overview of the internal module structure of the Changelogen project. ```text changelogen/ ├── config.ts ← Configuration loading ├── git.ts ← Git operations and commit parsing ├── markdown.ts ← Changelog generation ├── semver.ts ← Version bumping ├── repo.ts ← Repository detection and linking ├── github.ts ← GitHub release management ├── package.ts ← package.json management ├── exec.ts ← Command execution ├── commands/ │ ├── default.ts ← Main CLI command (generate changelog, bump, release) │ └── github.ts ← GitHub release sync command └── index.ts ← Main entry point (exports all public APIs) ``` -------------------------------- ### Get Current Git Tag Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Retrieves the tag that points to the current HEAD commit, if one exists. Returns an empty string if HEAD is not tagged. The working directory can be specified. ```typescript import { getCurrentGitTag } from 'changelogen'; const tag = getCurrentGitTag(); console.log(tag); // "v2.0.0" or "" ``` -------------------------------- ### Get Git Diff Commits Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Retrieves all commits between two git references. It can fetch commits from the initial commit up to a specified reference, or within a range between two references. This is an asynchronous operation. ```typescript import { getGitDiff } from 'changelogen'; const commits = await getGitDiff('v1.0.0', 'v2.0.0'); console.log(commits.length); // number of commits between versions // Get all commits from initial commit to v2.0.0 const allCommits = await getGitDiff(undefined, 'v2.0.0'); ``` -------------------------------- ### Configure GitHub Token in Configuration File Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Store your GitHub token within a JSON configuration file under the 'tokens.github' key. ```json { "tokens": { "github": "ghp_..." } } ``` -------------------------------- ### Get Last Git Tag Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/git.md Retrieves the most recent git tag in the repository. Useful for determining the latest release version. Specify a working directory if not running in the repo's root. ```typescript import { getLastGitTag } from 'changelogen'; const lastTag = await getLastGitTag('/path/to/repo'); console.log(lastTag); // "v1.2.3" ``` -------------------------------- ### Generate Changelog Source: https://github.com/unjs/changelogen/blob/main/README.md Generates a changelog in Markdown format and displays it in the console. This is the most basic usage. ```sh npx changelogen@latest ``` -------------------------------- ### Rename npm package Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/package.md Renames the npm package in package.json. If the new name starts with a hyphen, it's appended to the current package name. Skips if the package already has the given name. Logs the operation and updates package.json on disk. ```typescript import { renamePackage } from 'changelogen'; const config = await loadChangelogConfig(process.cwd()); // Rename to specific name await renamePackage(config, 'my-new-package'); // Add suffix to existing name await renamePackage(config, '-canary'); ``` -------------------------------- ### syncGithubRelease Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Creates or updates a GitHub release based on provided version and body. It handles authentication and provides a URL for manual creation if no token is available. ```APIDOC ## syncGithubRelease ### Description Creates or updates a GitHub release from changelog data. ### Method ```typescript async function syncGithubRelease(config: ResolvedChangelogConfig, release: { version: string; body: string }): Promise<{ status: "created" | "updated" | "manual"; id?: string; url?: string; error?: any; }> ``` ### Parameters #### Path Parameters - **config** (ResolvedChangelogConfig) - Required - Configuration with repo and token - **release** (object) - Required - Release data with version and body - **release.version** (string) - Required - Version number (without "v" prefix) - **release.body** (string) - Required - Release description markdown ### Response #### Success Response - **status** (string) - Indicates the outcome: "created", "updated", or "manual". - **id** (string) - The ID of the created or updated release (if applicable). - **url** (string) - The URL for manual release creation (if applicable). - **error** (any) - An error object if an API error occurred during sync (if applicable). ### Behavior - Checks if a release already exists for the given version tag. - If an authentication token is available, it creates or updates the release via the GitHub API. - If no authentication token is found, it returns a URL for manual creation in the browser. - Transforms the release body by removing markdown link formatting: `([@user](url))` becomes `(@user)`. ### Request Example ```typescript import { syncGithubRelease } from 'changelogen'; // With authentication const result = await syncGithubRelease(config, { version: '2.0.0', body: '## Features\n- Feature 1\n- Feature 2' }); if (result.status === 'created') { console.log('Release created:', result.id); } else if (result.status === 'updated') { console.log('Release updated:', result.id); } else { console.log('Manual release:', result.url); } // Without authentication // result.status === 'manual' // result.url contains URL to create release manually in browser ``` ``` -------------------------------- ### Configure Authentication Tokens Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Provide API tokens for different Git providers to authenticate requests, such as for fetching commit history or creating releases. ```json { "tokens": { "github": "string", "gitlab": "string", "bitbucket": "string" } } ``` -------------------------------- ### Configure Publishing Options Source: https://github.com/unjs/changelogen/blob/main/_autodocs/configuration.md Customize npm publishing behavior, including the distribution tag, package privacy, and additional arguments for the `npm publish` command. ```json { "publish": { "tag": "next", "args": ["--dry-run"] } } ``` -------------------------------- ### Publish package to npm Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/package.md Publishes the package to the npm registry. Constructs the npm publish command with configuration options, checks the private field, adds `--access public` if the package is public, and includes a distribution tag. Adds `--provenance` in CI environments. Executes npm publish in the config.cwd directory and returns the command output. Requires npm CLI, authentication, and a registered package. ```typescript import { npmPublish } from 'changelogen'; const config = await loadChangelogConfig(process.cwd()); // Configure publish options config.publish.tag = 'next'; config.publish.args = ['--dry-run']; const output = await npmPublish(config); console.log(output); ``` -------------------------------- ### Generate Changelog Source: https://github.com/unjs/changelogen/blob/main/_autodocs/index.md Use this command to generate a changelog. It supports options for specifying commit ranges, output files, and controlling version bumping and release creation. ```bash changelogen [options] ``` -------------------------------- ### createGithubRelease Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Creates a new GitHub release. Allows the creation of a new release on GitHub with specified details like tag name, title, and body. ```APIDOC ## createGithubRelease ### Description Creates a new GitHub release. ### Function Signature ```typescript async function createGithubRelease( config: ResolvedChangelogConfig, body: GithubRelease ): Promise ``` ### Parameters #### Path Parameters - **config** (ResolvedChangelogConfig) - Required - Configuration with repo and token - **body** (GithubRelease) - Required - Release object with tag_name and optional name/body ### Returns - **Promise** — Created release with API response ### Example ```typescript import { createGithubRelease } from 'changelogen'; const release = await createGithubRelease(config, { tag_name: 'v2.0.0', name: 'Version 2.0.0', body: '## Features\n- New feature 1\n- New feature 2', draft: false, prerelease: false }); console.log(release.id); // GitHub API release ID ``` ### Throws - If GitHub token is missing or API request fails ``` -------------------------------- ### Create Release Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/github.md Creates a new release for the repository. ```APIDOC ## POST /repos/{owner}/{repo}/releases ### Description Create a new release for the repository. ### Method POST ### Endpoint /repos/{owner}/{repo}/releases ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. #### Request Body (Request body structure not provided in source) ### Request Example (Example request body not provided in source) ### Response #### Success Response (200) - **release** (object) - The newly created release object. #### Response Example (Example response structure not provided in source) ``` -------------------------------- ### writePackageJSON Source: https://github.com/unjs/changelogen/blob/main/_autodocs/api-reference/package.md Writes the package.json file to disk. It resolves the package.json path relative to the provided configuration's cwd, writes the JSON to disk with proper formatting, and preserves file permissions. ```APIDOC ## writePackageJSON ### Description Writes the package.json file to disk. ### Method ```typescript function writePackageJSON( config: ChangelogConfig, pkg: PackageJson ): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (ChangelogConfig) - Required - Configuration containing cwd path - **pkg** (PackageJson) - Required - Package.json object to write ### Request Example ```typescript import { readPackageJSON, writePackageJSON } from 'changelogen'; const config = await loadChangelogConfig(process.cwd()); const pkg = await readPackageJSON(config); pkg.version = '2.0.0'; await writePackageJSON(config, pkg); ``` ### Response #### Success Response Resolves when write is complete ### Throws If write fails (permissions, disk full, etc.) ```