Git: how to deal with different shebang

1.8k Views Asked by At

How do people deal with different shebangs between local and remote?

For example, my local python is /usr/bin/python, whereas my web host is a purpose-built python at ~/local/bin/python. A lead developer may have ruby at /usr/bin/ruby, whereas mine is /usr/local/bin/ruby.

I manually edit the shebang, but then git marks it as a change. Ideally, I would like git to ignore the first line of the file, or perhaps to ignore a regex match of lines within the file.

It seems to me this must be a very common problem, but I cannot find any mention of it.

I use git, but I would not call myself an expert by any stretch.

3

There are 3 best solutions below

7
On

Change it to

#!/usr/bin/env python

or

#!/usr/bin/env ruby

Then it should work on all your systems, provided you have python and ruby in your PATH environment variable.

0
On

This belongs in the comments but I don't have enough reputation yet... You could just remove the hash bang and always run it with python when you run it from the command line... maybe...

1
On

The solution to your problem is git’s smudge/clean filter rule. This allows you to set up filters that will modify files on checkout and undo those changes on checkin. Here’s a nice graphic:

enter image description here

First set up a the filters that can do the change in both directions, by adding something like the following to you .git/config. The smudge filter transforms the file in the repo to the working copy, the clean filter undoes that change. It is important that running smudge -> clean yields exactly the original file. The filters given here will replace the first line with #!~/local/bin/python in the working copy if it is #!/usr/bin/env python in the repo

[filter "pyshebang"]
    smudge = sed '1s?^#!/usr/bin/env python$?#!~/local/bin/python?'
    clean = sed '1s?^#!~/local/bin/python$?#!/usr/bin/env python?'

Now activate this filter by adding a line like this to .git/info/attributes (create that file if it doesn’t exist):

*.py filter=pyshebang

If your python files don’t end in .py, just configure the filter on the correct files / a whole folder / all the files. If you set up the filter correctly it will only change files with a python shebang anyways.

I would recommend to read up on smudge filters, to understand the details of what’s going.