Sean Allred
Sean Allred

Reputation: 3658

git-add only whitespace changes?

The style of my project does say to trim trailing whitespace, but this makes diffs very, very messy. I like to consolidate them to one commit before I commit the actual fix.

This is closely related to Add only non-whitespace changes, but it is asking the exact opposite:

Is there a way to add only the whitespace changes to the staging area?

Upvotes: 36

Views: 12642

Answers (3)

pLiKT
pLiKT

Reputation: 130

I had to combine and modify Tobias' and nneonneo's answer to commit the whitespace of multiple files with large diffs. Make sure to run this from the root of your repository.

git add -A
for FILE_NAME in $(git --no-pager diff --name-only --diff-filter=ACMR --full-index HEAD)
do  
    git --no-pager diff --cached -w $FILE_NAME | git apply --cached -R  
done

git --no-pager prevents the default scrolling that git uses to display large amounts of content. The --name-only loop allows the command to work on multiple files.

Upvotes: 2

Tobias
Tobias

Reputation: 51

here is a bash solution that worked for me

for fname in $(git diff --name-only  --diff-filter=ACMR --full-index HEAD)
do
   diff=$(git diff -w --ignore-blank-lines --exit-code $fname)
   if [ $? -eq 0 ]; then
      echo "only whitespace diff on $fname ! adding to git..."
      git add $fname
   else
      echo "diff on $fname!"
   fi
done

Upvotes: 3

nneonneo
nneonneo

Reputation: 179402

You can try the following "trick":

git add -A
git diff --cached -w | git apply --cached -R

This basically adds everything to the index, then unstages all changes which affect more than whitespace.

Upvotes: 50

Related Questions