I’ve always asked myself, if git can ignore files (using .gitignore), can it also ignore file lines? Well, not by default, but you can hack it.
It might sound stupid, but say you are working with a bunch of guys on a project, where somewhere in an important file you have something like this;
... def connect_db(): username = "root" password = "password" host = "localhost" ...
Of course this is a stupid example, you would probably put the username, password and other important stuff in another file, say a config file, but let’s assume that this is not possible, or somehow this variable cannot be else where.
What do you do? Because now we have a problem, when cloning the repository, you will need to fill these information, run your code and eventually make some changes and just before commiting, you will go back to the line with your personal information, remove that information (leave it blank or whatever), then you will commit and push your changes. Imagine doing this 30 times a day.
So how can we do this? We can tell git to ignore the line when commiting.
We need to create a .gitattributes in your repository (remember that .gitattributes will be commited into the repository, if you don’t want that, add it to .git/info/attributes)
.py filter=ignoreline(run filter named
Now, we need to define
git config --global filter.ignoreline.clean "sed '/#ignoreline$/'d"(delete these lines)
git config --global filter.ignoreline.smudge cat(do nothing when pulling file from the repository)
Now we are set. Basically this will be applied for every Python file everytime a line ends with
... def connect_db(): username = "root" #ignoreline password = "password" #ignoreline host = "localhost" #ignoreline ...
Every time you commit and push, these lines will be ignored. Though, there is one problem, this will leave your working file different from your repository (makes sense, uh?), so, if you checkout or rebase your current branch, these lines will be lost, no where to find.
There is one solution, though a very ugly one.
git stash save "personal-details" while the filter is off (temporarily disable in
Using the stash, I can always
stash apply to my code without doing anything silly and get those lines back.
|This should be used for fun only, since this aproach sucks and you should have a separated config file somewhere else, only use this approach in case there really isn’t any other way (if this is the case, you should rethink your code design).|