Daily Archives: 24 August 2017

Forcing user to remove trailing spaces in git

There are simple ways to force the user in removing trailing spaces before committing code in git using hooks.
Below we will present a solution that is applied at the local computer before the commit stage, which each developer needs to perform in each repository clone they own.
Note: If you would like to have the hooks on the server, you will need extra access rights to modify the hooks on the remote machine, maybe you will even need your systems administrator to configure it.


Attached you will find a file named pre-commit ([download id=”3933″]) it is a hook that get applied before the user is allowed to even commit.
That file you need to copy it (after you extract it) in the .git/hooks folder of your cloned repositories and you are done!

What this script does is simple, if there are whitespace errors, it prints the offending file names and fails.
What are considered whitespace errors is controlled by core.whitespace configuration.
By default, trailing whitespaces (including lines that solely consist of whitespaces) and a space character that is immediately followed by a tab character inside the initial indent of the line are considered whitespace errors.

In case you need to commit files that have whitespace errors, you can bypass the checks that are applied by the hooks using the --no-verify flag as follows:

git commit -m "Some informative message" --no-verify;

There are more ways to achieve this result, others are more verbose but this one is the simplest and more flexible as you can configure it using the git configuration variables.

[download id=”3933″]

# This hook script verifies that there are no whitespace errors in the files to be committed

if git rev-parse --verify HEAD >/dev/null 2>&1
 # Initial commit: diff against an empty tree object

# Redirect output to stderr.
exec 1>&2

# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --

[download id=”3933″]