Showing posts with label git. Show all posts
Showing posts with label git. Show all posts

Thursday, October 07, 2021

Git tip: Visual indicator of the 50-character git commit summary message limit

Although it's somewhat too short for my taste, I generally comply with the conventional wisdom of having the summary line of git commit messages be no more than 50 characters.

Even using an editor that shows the current position of the insertion point (such as vim with set ruler enabled), it's not readily discernible how much of the available 50 characters remains, relative to text that has been keyed in so far.

My solution to this has been to set up a ".gitmessage" commit message template that includes a comment showing the 50-character limit:

 
 
#                                                  |<-- 50 char summary line limit

As long as my summary message ends before that vertical pipe character, I'm good!

Friday, January 08, 2021

Configuring git to prevent commits of temporary/debug code

Developers, have you ever embarrassingly pushed a commit that inadvertently included temporary debug log/print statements, or other code that you intended to remove before committing? I have!

I wondered if it was possible to add some keyword to a code file -- for example, DONOTCOMMIT -- which, if present, would cause git to automatically reject the commit. This could be added as a comment alongside any temporary debug code, to make it impossible to forget to remove that code before committing.

It turns out that it is possible to do this -- and have it apply automatically to all of your local git repositories -- using a git pre-commit hook.

Quick instructions

(The specifics in these instructions apply to Unix-like filesystems, including Mac OS.)

1. If it doesn't already exist, create the directory: ~/.git_templates/hooks/

2. If it doesn't already exist, in that hooks directory, create a text file named: pre-commit (no extension).

3. Add the following content to the pre-commit file:

#!/bin/bash

FOUND=$(git diff-index --cached -U0 HEAD -- | grep DONOTCOMMIT | wc -l)

if [[ $FOUND -gt 0 ]]; then
    echo "pre-commit hook: DONOTCOMMIT detected, commit not allowed"
    echo "(enforced from: ~/.git_templates/hooks/pre-commit)"
    exit 1
fi

4. To apply that pre-commit hook to all git commit operations on your local machine, from the terminal, run:

git config --global core.hooksPath ~/.git_templates/hooks

References

Credit to https://github.com/mudrd8mz for the pre-commit hook code.

Credit to https://stackoverflow.com/users/6309/vonc for the core.hooksPath global git config command.