Git command abstractions and staging area utilities that provide direct git repository interaction with support for various git operations and hook integration.
Core git commit functionality with support for both direct command execution and git hook integration.
/**
* Executes git commit with the provided message and options
* @param repoPath - Path to git repository
* @param message - Commit message template (supports multi-line)
* @param options - Git commit options and flags
* @param done - Callback function called on completion
*/
function commit(
repoPath: string,
message: string,
options: GitCommitOptions,
done: ErrorCallback
): void;
interface GitCommitOptions {
args?: string[]; // Additional git commit arguments
quiet?: boolean; // Suppress git command output
hookMode?: boolean; // Write to COMMIT_EDITMSG instead of executing commit
}
type ErrorCallback = (error: Error | null) => void;Usage Examples:
const { git } = require('commitizen');
// Basic commit execution
git.commit(process.cwd(), 'feat: add new feature', {
args: ['--signoff'],
quiet: false
}, (error) => {
if (error) {
console.error('Commit failed:', error.message);
if (error.code === 128) {
console.log('Check git user configuration');
}
} else {
console.log('Commit successful!');
}
});
// Quiet commit (suppress output)
git.commit(process.cwd(), 'fix: resolve bug', {
quiet: true
}, (error) => {
// Handle error silently
});
// Hook mode (prepare-commit-msg)
git.commit(process.cwd(), 'docs: update README', {
hookMode: true,
quiet: true
}, (error) => {
// Writes to .git/COMMIT_EDITMSG instead of executing commit
});Git commit supports complex commit message templates with automatic formatting:
const { git } = require('commitizen');
const multilineMessage = `feat(auth): add OAuth2 integration
Implements OAuth2 authentication flow with support for:
- Authorization code flow
- Token refresh
- Scope validation
This change updates the authentication API and requires
configuration updates.
Closes #123
BREAKING CHANGE: Authentication API changed`;
git.commit(process.cwd(), multilineMessage, {}, (error) => {
if (error) console.error('Commit failed:', error);
});Add files and paths to the git staging area.
/**
* Synchronously adds all files (.) to git staging area
* @param repoPath - Path to git repository
*/
function addPath(repoPath: string): void;
/**
* Synchronously adds a specific file to git staging area
* @param repoPath - Path to git repository
* @param filename - Name of file to add
*/
function addFile(repoPath: string, filename: string): void;Usage Examples:
const { git } = require('commitizen');
// Add all files to staging
git.addPath(process.cwd());
// Add specific file to staging
git.addFile(process.cwd(), 'src/index.js');
git.addFile(process.cwd(), 'README.md');Extended git functionality for repository management and information retrieval.
/**
* Synchronously creates a new git repository at a path
* @param repoPath - Path where to initialize repository
*/
function init(repoPath: string): void;
/**
* Asynchronously gets the git log output
* @param repoPath - Path to git repository
* @param done - Callback function to receive log output
*/
function log(repoPath: string, done: (output: string) => void): void;
/**
* Asynchronously gets the git whatchanged output
* @param repoPath - Path to git repository
* @param done - Callback function to receive whatchanged output
*/
function whatChanged(repoPath: string, done: (output: string) => void): void;Usage Examples:
const { git } = require('commitizen');
// Initialize new git repository
git.init('./new-project');
// Get git log
git.log(process.cwd(), (logOutput) => {
console.log('Git log:');
console.log(logOutput);
});
// Get what changed
git.whatChanged(process.cwd(), (changes) => {
console.log('Changes:');
console.log(changes);
});Hook mode allows commitizen to integrate with git hooks like prepare-commit-msg:
When hookMode: true is specified:
git commit, the message is written to .git/COMMIT_EDITMSGquiet: true to suppress output// In prepare-commit-msg hook
const { git } = require('commitizen');
// Get commit message from commitizen
git.commit(process.cwd(), commitMessage, {
hookMode: true,
quiet: true
}, (error) => {
if (error) {
console.error('Hook failed:', error.message);
process.exit(1);
}
process.exit(0);
});Hook mode writes to .git/COMMIT_EDITMSG with cross-platform compatibility:
// Automatic git directory detection
const gitDirPath = execSync('git rev-parse --absolute-git-dir', {
cwd: repoPath,
encoding: 'utf8'
}).trim();
const commitFilePath = path.join(gitDirPath, 'COMMIT_EDITMSG');
// Cross-platform file writing
// - Unix/Linux: Opens in 'w' mode
// - Windows: Falls back to 'r+' mode for existing hidden filesGit integration provides comprehensive error handling:
const { git } = require('commitizen');
git.commit(process.cwd(), 'message', {}, (error) => {
if (error) {
switch (error.code) {
case 128:
console.error('Git configuration error');
console.log('Run: git config --global user.email "you@example.com"');
console.log('Run: git config --global user.name "Your Name"');
break;
case 1:
console.error('Git command failed:', error.message);
break;
default:
console.error('Unexpected error:', error);
}
}
});const { staging } = require('commitizen');
staging.isClean(process.cwd(), (error, clean) => {
if (error) {
console.error('Could not check staging area');
console.error('Ensure you are in a git repository');
return;
}
// Process clean status
});Hook mode handles file system errors gracefully:
Git commit uses spawn for better control and output handling:
// Uses child_process.spawn for git commit
const child = spawn('git', args, {
cwd: repoPath,
stdio: options.quiet ? 'ignore' : 'inherit'
});
// Handles process events
child.on('error', callback);
child.on('exit', (code, signal) => {
// Process exit codes and signals
});Commit messages are processed with dedent for consistent formatting:
const dedent = require('dedent');
// Automatic indentation removal
const formattedMessage = dedent(message);
// Supports complex templates
const template = `
feat(api): add user authentication
This implements JWT-based authentication with:
- Login endpoint
- Token refresh
- Role-based access
Closes #456
`;
// Results in properly formatted commit messageGit arguments are safely passed through to git commands:
// Safe argument construction
const args = ['commit', '-m', dedent(message), ...(options.args || [])];
// Supports various git flags
const options = {
args: ['--signoff', '--author="Bot <bot@example.com>"', '--no-verify']
};