Atomic Commits Using Partial Commits
Hey đ,
I have been using Git for a long time, but never really focused on doing smaller commits until three years ago. When I joined Automattic.
I think there is a healthy obsession on doing granular commits with meaningful descriptions.
Since then, I have become much more conscious about doing just the change I have in mind, and working step by step. With a clear vision on why I am going every change I am doing.
Despite that, I still sometimes get carried away (the flow people say) and I end up with a big set of changes. Oopsy.
It’s in these times that partial commits makes a lot of sense.
Partial Commits with GIT
âšī¸ I use GIT mostly from CLI. If you are using some UI this might not be as useful, but probably the steps are similar. Look for “partial commits” in your tool of choice.
Usually I do some changes and the git add .
and git commit
. But if I don’t want to commit all the changes in a single commit then this is what I do.
First, if I am lucky there is enough separation of concerns betweeen the files so I can choose what files to commit by separate.
In these situations instead of git add .
(which adds everything) I do git add <file1> <file2> <file3>
. Then git commit
.
Most times this is not enough, because I have in fact made multiple different changes to the same file.
Maybe I added a function, refactor another method, included a new dependency… Multiple different smaller things.
This is when git add -p .
(or git add -p <file1>
) comes handy.
It will interactively ask you if a chunk of changes needs to be added or not. You can choose between different options by pressing the corresponding letter.
You can get a sense of what each option makes by using the ?
response. But I will mention the ones I use the most:
y
: Yes. Please, add this chunk to the staged (to be included in the nextgit commit
action).n
: No. Please don’t add it. This will be part of another later commit.s
: This chunk is too big, contains multiple things. Please split it into smaller parts.d
: I am done with this file. Interactive session will continue with the next file (if there is any).q
: I am done adding partials. Quit this inveractive session.
Easy right? Next you should try it yourself and get used to it.
Extra notes
- Initially what I do is review the full set of changes (
git diff
) to decide what part I can commit separately. - Sometims
s
pliting is not possible. In these situations I usually go with the bigger chunk as it is. There is an option toe
dit a chunk manually, but I’ve never used it yet. - Even though I try, sometimes this leads to commits in which the code is actually broken. I don’t like this, but it’s not a big deal since I usually work on
feature/
branches.
Was this useful to you? Please let me know by clicking the like button below.
Also feel free to reach out to me. I though on doing some short video with an example but didn’t find the time.