Git commits essentials

by Hélio Correia

git

The art of good commits

To make good commits is quite simple. A good commit isn’t a long paragraph with a lot files and neither some sloppy commit messages like ‘fix’, ‘ok’ or a simple ‘.’.

Good commits is when you do one thing and you commit that simple thing.

For example, if you have a website and you want to change the title. You change the title and you commit with the message ‘Change website title’.

One paragraph isn’t enough and now??

Sometimes just one paragraph is not enough to explain what you did. In that situation you can do this trick:

Git commit -m "Fix a translation bug:

    - Change DummyTemplateTag
    - Make a migration on Dummy Model
    - Change the base template"

This is useful because your git log —online and most services (github, gitlab, bitbucket) only shows one line. Then when you see the ‘:’ in the end, you know that there is more content there.

Sometimes you already know this things

Yes, you are reading this and you probably know this, but don’t be sad the last part is for you.

You forget to make commits

This is my common oversight, I done so much work, then I notice ’Today I didn’t make any commit’. When I do this I use the command *git diff to understand what I did in each file and make a few commits with concise messages.

Oh man! I did so many different things in this file

Sometimes you make a bad commit because you did so many things in one file and you don’t know that to do. Then you make a commit with the word ‘and’ right? Like ‘Add this feature and fix this bug’ wow!

Git add -p

This command exists to add only a part of the file. To use that, you add a file with this command.

git add -p path/to/file

After that, it opens the file and divide the changes in stacks and shows the first stack with the following options ([y,n,q,a,d,/,K,g,s,e,?]?).

From this options you only need this four:

y - Yes, add this hunk.
n - No, don’t add this hunk.
s - Split the current hunk into smaller hunks, this is useful when the stack that git shows two different things that you want to commit it separately. If the ’s’ didn’t show, you pick the ‘e’ options and you edit it.
q - Quit; do not stage this hunk or any of the remaining ones.

It may seems confusing but give a try and you will find it easy.

You make a mistake? Make an amend

Sometimes you make a commit but you forget to add some files to the stage area right? What you can do in that situation? Make another commit with a new message? No! In this situation you do an amend:

git commit --amend

With this command, the files that you forgot to add, will be included in the last commit that you made.

Amend the commit message

Sometimes you may choose a bad commit message and you want to change it, in this situation this command will do the trick:

git commit --amend -m 'New commit message'