Programmatic interface for integrating commitlint into other tools and workflows. Provides functions for configuration loading, commit message linting, result formatting, and git integration.
Load and resolve commitlint configuration from various sources.
/**
* Load and resolve commitlint configuration
* @param seed - Base configuration to merge with loaded config
* @param options - Loading options
* @returns Promise resolving to qualified configuration
*/
function load(seed?: UserConfig, options?: LoadOptions): Promise<QualifiedConfig>;
interface LoadOptions {
cwd?: string; // Working directory (default: process.cwd())
file?: string; // Specific config file path
}
interface UserConfig {
extends?: string | string[]; // Shareable configurations to extend
formatter?: string; // Custom formatter
rules?: Partial<RulesConfig>; // Rule configuration
parserPreset?: string | ParserPreset; // Parser preset
ignores?: ((commit: string) => boolean)[]; // Custom ignore functions
defaultIgnores?: boolean; // Use default ignores
plugins?: (string | Plugin)[]; // Plugins
helpUrl?: string; // Help URL for errors
prompt?: UserPromptConfig; // Prompt configuration
}
interface QualifiedConfig {
extends: string[];
formatter: string;
rules: QualifiedRules;
parserPreset: ParserPreset;
ignores: ((commit: string) => boolean)[];
plugins: Plugin[];
helpUrl?: string;
prompt: UserPromptConfig;
}Usage Examples:
const {load} = require('@commitlint/core');
// Load default configuration
const config = await load();
// Load with base configuration
const config = await load({
extends: ['@commitlint/config-conventional'],
rules: {
'subject-max-length': [2, 'always', 50]
}
});
// Load from specific directory
const config = await load({}, {cwd: '/path/to/project'});
// Load specific config file
const config = await load({}, {file: './custom-commitlint.config.js'});Lint commit messages against configuration rules.
/**
* Lint commit message against rules
* @param message - Commit message to lint
* @param rules - Rule configuration (optional, uses loaded config if not provided)
* @param opts - Linting options
* @returns Promise resolving to lint outcome
*/
function lint(
message: string,
rules?: QualifiedRules,
opts?: LintOptions
): Promise<LintOutcome>;
interface LintOptions {
ignores?: ((commit: string) => boolean)[]; // Custom ignore functions
defaultIgnores?: boolean; // Use default ignores
parserOpts?: ParserOptions; // Parser options
plugins?: Plugin[]; // Plugin instances
helpUrl?: string; // Help URL for errors
}
interface LintOutcome {
valid: boolean; // Overall validity
errors: LintRuleOutcome[]; // Rule errors
warnings: LintRuleOutcome[]; // Rule warnings
input: string; // Original input message
}
interface LintRuleOutcome {
level: RuleConfigSeverity; // Severity level (0=disabled, 1=warning, 2=error)
valid: boolean; // Rule validity
name: string; // Rule name
message: string; // Error/warning message
}Usage Examples:
const {lint, load} = require('@commitlint/core');
// Load config and lint message
const config = await load();
const result = await lint('feat: add new feature', config.rules);
if (!result.valid) {
console.log('Errors:', result.errors);
console.log('Warnings:', result.warnings);
}
// Lint with custom rules
const result = await lint('fix: correct bug', {
'type-enum': [2, 'always', ['feat', 'fix', 'docs']],
'subject-max-length': [2, 'always', 50]
});
// Lint with custom options
const result = await lint('feat: add feature', undefined, {
ignores: [(message) => message.includes('[skip]')],
defaultIgnores: false
});Parse commit messages into structured format.
/**
* Parse commit message using conventional-commits-parser
* @param message - Commit message to parse
* @param parser - Parser function (optional, defaults to sync parser)
* @param parserOpts - Parser options
* @returns Promise resolving to parsed commit
*/
function parse(
message: string,
parser?: Parser,
parserOpts?: ParserOptions
): Promise<Commit>;
interface Commit {
raw: string; // Original commit message
header: string; // Commit header
type: string | null; // Commit type (feat, fix, etc.)
scope: string | null; // Commit scope
subject: string | null; // Commit subject
body: string | null; // Commit body
footer: string | null; // Commit footer
mentions: string[]; // GitHub mentions (@username)
notes: CommitNote[]; // Commit notes (BREAKING CHANGE:, etc.)
references: CommitReference[]; // Issue references (#123)
revert: any; // Revert information
merge: any; // Merge information
}
interface CommitNote {
title: string; // Note title (e.g., "BREAKING CHANGE")
text: string; // Note content
}
interface CommitReference {
action: string; // Action (closes, fixes, etc.)
owner: string | null; // Repository owner
repository: string | null; // Repository name
issue: string; // Issue number
raw: string; // Raw reference text
prefix: string; // Reference prefix (#, etc.)
}Usage Examples:
const {parse} = require('@commitlint/core');
// Parse conventional commit
const commit = await parse('feat(api): add user authentication\n\nImplements JWT-based auth\n\nCloses #123');
console.log(commit.type); // 'feat'
console.log(commit.scope); // 'api'
console.log(commit.subject); // 'add user authentication'
console.log(commit.body); // 'Implements JWT-based auth'
console.log(commit.references); // [{action: 'Closes', issue: '123', ...}]
// Parse with custom parser options
const commit = await parse('fix: bug fix', undefined, {
noteKeywords: ['BREAKING CHANGE', 'DEPRECATED'],
referenceActions: ['close', 'closes', 'closed', 'fix', 'fixes', 'fixed']
});Format lint results for console output.
/**
* Format lint report for console output
* @param report - Report containing results to format
* @param options - Formatting options
* @returns Formatted string for console output
*/
function format(report?: FormattableReport, options?: FormatOptions): string;
/**
* Format individual lint result
* @param result - Individual result to format
* @param options - Formatting options
* @returns Array of formatted lines
*/
function formatResult(result?: FormattableResult, options?: FormatOptions): string[];
interface FormattableReport {
valid: boolean; // Overall report validity
errorCount: number; // Number of errors
warningCount: number; // Number of warnings
results: FormattableResult[]; // Individual results
}
interface FormattableResult {
valid: boolean; // Result validity
input: string; // Original input
errors: LintRuleOutcome[]; // Errors
warnings: LintRuleOutcome[]; // Warnings
}
interface FormatOptions {
color?: boolean; // Enable colored output (default: true)
signs?: [string, string, string]; // Signs for [error, warning, info]
verbose?: boolean; // Enable verbose output
helpUrl?: string; // Help URL to include in output
}Usage Examples:
const {format, lint, load} = require('@commitlint/core');
// Format lint results
const config = await load();
const result = await lint('invalid commit message', config.rules);
const report = {
valid: result.valid,
errorCount: result.errors.length,
warningCount: result.warnings.length,
results: [result]
};
const formatted = format(report, {
color: true,
verbose: true,
helpUrl: 'https://example.com/commit-guidelines'
});
console.log(formatted);
// Format individual result
const lines = formatResult(result, {color: false});
lines.forEach(line => console.log(line));Read commit messages from git history.
/**
* Read commit messages from git history
* @param settings - Options for reading commits
* @returns Promise resolving to array of commit messages
*/
function read(settings: GetCommitMessageOptions): Promise<string[]>;
interface GetCommitMessageOptions {
cwd?: string; // Working directory (default: process.cwd())
from?: string; // Lower commit range (git ref)
to?: string; // Upper commit range (git ref)
edit?: boolean | string; // Read from edit file or .git/COMMIT_EDITMSG
gitLogArgs?: string; // Additional git log arguments
}Usage Examples:
const {read} = require('@commitlint/core');
// Read commits in range
const messages = await read({
from: 'HEAD~5',
to: 'HEAD'
});
// Read from specific directory
const messages = await read({
cwd: '/path/to/git/repo',
from: 'main',
to: 'feature-branch'
});
// Read from commit edit file
const messages = await read({
edit: '.git/COMMIT_EDITMSG'
});
// Read with additional git log arguments
const messages = await read({
from: 'HEAD~10',
gitLogArgs: '--merges --first-parent'
});const {load, lint, read, format, parse} = require('@commitlint/core');
async function lintCommits() {
try {
// Load configuration
const config = await load({
extends: ['@commitlint/config-conventional']
});
// Read commits from git history
const messages = await read({
from: 'HEAD~5',
to: 'HEAD'
});
// Lint each commit
const results = [];
for (const message of messages) {
const result = await lint(message, config.rules, {
parserOpts: config.parserPreset.parserOpts
});
results.push(result);
// Parse for additional analysis
const parsed = await parse(message, undefined, config.parserPreset.parserOpts);
console.log(`Type: ${parsed.type}, Scope: ${parsed.scope}`);
}
// Format results
const report = {
valid: results.every(r => r.valid),
errorCount: results.reduce((sum, r) => sum + r.errors.length, 0),
warningCount: results.reduce((sum, r) => sum + r.warnings.length, 0),
results: results
};
const formatted = format(report, {
color: true,
verbose: true
});
console.log(formatted);
return report.valid;
} catch (error) {
console.error('Error linting commits:', error);
return false;
}
}
lintCommits().then(valid => {
process.exit(valid ? 0 : 1);
});