### Install Husky and Setup Commit Message Hook (pnpm) Source: https://commitlint.js.org/guides/local-setup Installs Husky via pnpm and configures the 'commit-msg' hook to run commitlint. This provides an alternative installation path for managing dependencies. ```bash pnpm install --save-dev husky # husky@v9 npx husky init # husky@v8 or lower npx husky install # Add commit message linting to commit-msg hook echo "npx --no -- commitlint --edit $1" > .husky/commit-msg # Windows users should use ` to escape dollar signs echo "npx --no -- commitlint --edit `$1`" > .husky/commit-msg ``` -------------------------------- ### Install Husky and Setup Commit Message Hook (npm) Source: https://commitlint.js.org/guides/local-setup Installs Husky as a dev dependency and sets up the 'commit-msg' hook to run commitlint. This is the recommended approach for managing git hooks. Ensure UTF-8 encoding for Windows users. ```bash npm install --save-dev husky # husky@v9 npx husky init # husky@v8 or lower npx husky install # Add commit message linting to commit-msg hook echo "npx --no -- commitlint --edit $1" > .husky/commit-msg # Windows users should use ` to escape dollar signs echo "npx --no -- commitlint --edit `$1`" > .husky/commit-msg ``` -------------------------------- ### Install Husky and Setup Commit Message Hook (yarn) Source: https://commitlint.js.org/guides/local-setup Installs Husky using yarn and configures the 'commit-msg' hook to execute commitlint. This method is an alternative to npm for package management. ```bash yarn add --dev husky # husky@v9 npx husky init # husky@v8 or lower npx husky install # Add commit message linting to commit-msg hook echo "npx --no -- commitlint --edit $1" > .husky/commit-msg # Windows users should use ` to escape dollar signs echo "npx --no -- commitlint --edit `$1`" > .husky/commit-msg ``` -------------------------------- ### Install Commitlint CLI, Conventional Config, and Prompt CLI Source: https://commitlint.js.org/guides/use-prompt Installs the necessary @commitlint packages for command-line interface, conventional commit configuration, and prompt-based commit message authoring. Supports npm, yarn, pnpm, bun, and deno. ```shell npm install --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js ``` ```shell yarn add --dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js ``` ```shell pnpm add --save-dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js ``` ```shell bun add --dev @commitlint/cli @commitlint/config-conventional @commitlint/prompt-cli echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js ``` ```shell deno add --dev npm:@commitlint/cli npm:@commitlint/config-conventional npm:@commitlint/prompt-cli echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js ``` -------------------------------- ### Setup Commitlint Script in package.json Source: https://commitlint.js.org/guides/local-setup Creates a 'commitlint' script in 'package.json' and configures the 'commit-msg' hook to use this script. This offers an alternative to directly calling npx commitlint. ```bash npm pkg set scripts.commitlint="commitlint --edit" echo "npm run commitlint ${1}" > .husky/commit-msg ``` -------------------------------- ### Install Commitlint and Conventional Config Source: https://commitlint.js.org/support/upgrade Installs the commitlint CLI and the conventional commit configuration package. This is a common first step when migrating from 'validate-commit-msg' or setting up a new project. ```shell npm install --save-dev @commitlint/cli @commitlint/config-conventional ``` -------------------------------- ### Install CommitLint CLI and Conventional Config with bun Source: https://commitlint.js.org/guides/getting-started Installs the CommitLint CLI and the conventional configuration package as a development dependency using bun. ```sh bun add -d @commitlint/cli @commitlint/config-conventional ``` -------------------------------- ### GitLab CI: Pre-built Container for Linting Source: https://commitlint.js.org/guides/ci-setup This GitLab CI configuration utilizes a pre-built `commitlint/commitlint` Docker image for linting merge request commits. It simplifies setup by providing a container with commitlint pre-installed and configured. ```yaml stages: ["lint", "build", "test"] lint:commit: image: name: registry.hub.docker.com/commitlint/commitlint:latest entrypoint: [""] stage: lint script: # Uncomment the next line if you are extending the @commitlint/config-nx-scopes in your commitlint configuration #- npm i -g nx@$(node -pe "require('./package.json').devDependencies.nx") - commitlint --from ${CI_MERGE_REQUEST_DIFF_BASE_SHA} --to ${CI_COMMIT_SHA} ``` -------------------------------- ### Initialize package.json with npm, yarn, pnpm, or bun Source: https://commitlint.js.org/guides/use-prompt Initializes a package.json file for managing project dependencies and scripts. This command is available for npm, yarn, pnpm, and bun. ```shell npm init ``` ```shell yarn init ``` ```shell pnpm init ``` ```shell bun init ``` -------------------------------- ### Install CommitLint CLI and Conventional Config with deno Source: https://commitlint.js.org/guides/getting-started Installs the CommitLint CLI and the conventional configuration package as a development dependency using deno. ```sh deno add -D npm:@commitlint/cli npm:@commitlint/config-conventional ``` -------------------------------- ### Initialize Git Repository Source: https://commitlint.js.org/guides/use-prompt Initializes a new Git repository in the current directory. This is a prerequisite for using version control and commitlint. ```shell git init ``` -------------------------------- ### Install @commitlint/lint Source: https://commitlint.js.org/api/lint Installs the @commitlint/lint package using npm. This is the first step to using the linting functionality. ```sh npm install --save @commitlint/lint ``` -------------------------------- ### Install Conventional Changelog Lint Source: https://commitlint.js.org/support/upgrade Installs the `conventional-changelog-lint` package, which was a precursor to commitlint. This command is typically used when upgrading from older versions of commitlint or related tools. ```shell npm install --save-dev conventional-changelog-lint@latest ``` -------------------------------- ### Test Commitlint Simple Usage (CLI) Source: https://commitlint.js.org/guides/local-setup Tests the commitlint CLI by checking the last commit against the configured rules. The --verbose flag provides output even if the commit is valid. ```bash npx commitlint --from HEAD~1 --to HEAD --verbose ``` ```bash yarn commitlint --from HEAD~1 --to HEAD --verbose ``` ```bash pnpm commitlint --from HEAD~1 --to HEAD --verbose ``` ```bash bun commitlint --from HEAD~1 --to HEAD --verbose ``` ```bash deno task --eval commitlint --from HEAD~1 --to HEAD --verbose ``` -------------------------------- ### Install CommitLint CLI and Conventional Config with npm Source: https://commitlint.js.org/guides/getting-started Installs the CommitLint CLI and the conventional configuration package as a development dependency using npm. ```sh npm install -D @commitlint/cli @commitlint/config-conventional ``` -------------------------------- ### Migrate from conventional-changelog-lint to Commitlint Source: https://commitlint.js.org/support/upgrade Provides commands to migrate from `conventional-changelog-lint` to `commitlint`. This involves removing the old package, installing the new one, and renaming configuration files. ```shell npm remove --save-dev conventional-changelog-lint npm install --save commitlint mv .conventional-changelog-lintrc commitlint.config.js ``` -------------------------------- ### Travis CI: Lint Commit Messages Source: https://commitlint.js.org/guides/ci-setup This configuration for Travis CI integrates commitlint to validate commit messages. It first installs the `@commitlint/travis-cli` package and then uses the `commitlint-travis` script in the `script` section of the `.travis.yml` file. ```bash # Install and configure if needed npm install --save-dev @commitlint/travis-cli ``` ```yml # travis.yml language: node_js node_js: - node script: - commitlint-travis ``` -------------------------------- ### Example Commit Log with Emojis (Text) Source: https://commitlint.js.org/reference/examples Demonstrates the expected format of commit messages after applying the configuration to include emojis in the commit header. This output can be verified using `git log`. ```text ⚙️ ci(scope): short 🛠 build(scope): short 🐛 fix(scope): short ✨ feat(scope): short ``` -------------------------------- ### Install CommitLint CLI and Conventional Config with pnpm Source: https://commitlint.js.org/guides/getting-started Installs the CommitLint CLI and the conventional configuration package as a development dependency using pnpm. ```sh pnpm add -D @commitlint/cli @commitlint/config-conventional ``` -------------------------------- ### Validate Commits with CommitLint in BitBucket Pipelines Source: https://commitlint.js.org/guides/ci-setup This snippet configures a BitBucket pipeline to install and run CommitLint for validating commit messages in pull requests. It installs the necessary CommitLint packages and then executes the commitlint command using BitBucket's default variables to specify the commit range. Note that BitBucket's default git clone depth is 20 commits. ```yaml image: node:18 pipelines: pull-requests: default: - step: name: Lint commit messages script: - npm install --save-dev @commitlint/config-conventional @commitlint/cli - npx commitlint --from $BITBUCKET_COMMIT~$(git rev-list --count $BITBUCKET_BRANCH ^origin/$BITBUCKET_PR_DESTINATION_BRANCH) --to $BITBUCKET_COMMIT --verbose ``` -------------------------------- ### JavaScript Configuration Object Example for Commitlint Source: https://commitlint.js.org/reference/configuration An example of a commitlint configuration object in JavaScript. This configuration includes extending conventional configurations, setting a parser preset, defining rules, and customizing ignore patterns and help URLs. It demonstrates how to resolve and load configurations from node_modules. ```javascript const Configuration = { /* * Resolve and load @commitlint/config-conventional from node_modules. * Referenced packages must be installed */ extends: ["@commitlint/config-conventional"], /* * Resolve and load conventional-changelog-atom from node_modules. * Referenced packages must be installed */ parserPreset: "conventional-changelog-atom", /* * Resolve and load @commitlint/format from node_modules. * Referenced package must be installed */ formatter: "@commitlint/format", /* * Any rules defined here will override rules from @commitlint/config-conventional */ rules: { "type-enum": [2, "always", ["foo"]], }, /* * Array of functions that return true if commitlint should ignore the given message. * Given array is merged with predefined functions, which consist of matchers like: * * - 'Merge pull request', 'Merge X into Y' or 'Merge branch X' * - 'Revert X' * - 'v1.2.3' (ie semver matcher) * - 'Automatic merge X' or 'Auto-merged X into Y' * * To see full list, check https://github.com/conventional-changelog/commitlint/blob/master/%40commitlint/is-ignored/src/defaults.ts. * To disable those ignores and run rules always, set `defaultIgnores: false` as shown below. */ ignores: [(commit) => commit === ""], /* * Whether commitlint uses the default ignore rules, see the description above. */ defaultIgnores: true, /* * Custom URL to show upon failure */ helpUrl: "https://github.com/conventional-changelog/commitlint/#what-is-commitlint", /* * Custom prompt configs */ prompt: { messages: {}, questions: { type: { description: "please input type:", }, }, }, }; export default Configuration; ``` -------------------------------- ### Configure CommitLint with Conventional Config Source: https://commitlint.js.org/guides/getting-started Creates a commitlint.config.js file to configure CommitLint to use the conventional configuration. This is a common setup for enforcing conventional commit message standards. ```sh echo "export default { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js ``` -------------------------------- ### Install CommitLint CLI and Conventional Config with yarn Source: https://commitlint.js.org/guides/getting-started Installs the CommitLint CLI and the conventional configuration package as a development dependency using yarn. ```sh yarn add -D @commitlint/cli @commitlint/config-conventional ``` -------------------------------- ### Validate Commits with CommitLint in Azure Pipelines Source: https://commitlint.js.org/guides/ci-setup This configuration sets up an Azure Pipeline to validate commit messages using CommitLint. It includes steps to check out the repository with full history, install Node.js, print versions of relevant tools, install CommitLint, and then validate commits. It handles both regular builds and pull requests, using the Azure DevOps API to fetch PR commit details for validation. ```yaml steps: - checkout: self fetchDepth: 0 - task: NodeTool@0 inputs: versionSpec: "20.x" checkLatest: true - script: | git --version node --version npm --version npx commitlint --version displayName: Print versions - script: | npm install conventional-changelog-conventionalcommits npm install commitlint@latest displayName: Install commitlint - script: npx commitlint --last --verbose condition: ne(variables['Build.Reason'], 'PullRequest') displayName: Validate current commit (last commit) with commitlint - script: | echo "Accessing Azure DevOps API..." response=$(curl -s -X GET -H "Cache-Control: no-cache" -H "Authorization: Bearer $(System.AccessToken)" $(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.Name)/pullRequests/$(System.PullRequest.PullRequestId)/commits?api-version=6.0) numberOfCommits=$(echo "$response" | jq -r '.count') echo "$numberOfCommits commits to check" npx commitlint --from $(System.PullRequest.SourceCommitId)~${numberOfCommits} --to $(System.PullRequest.SourceCommitId) --verbose condition: eq(variables['Build.Reason'], 'PullRequest') displayName: Validate PR commits with commitlint ``` -------------------------------- ### Install @commitlint/load Source: https://commitlint.js.org/api/load Installs the @commitlint/load package as a project dependency using npm. ```shell npm install --save @commitlint/load ``` -------------------------------- ### CircleCI: Lint Commit Message Source: https://commitlint.js.org/guides/ci-setup This CircleCI configuration validates the last commit message. It uses a Node.js Docker image, checks out the code, installs dependencies, and then defines an environment variable with the latest commit's message before linting it with `npx commitlint`. ```yml version: 2.1 executors: my-executor: docker: - image: cimg/node:current working_directory: ~/project jobs: setup: executor: my-executor steps: - checkout - restore_cache: key: lock-{{ checksum "package-lock.json" }} - run: name: Install dependencies command: npm install - save_cache: key: lock-{{ checksum "package-lock.json" }} paths: - node_modules - persist_to_workspace: root: ~/project paths: - node_modules lint_commit_message: executor: my-executor steps: - checkout - attach_workspace: at: ~/project - run: name: Define environment variable with latest commit's message command: | echo 'export COMMIT_MESSAGE=$(git log -1 --pretty=format:"%s")' >> $BASH_ENV source $BASH_ENV - run: name: Lint commit message command: echo "$COMMIT_MESSAGE" | npx commitlint workflows: version: 2.1 commit: jobs: - setup - lint_commit_message: requires: - setup ``` -------------------------------- ### Test Commitlint Hook Failure Source: https://commitlint.js.org/guides/local-setup Demonstrates testing the commitlint hook by attempting to commit a message that violates the configured rules. This shows the expected error output when linting fails. ```bash git commit -m "foo: this will fail" # husky > commit-msg No staged files match any of provided globs. ⧗ input: foo: this will commit ✖ type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test] [type-enum] ✖ found 1 problems, 0 warnings ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint husky - commit-msg script failed (code 1) ``` -------------------------------- ### Install Husky for Git Hooks Source: https://commitlint.js.org/support/upgrade Installs the husky package as a dev dependency. Husky is a tool that helps manage Git hooks, allowing you to automate tasks like running commitlint checks before a commit is finalized. ```shell npm install --save-dev husky ``` -------------------------------- ### Test Commitlint Prompt with npm, yarn, pnpm, bun, or deno Source: https://commitlint.js.org/guides/use-prompt Executes the commitlint prompt to author a commit message after staging changes. This demonstrates the usage of the 'commit' script configured in package.json, supporting various package managers. ```shell git add . npm run commit ``` ```shell git add . yarn commit ``` ```shell git add . pnpm commit ``` ```shell git add . bun commit ``` ```shell git add . deno task commit ``` -------------------------------- ### Install @commitlint/read Source: https://commitlint.js.org/api/read Installs the @commitlint/read package using npm. This is the first step to using the package in your project. ```shell npm install --save @commitlint/read ``` -------------------------------- ### Test Commitlint Hook Success Source: https://commitlint.js.org/guides/local-setup Shows the expected output when a commit message passes the commitlint rules. If the --verbose flag is not used, commitlint will not output anything on success. ```bash git commit -m "chore: lint on commitmsg" # husky > pre-commit No staged files match any of provided globs. # husky > commit-msg ``` -------------------------------- ### Install @commitlint/format using npm Source: https://commitlint.js.org/api/format Installs the @commitlint/format package as a project dependency using npm. ```sh npm install --save @commitlint/format ``` -------------------------------- ### Read git history and lint commits Source: https://commitlint.js.org/api/lint This example demonstrates reading commit history using `@commitlint/read` and then linting each commit individually using the `lint` function with a predefined set of rules. ```js import lint from "@commitlint/lint"; import read from "@commitlint/read"; const RULES = { "type-enum": [2, "always", ["foo"]], }; const commits = await read({ to: "HEAD", from: "HEAD~2" }); console.info(commits.map((commit) => lint(commit, RULES))); ``` -------------------------------- ### TypeScript Configuration Example for Commitlint Source: https://commitlint.js.org/reference/configuration An example of a commitlint configuration written in TypeScript. It utilizes types from '@commitlint/types' for better type safety and demonstrates how to import and use `RuleConfigSeverity`. This configuration extends conventional settings and defines custom rules. ```typescript import type { UserConfig } from "@commitlint/types"; import { RuleConfigSeverity } from "@commitlint/types"; const Configuration: UserConfig = { extends: ["@commitlint/config-conventional"], parserPreset: "conventional-changelog-atom", formatter: "@commitlint/format", rules: { "type-enum": [RuleConfigSeverity.Error, "always", ["foo"]], }, // ... }; export default Configuration; ``` -------------------------------- ### Install Commitlint Shareable Configuration (Shell) Source: https://commitlint.js.org/concepts/shareable-config Provides the command to install a commitlint shareable configuration package as a development dependency using npm. This step is necessary to make the extended configuration available to commitlint. ```shell npm install --save-dev commitlint-config-example ``` -------------------------------- ### Validate Last Commit with CommitLint in Codemagic Source: https://commitlint.js.org/guides/ci-setup This Codemagic configuration snippet demonstrates how to set up a workflow to lint the last commit message using CommitLint. It defines a 'commitlint' workflow that runs an npm script to execute CommitLint, validating the most recent commit against conventional commit standards. ```yaml #codemagic.yaml workflows: commitlint: name: Lint commit message scripts: - npx commitlint --from=HEAD~1 ``` -------------------------------- ### Include Emojis in Commit Headers (TypeScript) Source: https://commitlint.js.org/reference/examples Enables the inclusion of emojis in the actual commit header, not just the prompt. This configuration uses a custom parser preset based on conventional commits to validate headers starting with emojis and includes a setting to enable this feature. ```typescript import type { ParserPreset, UserConfig } from "@commitlint/types"; import config from "@commitlint/config-conventional"; import createPreset from "conventional-changelog-conventionalcommits"; import { merge } from "lodash-es"; // A helper function to create the custom emoji parser preset. async function createEmojiParser(): Promise { // Generates the regex from the emojis defined in the conventional config. const emojiRegexPart = Object.values(config.prompt.questions.type.enum) .map((value) => value.emoji.trim()) .join("|"); const parserOpts = { // This regular expression validates commit headers with an emoji. breakingHeaderPattern: new RegExp( `^(?:${emojiRegexPart})\\s+(\\w*)(?:\\((.*)\\))?!:\s+(.*)$`, ), headerPattern: new RegExp( `^(?:${emojiRegexPart})\\s+(\\w*)(?:\\((.*)\\))?!?:\s+(.*)$`, ), }; const emojiParser = merge({}, await createPreset(), { conventionalChangelog: { parserOpts }, parserOpts, recommendedBumpOpts: { parserOpts }, }); return emojiParser; } const emojiParser = await createEmojiParser(); export default { extends: ["@commitlint/config-conventional"], parserPreset: emojiParser, prompt: { questions: { type: { enum: { // Customize emojis and add the extra space for better alignment. build: { emoji: "🛠️ " }, chore: { emoji: "♻️ " }, ci: { emoji: "⚙️ " }, revert: { emoji: "🗑️ " }, }, // This setting includes the emoji in the final commit header. headerWithEmoji: true, }, }, }, } satisfies UserConfig; ``` -------------------------------- ### Jenkins X: Lint Commit Messages with Tekton Source: https://commitlint.js.org/guides/ci-setup This Jenkins X configuration uses Tekton to lint commit messages for pull requests. It defines a `PipelineRun` with a task that uses the `commitlint/commitlint` Docker image to perform the linting, referencing base and head SHAs for the pull request. ```yml apiVersion: tekton.dev/v1beta1 kind: PipelineRun metadata: name: pullrequest spec: pipelineSpec: tasks: - name: conventional-commits taskSpec: steps: - name: lint-commit-messages image: commitlint/commitlint script: | #!/usr/bin/env sh . .jx/variables.sh commitlint --extends '@commitlint/config-conventional' --from $PR_BASE_SHA --to $PR_HEAD_SHA serviceAccountName: tekton-bot timeout: 15m ``` -------------------------------- ### Commitlint Configuration Equivalents Source: https://commitlint.js.org/support/upgrade A JavaScript object illustrating the mapping between 'validate-commit-msg' options and their corresponding commitlint configuration rules. This helps in translating existing custom configurations to the commitlint format. ```javascript { "types": ["a", "b"], // 'type-enum': [2, 'always', ['a', 'b']] "scope": { "required": true, // 'scope-empty': [2, 'never'] "allowed": ["a", "b"], // 'scope-enum': [2, 'always', ['a', 'b']]; specify [0] for allowed: ["*"] "validate": false, // 'scope-enum': [0], 'scope-empty': [0] "multiple": false // multiple scopes are not supported in commitlint }, "warnOnFail": false, // no equivalent setting in commitlint "maxSubjectLength": 100, // 'header-max-length': [2, 'always', 100] "subjectPattern": ".+", // may be configured via `parser-preset`, contact us "subjectPatternErrorMsg": "msg", // no equivalent setting in commitlint "helpMessage": "", // no equivalent setting in commitlint "autoFix": false // no equivalent setting in commitlint } ``` -------------------------------- ### Add npm run-script for Commitlint Prompt Source: https://commitlint.js.org/guides/use-prompt Adds a 'commit' script to the package.json file, allowing the user to invoke the @commitlint/prompt-cli tool with a simple command. This streamlines the commit message authoring process. ```json { "scripts": { "commit": "commit" } } ``` -------------------------------- ### Configure Commitlint with Custom Rules Source: https://commitlint.js.org/support/upgrade Sets up a commitlint configuration file (e.g., commitlint.config.js) with extended conventional configuration and custom rules. This allows for fine-grained control over commit message validation beyond the default settings. ```javascript module.exports = { extends: ["@commitlint/config-conventional"], rules: { // Place your rules here "scope-enum": [2, "always", ["a", "b"]], // error if scope is given but not in provided list }, }; ``` -------------------------------- ### Extending Shareable Configurations in Commitlint (JS) Source: https://commitlint.js.org/reference/configuration This JavaScript configuration demonstrates how to extend multiple shareable commitlint configurations. It shows how to reference configurations installed via npm, including prefixed (`commitlint-config-*`) and scoped packages. Ensure the referenced packages are installed as dev dependencies. ```sh npm install --save-dev commitlint-config-lerna @commitlint/config-conventional ``` ```javascript export default { extends: [ 'lerna', // prefixed with commitlint-config-* '@commitlint/config-conventional' // scoped packages are not prefixed ] } ``` -------------------------------- ### Configuring Formatter in Commitlint (JS) Source: https://commitlint.js.org/reference/configuration This JavaScript configuration example demonstrates how to set a custom formatter for commitlint's output. The formatter is specified using an ID that can be resolved by the node resolution algorithm, allowing for different output formats for linting issues. ```javascript export default { formatter: "@commitlint/format", }; ``` -------------------------------- ### Extend Commitlint Configuration with Relative Path (JavaScript) Source: https://commitlint.js.org/concepts/shareable-config Shows how to extend commitlint's configuration using a local file path. The path must start with a dot ('.') and refers to a local JavaScript configuration file. This is useful for project-specific configurations that are not shared via npm. ```javascript export default { extends: ["./example"], // => ./example.js }; ``` -------------------------------- ### Simplified last-commit checker Source: https://commitlint.js.org/api/lint A concise example that loads the project's commitlint configuration, reads the last commit from git history, and then lints that commit. It then logs the validity of the last commit. ```js import load from "@commitlint/load"; import read from "@commitlint/read"; import lint from "@commitlint/lint"; const { rules, parserPreset } = load(); const [commit] = await read({ from: "HEAD~1" }); const report = await lint( commit, rules, parserPreset ? { parserOpts: parserPreset.parserOpts } : {}, ); console.log(JSON.stringify(result.valid)); ``` -------------------------------- ### Lint commit message with type-enum rule Source: https://commitlint.js.org/api/lint Illustrates how to lint a commit message using a specific `type-enum` rule. This example shows both a valid message that passes the rule and an invalid message that generates a warning. ```js const report = await lint("foo: bar", { "type-enum": [1, "always", ["foo"]] }); console.log(report); // => { valid: true, errors: [], warnings: [] } ``` ```js const report = await lint("foo: bar", { "type-enum": [1, "always", ["bar"]] }); console.log(report); /* => { valid: false, errors: [], warnings: [ { level: 1, valid: false, name: 'type-enum', message: 'type must be one of [bar]' } ] } */ ``` -------------------------------- ### Lint commit message without configuration Source: https://commitlint.js.org/api/lint Shows a basic example of using the `lint` function to validate a commit message string without providing any specific rules or configuration. It defaults to standard commitlint rules if available. ```js const report = await lint("foo: bar"); console.log(report); // => { valid: true, errors: [], warnings: [] } ``` -------------------------------- ### Configure commitlint Prompt in JavaScript Source: https://commitlint.js.org/reference/prompt This JavaScript code configures the prompt settings, messages, and questions used by commitlint. It defines rules for commit message validation, including character limits and required fields. The configuration is used to guide users in creating compliant commit messages. ```javascript export default { parserPreset: 'conventional-changelog-conventionalcommits', rules: { ... }, prompt: { settings: {}, messages: { skip: ':skip', max: 'upper %d chars', min: '%d chars at least', emptyWarning: 'can not be empty', upperLimitWarning: 'over limit', lowerLimitWarning: 'below limit' }, questions: { type: { description: "Select the type of change that you're committing:", enum: { feat: { description: 'A new feature', title: 'Features', emoji: '✨', }, fix: { description: 'A bug fix', title: 'Bug Fixes', emoji: '🐛', }, docs: { description: 'Documentation only changes', title: 'Documentation', emoji: '📚', }, style: { description: 'Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)', title: 'Styles', emoji: '💎', }, refactor: { description: 'A code change that neither fixes a bug nor adds a feature', title: 'Code Refactoring', emoji: '📦', }, perf: { description: 'A code change that improves performance', title: 'Performance Improvements', emoji: '🚀', }, test: { description: 'Adding missing tests or correcting existing tests', title: 'Tests', emoji: '🚨', }, build: { description: 'Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)', title: 'Builds', emoji: '🛠', }, ci: { description: 'Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)', title: 'Continuous Integrations', emoji: '⚙️', }, chore: { description: "Other changes that don't modify src or test files", title: 'Chores', emoji: '♻️', }, revert: { description: 'Reverts a previous commit', title: 'Reverts', emoji: '🗑', }, }, }, scope: { description: 'What is the scope of this change (e.g. component or file name)', }, subject: { description: 'Write a short, imperative tense description of the change', }, body: { description: 'Provide a longer description of the change', }, isBreaking: { description: 'Are there any breaking changes?', }, breakingBody: { description: 'A BREAKING CHANGE commit requires a body. Please enter a longer description of the commit itself', }, breaking: { description: 'Describe the breaking changes', }, isIssueAffected: { description: 'Does this change affect any open issues?', }, issuesBody: { description: 'If issues are closed, the commit requires a body. Please enter a longer description of the commit itself', }, issues: { description: 'Add issue references (e.g. "fix #123", "re #123".)', }, }, } }; ``` -------------------------------- ### Customize Emojis and Alignment in VS Code (TypeScript) Source: https://commitlint.js.org/reference/examples Addresses VS Code terminal alignment issues with Unicode emojis by adding an extra space after specific emojis in the commit prompt configuration. This ensures proper text alignment in the commit prompt. ```typescript import { type UserConfig } from "@commitlint/types"; export default { // Use the conventional commit rules as a base. extends: ["@commitlint/config-conventional"], prompt: { questions: { type: { enum: { // Add a space to a few common types for better alignment. build: { emoji: "🛠️ ", // The extra space fixes the alignment. }, chore: { emoji: "♻️ ", }, ci: { emoji: "⚙️ ", }, revert: { emoji: "🗑️ ", }, }, }, }, }, } satisfies UserConfig; ``` -------------------------------- ### GitHub Actions: Validate Commits with commitlint Source: https://commitlint.js.org/guides/ci-setup This snippet demonstrates a GitHub Actions workflow to validate the last commit message on push events or all commit messages within a Pull Request. It checks out the code, sets up Node.js, installs commitlint, and then runs the validation using `npx commitlint`. ```yml name: CI on: [push, pull_request] permissions: contents: read jobs: commitlint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - name: Setup node uses: actions/setup-node@v4 with: node-version: lts/* cache: npm - name: Install commitlint run: npm install -D @commitlint/cli @commitlint/config-conventional - name: Print versions run: | git --version node --version npm --version npx commitlint --version - name: Validate current commit (last commit) with commitlint if: github.event_name == 'push' run: npx commitlint --last --verbose - name: Validate PR commits with commitlint if: github.event_name == 'pull_request' run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose ``` -------------------------------- ### GitLab CI: Validate Merge Request Commits Source: https://commitlint.js.org/guides/ci-setup This GitLab CI configuration validates commits within a merge request. It uses a Node.js Alpine image, ensures Git history is fully available by setting `GIT_DEPTH: 0`, installs commitlint, and then runs the validation using `npx commitlint` with the appropriate commit SHA references. ```yaml lint:commit: image: registry.hub.docker.com/library/node:alpine variables: GIT_DEPTH: 0 before_script: - apk add --no-cache git - npm install --save-dev @commitlint/config-conventional @commitlint/cli script: - npx commitlint --from ${CI_MERGE_REQUEST_DIFF_BASE_SHA} --to ${CI_COMMIT_SHA} ``` -------------------------------- ### Display commitlint CLI Help Source: https://commitlint.js.org/reference/cli This command displays the help message for the commitlint CLI, providing a comprehensive list of available options and their descriptions. It's useful for understanding the tool's capabilities and usage. ```shell npx commitlint --help ``` -------------------------------- ### Upgrade Commitlint Config Angular to Conventional Source: https://commitlint.js.org/support/upgrade Commands to upgrade commitlint from the Angular-specific configuration to the more general conventional configuration. This involves removing the old config package and installing the new one. ```shell npm remove --save-dev @commitlint/config-angular npm install --save @commitlint/cli @commitlint/config-conventional echo 'module.exports = {extends: ["@commitlint/config-conventional"]};'; ``` -------------------------------- ### Load commitlint configuration by referencing a file Source: https://commitlint.js.org/api/load Loads a commitlint configuration by extending from a local file named `package`. The configuration from the specified file is merged. The result is logged to the console. ```javascript const config = await load({ extends: ["./package"] }); console.log(config); // => { extends: ['./package', './package-b'], rules: {} } ``` -------------------------------- ### Use Local Commitlint Plugin with Custom Rule (JavaScript) Source: https://commitlint.js.org/reference/plugins This JavaScript configuration file ('commitlint.config.js') illustrates how to define and use a local commitlint plugin. It includes a custom rule 'hello-world-rule' within the 'plugins' array, demonstrating how to integrate custom validation logic directly into the project. ```javascript export default { rules: { "hello-world-rule": [2, "always"], }, plugins: [ { rules: { "hello-world-rule": ({ subject }) => { const HELLO_WORLD = "Hello World"; return [ subject.includes(HELLO_WORLD), `Your subject should contain ${HELLO_WORLD} message`, ]; }, }, }, ], }; ``` -------------------------------- ### Test Local Commitlint Plugin with CLI (Bash) Source: https://commitlint.js.org/reference/plugins This bash script demonstrates testing a commitlint configuration that uses a local plugin. It pipes commit messages to the 'commitlint' command, showing how a commit without 'Hello World' fails validation, while one with it passes, verifying the custom rule's functionality. ```bash > echo "feat: random subject" | commitlint # fails > echo "feat: Hello World" | commitlint # passes ``` -------------------------------- ### Load configuration and lint commit message Source: https://commitlint.js.org/api/lint Shows how to load a commitlint configuration (e.g., from `@commitlint/config-conventional`), then use the loaded rules and parser options to lint a commit message. This is a common pattern for integrating commitlint into a project. ```js import load from "@commitlint/load"; import lint from "@commitlint/lint"; const CONFIG = { extends: ["@commitlint/config-conventional"], }; const opts = await load(CONFIG); const report = await lint( "foo: bar", opts.rules, opts.parserPreset ? { parserOpts: opts.parserPreset.parserOpts } : {}, ); console.log(report); /* => { valid: false, errors: [ { level: 2, valid: false, name: 'type-enum', message: 'type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test]' } ], warnings: [] } */ ``` -------------------------------- ### Configure Commitlint Rules with Function Returning Array Source: https://commitlint.js.org/reference/rules-configuration Shows how to configure a Commitlint rule using a function that returns a configuration array. This approach allows for dynamic rule configuration based on certain conditions or logic within the function. ```javascript export default { // ... rules: { "header-max-length": () => [0, "always", 72] }, // ... }; ``` -------------------------------- ### Import lint function Source: https://commitlint.js.org/api/lint Demonstrates how to import the `lint` function from the @commitlint/lint package into a JavaScript or TypeScript project. ```js import lint from "@commitlint/lint"; ``` -------------------------------- ### Load commitlint configuration with inline rules Source: https://commitlint.js.org/api/load Loads a commitlint configuration with inline rules defined. The `body-leading-blank` rule is set to level 2 (throw) and condition `always`. The result is logged to the console. ```javascript const config = await load({ rules: { "body-leading-blank": [2, "always"], }, }); console.log(config); // => { extends: [], rules: { 'body-leading-blank': [ 2, 'always' ] } } ``` -------------------------------- ### Configure Commitlint Rules with Plain Array Source: https://commitlint.js.org/reference/rules-configuration Demonstrates how to configure a Commitlint rule using a plain array. The array specifies the rule's level, applicability, and value. This is a common and straightforward method for rule configuration. ```javascript export default { // ... rules: { "header-max-length": [0, "always", 72] }, // ... }; ``` -------------------------------- ### Validate Issue/Ticket Numbers in Commit Messages (JSON) Source: https://commitlint.js.org/reference/examples Configures commitlint to enforce the presence of issue or ticket numbers in commit messages. It specifies that references should 'never' be empty and sets custom issue prefixes like 'PROJ-'. ```json { // ... "commitlint": { "rules": { "references-empty": [2, "never"], }, "parserPreset": { "parserOpts": { "issuePrefixes": ["PROJ-"], }, }, }, // ... } ``` -------------------------------- ### Load commitlint configuration with inline parserPreset Source: https://commitlint.js.org/api/load Loads a commitlint configuration with an inline `parserPreset` defined. The `parserPreset` specifies a local JavaScript file to use for parsing commit messages. The resulting configuration, including the expanded parser preset, is logged. ```javascript const config = await load({ parserPreset: "./parser-preset.js" }); console.log(config); /* => { extends: [], rules: {}, parserPreset: { name: './parser-preset.js', path: './parser-preset.js', opts: {} } } */ ``` -------------------------------- ### Extend Commitlint Configuration with npm Package (JavaScript) Source: https://commitlint.js.org/concepts/shareable-config Demonstrates how to extend commitlint's configuration by referencing an npm package in the 'extends' array. This allows for modular and reusable commit message linting rules. The specified package, prefixed with 'commitlint-config-', is automatically resolved and its rules are merged. ```javascript /** * @type {import('@commitlint/types').UserConfig} */ export default { extends: ["example"], // => commitlint-config-example }; ``` -------------------------------- ### Configure commitmsg script in package.json Source: https://commitlint.js.org/support/upgrade Adds a 'commitmsg' script to your package.json file, which is used by Git hooks (like husky) to run commitlint checks on commit messages. This ensures that all commit messages adhere to the configured commit message conventions. ```json { "scripts": { "commitmsg": "commitlint -x @commitlint/config-conventional -E GIT_PARAMS" } } ``` -------------------------------- ### Format commitlint report with default options Source: https://commitlint.js.org/api/format Demonstrates the basic usage of the format function without any arguments, which formats an empty report with default settings (including colors). The output indicates no problems found. ```js format(); /* => [ '\u001b[1m\u001b[32m✔\u001b[39m found 0 problems, 0 warnings\u001b[22m' ] */ ``` -------------------------------- ### Load commitlint configuration from a file in the current working directory Source: https://commitlint.js.org/api/load Loads a commitlint configuration from a specified file (`.commitlintrc.yml`) within the current working directory. The `cwd` option ensures the file is resolved correctly. The loaded configuration, including rules and other properties, is logged. ```javascript const config = await load( {}, { file: ".commitlintrc.yml", cwd: process.cwd() }, ); console.log(config); /* => { extends: [], rules: { 'body-leading-blank': [ 1, 'always' ] }, formatter: '@commitlint/format', plugins: {} } */ ``` -------------------------------- ### Configuring Parser Preset in Commitlint (JS) Source: https://commitlint.js.org/reference/configuration This JavaScript configuration snippet shows how to specify a custom parser preset for commitlint. The preset, identified by an ID resolvable by the node resolution algorithm, allows for custom parsing of commit messages. Ensure the preset package is installed. ```sh npm install --save-dev conventional-changelog-atom ``` ```javascript export default { parserPreset: "conventional-changelog-atom", }; ```