Agent Coop
Agent Coop

Reputation: 390

How to patch all changed files before a commit in Git

I need to remove all trailing whitespaces before changed files will be committed. The question is how to do it?

Upvotes: 2

Views: 122

Answers (3)

Agent Coop
Agent Coop

Reputation: 390

Well, eventually I decided to write gitadd command for that.

#!/bin/bash


# Number of arguments passed
argc=$#


if [ $argc -eq 0  ]; then
        argv=( $(git diff --name-only HEAD) )
else
        argv=( $@ )
fi

for file in "$argv"; do

        sed -i -e 's/^[[:blank:]]\+$//' $file

        git add $file # stage patched file

done

Upvotes: 0

nickgrim
nickgrim

Reputation: 5437

I don't believe there's a good way to just automatically remove trailing whitespace at commit time (and I don't believe it'd be a good idea to do it if you could).

I've used a hook before to reject commits that add trailing whitespace, which worked well for me; create/add the following to .git/hooks/pre-commit and make it executable:

# Work out what to diff against
if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

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

Upvotes: 1

Simon Richter
Simon Richter

Reputation: 29586

Git by default warns about trailing whitespace, and can be configured to reject commits that add whitespace errors.

Removing the whitespace works only by changing the files and redoing the git-add stage -- while it would be possible to do this automatically on add, this would leave a working tree that is different than what is staged, so the files would still show up as "changed but not updated" in git-status output.

The easiest way to remove trailing whitespace is

sed -i -e 's/[:blank:]*$//' file.c ...

Upvotes: 0

Related Questions