World map

 

BM: Baca dalam Bahasa Melayu

World 1: Save Points

Small, focused commits

You will learn: how to split your work into small commits with git add -p.

The problem

index.html wobbles with a changed tag. It holds two different changes.

You fixed a typo in the title. You also wrote Day 4. Both changes are in index.html. Should they share one commit?

Watch

One big commit called Fix typo and add day 4 splits into two small commits: Fix title typo, and Add day 4 entry.

Good commits are small: one change per commit. Then every message tells the whole truth. And you can undo one change without losing the other.

Watch

git diff for index.html shows two separate pieces. The first fixes the title. The second adds Day 4. Terminal output: $ git diff diff --git a/index.html b/index.html index 9d0e2be..eba3f8d 100644 --- a/index.html +++ b/index.html @@ -1,7 +1,7 @@ <!DOCTYPE html> <html> <head> -<title>My Dairy</title> +<title>My Diary</title> <link rel="stylesheet" href="style.css"> </head> <body> @@ -10,5 +10,6 @@ <p>Day 1: I made a repo.</p> <p>Day 2: I learned the box.</p> <p>Day 3: I made my first commit.</p> +<p>Day 4: I learned small commits.</p> </body> </html>

git diff shows two separate pieces of change. Each piece is a hunk. Git can save one hunk and leave the other.

Try it

This commit will be “Add day 4 entry”. Pick only the pieces that belong.

Pick the changes that belong in this commit.

index.html

  1. -<title>My Dairy</title>+<title>My Diary</title>
  2. +<p>Day 4: I learned small commits.</p>
  3. +<p>test test 123</p>

Try it

Type git add -p. Answer n for the typo fix, and y for Day 4.

Working folder
Staging area
  • Empty
Repository
  • 2 save points
  • Add home page
  • Add README

Predict

Now you run git status -s. What do you see for index.html?

Pick one answer.

You did it!

You can now split your work into small, focused commits.

Go deeper (optional)

More answers for git add -p:

  • q quits.
  • a takes this hunk and the rest of the file.
  • d skips the rest of the file.
  • ? shows help.

Real Git has even more, like s to split a big hunk.