Home > Uncategorized > A git hook to lock master and more

A git hook to lock master and more

Here is the hooks/update git script I’m using when I’m working with people not aware of how to use VCS software. It:

  • Check commit messages
  • Possibly lock master.
  • Check that nobody push -f on master.
#! /usr/bin/env python
import sys, os
from subprocess import *

lock_master = True

def revlist(old, new):
    r = Popen(["git", "rev-list", old+".."+new], stdout=PIPE).communicate()[0]
    return r.strip().split('\n')

def mergebase(old, new):
    return Popen(["git", "merge-base", old, new], stdout=PIPE).communicate()[0].strip()

def granted(user):
    return not user or "obiwan" == user

refname=sys.argv[1]
oldrev=sys.argv[2]
newrev=sys.argv[3]
user = os.environ.get('REMOTE_USER')
if not user:
    user = os.environ.get('USER')

if lock_master:
    if refname == "refs/heads/master" and not granted(user):
        print "Changing master not allowed."
        quit(1)
else:
    if mergebase(oldrev, newrev) != oldrev:
        if granted(user):
            print "Non fast forward push allowed."
            quit(0)
        else:
            print "Non fast forward push not allowed."
            quit(1)

for rev in revlist(oldrev, newrev):
    commit=Popen(["git", "cat-file", "commit", rev], stdout=PIPE).communicate()[0]
    commit_lines = commit.split("\n")
    for i in xrange(len(commit_lines)):
        line = commit_lines[i]
        if line.startswith("committer "):
            commiter = " ".join(line.split(" ")[1:-2])
            title_line = i+2
    title = commit_lines[title_line].strip()
    if "Signed-off-by" in title or len(title) == 0 or title.startswith("-"):
        print "Invalid commit comment:"
        print title
        print "The first line must be the commit title."
        quit(1)
Advertisements
Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: