Commits and branches

Introduction

Git is the tool nearly every open-source project uses to record its history. A commit is one saved step in that history, and a branch is a line of commits where you can try a change safely. The way you commit decides whether your work is easy or hard for a maintainer to review, so it is worth learning the habits early.

You will not run Git in this course, but the commands are shown as text, and the programs here model what Git and its tools do: they parse messages and count lines in a diff.

How it works

You start a change by making a branch from the up-to-date main branch, then edit files, check what you changed, collect it, and commit it:

git switch -c fix/empty-average     make a branch and move to it
git status                          which files changed
git diff                            what exactly changed
git add average.py tests.py         put these files in the next commit
git commit -m "Fix crash on empty list"
git log --oneline                   the history, one line per commit

A diff shows each changed file, with lines that start with + for added lines and - for removed lines. Reading your own diff before you commit catches debug prints, stray files and unrelated edits.

Make small commits: one idea per commit, so each one can be understood, reviewed and, if needed, reverted alone. Write the message so that it finishes the sentence "If applied, this commit will ...": use the imperative, Fix crash on empty list, not Fixed or Fixes. Many projects want a first line of at most 50 characters, a capital letter at the start and no period at the end, then a blank line and a longer explanation of why the change was made.

Some projects use conventional commits: type(scope): description, for example feat(parser): support nested lists. The type (feat, fix, docs, test, chore) lets tools build a changelog and choose the next version number by themselves.

Name a branch for what it does: fix/empty-average, feature/dark-mode or docs/install-steps. Lower case and hyphens keep names easy to type.

Example

log = [
    "feat(parser): support nested lists",
    "fix(cli): exit with code 1 on bad input",
    "docs: explain the install steps",
    "fix(parser): handle empty files",
    "chore: update dependencies",
]

groups = {}
for message in log:
    head, _, description = message.partition(": ")
    kind = head.split("(")[0]
    scope = head[len(kind) + 1:-1] if "(" in head else "-"
    groups.setdefault(kind, []).append((scope, description))

for kind in sorted(groups):
    print(f"{kind} ({len(groups[kind])})")
    for scope, description in groups[kind]:
        print(f"  [{scope}] {description}")
Open in compiler

Line by line

  1. log holds five commit messages in the conventional style.
  2. partition(": ") splits each message into the head (feat(parser)) and the description.
  3. The head is split again into the type and, when there are brackets, the scope; setdefault collects messages by type.
  4. The last loop prints the types in alphabetical order, each with its messages.

Expected result

chore (1)
  [-] update dependencies
docs (1)
  [-] explain the install steps
feat (1)
  [parser] support nested lists
fix (2)
  [cli] exit with code 1 on bad input
  [parser] handle empty files

In the real world

Release tools read conventional commits to write the changelog and to decide the next version, as the later lesson on versions shows. Even without tools, a clean history helps: git log and git blame are how future contributors learn why the code is the way it is, and a history full of "stuff" and "more fixes" hides that.

Common mistakes

  • One giant commit with ten unrelated changes. Nobody can review it.
  • Committing on the main branch of your fork, which makes it hard to keep up to date.
  • Vague messages like update or fix. Say what changed.
  • Committing files that should not be there: build output, secrets and editor files. Check git status first.

Best practices

  • One logical change per commit, with the tests that go with it.
  • Imperative first line under 50 characters, then why in the body.
  • Make a new branch for every change, named for what it does.
  • Run git diff and read it before every commit.

Summary

A commit is a small, described step in a project's history and a branch keeps your work apart from the main line. Read your diff, make one change per commit, and write the message in the imperative. Following a fixed message style such as conventional commits lets tools read the history too.

Quick check

1. Which commit message follows the usual rules?
2. In a diff, which lines start with a minus sign?
3. Why work on a branch and not on main?
4. What does the type in feat(parser): support lists tell a tool?

Key takeaways

  • A commit is a small, complete step with a message that says what and why.
  • Work on a branch, never directly on the main branch.
  • Read your own diff before you commit or open a pull request.
  • A message that follows a fixed style can be read by tools as well as by people.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.