Sunday, 13 January 2013

A git pre-commit hook to check the year of copyright notices

Like every year, touching a source file means you also need to update the year of the copyright notice you should have at the top of the file. I always end up forgetting about them, this is where a git pre-commit hook would be ultra-useful, so I wrote one:
#
# Check if copyright statements include the current year
#
files=`git diff --cached --name-only`
year=`date +"%Y"`

for f in $files; do
    head -10 $f | grep -i copyright 2>&1 1>/dev/null || continue

    if ! grep -i -e "copyright.*$year" $f 2>&1 1>/dev/null; then
        missing_copyright_files="$missing_copyright_files $f"
    fi
done

if [ -n "$missing_copyright_files" ]; then
    echo "$year is missing in the copyright notice of the following files:"
    for f in $missing_copyright_files; do
        echo "    $f"
    done 
    exit 1
fi
Hope this helps!

1 comment:

  1. Hi Damien,
    thanks for the hook, nice idea! Here are two ideas for improvement:

    files=`git diff HEAD --name-only`
    year=`date +"%Y"`

    for f in $files; do
    head -10 $f | grep -i copyright 2>&1 1>/dev/null || continue

    if ! head -10 $f | grep -i -e "copyright.*$year" 2>&1 1>/dev/null; then
    missing_copyright_files="$missing_copyright_files $f"
    fi
    done
    [...]

    Firstly, the `$files` now include unstaged files - I often use `git commit -am "..."`, so it is nice to check those as well.
    Secondly, the `grep` that checks for the missing year is now confined to the first 10 lines, in accordance with the first `head`. I had an issue were the pre-commit hook would not be triggered when editing my license header, because it contains the license again in another part of the file...

    Best
    Lucas

    ReplyDelete