views:

672

answers:

2

I use tabs for indentation in my python programs, but I would like to collaborate (using git) with people who use spaces instead.

Is there a way for git to automatically convert between spaces and tabs (say, 4 spaces = 1 tab) on pushing/fetching? (similar to the CR/LF conversion)

+19  A: 

Yes, one potential solution is to use a git attribute filter driver (see also GitPro book), to define a smudge/clean mechanism.

alt text

That way:

  • each time you checkout some files of your repo, spaces can be converted in tabs,
  • but when you check-in (and push and publish), those same files are stored back using only spaces.

You can declare this filter driver (named here 'tabspace') in the .git/info/attributes (for a filter applied to all files within the Git repo), with the following content:

*.py  filter=tabspace

Now run the commands:

git config --global filter.tabspace.smudge 'script_to_make_tabs'
git config --global filter.tabspace.clean 'script_to_make_spaces'

See Olivier's answer for a concrete working example of such a smudge/clean set of instructions.

VonC
This seems to be *precisely* what I was looking for! Could you fix the links in your post, please? Thanks a lot!
Olivier
@Olivier: I just fixed the links ;)
VonC
Unfortunately, it just doesn't work. I followed all the instructions, but git does not apply the fiter. :-( When I checkout, the smudge filter is not applied, and when I checkin, nothing happens either... git is so frustrating sometimes...
Olivier
@Olivier: Strange, I never had any problem with that, as long as I carefully limit the scope of the attribute filter (to a specific subtree, for a specific type of files only) in order to not slow down the checkout/check-in process. See for instance http://stackoverflow.com/questions/62264/dealing-with-svn-keyword-expansion-with-git-svn
VonC
Thanks! Now it works. See the complete solution: http://stackoverflow.com/questions/2316677/can-git-automatically-switch-between-spaces-and-tabs/2318063#2318063
Olivier
+13  A: 

Here is the complete solution:

In your repository, add a file .git/info/attributes which contains:

*.py  filter=tabspace

Now run the commands:

git config --global filter.tabspace.smudge 'unexpand --tabs=4 --first-only'
git config --global filter.tabspace.clean 'expand --tabs=4 --initial'

You may now check out all the files of your project. You can do that with:

git checkout --force

and all the python files will now have tabs instead of spaces.

Olivier
Interesting feedback. Thank you. +1
VonC
@Olivier: nice trice, the `git checkout --force` (quicker than remove and checkout again the relevant files)
VonC