Skip to content

Instantly share code, notes, and snippets.

@kasparsd
Created October 18, 2024 09:20
Show Gist options
  • Save kasparsd/7c686dbd1f187d4af6c2d0a430d98f53 to your computer and use it in GitHub Desktop.
Save kasparsd/7c686dbd1f187d4af6c2d0a430d98f53 to your computer and use it in GitHub Desktop.
Git hook commit-msg script to enforce Conventional Commits
<?php
$commit_message = file_get_contents( $argv[1] );
$is_common_commit = preg_match(
'/^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([\w\-\.,\|\:]+\))?(!)?:\s?([\w ])+([\s\S]*)/m',
$commit_message,
$matches
);
if ( ! $is_common_commit ) {
throw new Exception( 'All commits must follow the Conventional Commits format' );
}
$commit_scopes = [ 'plugin:something', 'php:this' ]; // TODO: Determine this from the list of files included in this commit.
if ( ! empty( $matches[2] ) ) {
$message_scopes = explode( '|', str_replace( [ ',', ';', '/' ], '|', trim( $matches[2], '()' ) ) );
$commit_scopes = array_unique( array_merge( $message_scopes, $commit_scopes ) );
}
$updated_message = str_replace(
$matches[2],
sprintf( '(%s)', implode( '|', $commit_scopes ) ),
$commit_message
);
file_put_contents( $argv[1], $updated_message );
// exit(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment