6

I need to validate the commit messages that are pushed to the remote in order to prevent developers from not putting enough detail in (string length) or only putting a ticket number.

I thought an update hook would work for this but it doesn't- it seemed to, but it only works for a reference that's been pushed previously. When I tried to push a new branch it rejected because it couldn't find the ref. I suspect it may also only be running against the latest commit in a pushed series.

What would be the right choice of hook to perform this task?

Snippet:

#!/usr/bin/env php
<?php

define('MINIMUM_MESSAGE_LENGTH', 10);

$exit = 0; // default exit code -> success

$ref = $argv[1];
$commitMessage = exec('git log -1 ' . $ref . ' --pretty=format:%s');
$commitMessage = trim($commitMessage);

// validations & exit($exit) follow; 

yep this is PHP but the question is language agnostic

Nick Volynkin
  • 14,023
  • 6
  • 43
  • 67
bcmcfc
  • 25,966
  • 29
  • 109
  • 181
  • Mentioning [this answer](http://stackoverflow.com/a/3512275/149998) here in order to link it to the question - this was the next step for me in getting this working, so I wanted to link it for future searchers finding this question. – bcmcfc Jul 05 '15 at 09:13

2 Answers2

6

Policy enforcement means server-side hook.

  • A client-side hook like a pre-commit can be bypassed, and is not easy to deploy.
  • A server-side is deployed once (on the Git repo hosting server), and you are done.

The Git Pro book has an example ("Customizing Git - An Example Git-Enforced Policy") which should work for new branches as well as legacy branches pushes.

You will find other examples at "How do we verify commit messages for a push?".

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Do you know which server side hook would work for this use case? I agree re client side hooks - hard to enforce and wouldn't work out of the box for new starters / fresh clones. – bcmcfc Jul 04 '15 at 08:51
0

You are right, a update hook wouldn't work. If you need to enforce a commit message standard, you should use a pre-commit hook. It will run before a commit is made and make sure it the commit is standard and then go ahead and create the commit. Here is a pre-commit hook sample

https://github.com/git/git/blob/master/templates/hooks--pre-commit.sample

For more on git hooks check this

http://githooks.com/

TheGeorgeous
  • 3,927
  • 2
  • 20
  • 33
  • 1
    The pre-commit hook is a client-side hook. To enforce a policy with such a hook, you need to make sure that all contributors have it up and running in their local clones, which can be tricky. See [VonC's answer](http://stackoverflow.com/a/31218445/2541573). – jub0bs Jul 04 '15 at 09:55