Some git tricks - 1/2

With a teammate at work, we had the idea of sharing a new git tricks/tips everyday. You'll find below some of them that I think can be useful for everyone.

Who added this file ? 🤓

When entering a project, I wanted to check if there was any .gitignore file before creating one. And yes, there was one, and by curiosity, I wanted to check who added it.

I was able to figure it out by doing :

git log --diff-filter=A -- fileName

commit 4b8d6c960e0850273901f1e0dc9a5de0b3ab7d29  
Author: Aymen Rebouh <aymen***@gmail.com>  
Date:   Wed Oct 19 11:51:20 2016 +0100

    Add .gitignore file

If you look at the value affected to the filter --diff-filter=A, A means Add, so it works also with D for Delete, M for Modified, etc...

But this command line is not that easy to remember, right ? By adding this alias :

git config --global alias.whoadded 'log --diff-filter=A'  

You can now do :

git whoadded .gitignore  

Better, right ?

Git amend without without updating commit message 😎

For those who don't know the amend trick, it's an option when committing that lets you add new changes directly to your last commit.

git log

5cac4fe (HEAD -> master) Add Test  

We can see that there is a commit with Add Test as title.
But what if you forgot to add for example comments to your code ?

One thing we generally do is making the changes and creating a new commit, something like :

git add .  
git commit -m "Add comments for better use"  
git log

9b20d05 (HEAD -> master) Add comments for better use  
5cac4fe Add Test  

But why creating a new commit for that and making your git history horrible, if one commit is enough ? By using the --amend option, I can add all my current changes to the last commit and have a clean git history :

git add .  
git commit --amend  
git log

5095e00 Add Test  

Your comments have been added to the Add Test commit, and you can see that the commit hash changed as well.

We're not finished. When amending, git offers you the possibility to change the commit message (by default), and it can be annoying if it always open a text editor for that 😒.

So if you don't want to change the commit message, you can add the --no-edit option.

✅ git --amend --no-edit

Last but not least 😈

Well, it's not an amazing trick, but this is how your manager can see how many lines of codes you wrote today :

git diff --shortstat "@{0 day ago}"`

20 files changed, 4844 insertions(+), 4362 deletions(-)