Skip to main content

08 - Atomic Commits and Messages You Can Still Read in a Year

Split an afternoon of edits into commits you can undo one at a time, with a title, body and footer that explain why.

What do you think about this article?

08 - Atomic Commits and Messages You Can Still Read in a Year
Gitfedericocalo.dev

At a Glance

Split an afternoon of edits into commits you can undo one at a time, with a title, body and footer that explain why.

One commit, one reason to exist

A year from now someone will open git log to understand why a cart discount is computed a certain way, and will find a line that says "fix". That someone will almost always be you. An atomic commit holds a single change that you can describe in one sentence without an "and" in the middle; its message has a short first line saying what changes, an empty line, and a body explaining why.

The git commit manual recommends a summary line of no more than 50 characters, and notes that the text up to the first empty line is the title Git uses everywhere, for example as the subject of the emails that git format-patch generates from commits.

The two habits reinforce each other. A small commit has a title that is easy to write; a precise title makes it obvious when a commit contains two things.

The payoff shows when you must undo one change without taking the others with it, when you search with git log --grep, and when whoever reviews the pull request reads one reason at a time.

You only need the concepts of staging area and commit; if you want to rewrite commits already made, see the article on interactive rebase.

Every command was run with Git 2.53.0 in a test repository created in a temporary folder and never pushed; the commit identifiers in your repository will differ, and in the text I abbreviated a single path with [...]. The test repository was configured with an Italian locale, so some messages Git prints in the listings are in Italian: they are real output, left untouched.

One evening, three changes in the same tree

The typical case is not the tidy commit: it is the afternoon in which, while fixing a bug, you add a function you needed and update a documentation file. At the end you have a working tree with three distinct changes.

The test repository has a carrello.py module with an error (the percentage discount is subtracted as a flat amount) and a README.md.

The block below shows the result of the day: git status --short lists two modified files and git diff on the module shows two hunks, that is, two blocks of change separated by unchanged lines. The first is the fix, the second is the new function con_iva.

Three changes, two files
$ git status --short
 M README.md
 M carrello.py

$ git diff carrello.py
diff --git a/carrello.py b/carrello.py
index d7ff1fd..d288744 100644
--- a/carrello.py
+++ b/carrello.py
@@ -5,8 +5,7 @@ def totale(righe, sconto_percento=0):
     somma = 0
     for prezzo, quantita in righe:
         somma += prezzo * quantita
-    # BUG: lo sconto viene sottratto come cifra, non come percentuale
-    return somma - sconto_percento
+    return somma * (100 - sconto_percento) / 100
 
 
 def formatta(importo):
@@ -19,3 +18,7 @@ def righe_vuote(righe):
 
 def descrizione(righe):
     return "%d righe" % len(righe)
+
+
+def con_iva(importo, aliquota=22):
+    return importo * (100 + aliquota) / 100

A single git add carrello.py would stage both hunks and produce a commit that does two things. Before touching any command, it is worth asking whether the commit you are about to make passes these checks.

  • Can I describe it in one sentence without an "and"?
  • If I undid it on its own, would the rest of the work stay consistent?
  • Does the reviewer have to keep a single reason in mind?
  • Can the message say why, and not only what?
  • Does the test that proves the change live in the same commit as the change?

These are questions, not mechanical rules: the last one, for example, tells you to keep the code together with the test that proves it, because a test in a separate commit is easily lost when someone undoes only the code. If two answers out of five are "no", the commit should be split before it is made, and git add -p is the tool for doing it.

Separating hunks with git add -p

The -p option (--patch) of git add shows one hunk at a time and asks whether to stage it. Among others it accepts y (yes), n (no), s to split a hunk into smaller pieces when there is enough space between the changed lines, e to edit it by hand and q to quit; without restriction options it acts on all modified files, and here I limited it to carrello.py.

In the block the answers come from a pipe, y for the first hunk and n for the second, so that the run is reproducible; in a terminal you type them yourself.

After the selection the status is MM for the module: the first letter says that one part is staged, the second that another part is still only in the working tree. git diff --cached --stat confirms that the staging area holds one added line and two removed ones, that is, the fix and nothing else.

Selecting hunks, with the answers from a pipe
$ printf 'y\nn\n' | git add -p carrello.py
diff --git a/carrello.py b/carrello.py
index d7ff1fd..d288744 100644
--- a/carrello.py
+++ b/carrello.py
@@ -5,8 +5,7 @@ def totale(righe, sconto_percento=0):
     somma = 0
     for prezzo, quantita in righe:
         somma += prezzo * quantita
-    # BUG: lo sconto viene sottratto come cifra, non come percentuale
-    return somma - sconto_percento
+    return somma * (100 - sconto_percento) / 100
 
 
 def formatta(importo):
(1/2) Eseguire lo stage di quest'hunk [y,n,q,a,d,k,K,j,J,g,/,e,p,P,?]? @@ -19,3 +18,7 @@ def righe_vuote(righe):
 
 def descrizione(righe):
     return "%d righe" % len(righe)
+
+
+def con_iva(importo, aliquota=22):
+    return importo * (100 + aliquota) / 100
(2/2) Eseguire lo stage di quest'hunk [y,n,q,a,d,K,J,g,/,e,p,P,?]? 

$ git status --short
 M README.md
MM carrello.py

$ git diff --cached --stat
 carrello.py | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

The command has a faster cousin: git commit -p chooses the hunks and commits in one step, but it skips the stage where you can reread with git diff --cached what you selected. I prefer the two separate steps until the habit is in place. The limit of -p is that an indivisible hunk stays indivisible: if the fix and the new function were three lines apart, s would not separate them and you would have to use e, that is, edit the patch by hand, a delicate operation where a mistake produces a hunk that Git refuses to apply.

The message: title, empty line, body

Now that the staging area holds a single change, the message can be precise. The block uses git commit -m twice. The -m option accepts a text and uses it as the message; the manual says that if you pass more than one, the values are concatenated as separate paragraphs, which is why the first becomes the title and the second the body, with the empty line in between without you writing it. If you do not pass -m, Git opens the configured editor with a message template, which is the convenient form for long bodies; the -v option appends to the template the difference you are about to save, useful to remember what you did.

What goes wrong: unclosed quotes in the shell, which turn the body into a broken command, and apostrophes inside a text wrapped in apostrophes.

The body of the message shown explains the why with a verifiable number, because 200 minus 10 gives 190 and not 180, a detail the diff alone does not tell.

A commit with title and body
$ git commit -q -m 'fix(carrello): sconto come percentuale' -m 'Prima lo sconto veniva sottratto come cifra: con sconto_percento=10 un
totale di 200 diventava 190 invece di 180. Ora il totale è moltiplicato
per (100 - sconto) / 100.'

$ git log -1 --stat
commit 94430c178c691b84f37ba37af57a257b7ff51704
Author: Prova <prova@example.invalid>
Date:   Thu Nov 19 15:32:34 2026 +0100

    fix(carrello): sconto come percentuale
    
    Prima lo sconto veniva sottratto come cifra: con sconto_percento=10 un
    totale di 200 diventava 190 invece di 180. Ora il totale è moltiplicato
    per (100 - sconto) / 100.

 carrello.py | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

What do I put in the body, in practice? Almost never the "what", which the diff already shows better than any description. I write the information that the code does not contain and that the future reader cannot reconstruct.

  • The behavior before and after, with a concrete case.
  • The reason I chose this solution and not another.
  • A known limit or a side effect the reviewer must check.
  • The reference to an issue or a decision, as the last line.

If the change is trivial (a typo in the documentation) the body is not needed and the title is enough: a body written out of duty becomes noise. The rule I apply is that the body exists when the answer to the question "why?" is not obvious from the title.

The project format and Conventional Commits

A title without structure reads well as long as the history is short. This site's project uses the form <type>(<scope>): <subject>, with the types feat, fix, refactor, docs, test, chore, perf and ci; the rule lives in the instructions file at the root of the repository, in the "Branch e workflow" section, and it is an internal document I cannot link.

The form matches the public Conventional Commits 1.0.0 specification, which defines it like this: a type (a name such as feat or fix), an optional scope in parentheses, an optional exclamation mark, a colon and a space, then the description; after an empty line a free body, and after another empty line one or more footers.

  • feat adds a feature and, according to the specification, corresponds to a MINOR release in semantic versioning.
  • fix corrects an error and corresponds to a PATCH release.
  • refactor changes the structure without changing the behavior.
  • docs, test and ci touch only documentation, tests and automation.
  • perf improves performance; chore collects the maintenance that fits nowhere else.

In the specification only feat and fix have a mandatory meaning; the other types are a widespread habit that the specification cites as an example and does not impose, and they have no effect on versioning unless the commit declares a break.

The concrete advantage is that the history becomes filterable and that tools can build a list of changes; the cost is that the prefix consumes characters of the title. Measuring it takes one command: in my repository the four titles are between 24 and 39 characters long, but feat(carrello): aggiungi con_iva al 22% already has 39 and the prefix eats 16 of them.

Three commits, titles measured
$ git add carrello.py && git commit -q -m 'feat(carrello): aggiungi con_iva al 22%' && git add README.md && git commit -q -m "docs: documenta l'aliquota IVA"

$ git log --oneline
78f9067 docs: documenta l'aliquota IVA
1b80ba6 feat(carrello): aggiungi con_iva al 22%
94430c1 fix(carrello): sconto come percentuale
9867151 chore: carrello iniziale

$ python3 -c 'import carrello as c; print(c.totale([(100, 2)], 10), c.con_iva(100))'
180.0 122.0

$ git log --format=%s | awk '{print length($0) ": " $0}'
30: docs: documenta l'aliquota IVA
39: feat(carrello): aggiungi con_iva al 22%
38: fix(carrello): sconto come percentuale
24: chore: carrello iniziale

The python3 -c line is the proof that the two halves of the work function together: 180.0 for the 10% discount on 200, 122.0 for a price of 100 with 22% VAT. The check with awk is the way to know how far under the manual's 50-character suggestion you are, which is indeed a recommendation ("though not required") and not a limit imposed by Git. The trade-off is yours: a structured prefix makes the history machine-readable, but with titles as long as a whole sentence it is better to move the detail into the body.

Incompatible changes and footers

A change that breaks whoever uses it must be declared where the history shows it. The specification provides two ways, which can be used together: an exclamation mark right before the colon, or a footer whose token is BREAKING CHANGE in capitals; a footer is a line with a word, a separator : or #, and a value.

In the block the commit adds to totale a check that raises ValueError for discounts outside 0-100, as the body says, and proves it with a call at 120. The exception is real and the file line is true; I abbreviated only the path. The footer here uses BREAKING-CHANGE with the hyphen, and the reason is in the next block.

A declared break, and proven
$ git commit -q -a -m 'feat(carrello)!: valida lo sconto da 0 a 100' -m 'Un valore fuori intervallo ora solleva ValueError invece di produrre
un totale negativo.' -m 'BREAKING-CHANGE: chi passava sconti oltre il 100 riceve un errore.
Refs: #123'

$ python3 -c 'import carrello as c; c.totale([(100, 2)], 120)'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import carrello as c; c.totale([(100, 2)], 120)
                          ~~~~~~~~^^^^^^^^^^^^^^^^
  File "[...]/negozio/carrello.py", line 9, in totale
    raise ValueError("sconto fuori da 0-100: %s" % sconto_percento)
ValueError: sconto fuori da 0-100: 120

The hyphen is not a whim. The footer of a commit is also a Git trailer, and git interpret-trailers documents that in trailer lines there are no spaces before or inside the key. The Conventional Commits specification provides the solution: BREAKING-CHANGE is a synonym of BREAKING CHANGE when used as a footer token. In the next block the same message is read by Git twice, and the second time with a space in place of the hyphen: the result is empty, that is, Git recognizes no trailer at all, not even Refs: #123, which is written correctly.

What Git recognizes as a trailer
$ git log -1 --format='%(trailers:only)'
BREAKING-CHANGE: chi passava sconti oltre il 100 riceve un errore.
Refs: #123


$ git log -1 --format=%B | git interpret-trailers --parse
BREAKING-CHANGE: chi passava sconti oltre il 100 riceve un errore.
Refs: #123

$ git log -1 --format=%B | sed 's/BREAKING-CHANGE/BREAKING CHANGE/' | git interpret-trailers --parse

The practical consequence is this: if you want Git itself to extract the footer (with %(trailers) or with other tools that rely on it), the hyphen works; if your tool reads only the form with the space, the space works for it and not for Git. I have not verified how individual changelog generators behave, so the choice must be made on yours.

Fixing a commit without dirtying the history

It happens that you notice after committing that you forgot a line. For the top commit there is git commit --amend, which according to the manual replaces the tip of the branch with a new commit with the same parents and the same author, using the previous message as a starting point. For a commit further back there is --fixup=<commit>: it creates a commit whose title starts with fixup! and which git rebase --autosquash merges into the indicated commit, leaving its message intact.

The manual specifies that the rebase uses the interactive machinery but can run without -i; with GIT_SEQUENCE_EDITOR=true I accept the proposed list without opening the editor.

The --root option rewrites the first commit too, and it is needed here because the repository has few; in a real one you will indicate the commit above which you want to reorder.

fixup and autosquash
$ printf 'Le aliquote ridotte non sono ancora supportate.\n' >> README.md

$ git add README.md && git commit --fixup=78f9067
[main a14f530] fixup! docs: documenta l'aliquota IVA
 1 file changed, 1 insertion(+)

$ git log --oneline
a14f530 fixup! docs: documenta l'aliquota IVA
78f9067 docs: documenta l'aliquota IVA
1b80ba6 feat(carrello): aggiungi con_iva al 22%
94430c1 fix(carrello): sconto come percentuale
9867151 chore: carrello iniziale

$ GIT_SEQUENCE_EDITOR=true git rebase --autosquash --root
Rebase in corso (1/5)Rebase in corso (2/5)Rebase in corso (3/5)Rebase in corso (4/5)Rebase in corso (5/5)Rebase e aggiornamento di refs/heads/main eseguiti con successo.

$ git log --oneline
4d4027b docs: documenta l'aliquota IVA
1b80ba6 feat(carrello): aggiungi con_iva al 22%
94430c1 fix(carrello): sconto come percentuale
9867151 chore: carrello iniziale

Look at the identifier: the documentation commit was 78f9067 and is now 4d4027b. As in the article on rebase and merge, rewriting a commit changes its hash, and therefore both --amend and --autosquash should be used only on commits that nobody else has downloaded yet. For interactive rebase the manual provides that rebase.autoSquash enables the reordering by default; here I passed --autosquash explicitly, so that the result does not depend on your configuration.

Why it matters: undoing a single change

The advantage of atomic commits is measured when you need git revert, which creates a new commit able to cancel the effects of an earlier one. In the tidy repository the con_iva function turns out to be wrong, and I undo commit 1b80ba6: the discounted total keeps being 180.0 and the function disappears. The separate commit with the discount fix is untouched. Moreover git log --grep=sconto finds the fix because the title names it.

Undoing only the new function
$ git revert --no-edit 1b80ba6
[main da333a6] Revert "feat(carrello): aggiungi con_iva al 22%"
 Date: Thu Nov 19 15:32:34 2026 +0100
 1 file changed, 4 deletions(-)

$ git log --oneline
da333a6 Revert "feat(carrello): aggiungi con_iva al 22%"
4d4027b docs: documenta l'aliquota IVA
1b80ba6 feat(carrello): aggiungi con_iva al 22%
94430c1 fix(carrello): sconto come percentuale
9867151 chore: carrello iniziale

$ python3 -c 'import carrello as c; print(c.totale([(100, 2)], 10), hasattr(c, "con_iva"))'
180.0 False

$ git log --oneline --grep=sconto
94430c1 fix(carrello): sconto come percentuale

Note also what the revert did not do: the documentation commit, which talks about the VAT rate, is still there, and now describes a function that does not exist. Atomicity does not solve dependencies between commits; it reduces the damage and makes it visible, but cleaning up the commit that follows remains your job. For comparison, the next block redoes the same day as a single commit titled "fix", in a clone of the repository brought back to the first commit.

The same work in a single commit
$ git commit -q -a -m fix

$ git log --oneline
fa4f898 fix
9867151 chore: carrello iniziale

$ git revert --no-edit HEAD
[main 674d09b] Revert "fix"
 Date: Thu Nov 19 15:32:35 2026 +0100
 1 file changed, 2 insertions(+), 5 deletions(-)

$ python3 -c 'import carrello as c; print(c.totale([(100, 2)], 10), hasattr(c, "con_iva"))'
190 False

$ git log --oneline --grep=sconto

To remove the function I had to undo everything, and the discount bug came back: 190 instead of 180. The keyword search returns nothing, because neither the title nor a body (absent) names the discount. A year later, whoever finds the wrong cart has no clue where to look.

When not to split

The rule is not "more commits is better". Splitting has a cost, and in some cases it is better to keep things together.

  • A change and the test that proves it live in the same commit: separated, reverting the code leaves a failing test.
  • Renaming a function and all its call sites go together: halfway, the program does not start.
  • A large refactoring can be divided into steps, but each must leave the project runnable, otherwise git bisect stops on commits that do not compile.
  • Twenty one-line commits for the same change are not atomic, they are noise: the unit is the change, not the line.

The common criterion is that each commit, on its own, leaves the project in a state you can run and explain. In my test repository I did not verify the intermediate steps with a test suite, which does not exist: the only check is the small python3 -c shown, and for a real project the right check is a pipeline that also tests the intermediate commits.

Finally there is the question of enforcing the format: a commit-msg hook with commitlint rejects out-of-form titles before they enter the history, as the article on hooks shows, but a local hook can be skipped and does not replace a review.

What you can do now

You can split a working tree with several changes into distinct commits, choosing hunks with git add -p and checking the staging area with git diff --cached. You can write a message with a short title, an empty line and a body that answers "why", in the Conventional Commits form type(scope): description, and measure titles against the 50-character suggestion.

You can declare a break with the exclamation mark and a footer that Git recognizes as a trailer, fix an already-made commit with --fixup and --autosquash without forgetting that it changes the hash, and undo a single change with git revert, knowing that dependencies between commits still have to be checked by hand.

Frequently asked questions

What is an atomic commit in Git?

It is a commit that contains a single change, describable in one sentence without an "and". It can be undone, searched and reviewed on its own, without dragging along unrelated changes.

How long should the first line of a commit message be?

The git commit manual recommends no more than 50 characters, followed by an empty line and a fuller description. It is a recommendation and not a limit imposed by Git.

How do I put only part of a file's changes in a commit?

With git add -p you choose the hunks one at a time (y to include, n to skip). Before committing, you check what is staged with git diff --cached.

Why is the BREAKING CHANGE footer not read as a trailer by Git?

Because git interpret-trailers does not allow spaces inside a trailer key. The Conventional Commits specification accepts the synonym BREAKING-CHANGE, which Git recognizes.

Sources

  • git-commit - official Git documentation - 50-character title and empty line (Discussion section), repeated -m, --amend, --fixup; page reached and local manual read with git help -m commit, consulted on 2026-11-19
  • Conventional Commits 1.0.0 - structure of type, scope, description, body and footer; feat and fix; BREAKING-CHANGE as a synonym; consulted on 2026-11-19
  • git-interpret-trailers - official Git documentation - no space inside a trailer key (read with git help -m interpret-trailers, consulted on 2026-11-19)
  • git-rebase - official Git documentation - --autosquash and rebase.autoSquash (read with git help -m rebase, consulted on 2026-11-19)
  • Project commit format: instructions file at the root of the repository (private, not linkable), "Branch e workflow" section.
  • Examples run with Git 2.53.0 (git --version) in a local test repository, without any push, on 2026-11-19.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects