All in One View

Content from Welcome and the Story


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • What will we do over these two half-days, and why?
  • What is the project we’ll be working on?

Objectives

  • Explain what “curating history” means
  • Check your setup works
  • Meet peakfinder and your pair partner

Welcome


This workshop is about a habit more than a command:

Leave a git trail that is easy to review, merge and understand.

You already know how to make history. Over the next two half-days we’ll learn how to curate it: to shape the commits you leave behind so that the people who read them, including you in six months, can follow what happened and why.

It is not a course on obscure git commands. It’s a course on how one working style, with a handful of tools, makes collaboration much easier. Along the way we’ll look inside git, because the tools make more sense when you know what git is doing.

Why bother?


Two versions of the same piece of work, as a git log. Take a moment to read them.

Version A

OUTPUT

d8cc138 readme
9e1626f try smoothing
4244130 fix typo
2b17bef cli stuff
9a6471e remove print
89f7c6f add tests
33aa1de fix
21dd6b4 tidy up
ead2b48 wip
cd6792e add background module

Version B

OUTPUT

b8f52dd Document --subtract-background in the README
e7fab65 Add --subtract-background option to the CLI
514955f Add tests for background subtraction
37e6d49 Add rolling minimum background subtraction
17f1b3d Check x and y are the same length in find_peaks
754c449 Let load_spectrum skip a variable number of header rows
5fb3ed3 Handle constant spectra in normalise

The two contain exactly the same code. Only the story is different.

Challenge

Discussion: which would you rather review?

Vote (a show of hands in the room, or a reaction in the chat) for the one you’d rather review. Then, with the person next to you (or in the chat), say why. Think about:

  • Could you tell what each commit is for?
  • What if a bug turned up in one of the changes? Which log makes it easier to find, undo or copy somewhere else?
  • Which one tells you why the code changed, not just that it did?

Nearly everyone picks B. In A, you can’t tell what wip, fix or tidy up mean without opening each commit. Some of the changes are unrelated to each other. And one commit, try smoothing, is an experiment that was abandoned.

In B, every line says what the change is, and each change is separate. You can review them one at a time, revert one, or copy a single fix onto another branch.

By the end of tomorrow, you’ll be able to turn A into B, and better, you’ll learn how to write B in the first place.

The story


Throughout the workshop we’ll work on a small Python package called peakfinder. It finds peaks in spectra: the bumps in a curve that tell you something about a sample. You’ll need no knowledge of spectroscopy. The code is deliberately short and plain.

Try it, now. In your peakfinder clone (with your virtual environment active):

BASH

python -m peakfinder.cli data/example_spectrum.csv | wc -l
python -m peakfinder.cli data/example_spectrum.csv --plot

OUTPUT

71

The program reports 71 “peaks”, but there are only three real ones. All the other bumps are noise. (If a plot window appears, you’ll see the three big peaks and a lot of little red dots. If no window opens, use --save-plot spectrum.png and open the file.)

We have a job to do. We’re going to improve peakfinder, and we want to do it in a way our collaborators can follow.

flowchart LR
    accTitle: {The story across the two days}
    accDescr: {Six steps in order. Day 1, shown in green: rescue a messy branch, then build your own feature with tidy commits. Day 2, shown in blue: a colleague's work lands first and you resolve the conflict, you find the change that caused a bug, you review each other's work and set up CI, and you release a fix.}
    A1["Day 1<br/>Rescue a<br/>messy branch"] --> A2["Day 1<br/>Build your own<br/>feature, tidily"]
    A2 --> B1["Day 2<br/>Colleague's work lands:<br/>resolve the conflict"]
    B1 --> B2["Day 2<br/>Find the change<br/>that caused a bug"]
    B2 --> B3["Day 2<br/>Review each other,<br/>set up CI"]
    B3 --> B4["Day 2<br/>Release<br/>a fix"]
    classDef day1 fill:#dfd,stroke:#080,color:#000
    classDef day2 fill:#def,stroke:#05a,color:#000
    class A1,A2 day1
    class B1,B2,B3,B4 day2
  • Day 1: you are the author. You’ll learn how git really works, how to plan changes, and how to rescue a messy branch. Then you’ll build a feature of your own, one tidy commit at a time.
  • Day 2: you are a collaborator. A colleague’s work lands on main while you were busy, so you’ll deal with the conflict. Then you’ll track down the change that caused a bug, review each other’s work, and release a fix.

The plan for the two days


  • Day 1: making history. How git really works, planning and atomic commits, a safety net, shaping commits, rewriting a messy branch, and the daily loop that keeps history tidy.
  • Day 2: sharing and maintaining history. Rebase versus merge and conflicts, tracking down a bug, pull requests, catching problems early with CI, and releasing a fix.

The episodes are listed in the sidebar. We’d rather go at a comfortable pace than cover everything. If we run short of time, we’ll skip things at the end, rather than rush.

Work in pairs


You’ll work in pairs. Your partner is the person who reviews your pull request on day 2, and who you can ask for help. You each work on your own computer and your own copy of the project.

Online, we’ll put you in breakout rooms of two.

Do this now, to save time tomorrow. Give your partner access to your fork:

  1. On GitHub, open your fork of peakfinder, then Settings, then Collaborators, then Add people.
  2. Enter your partner’s GitHub username.
  3. Your partner will get an email invitation, and should accept it. (You can also accept at https://github.com/YOUR-USERNAME/peakfinder/invitations, using your own username.)

Do it in both directions, so you each have access to the other’s fork.

Quick check before we start


Please check the following. Put a hand up (or message the helpers) if any of them is a problem:

Ground rules


  • Ask questions at any time. If something looks odd, it probably is, and someone else is wondering too.
  • Help your partner, but let them type. People learn from doing.
  • Nothing here is permanent. We’ll be breaking things deliberately, and git almost always lets us get back. We’ll learn how in episode 4.
  • We follow The Carpentries Code of Conduct.
Key Points
  • This workshop is about curating history: leaving commits that are easy to review, merge and understand
  • The same code can have a confusing history or a clear one, and the clear one is far easier to work with
  • Day 1 is about producing good history, and day 2 is about sharing and maintaining it
  • You’ll work in pairs, and your partner reviews your pull request

Content from A Mental Model: Snapshots and Labels


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • What is a commit, really?
  • What are branches and HEAD?
  • Why does “rewriting history” create new commits, rather than editing old ones?

Objectives

  • Describe a commit as a snapshot that points to its parent
  • Explain why changing a commit changes its hash, and the hashes of everything after it
  • Explain branches and HEAD as labels that point at commits
  • Use this model to predict what a command will do

Why bother?


You already use git every day without knowing what is inside it, and that’s fine. But in this workshop we will be changing history, and it’s much less scary if you know what git is actually doing. We need just four ideas.

Idea 1: a commit is a snapshot


You have probably heard that a commit is “a set of changes”. That is a useful way to think about it, and we will use it too. But it is not what git stores.

Git stores a snapshot of your whole project at that moment, along with a message, an author, and a pointer to the previous commit (the parent).

Let’s look inside a real one. In your peakfinder clone, first list the latest commits. The top one is the commit that HEAD is on, which means “where you are now”:

BASH

git log --oneline -3

Now print the commit object for that commit. This is the commit as git stores it:

BASH

git cat-file -p HEAD

OUTPUT

tree 82fa2f38d5d1864f890ecd4ef923bafbb8e65985
parent b7cf029bfa65c05266bfce11a30c889f9e36378d
author Sam Scientist <sam.scientist@example.org> 1736175600 +0000
committer Sam Scientist <sam.scientist@example.org> 1736175600 +0000

Add plotting of the spectrum and its peaks

That is all a commit is: a small piece of text. (cat-file -p prints a git object, and here the object is the commit at HEAD.) Three things are worth noticing:

  • tree is the hash of another git object (a tree), which stores a snapshot of every file in the project at this point in time. We won’t go any deeper than that.
  • parent is the hash of another commit: the one that came before. Look back at your git log output and you’ll find it just below.
  • The rest is the author, date and message.

Here is the part that matters. A commit’s hash is (essentially) a hash of this text. You can check:

BASH

git rev-parse HEAD
git cat-file -p HEAD | git hash-object -t commit --stdin

OUTPUT

1e81f2713978c508941a5b8366aabd892b635104
1e81f2713978c508941a5b8366aabd892b635104

The same hash, twice. (git log --oneline only shows the first 7 characters.) Keep this in mind, as the text includes the parent’s hash, and we’ll see in a moment why that matters.

So where is the “change”? It isn’t there. When you run git show or git diff, git works out the differences between two snapshots on the spot.

flowchart RL
    accTitle: {Commits are snapshots that point to their parent}
    accDescr: {Three commits, C1, C2 and C3, drawn left to right. Each is a snapshot of the whole project. Each has an arrow pointing back to the commit before it, which is its parent.}
    C3["C3<br/>snapshot"] -->|parent| C2["C2<br/>snapshot"]
    C2 -->|parent| C1["C1<br/>snapshot"]

Notice that the arrows point backwards, from each commit to its parent. That’s how git stores it: a commit knows its parent, but it doesn’t know its children. So in all the diagrams from here on, time runs from left to right: the oldest commit is on the left, and the arrows point back towards it.

Callout

So is a commit a snapshot or a diff?

Both ideas are useful, a bit like light being a wave and a particle.

  • When you review, cherry-pick or write a commit message, think of a commit as a change (a diff).
  • When you ask “what does the project look like at this commit?”, or you wonder how rebase works, think of it as a snapshot.

We will tell you which one we mean when it matters.

Idea 2: hashes chain commits together


Every commit has an ID, like 1e81f27. It’s called a hash, and it’s calculated from the contents of the commit, including the parent’s hash.

This has an important consequence:

If you change anything about a commit, it gets a new hash. And then its child has a different parent, so the child gets a new hash too, and so on all the way to the tip of the branch.

Before:

flowchart RL
    accTitle: {Four commits in a chain}
    accDescr: {Four commits, C1 to C4. Each points back to the one before it.}
    C4 --> C3 --> C2 --> C1

After changing C2:

flowchart RL
    accTitle: {The same chain after C2 is changed}
    accDescr: {C1 is unchanged. C2 has been changed, so it is a new commit, C2 prime. C3 and C4 now point at new parents, so they are new commits too, C3 prime and C4 prime. The new commits are marked in green.}
    C4p["C4'"] --> C3p["C3'"] --> C2p["C2'"] --> C1
    classDef new fill:#dfd,stroke:#080,color:#000
    class C2p,C3p,C4p new

Green marks commits that are new. Everything after the change gets a new hash.

There is no such thing as editing a commit in git. You can only make a new, similar commit. This is exactly why rewriting history is a thing you have to do carefully.

Try it. Make a scratch branch and change the message of the latest commit:

BASH

git switch -c scratch
git log --oneline -1
git commit --amend -m "A different message"
git log --oneline -1

OUTPUT

1e81f27 Add plotting of the spectrum and its peaks
...
c91e7a2 A different message

The hash is different. (Yours will be, too, as it also depends on the time you did it.)

Idea 3: old commits don’t disappear


So what happened to 1e81f27? Ask git for it:

BASH

git show 1e81f27 --stat

It’s still there, and still intact. Nothing points to it from scratch any more, but git hasn’t deleted it. Git keeps a private diary of where HEAD has been, called the reflog, and we’ll use it in episode 4 to get back to commits like this one. It’s why we can be relaxed about trying risky things in episode 6.

(The commit stays until git’s garbage collection removes unreachable commits, which only happens after a few weeks.)

Idea 4: branches and HEAD are labels


If commits never change, how does a branch “move” when you add a commit?

A branch is a label (a name) that points at one commit. It’s a tiny file containing a hash:

BASH

cat .git/refs/heads/scratch
git log --oneline -1

When you commit, git makes the new commit and moves the label forward to it.

HEAD is also a label: it says “where you are now”. Usually it points at a branch, which points to a commit:

BASH

cat .git/HEAD

OUTPUT

ref: refs/heads/scratch
flowchart RL
    accTitle: {HEAD points at a branch, which points at a commit}
    accDescr: {HEAD points to the branch called scratch. The scratch branch points to commit C3. C3 points back to C2, which points back to C1.}
    HEAD(["HEAD"]) --> scratch(["scratch"]) --> C3
    C3 --> C2 --> C1

Now add a commit and the label moves:

flowchart RL
    accTitle: {After a new commit, the branch label moves forward}
    accDescr: {HEAD still points to the scratch branch, but scratch now points to the new commit C4. C4 points back to C3, then C2, then C1.}
    HEAD(["HEAD"]) --> scratch(["scratch"]) --> C4
    C4 --> C3 --> C2 --> C1

git switch moves HEAD to a different label. git branch name sticks a new label on the current commit. Making and deleting branches is cheap because a label is all they are.

Callout

What is “detached HEAD”?

It’s HEAD pointing at a commit directly, instead of at a branch. You get it if you check out an old commit, and git warns you about it. It isn’t a problem. It simply means that if you commit now, no branch label will move to follow you. We’ll use it deliberately in the bisect episode.

Clean up your scratch branch:

BASH

git switch main
git branch -D scratch
Challenge

Knowledge check: where are the labels?

You don’t need to type anything for this one. Start from here:

flowchart RL
    accTitle: {Starting point: main is at C3 and HEAD is on main}
    accDescr: {Three commits, C1, C2 and C3. The branch main points at C3, and HEAD points at main.}
    HEAD(["HEAD"]) --> main(["main"]) --> C3
    C3 --> C2 --> C1

Now these commands are run, one after the other. (--allow-empty just lets us make commits without changing any files.)

BASH

git switch -c feature
git commit --allow-empty -m "C4"
git commit --allow-empty -m "C5"
git switch main
git commit --allow-empty -m "C6"

On paper, or in your head: where do main, feature and HEAD point at the end? Which label moved at each step?

Step by step, the labels move like this. (Green marks commits that are new.)

After git switch -c feature: nothing moved except HEAD. A new label was stuck on C3.

flowchart RL
    accTitle: {After switching to a new branch called feature}
    accDescr: {Nothing has moved except HEAD. The new branch feature points at C3, the same commit as main, and HEAD now points at feature.}
    HEAD(["HEAD"]) --> feature(["feature"]) --> C3
    main(["main"]) --> C3
    C3 --> C2 --> C1

After the two commits (C4, C5): each commit moved the label HEAD was on, feature, forwards. main stayed where it was.

flowchart RL
    accTitle: {After two commits on feature}
    accDescr: {Two new commits, C4 and C5, shown in green, sit on top of C3. The feature branch has moved forward to C5, and HEAD is still on feature. Main has not moved: it is still at C3.}
    HEAD(["HEAD"]) --> feature(["feature"]) --> C5
    C5 --> C4 --> C3
    main(["main"]) --> C3
    C3 --> C2 --> C1
    classDef new fill:#dfd,stroke:#080,color:#000
    class C4,C5 new

After git switch main and the commit C6: switching moved only HEAD. Then C6 moved main. The history has diverged from C3.

flowchart RL
    accTitle: {After switching back to main and making a commit}
    accDescr: {The history has diverged from C3. Feature points at C5, on a line C4 then C5. A new commit C6, shown in green, sits on top of C3 on a second line, and main points at it. HEAD is now on main.}
    HEAD(["HEAD"]) --> main(["main"]) --> C6
    feature(["feature"]) --> C5 --> C4 --> C3
    C6 --> C3
    C3 --> C2 --> C1
    classDef new fill:#dfd,stroke:#080,color:#000
    class C6 new

So at the end feature is at C5, and main and HEAD are at C6. We’ll see two ways to bring the two lines together in episode 9.

Challenge

Knowledge check: new hash or not?

Which of these gives the commit a new hash?

  1. Fixing a typo in its message
  2. Moving the branch label to a different commit
  3. Changing the commit that comes before it
  1. Yes: the message is part of the commit’s contents.
  2. No: the commit isn’t changed, only the label.
  3. Yes: the parent is part of its contents, so the hash changes as well.
Key Points
  • A commit is a snapshot of the project plus a pointer to its parent. Diffs are worked out when needed
  • A commit’s hash depends on its contents and its parent, so changing one commit changes all those after it
  • You can’t edit a commit, only make a new one. The old one is still there
  • Branches and HEAD are just labels pointing at commits. Committing moves the label

Content from Planning and Atomic Commits


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • How do I plan a change before I start typing?
  • What makes a commit easy to review?
  • What should a commit message say?

Objectives

  • Sketch a commit plan for a small change
  • Describe an atomic commit
  • Write a commit message with a short subject and a body that says why
  • Spot a commit that mixes unrelated changes

Why history matters


Think about the last time you looked back through a project’s history. You might have been:

  • trying to work out why a line is the way it is
  • hunting for when something broke
  • reviewing a colleague’s changes
  • copying a fix onto another branch

Every one of those jobs is easier if the history was written for a reader. Everything else in this workshop is a tool for doing that. First we need to know what we are aiming at.

Plan the work, then the commits


Most people start a piece of work by opening a file and typing. Try this instead. Before you write any code, spend a couple of minutes on two questions.

1. What is the overall change you want to make?

Say it in one sentence, and say what “done” looks like. For example:

“Peaks that are lower than a minimum height should be ignored, because our example data reports 71 peaks when only three are real.”

If it takes a paragraph, or a lot of “and”s, the change is probably too big for one branch. Split it up now.

2. What changes are needed along the way?

List the steps it takes to get there. Any step that can stand on its own is a candidate for a commit. For the example above:

1. Add a min_height option to find_peaks
2. Add tests for min_height
3. Add a --min-height option to the command line

That list is your commit plan. It:

  • tells you whether the change is small enough. If you’ve written ten steps, the work should probably be split into two branches.
  • gives each step a name before you’ve started, which makes the commit message easy later
  • helps you notice what’s missing, like the tests or the command line
Callout

The plan is a guess

You will get it wrong, and that is fine. You might find a bug that has to be fixed first, or realise step 2 should come before step 1. Update the plan and carry on. We’ll cover how to put commits in the right order after the fact, so a wrong plan costs you very little.

The point isn’t to follow the plan exactly. It’s to stop yourself producing one giant lump of work.

If you’ve come across them, this is the same instinct as slicing a big task into small stories in an agile team: the smaller the piece, the easier it is to plan, do and review.

What is an atomic commit?


An atomic commit is one complete, logical change. It:

  • does one thing, so you can describe it in one sentence without using “and”
  • leaves the project working: the tests pass at that commit, not just at the end of the branch
  • can be understood on its own, and could be undone or copied elsewhere without dragging other changes along

“Atomic” doesn’t mean “tiny”. A commit that adds a function and its tests can be perfectly atomic. A one-line commit that fixes a bug and renames a variable is not.

Not atomic:   "Fix normalise and add background subtraction and update README"
Atomic:       "Handle constant spectra in normalise"
              "Add rolling minimum background subtraction"
              "Document --subtract-background in the README"

Why bother?

These commits pay off throughout the workshop, and long after:

When you… atomic commits mean…
review a branch’s pull request you can read one idea at a time
revert a mistake you can undo just the bad bit
cherry-pick a fix onto a release you can take the fix and nothing else (episode 13)
bisect to find a bug the commit that introduced a problem is one small commit, not a large lump (episode 10)
Callout

An example: keep the refactor apart from the change

Imagine you need to change what a function returns, and the code is in an awkward place, so you also move it into a new file and reorganise it as you go. Here is the same work as one commit, and as two:

Two panels. On the left, one commit: the old file is shown entirely in red and the new file entirely in green, so you cannot see what changed. On the right, two commits: the first is a pure move with no changed lines, and the second is a small diff showing only the real change.
The same change as one commit, where the old file is all red and the new file all green, and as two commits, where a pure move is followed by a small focused diff

As one commit, the reviewer can’t tell what was moved and what was changed, so they have to read all of it as if it were new code. As two commits, the first is a pure refactor they can skim, check the tests still pass, and move on. The second is a small diff about the one thing that really changed. They can trust that the first commit is boring, and spend their attention on the second.

Callout

We’re not being obsessed

Nobody will mind if a commit is slightly more or less than one thing. The aim is that a reviewer can follow your reasoning. When you’re not sure, ask: if this commit turns out to be wrong, would I want to throw away all of it?

A good commit message


Here is a message from the peakfinder history:

Add mode option to normalise

Adds 'max' and 'area' modes alongside the default 'range'.

A good message has:

  1. A subject line: short (about 50 characters), in the imperative mood, as if giving an order. “Add”, “Fix”, “Remove”, not “Added” or “Adds”. A handy test: “If applied, this commit will … [subject]”.
  2. A blank line.
  3. An optional body, for anything the subject can’t say. Explain why, because the diff already shows what.

Most commits need only a subject. Use the body when the reason isn’t obvious from the code:

Handle constant spectra in normalise

A flat spectrum has max equal to min, so we were dividing by zero.
Return zeros instead.

Compare these:

Weak Better
fix Fix 'range' mode of normalise for spectra that don't start at zero
updates Let load_spectrum skip a variable number of header rows
wip (something you’d fix before sharing, see episode 6)
Callout

Optional: commit message prefixes

Some projects start every subject line with a short tag that says what kind of change it is. This makes a long git log easier to scan, and it can be used to build a changelog automatically. There are two common styles:

Kind of change Scientific Python style (NumPy, pandas) Conventional Commits
New feature ENH: feat:
Bug fix BUG: fix:
Tests TST: test:
Documentation DOC: docs:
Refactor (no behaviour change) MAINT: or REF: refactor:
Formatting, style STY: style:
ENH: Add min_height option to find_peaks
BUG: Fix 'range' mode of normalise for spectra that don't start at zero

Neither is “right”, and many projects use no prefix at all. If your project has a convention, follow it. If not, it’s up to you and your team, and it’s more important to be consistent than to pick the best one. We won’t use prefixes in the workshop examples.

There is a bonus: a prefix is an atomicity check. If you can’t choose just one, such as BUG: or REF:, you have probably got two commits.

Challenge

Knowledge check: atomic or not?

Which of these would you be happy to see as a single commit?

  1. “Add min_height option to find_peaks, with tests”
  2. “Fix bug in normalise, rename y to intensity everywhere, update README”
  3. “Remove unused import from cli.py”
  4. “Many changes”
  1. Yes. The feature and its tests are one logical change.
  2. No. Three unrelated changes. A reviewer has to untangle them, and if the rename causes trouble you can’t undo it without undoing the bug fix.
  3. Yes. Small, but it is complete and has a clear purpose.
  4. No. It says nothing about what, or why.
Challenge

Challenge: spot the smells, and make a plan

You have been working on background subtraction for a week, and you’re about to ask for a review. Take a look at your branch:

BASH

git switch background-subtraction
git log --reverse --stat --format='%h %s' main..

OUTPUT

cd6792e add background module
 peakfinder/background.py | 8 ++++++++
ead2b48 wip
 peakfinder/background.py | 9 ++++++++-
21dd6b4 tidy up
 peakfinder/io.py        | 6 +++---
 peakfinder/normalise.py | 5 ++++-
 peakfinder/peaks.py     | 2 ++
 tests/test_normalise.py | 4 ++++
 tests/test_peaks.py     | 7 +++++++
33aa1de fix
 peakfinder/background.py | 4 ++--
...

(Use the arrow keys to scroll, and q to quit.)

Work with the person next to you, and don’t run any more git commands that change things. Just read, and answer:

  1. Which commits have messages that tell you nothing?
  2. Which commit mixes unrelated changes? How can you tell?
  3. Which commits are really corrections to an earlier commit, or shouldn’t be in the history at all?
  4. Write down the list of commits you wish the branch contained. In episode 6 you’ll turn this branch into your list.

Tip: git show <hash> shows what a commit actually changed, and the Source Control view and Timeline in VS Code are another way of browsing it.

  1. wip, tidy up, fix, cli stuff, fix typo, readme, add tests and add background module all say little or nothing about the change.
  2. tidy up. It touches five files and does three unrelated things: a fix in normalise, a change to load_spectrum, and a new check in find_peaks. The stat shows several files that have nothing to do with each other, and the vague message hides it.
  3. wip, fix, remove print and fix typo all correct or finish the add background module commit. And try smoothing adds an experiment (scratch_smoothing.py) that nothing uses.
  4. One sensible plan:
    1. Handle constant spectra in normalise
    2. Let load_spectrum skip a variable number of header rows
    3. Check x and y are the same length in find_peaks
    4. Add rolling minimum background subtraction
    5. Add tests for background subtraction
    6. Add --subtract-background option to the CLI
    7. Document --subtract-background in the README
    Yours might be slightly different (for example, you may fold the tests into commit 4), and that is OK as long as you can explain it.

That gap, between the branch you have and the list you wish you had, is what episode 6 closes.

Key Points
  • Plan your commits before you start: a short list keeps each change small
  • An atomic commit does one logical thing and leaves the project working
  • A commit message has a short imperative subject, and a body that says why when it isn’t obvious
  • Atomic commits make review, revert, cherry-pick and bisect much easier

Content from The Safety Net: Reflog


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • How do I undo a mistake in git?
  • Can I really lose work?

Objectives

  • Read the reflog
  • Recover from a bad git reset --hard
  • Bring back a deleted branch
  • Know what the reflog can’t save

Why now?


From the next episode on we will be changing history: amending, resetting and rebasing. If that sounds risky, this episode is the reason it isn’t. Git keeps a private diary of where you’ve been, and it can get you back.

Remember from episode 2: when you “change” a commit, git makes a new one and moves a label. The old commit is still there, but nothing points at it any more. The reflog is how you find it again.

What is the reflog?


Every time HEAD moves (when you commit, switch branch, reset, rebase, merge…) git writes a line in a log. See yours:

BASH

git reflog

OUTPUT

1e81f27 HEAD@{0}: checkout: moving from experiment to main
fba8092 HEAD@{1}: reset: moving to HEAD@{1}
1e81f27 HEAD@{2}: reset: moving to HEAD~2
fba8092 HEAD@{3}: commit: Note gaussian fitting idea in README
1634522 HEAD@{4}: commit: Note smoothing idea in README
...

(Use q to leave the pager.) Yours will look different, as it’s a record of your actions.

Each line says: the commit HEAD pointed to, HEAD@{n} (that position, counting back from now), and what you did to get there. The newest entry is at the top.

The reflog is:

  • local: it lives in your clone and is never pushed. Your colleagues have their own.
  • temporary: entries expire. By default after 90 days, or 30 days if the commit is no longer on any branch.
  • only about commits. Remember that last point, we’ll come back to it.

Oh no: a bad reset


Let’s make some work and then destroy it. Follow along with the instructor, and type each step yourself. Make a throwaway branch and two commits:

BASH

git switch -c experiment
echo "- Idea: smooth the spectrum before peak finding" >> README.md
git commit -am "Note smoothing idea in README"
echo "- Idea: fit gaussians to the peaks" >> README.md
git commit -am "Note gaussian fitting idea in README"
git log --oneline -3

OUTPUT

fba8092 Note gaussian fitting idea in README
1634522 Note smoothing idea in README
1e81f27 Add plotting of the spectrum and its peaks

Now the mistake. You meant to undo one commit, but you typed a 2 and also added --hard:

BASH

git reset --hard HEAD~2

OUTPUT

HEAD is now at 1e81f27 Add plotting of the spectrum and its peaks

Both commits seem to be gone, and the lines have vanished from README.md. (We’ll explain exactly what reset does in the next episode. For now: it moved the branch label back two commits and threw away the changes.)

Don’t panic. Look at the reflog. (The hashes in our examples will be different from yours, because they depend on the time you made the commits. Always use the ones on your screen.)

BASH

git reflog

OUTPUT

1e81f27 HEAD@{0}: reset: moving to HEAD~2
fba8092 HEAD@{1}: commit: Note gaussian fitting idea in README
1634522 HEAD@{2}: commit: Note smoothing idea in README
1e81f27 HEAD@{3}: checkout: moving from main to experiment
...

The line fba8092 HEAD@{1}: commit: Note gaussian fitting idea in README is where we were before the reset.

flowchart RL
    accTitle: {After a reset, the commits still exist and the reflog remembers them}
    accDescr: {A chain of three commits, C1, C2 and C3. After the reset the branch experiment points at C1, so C2 and C3 are shown dashed because nothing points at them. The reflog, shown as a dotted note, remembers that HEAD was at C3.}
    experiment(["experiment<br/>(after the reset)"]) --> C1
    C2 --> C1
    C3 --> C2
    reflog[/"reflog remembers:<br/>HEAD was at C3"/] -.-> C3
    classDef orphan stroke-dasharray: 5 5
    class C2,C3 orphan

Dashed commits still exist, but no branch points at them. The reflog is how you find your way back to one.

Move the branch label back there:

BASH

git reset --hard fba8092

OUTPUT

HEAD is now at fba8092 Note gaussian fitting idea in README

Both commits are back, and so is the file’s content.

Callout

Use the hash, not HEAD@{n}

You can write git reset --hard HEAD@{1}, and it often works. But the numbers shift every time HEAD moves, including when you run the recovery commands. Read the reflog and copy the hash of the line you want. It never changes.

Callout

A quicker undo: ORIG_HEAD

Before risky commands such as reset, merge and rebase, git remembers where you were in ORIG_HEAD. So straight after a mistake, git reset --hard ORIG_HEAD often puts you back. The reflog covers the cases where you’ve done other things since.

Oh no: a deleted branch


Delete the branch (we have to switch away first, and -D forces deletion of unmerged work):

BASH

git switch main
git branch -D experiment

OUTPUT

Deleted branch experiment (was fba8092).

Look: git even tells you the hash. If you missed that, the reflog still has it:

BASH

git reflog

Find the last commit of the branch (the line that says commit: Note gaussian fitting idea in README) and make a new label there:

BASH

git branch experiment fba8092
git log --oneline experiment -3

The branch is back, with both commits. Now tidy up:

BASH

git switch main
git branch -D experiment

What the reflog can’t save


The reflog records commits. Work that was never committed isn’t in it:

  • Edits you made and never committed, then threw away with git restore . or git reset --hard: gone.
  • Edits you staged but never committed: usually gone too (technically git may keep the content, but finding it is painful).
  • Anything older than the expiry time.
  • Commits only ever made on someone else’s computer.

The rule that follows: commit before you try something risky. Even a messy “wip” commit, which we know how to tidy up afterwards. A commit can be recovered, and an uncommitted edit cannot.

Challenge

Knowledge check: can I get it back?

For each situation, can you get the work back? How?

  1. You committed three times on a branch, then ran git reset --hard main.
  2. You edited peaks.py, never committed, and ran git restore peaks.py.
  3. You ran git branch -D feature before it was merged.
  4. You did an interactive rebase last week and now realise you dropped a commit you needed.
  1. Yes. Find the last of the three commits in git reflog and git reset --hard <hash>.
  2. No. The changes were never committed, so git has no record of them.
  3. Yes. git branch -D prints the hash of the tip, and the reflog has it too: git branch feature <hash>.
  4. Yes, as long as it’s within the expiry (90 days / 30 days). The reflog shows where the branch was before the rebase. Look for the rebase (start) entry and the one before it. This is why we’ll be relaxed about rebasing.
Key Points
  • Git rarely deletes commits straight away. The reflog records where HEAD has been, so you can find them
  • Recover by copying the hash from git reflog and using git reset --hard <hash> or git branch <name> <hash>
  • The reflog is local and expires, and doesn’t cover uncommitted work
  • Commit before trying something risky

Content from Shaping a Commit: Staging, Amend, Reset and Restore


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • How do I commit only part of my changes?
  • How do I fix the commit I just made?
  • What do reset and restore do?

Objectives

  • Stage individual hunks and lines using the VS Code Source Control view
  • Amend the last commit, to change its message or add to it
  • Describe what git reset --soft, --mixed and --hard each move
  • Discard or unstage changes with git restore

The staging area is a drafting table


You know the three places a change can be:

flowchart LR
    accTitle: {Where a change lives: working files, staging area and repository}
    accDescr: {Three boxes from left to right. Changes start in your working files. Staging moves them to the staging area, which holds the next commit. Committing moves them to the repository. Unstaging moves a change back from the staging area to the working files.}
    W["Working files<br/>(what is on disk)"] -->|"stage<br/>(git add)"| S["Staging area<br/>(the next commit)"]
    S -->|"git commit"| R["Repository<br/>(committed history)"]
    S -.->|"unstage<br/>(git restore --staged)"| W

The staging area (also called the index) is where you assemble the next commit. It’s the feature that makes atomic commits possible: you don’t have to commit everything you changed. You choose.

Most beginners stage whole files. But often one file contains two ideas. You can stage parts of a file as well.

Staging parts of a file in VS Code


Open the Source Control view: click the branch icon in the left sidebar, or press Ctrl+Shift+G (Cmd+Shift+G on a Mac).

Every changed file is listed. Click one, and VS Code shows a side-by-side diff: the old version on the left and your working copy on the right.

Now you can stage part of it:

  1. Select some lines in the diff, on the right-hand side. Click and drag, or click one line.
  2. Right-click and choose Stage Selected Ranges.

Only those lines go into the staging area. The file now appears in both lists: Staged Changes has the part you picked, and Changes has the rest.

You can also:

  • Use the Stage and Revert buttons in the gutter of the diff editor (next to your selection or a change), to stage or revert just those lines, or a whole block (a hunk), in one click.

Commit as usual: type the message in the box at the top of the Source Control view and press Ctrl+Enter.

Changed your mind? Unstage versus discard

These two sound alike, and they are very different:

I want to… VS Code Command
Unstage: keep my edits, but leave them out of the next commit click the - icon, or select lines and Unstage Selected Ranges git restore --staged <file>
Discard: throw my edits away, for good right-click the file, Discard Changes (or select lines and Revert Selected Ranges) git restore <file>

Unstaging is always safe. Discarding isn’t: uncommitted edits aren’t in the reflog (episode 4), so there’s no way back. (Older guides use git checkout -- <file> and git reset <file> for these. They do the same thing, but restore has a clearer name.)

Callout

The command line version: git add -p

You may see this in documentation, or need it over ssh where there is no VS Code:

BASH

git add -p peakfinder/plot.py

Git shows one hunk at a time and asks what to do:

OUTPUT

@@ -2,22 +2,24 @@ ...
-def draw(ax, x, y, peaks):
+def draw(ax, x, y, peaks, title=None):
...
(1/1) Stage this hunk [y,n,q,a,d,s,e,?]?
Key Meaning
y stage this hunk
n don’t stage it
s split it into smaller hunks
e edit the hunk by hand
q quit
? help

It does the same thing as the VS Code view. Use whichever you find clearer. We’ll use VS Code in this workshop, because you can see the whole file and the context while you decide.

Fixing the last commit: amend


You’ve just committed, and you notice a typo in the message. Or you forgot to include a file. Instead of making a “fix typo” commit, you can amend the last one.

VS Code:

  • To change the message or to add more changes: stage what you want to add, then open the dropdown arrow on the Commit button and choose Commit (Amend). (The same thing is under the ... menu, then Commit, then Commit Staged (Amend).)

Command line:

BASH

git commit --amend                  # change the message (opens your editor)
git commit --amend --no-edit        # add staged changes, keep the message

Remember episode 2: the amended commit is a new commit with a new hash. The old one is still in the reflog. So only amend commits you haven’t shared with anyone. (Amend only works on the last commit. For an earlier one, you’ll use --fixup and interactive rebase, in episodes 6 and 7.)

Moving where you are: reset


git reset moves the branch label (and HEAD with it) to another commit. We saw in episode 2 that a branch is just a label, so this is simple to picture.

Before:

flowchart RL
    accTitle: {Before the reset: main points at C4}
    accDescr: {Four commits, C1 to C4. The branch main points at C4.}
    main(["main"]) --> C4 --> C3 --> C2 --> C1

After git reset HEAD~2:

flowchart RL
    accTitle: {After git reset HEAD~2: main points at C2}
    accDescr: {The branch main now points at C2. Commits C3 and C4 still exist, shown with dashed outlines, but nothing points at them.}
    main(["main"]) --> C2 --> C1
    C4 --> C3 --> C2
    classDef orphan stroke-dasharray: 5 5
    class C3,C4 orphan

Dashed commits still exist, but no branch points at them. Older commits are on the left.

What happens to your files? That depends on the mode:

Command Branch label Staging area Working files
git reset --soft <commit> moves kept (the undone changes stay staged) kept
git reset --mixed <commit> (the default) moves reset (the undone changes are unstaged) kept
git reset --hard <commit> moves reset reset: your changes are lost

In plain words:

  • soft: “undo the commit, but keep all the changes ready to commit again”
  • mixed: “undo the commit, and keep the changes, but I’ll choose what to stage again”
  • hard: “throw it all away” (the dangerous one)

You’ll use mixed all the time in this workshop. It means: take this commit apart so I can build it again, better.

Resetting in VS Code

VS Code doesn’t have a button for each mode, but you can build all three from its buttons. Start from the Source Control view:

You want Click Same as
soft: undo the last commit, keep the changes staged ... menu, Commit, Undo Last Commit git reset --soft HEAD^
mixed: undo the last commit, keep the changes unstaged Undo Last Commit, then Unstage All Changes (the - next to Staged Changes) git reset HEAD^
hard: undo the last commit and throw its changes away Undo Last Commit, then Discard Changes on each file (right-click a file under Changes, it asks you to confirm) git reset --hard HEAD^

(Undo Last Commit and Discard Changes are in VS Code’s own documentation. The buttons that act on a whole list at once, such as Unstage All Changes, appear when you hover over the Staged Changes header.)

Resetting on the command line

The commands in the table above are all you need: add HEAD^ (or HEAD~1, “the commit before this one”) to go back one commit, or HEAD~3 to go back three. Unlike the buttons, the command line can move the branch to any commit (git reset --hard <hash>, as we did in episode 4).

Challenge

Knowledge check: which reset?

Which mode would you use if you wanted to:

  1. Undo your last commit but keep every change staged, so you can fix the message and recommit?
  2. Undo your last commit and unstage everything, so you can split it into two commits?
  3. Throw away your last commit and all the work in it? (Think carefully!)
  1. --soft
  2. --mixed (the default)
  3. --hard. Only if you’re sure! If you aren’t, commit the work to a new branch first, or remember that the reflog can find the commit again (episode 4).
Challenge

Challenge: untangle a commit

It’s the end of a long day, and you have committed everything in one go. Your branch untangle has a single commit, badly named plot stuff. It contains three different things:

  1. A new feature: a --title option so you can put a title on the plot (changes in cli.py and plot.py)
  2. A small fix: the red peak markers were hiding behind the line, so they’re now drawn on top (one line in plot.py)
  3. A leftover debug print in cli.py that should never be committed

Your job is to turn it into two clean commits, with the debug print gone:

  1. Add --title option for the plot
  2. Draw peak markers on top of the line

Steps:

  1. Switch to the branch and look at the commit.

    BASH

    git switch untangle
    git show --stat
  2. Take the commit apart so the changes are in your working files, but not staged. (Which reset mode? Which buttons?)

  3. Use the Source Control view to stage only the title feature, and commit it.

  4. Stage the marker fix and commit it.

  5. Discard the debug print.

Check your work:

BASH

git log --oneline -3
git show --stat HEAD~1
git show --stat HEAD
git grep DEBUG
pytest
python -m peakfinder.cli data/example_spectrum.csv --save-plot title.png --title "Example"

You should see two new commits, the first touching cli.py and plot.py, the second only plot.py. git grep DEBUG should print nothing, the tests should pass, and title.png should have a title.

Hints:

  • In the diff editor, select a range of lines and use Stage Selected Ranges. You don’t have to stage whole files.
  • The title feature is spread over several places in both files. The easiest way to find them all: the lines that mention title.
  • Anything you leave unstaged stays in your working files, so it’s easy to do things in the right order.

Take the commit apart. A mixed reset keeps the changes in your files but unstages them. In VS Code, click ..., Commit, Undo Last Commit. The changes appear under Staged Changes, so click Unstage All Changes. (Or in the terminal:)

BASH

git reset HEAD^
git status --short

OUTPUT

 M peakfinder/cli.py
 M peakfinder/plot.py

Commit 1: the feature. In the Source Control view, open cli.py. In the diff, select the line parser.add_argument("--title", ...), right-click, Stage Selected Ranges. Do the same for the two changes that pass title=args.title to plot_spectrum. Don’t stage the line starting print("DEBUG".

Open plot.py. Stage every change that mentions title: the extra parameter on draw, the if title: lines, the extra parameter on plot_spectrum, and both calls to draw. Don’t stage the one line with zorder=3.

Type the message Add --title option for the plot and press Ctrl+Enter.

Commit 2: the fix. plot.py now only has the zorder=3 line left. Stage the file (click the +), and commit it as Draw peak markers on top of the line.

Discard the debug print. cli.py has one change left, the DEBUG print. Click Discard Changes next to it.

Command line version (for reference):

BASH

git add -p peakfinder/cli.py       # answer: s, y, n, y
git add -p peakfinder/plot.py      # answer: s, y, n, y, y, y, y
git commit -m "Add --title option for the plot"

git add peakfinder/plot.py
git commit -m "Draw peak markers on top of the line"

git restore peakfinder/cli.py

The s splits a big hunk up, and the n in the middle skips the zorder change in plot.py. In cli.py it skips the debug print.

Key Points
  • The staging area lets you assemble a commit. Stage hunks or individual lines in VS Code (or with git add -p)
  • git commit --amend replaces the last commit, so only do it for commits you haven’t shared
  • git reset moves the branch label: --soft keeps changes staged, --mixed (default) keeps them unstaged, --hard discards them
  • git restore discards edits or unstages files without moving any label

Content from Interactive Rebase: Rewriting a Messy Branch


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • How do I reword, reorder, combine, split and drop commits?
  • What does git rebase actually do to my commits?

Objectives

  • Run git rebase -i and use pick, reword, drop, fixup and edit
  • Reorder commits by moving lines in the todo list
  • Split one commit into several
  • Explain what rebase does in terms of snapshots and new commits
  • Back out of a rebase with git rebase --abort

Where we left off


For the last week you have been adding background subtraction to peakfinder, and you’ve just been told the work is ready for review. Take a look at your branch:

BASH

git switch background-subtraction
git log --oneline main..

The main.. means “the commits on this branch that aren’t on main”.

OUTPUT

d8cc138 readme
9e1626f try smoothing
4244130 fix typo
2b17bef cli stuff
9a6471e remove print
89f7c6f add tests
33aa1de fix
21dd6b4 tidy up
ead2b48 wip
cd6792e add background module

You wrote a list in episode 3 of the commits you wished the branch contained. Ours was:

  1. Handle constant spectra in normalise
  2. Let load_spectrum skip a variable number of header rows
  3. Check x and y are the same length in find_peaks
  4. Add rolling minimum background subtraction
  5. Add tests for background subtraction
  6. Add --subtract-background option to the CLI
  7. Document --subtract-background in the README

Compare it with yours. Today we turn the branch into that list. None of the code changes. We only change the story of how it got there.

Callout

The golden rule, for now

Only rewrite history that nobody else has. This branch is only on your computer (and maybe your fork), so it’s safe. We’ll see what goes wrong when you rewrite shared history in episode 9.

First, a safety net


Before changing anything, put a label on where you are:

BASH

git branch backup/background-subtraction

It’s a second name for the current tip (remember, a branch is just a label), so whatever happens we can get back. You also have git rebase --abort, which stops a rebase and puts everything back, and the reflog from episode 4.

What does rebase do?


Rebase takes some commits and replays them one at a time on top of a starting point. Each replayed commit is a new commit, with a new hash (episode 2: a changed commit, or a changed parent, means a new hash). “Interactive” means git stops first and lets you say what to do with each commit.

Before:

flowchart RL
    accTitle: {The branch before the rebase}
    accDescr: {The branch background-subtraction has four commits, A, B, C and D, on top of main.}
    bs(["background-subtraction"]) --> D --> C --> B --> A --> main

After git rebase -i main, dropping C and combining A and B:

flowchart RL
    accTitle: {The branch after the rebase, with the old commits kept by the backup branch}
    accDescr: {The branch background-subtraction now has two new commits, A B prime and D prime, on top of main, shown in green. The old commits A, B, C and D still exist, shown dashed, and the backup branch points at them.}
    bs(["background-subtraction"]) --> Dp["D'"] --> ABp["AB'"] --> main
    bk(["backup/background-subtraction"]) --> D --> C --> B --> A --> main
    classDef new fill:#dfd,stroke:#080,color:#000
    classDef old stroke-dasharray: 5 5
    class Dp,ABp new
    class D,C,B,A old

Green: new commits made by the rebase. Dashed: the old commits, kept by the backup branch. Older commits are on the left.

The todo list


Start an interactive rebase onto main. That’s where our branch began, so every commit on the branch since then gets replayed:

BASH

git rebase -i main

Your editor opens with a list of every commit on the branch. It’s the opposite order from git log: the oldest is at the top, because that’s the order git will replay them in.

pick cd6792e add background module
pick ead2b48 wip
pick 21dd6b4 tidy up
pick 33aa1de fix
pick 89f7c6f add tests
pick 9a6471e remove print
pick 2b17bef cli stuff
pick 4244130 fix typo
pick 9e1626f try smoothing
pick d8cc138 readme

# Rebase 1e81f27..d8cc138 onto 1e81f27 (10 commands)
# ...

Git will do the lines from top to bottom, one at a time. You change what happens by changing the word at the start of a line, or by moving lines (in VS Code, Alt+↑ and Alt+↓ move the current line):

Command What it does to the commit
pick keep it as it is
reword keep it, but let me change the message
edit stop here so I can change the commit (or split it)
squash merge it into the commit above it, and let me combine the messages
fixup merge it into the commit above it, and throw away its message
drop throw it away

Deleting a line is the same as drop. For now, close the editor without changing anything: git replays all ten commits as they were, and nothing happens.

Challenge

Knowledge check: which command?

For each of these, which command from the table would you use?

  1. A commit message says oops, but the change itself is fine.
  2. A commit adds a file you were only experimenting with.
  3. Two commits are really one change that you made in two goes, and you only want to keep the first message.
  1. reword
  2. drop
  3. fixup (or squash if you want to write a new message combining both)

Rebase 1: the easy fixes, all at once


We’ll do this in two rebases. In the first we deal with everything that is dropping, rewording, moving or folding in. In the second, which is your challenge, we’ll split a commit.

First, work out what each commit really is:

Commit What it really is
add background module the start of the feature: a new file with a first version of the function
wip carries on writing that function
tidy up three unrelated fixes, nothing to do with the feature (we’ll split it in the next rebase)
fix fixes a bug in the function
add tests tests for the function
remove print removes a debugging print from the function
cli stuff adds the --subtract-background option, but the message says nothing
fix typo fixes a typo in the function’s docstring
try smoothing an experiment that nothing uses
readme documents the new option
Challenge

Challenge: choose the commands

Now decide a command for each, using the table of commands above. Three things to think about:

  • Which commits are just corrections that belong inside another commit?
  • Which commit doesn’t belong with the feature at all, and should come first?
  • Which commit shouldn’t be here, and which has a message that tells you nothing?

Then start the rebase, edit the list, and save:

BASH

git rebase -i main

Git will open the editor again for the reword, so you can type the new message. When it finishes, check your work:

BASH

git log --oneline main..
git diff --stat backup/background-subtraction

You should have five commits, and the only difference from the backup should be the file from the commit you dropped.

The finished todo list:

pick 21dd6b4 tidy up
pick cd6792e add background module
fixup ead2b48 wip
fixup 33aa1de fix
fixup 9a6471e remove print
fixup 4244130 fix typo
pick 89f7c6f add tests
reword 2b17bef cli stuff
pick d8cc138 readme
drop 9e1626f try smoothing

Why:

  • tidy up moves to the top: the feature doesn’t depend on it, so it comes first. It’s still pick for now.
  • wip, fix, remove print and fix typo are all corrections to add background module, so they sit right under it, as fixup.
  • cli stuff is reword: change the message to Add --subtract-background option to the CLI.
  • try smoothing is drop.

(We could move these commits because they changed different files from the ones they jumped over. If you try to move a commit above one that changed the same lines, git stops with a conflict. Resolve it, or git rebase --abort and rethink the order.)

The result (your hashes will be different from ours):

OUTPUT

d71e0a5 readme
bddb2b7 Add --subtract-background option to the CLI
4d0a337 add tests
2383a68 add background module
734a867 tidy up

OUTPUT

 scratch_smoothing.py | 5 -----
 1 file changed, 5 deletions(-)
Callout

squash or fixup?

squash does the same as fixup, but opens an editor so you can write a message that combines both. Use fixup when the later commit is just a correction, and squash when both commits have something worth saying.

Challenge

Knowledge check: where did the old commits go?

Compare git log --oneline main.. with git log --oneline backup/background-subtraction.

  1. Why does every commit on your branch have a new hash, even tidy up, which you didn’t change?
  2. Where have the old ten commits gone? Did try smoothing vanish from the repository entirely?
  1. tidy up now sits on a different parent (it moved to the top, so its parent is now main), and rebase always makes a new commit when it replays one. A hash covers the contents and the parent, so the hash changes (episode 2).
  2. Nothing is gone. The old commits are still there, and backup/background-subtraction still points at them. try smoothing is only out of your branch. It’s in the reflog too (episode 4).

Rebase 2: split a commit


Five commits now, and one of them is still doing too much: tidy up. Look at what is inside it (it’s the first commit on the branch):

BASH

git show --stat HEAD~4

OUTPUT

commit 734a867...
Author: Sam Scientist <sam.scientist@example.org>

    tidy up

 peakfinder/io.py        | 6 +++---
 peakfinder/normalise.py | 5 ++++-
 peakfinder/peaks.py     | 2 ++
 tests/test_normalise.py | 4 ++++
 tests/test_peaks.py     | 7 +++++++
 5 files changed, 20 insertions(+), 4 deletions(-)

It has three unrelated fixes. A reviewer has to work out which hunk belongs to which idea.

Challenge

Challenge: split a commit, and finish the messages

Using an interactive rebase and the edit command, split tidy up into these three commits:

  1. Handle constant spectra in normalise (normalise.py and its test)
  2. Let load_spectrum skip a variable number of header rows (io.py)
  3. Check x and y are the same length in find_peaks (peaks.py and its test)

In the same rebase, give the other vague messages proper ones (hint: reword):

  • add background module becomes Add rolling minimum background subtraction
  • add tests becomes Add tests for background subtraction
  • readme becomes Document --subtract-background in the README

Hints:

  • edit stops the rebase after applying the commit. You then need to undo the commit, but keep its changes in your working files. Which reset do you want? (Episode 5: mixed. In VS Code, Undo Last Commit, then Unstage All Changes.)
  • Stage each group of files in the Source Control view (or git add <files>), then commit.
  • When you have made your three commits, tell git to carry on.
  • git status tells you what to do next, at any time.

When you finish, check your work:

BASH

git log --oneline main..
git diff --stat backup/background-subtraction

You should have seven commits, and a diff that only shows scratch_smoothing.py.

Start the rebase. Change pick to edit for tidy up, and to reword for the three vague messages. (Use the hashes from your log.)

BASH

git rebase -i main
edit 734a867 tidy up
reword 2383a68 add background module
reword 4d0a337 add tests
pick bddb2b7 Add --subtract-background option to the CLI
reword d71e0a5 readme

Git stops at tidy up. The commit has been applied, and HEAD is that commit. Undo the commit but keep the changes:

BASH

git reset HEAD^
git status --short

OUTPUT

 M peakfinder/io.py
 M peakfinder/normalise.py
 M peakfinder/peaks.py
 M tests/test_normalise.py
 M tests/test_peaks.py

Make three commits:

BASH

git add peakfinder/normalise.py tests/test_normalise.py
git commit -m "Handle constant spectra in normalise"

git add peakfinder/io.py
git commit -m "Let load_spectrum skip a variable number of header rows"

git add peakfinder/peaks.py tests/test_peaks.py
git commit -m "Check x and y are the same length in find_peaks"

Carry on with the rebase. It will stop at each reword so you can type the new message.

BASH

git rebase --continue

Finally:

BASH

git log --oneline main..

OUTPUT

16dc9b1 Document --subtract-background in the README
5f580ee Add --subtract-background option to the CLI
0c4a936 Add tests for background subtraction
2917647 Add rolling minimum background subtraction
28ec0e5 Check x and y are the same length in find_peaks
5d3c64c Let load_spectrum skip a variable number of header rows
0e4303b Handle constant spectra in normalise

(Your hashes will be different.)

Look at the result


BASH

git log --oneline main..

Compare this to the log at the start of the episode, and to the list you wrote in episode 3. The code didn’t change, but a reviewer can now:

  • read one commit at a time, each with a single purpose
  • trust the messages to say why the change was made
  • look at the three small fixes separately from the feature

In real life, the next step would be to push this branch and open a pull request for review (we’ll do that in episode 11, with a different branch). Once approved, it would be merged into main.

We aren’t going to merge this one. It was practice, and tomorrow’s story needs main to stay exactly as it is. So leave it where it is. It has done its job.

Challenge

Knowledge check: when would you not do this?

Think about these three situations. In which would you be happy to rewrite history, and in which not?

  1. A branch that only exists on your laptop.
  2. A branch you pushed to your fork, with an open pull request that someone has started reviewing.
  3. main in a repository the whole team uses.
  1. Happy. Nobody else is affected.
  2. Careful. Possible, and quite common, but the reviewer has to be told: we’ll see how to do it well in episode 11.
  3. Never. Everybody else’s copies have the old commits, and rewriting would put the team’s histories out of step.
Key Points
  • git rebase -i <base> lets you edit every commit on a branch since <base>
  • The todo list is oldest first: change the command word to reword, drop, fixup or edit, and move lines to reorder
  • Rebase makes new commits. The old ones remain, so a backup branch or the reflog gets you back
  • Use edit and git reset HEAD^ to split a commit into several
  • git rebase --abort undoes a rebase that is going badly
  • Only rewrite history that nobody else has yet

Content from The Daily Loop: Fixup and Autosquash


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • How do I keep my history clean while I’m still working?
  • How do I fix a mistake in an earlier commit without a “fix typo” commit?

Objectives

  • Plan a few commits, then build a feature one atomic commit at a time
  • Use git commit --fixup to correct an earlier commit
  • Use git rebase -i --autosquash to fold the fixups in
  • Push a tidy branch to your fork

The loop


In the last episode we rescued a messy branch. That was useful, but nobody wants to do it every time. Here is the habit that means you rarely need to:

flowchart TD
    accTitle: {The daily loop}
    accDescr: {A flowchart. Plan the commits, then make a small change and commit it. If you spot a mistake in an earlier commit, make a fixup commit for it. Repeat while there is more to do. When the work is done, run an interactive rebase with autosquash, then push and ask for review.}
    P["Plan the commits"] --> C["Make a small change<br/>and commit it"]
    C --> Q{"Spot a mistake in<br/>an EARLIER commit?"}
    Q -->|yes| F["git commit<br/>--fixup (that commit)"]
    Q -->|no| M{"More to do?"}
    F --> M
    M -->|yes| C
    M -->|no| A["Tidy up before sharing:<br/>git rebase -i<br/>--autosquash main<br/>(fixups, then reword,<br/>reorder or drop as needed)"]
    A --> S["Push, and ask for review"]

The idea: commit freely as you go, and tidy up before you share. You never have to stop and interrupt your flow to edit history. You leave a note (“this is a fix for that commit”) and tidy up at the end.

Start from a fresh branch


Always start new work from an up-to-date main, on a branch of its own:

BASH

git switch main
git status                      # should say "nothing to commit, working tree clean"
git switch -c min-height

(git switch -c creates the branch and moves you onto it. In real life you’d git pull first, and your pull.rebase true setting means that keeps history linear too.)

Plan


Remember episode 3? First, the overall change, in one sentence: “Ignore peaks that are lower than a minimum height, because our example data reports far too many.” Then the steps along the way, which is our commit plan:

1. Add a min_height option to find_peaks
2. Add tests for min_height

Why bother? Look at what the program does on our example data right now:

BASH

python -m peakfinder.cli data/example_spectrum.csv | wc -l

OUTPUT

71

71 “peaks”, but there are only three real ones. The rest are noise. A minimum height will help.

Build it


Commit 1. In peakfinder/peaks.py, add the option and use it. Only these lines change:

PYTHON

def find_peaks(x, y, min_height=None):
    ...
        if y[i] > y[i - 1] and y[i] > y[i + 1]:
            if min_height is None or y[i] >= min_height:
                peaks.append((x[i], y[i]))

BASH

git commit -am "Add min_height option to find_peaks"

Commit 2. Add a test at the end of tests/test_peaks.py:

PYTHON



def test_min_height_ignores_small_peaks():
    x = [0, 1, 2, 3, 4, 5, 6]
    y = [0, 3, 0, 1, 4, 1, 0]
    assert find_peaks(x, y, min_height=3.5) == [(4, 4)]

BASH

pytest
git commit -am "Add tests for min_height"

Read your own work, and leave a note


Before you share a branch, review it yourself, the way a reviewer will. In VS Code, open the Source Control view and look at the Graph section (below the lists of changes). It shows the commits on your branch. Click one to see which files it touched, and click a file to see that commit’s changes by themselves. (On the command line: git log --oneline main.. and git show <hash>.)

Looking at commit 1, you notice something: the function’s docstring doesn’t mention the new option. That’s a correction to commit 1, not a new idea, and it shouldn’t be a commit of its own on the end. Edit the docstring in peaks.py:

PYTHON

    """Return a list of (position, height) for each local maximum in y.

    Peaks lower than min_height are ignored, if it is given.
    """

git commit --fixup <commit> makes a new commit whose message is fixup! followed by the subject of the commit it corrects. It’s a note to your future self: “this belongs inside that commit”. Find the hash, stage the change (+ next to the file in the Source Control view), and commit it as a fixup of commit 1:

BASH

git log --oneline main..
git commit --fixup <hash of "Add min_height option to find_peaks">
git log --oneline main..

OUTPUT

cfcb779 fixup! Add min_height option to find_peaks
3eace0b Add tests for min_height
d1bc7ff Add min_height option to find_peaks

VS Code has no button for --fixup, so this is one of the few places we use the terminal. The pattern that works well: stage in the Source Control view, commit in the terminal.

Tidy up before sharing: autosquash


When you’re ready to share, you do one last interactive rebase. It has two jobs:

  1. Fold in the fixups, which --autosquash does for you.
  2. Tidy anything else, using the same todo list as episode 6: reword a message that’s gone stale, drop a commit that turned out to be unnecessary, edit one that should be split, or move lines to reorder. Keep going until the list of commits reads well.

BASH

git rebase -i --autosquash main

Here is what happens to the branch:

Before:

flowchart RL
    accTitle: {The branch before autosquash}
    accDescr: {Three commits on top of main. From the oldest: Add min_height option, then Add tests for min_height, then a fixup commit on the end, shown in yellow, which corrects the first commit.}
    branch(["min-height"]) --> F["fixup! Add min_height option"] --> T["Add tests for min_height"] --> O["Add min_height option"] --> main
    classDef fix fill:#ffd,stroke:#a80,color:#000
    class F fix

After:

flowchart RL
    accTitle: {The branch after autosquash}
    accDescr: {Two commits on top of main, shown in green because they are new. The fixup has been folded into the first commit, so Add min_height option now includes the docstring change, and Add tests for min_height follows it.}
    branch(["min-height"]) --> T["Add tests for min_height"] --> O["Add min_height option<br/>(now with the docstring)"] --> main
    classDef new fill:#dfd,stroke:#080,color:#000
    class T,O new

Yellow: a fixup note. Green: new commits made by the rebase. Older commits are on the left.

Your editor opens, and git has already moved the fixup under the commit it belongs to, and marked it fixup:

pick d1bc7ff Add min_height option to find_peaks
fixup cfcb779 fixup! Add min_height option to find_peaks
pick 3eace0b Add tests for min_height

This time there is nothing else to edit, so just save and close. (If your commit list needs more, this is the moment: change the words in the todo list before you save, exactly as in episode 6.)

BASH

git log --oneline main..

OUTPUT

37552d4 Add tests for min_height
43922bf Add min_height option to find_peaks

Two clean commits, in the order you planned them, and the missing docstring never appears in the history as a “fix” commit.

Callout

--autosquash and rebase.autoSquash

In the setup page you set rebase.autoSquash true, which makes git rebase -i do this automatically. Typing --autosquash as well does no harm, and works on a computer where the setting isn’t there.

Callout

Does every commit still pass?

Remember “atomic” means each commit works on its own. You can ask git to check, by running the tests after every commit of the rebase:

BASH

git rebase main --exec "pytest -q"

It stops at the first commit where the tests fail. This is a great final check before asking for a review.

Challenge

Knowledge check: which commit?

For each, which commit should the fix be a --fixup of?

  1. Your three commits are add a function, add the option that uses it, add tests. The test shows a bug in the function.
  2. You spot a typo in a comment you added two commits ago.
  3. You forgot to update the README, which is a new thing and goes with none of your commits.
  1. The commit that added the function. That’s where the bug was born.
  2. The commit that added the comment.
  3. None of them. If it’s a new, separate change, make an ordinary new commit (such as Document the new option in the README). --fixup is for corrections to earlier commits.

Push your branch


Your branch is tidy. Push it to your fork:

BASH

git push

Because of your push.autoSetupRemote setting, git creates the branch on GitHub and links it up for you. We aren’t opening a pull request yet. That’s on day 2.

Challenge

Challenge: your own feature

You’ve seen the loop with min_height. Now do it again, for a different feature. You and your partner each take one:

  • Feature A: min_prominence. Only keep peaks that stand out from their surroundings. (Whoever’s first name comes first alphabetically.)
  • Feature B: peak widths. Optionally return each peak’s width at half its height. (The other person.)

The code is provided below. Your job is the workflow, not the maths.

Start from main, on your own branch:

BASH

git switch main
git switch -c feature-prominence      # or feature-widths

Your plan (write it down before you start!):

1. Add a helper function to peaks.py
2. Add an option to find_peaks that uses it
3. Add a test

Follow it, committing after each step, with a good message for each. Then, when the test fails, fix the problem in the right commit using --fixup and --autosquash.

Finally, check each commit passes, and push the branch.


Feature A: prominence

Commit 1. Add this to the end of peakfinder/peaks.py. Commit message: Add prominence function

PYTHON



def prominence(y, i):
    """Height of the peak at i above the higher of the valleys either side."""
    left_min = y[i]
    for j in range(i - 1, -1, -1):
        if y[j] > y[i]:
            break
        left_min = min(left_min, y[j])
    right_min = y[i]
    for j in range(i + 1, len(y)):
        if y[j] > y[i]:
            break
        right_min = min(right_min, y[j])
    return y[i] - min(left_min, right_min)

Commit 2. Change find_peaks in the same file. The signature gets a new option, and the append is wrapped in a check:

PYTHON

def find_peaks(x, y, min_prominence=0):
    ...
        if y[i] > y[i - 1] and y[i] > y[i + 1]:
            if prominence(y, i) >= min_prominence:
                peaks.append((x[i], y[i]))

Commit message: Add min_prominence option to find_peaks

Commit 3. Add this test to the end of tests/test_peaks.py. Commit message: Add tests for min_prominence

PYTHON



def test_min_prominence_ignores_bumps_on_a_slope():
    x = list(range(8))
    y = [0, 5, 4, 4.5, 4, 3, 1, 0]
    assert find_peaks(x, y, min_prominence=1) == [(1, 5)]

Feature B: widths

Commit 1. Add this to the end of peakfinder/peaks.py. Commit message: Add peak_width function

PYTHON



def peak_width(x, y, i):
    """Width of the peak at i where it falls to half its height."""
    half = y[i] / 2
    left = i
    while left > 0 and y[left] >= half:
        left -= 1
    right = i
    while right < len(y) - 1 and y[right] >= half:
        right += 1
    return x[right] - x[left]

Commit 2. Change find_peaks in the same file. The signature gets a new option, and the append changes:

PYTHON

def find_peaks(x, y, with_widths=False):
    ...
        if y[i] > y[i - 1] and y[i] > y[i + 1]:
            if with_widths:
                peaks.append((x[i], y[i], peak_width(x, y, i)))
            else:
                peaks.append((x[i], y[i]))

Commit message: Add with_widths option to find_peaks

Commit 3. Add this test to the end of tests/test_peaks.py. Commit message: Add tests for peak widths

PYTHON



def test_peak_widths():
    x = [0, 1, 2, 3, 4, 5, 6]
    y = [0, 1, 4, 8, 4, 1, 0]
    assert find_peaks(x, y, with_widths=True) == [(3, 8, 2)]

Then, for both

  1. Run pytest before you commit the test. It fails. Read the failure, and think about which commit the bug came from.
  2. Fix the bug. (Hint for A: the docstring says the higher of the two valleys. Hint for B: should the half-height point itself count as inside the peak?)
  3. Make the fix a --fixup of the commit that introduced the bug, and commit the test as a normal commit.
  4. Run git rebase -i --autosquash main, and just save the todo list.
  5. Check: git log --oneline main.. shows three clean commits, with no fixup!. Then git rebase main --exec "pytest -q" passes.
  6. git push

The bug. In A, the function used min(left_min, right_min) and should use max(...). In B, both while loops used >= and should use >.

The workflow (A shown; B is the same with different names):

BASH

git switch main
git switch -c feature-prominence

# commit 1: paste the helper at the end of peaks.py
git commit -am "Add prominence function"

# commit 2: edit find_peaks
git commit -am "Add min_prominence option to find_peaks"

# write the test (don't commit yet)
pytest                          # fails!
# fix min -> max in prominence()
git log --oneline main..        # find the hash of "Add prominence function"
git add peakfinder/peaks.py
git commit --fixup <hash>       # the hash of commit 1
git add tests/test_peaks.py
git commit -m "Add tests for min_prominence"

git rebase -i --autosquash main # save and close the todo list
git log --oneline main..
git rebase main --exec "pytest -q"
git push

The log before autosquash:

OUTPUT

bb3dfef Add tests for min_prominence
59ccff4 fixup! Add prominence function
9a044d1 Add min_prominence option to find_peaks
29261e9 Add prominence function

and after:

OUTPUT

e6a6edb Add tests for min_prominence
20567d6 Add min_prominence option to find_peaks
535b14d Add prominence function

Notice the fixup crossed over commit 2 to land in commit 1, which is where the bug was.

Key Points
  • Plan a few commits, then commit small changes as you go
  • When you spot a mistake in an earlier commit, git commit --fixup <commit> leaves a note, without stopping your flow
  • Before sharing, git rebase -i --autosquash main folds each fixup into its target, and you can also reword, reorder, drop or edit commits until the history reads well
  • git rebase main --exec "pytest -q" checks every commit passes

Content from Day 2 Recap and Warm-up


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • What did we cover yesterday?
  • Is everyone ready to start?

Objectives

  • Recall the main ideas from day 1
  • Check your branch and your fork are as we left them

Yesterday in one minute


Yesterday we were the author. We learned:

  • A commit is a snapshot with a pointer to its parent, and a branch is just a label. Changing a commit makes a new one.
  • The reflog remembers where HEAD has been, so we can recover from mistakes.
  • Good commits are atomic: one logical change, with the project working at every step.
  • We can shape commits with the staging area, --amend and reset, and rewrite a branch with interactive rebase.
  • In our daily loop we commit as we go, leave --fixup notes for mistakes in earlier commits, and tidy up with git rebase -i --autosquash before sharing.

Today we’re a collaborator. Other people’s work is landing in the same project as ours, and we need to work with it.

Warm-up quiz


Try these on your own for a minute or two, then we’ll go through them together.

Challenge

Quiz

  1. When you make a new commit, what happens to the branch label?
  2. Why does git commit --amend give you a different hash?
  3. You made a fixup! commit for something three commits back. How do you fold it into the right commit?
  4. You lost a commit after a mistake. Where do you look to find it?
  5. Why do we try to make each commit atomic? Give one reason.
  1. It moves forward to the new commit. A branch is just a label that follows the newest commit.
  2. A commit’s hash is calculated from its contents, including the message and its parent. Change any of that and you get a new commit with a new hash.
  3. git rebase -i --autosquash main (or just git rebase -i main if rebase.autoSquash is on). It moves the fixup under its target and folds it in.
  4. The reflog: git reflog. Find the hash, then git reset --hard <hash> or git branch <name> <hash>.
  5. Any of: it’s easier to review one idea at a time; you can revert just the bad change; you can cherry-pick just the fix; git bisect finds a small, specific commit; each commit passes the tests.

Check your state


Make sure you’re ready for today. In your peakfinder clone, with your virtual environment active:

BASH

git status
git switch main
git log --oneline -1
git branch
git log --oneline main..feature-prominence      # or feature-widths

You should see:

  • git status: nothing to commit, working tree clean
  • main still at Add plotting of the spectrum and its peaks (hash 1e81f27). If main has any extra commits of your own, you can put it right with git reset --hard origin/main.
  • Your feature branch listed, with three clean commits and no fixup!.

Then check your work is on GitHub. Open your fork in the browser, switch to your feature branch, and check that you can see the three commits. Ask your partner to look too.

Callout

If you’re missing your feature branch

If your branch is missing, or in a bad state, don’t spend long on it. Ask a helper, or build a quick replacement:

BASH

git switch main
git switch -c feature-prominence

and redo the three commits from episode 7 (it’s fast now that you’ve done it before). The helpers can also give you a ready-made branch.

Today’s story


While you were working on your feature, a colleague was working on the same project, and their work has now been approved and merged into main.

Today we’ll:

  1. bring that work into our branch, and deal with the conflict between their changes and ours (episode 9)
  2. find out why a test is now failing, and which change caused it (episode 10)
  3. have our work reviewed by our partner (episode 11)
  4. set up automatic checks (episode 12)
  5. release a fix (episode 13)

Two rules for today

  • Every pull request is on your own fork, never on the course repository. GitHub proposes the original repository by default, so we’ll remind you where it matters.
  • Merge pull requests with “Rebase and merge”, so your carefully made commits stay exactly as you wrote them.
Key Points
  • Day 1 was about producing good history: snapshots, atomic commits, rewriting and the daily loop
  • Day 2 is about sharing it and working alongside other people’s changes
  • Check your branch and your fork are in order before starting

Content from Rebase vs Merge, and Resolving Conflicts


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • My teammate’s work landed while I was working. How do I bring it into my branch?
  • What is the difference between merging and rebasing?
  • How do I resolve a conflict?
  • Why can’t I push after a rebase?

Objectives

  • Explain the difference between merge and rebase using diagrams
  • Fast-forward main and see why it stays a straight line
  • Bring changes from main into a feature branch by rebasing
  • Resolve a conflict using the VS Code merge editor
  • Push a rebased branch safely with --force-with-lease
  • State the golden rule: don’t rewrite history other people are using

While you were working


Yesterday you built a feature on its own branch. Meanwhile, a colleague was working on the same project. Their pull request has just been approved, and merged into main. Our feature branch is now based on an out-of-date main:

flowchart RL
    accTitle: {Main has moved on while your branch stood still}
    accDescr: {A shared starting commit. Main now has the colleague's work on top of it. Your feature branch also starts from the same shared commit, but has your three commits and does not have the colleague's work.}
    main(["main"]) --> W["colleague's work<br/>(6 commits)"] --> base["starting point"]
    feature(["your feature"]) --> F3 --> F2 --> F1 --> base

We need their changes in our branch, so that we can be sure our work fits with theirs before anyone reviews it.

First, let’s simulate their pull request being merged. In real life GitHub does this when someone clicks the merge button. Your fork has a branch colleague/normalise-modes that stands in for their work:

BASH

git fetch
git switch main
git merge --ff-only origin/colleague/normalise-modes
git push
git log --oneline --graph -8

OUTPUT

* 1c13652 Document Peak in the README
* b83c177 Return Peak tuples from find_peaks
* df97539 Bump version to 0.2.0
* 25dbef6 Remove unused import from cli
* e2c7538 Add mode option to normalise
* 0b83055 Fix typo in README
* 1e81f27 Add plotting of the spectrum and its peaks
* b7cf029 Add command line interface

This was a fast-forward: main had nothing of its own, so git simply moved the main label along to the colleague’s last commit. No new commit was made, and the history is still a straight line. (--ff-only means “do this, or refuse”: it will never silently create a merge commit.)

Before:

flowchart RL
    accTitle: {Before the fast-forward}
    accDescr: {Main points at the starting point. The colleague's branch points at the colleague's six commits, which sit on top of the same starting point.}
    main(["main"]) --> base["starting point"]
    colleague(["colleague/normalise-modes"]) --> W["colleague's work<br/>(6 commits)"] --> base

After:

flowchart RL
    accTitle: {After the fast-forward}
    accDescr: {The main label has moved forward along the line to the colleague's last commit, so main and the colleague's branch point at the same commit. No new commit was made.}
    main(["main"]) --> W["colleague's work<br/>(6 commits)"]
    colleague(["colleague/normalise-modes"]) --> W
    W --> base["starting point"]

Only the main label moved. Older commits are on the left.

Two ways to bring it in


There are two ways to get main’s new commits into your branch.

Option 1: merge

BASH

git merge main

Git creates a merge commit that has two parents: the tip of your branch and the tip of main.

flowchart RL
    accTitle: {After merging main into your branch}
    accDescr: {A new merge commit sits on top of your branch. It has two parents: your last commit, and the colleague's work on main. The history is no longer a straight line, because it splits and joins.}
    main(["main"]) --> W["colleague's work"] --> base["starting point"]
    feature(["your feature"]) --> M["merge commit"]
    M --> F3 --> F2 --> F1 --> base
    M --> W
    classDef new fill:#dfd,stroke:#080,color:#000
    class M new

Green: the new merge commit. Everything else was there before the merge and hasn’t changed. Older commits are on the left.

Nothing has been rewritten, and that is the merge’s great strength: it’s safe. But your history now splits and rejoins. Do that every time main moves, and your branch fills up with “Merge branch ‘main’ into …” commits that say nothing about your work. A reviewer reading commit by commit has to read around them.

Callout

Merge commits are git’s default, and a fine default

Merging is what git does unless you tell it otherwise, and it’s the default button on GitHub (Create a merge commit). For most teams it’s a perfectly good default: it’s safe, it never rewrites anything, and it records exactly when branches were joined. We prefer a straight line because we want every commit to be readable one at a time, but a history with merge commits isn’t wrong. Follow your team’s convention.

Option 2: rebase

BASH

git rebase main

Git takes your commits one at a time and replays them on top of the new main. This is the same thing as in episode 6, but the new starting point is different.

flowchart RL
    accTitle: {After rebasing your branch onto main}
    accDescr: {Your three commits have been replayed on top of the colleague's work, so they are new commits, shown in green, with new hashes. The history is a straight line. The old versions of your commits still exist, shown dashed, but nothing points at them.}
    main(["main"]) --> W["colleague's work"] --> base["starting point"]
    feature(["your feature"]) --> F3p["F3'"] --> F2p["F2'"] --> F1p["F1'"] --> W
    F3 --> F2 --> F1 --> base
    classDef new fill:#dfd,stroke:#080,color:#000
    classDef old stroke-dasharray: 5 5
    class F3p,F2p,F1p new
    class F3,F2,F1 old

Green: new commits made by the rebase. Dashed: your old commits, which nothing points at now. Older commits are on the left.

It is as if you had started your work after the colleague’s. History is a straight line, with your commits neatly on top.

The difference in one sentence

Merge joins the two tips together, and leaves a join in the history. Rebase moves the base (the bottom) of your branch to the tip of main, and leaves no trace of the move.

Challenge

Knowledge check: merge or rebase?

Which one:

  1. creates a new commit with two parents?
  2. gives every one of your commits a new hash?
  3. leaves a history that is a straight line?
  4. doesn’t change any existing commit?
  1. Merge
  2. Rebase (they are replayed on a new parent, so remember episode 2: new parent, new hash)
  3. Rebase
  4. Merge

Watch: what a merge does


Your instructor will demonstrate this on screen. Watch, and follow the output below, but don’t run these commands yourself. In a few minutes you’ll resolve this same conflict for real, in a rebase, and there’s no point doing it twice.

The instructor switches to a feature branch and merges main into it:

BASH

git switch feature-prominence
git merge main

OUTPUT

Auto-merging tests/test_peaks.py
CONFLICT (content): Merge conflict in peakfinder/peaks.py
Automatic merge failed; fix conflicts and then commit the result.

A conflict. Git tried to combine the colleague’s changes with ours, but both of us changed the same lines of find_peaks, and git can’t decide whose change should win. It has stopped, and is waiting for us to decide.

What is a conflict?


Git merges changes automatically whenever it can. A conflict happens only when two sets of changes touch the same lines. Git marks the file with both versions. Open peakfinder/peaks.py and you’ll see something like:

<<<<<<< HEAD
@dataclass
class Peak: ...
def find_peaks(x, y):
    """Return a list of Peak tuples, one for each local maximum in y."""
=======
def find_peaks(x, y, min_prominence=0):
    """Return a list of (position, height) for each local maximum in y."""
>>>>>>> your branch

Everything between <<<<<<< and ======= is one side, and everything between ======= and >>>>>>> is the other. To resolve a conflict you edit the file so that it contains what you actually want, and delete the markers.

You can do that by hand in any editor. VS Code has a much friendlier way.

Resolving a conflict in VS Code


  1. Open the Source Control view. The conflicted file appears under Merge Changes.
  2. Click the file, and then Resolve in Merge Editor.
  3. The merge editor shows three panes:
    • Incoming (top left) and Current (top right): the two versions in conflict
    • Result (bottom): what the file will contain
  4. For each conflict, use the controls next to it to accept Incoming, accept Current, or accept both, or edit the Result directly. Most of the time you want a mix of both sides, so edit the result until it’s right. Check the Result after each choice: it tells you how many conflicts are still unresolved.
  5. When there are none left, click Complete Merge. VS Code saves the file and stages it. (It doesn’t finish the whole operation. See below.)

(You can also resolve small conflicts without the merge editor, using the Accept Current Change / Accept Incoming Change / Accept Both Changes links that VS Code shows above each conflict in the file itself.)

Callout

“Current” and “Incoming” swap during a rebase

In a merge, Current is your branch and Incoming is the branch you are merging in. That makes sense.

In a rebase, it’s the other way round: Current is the branch you’re rebasing onto (here, main, with the colleague’s work), and Incoming is your commit being replayed. It’s confusing, but there’s a reason: git is building your commits on top of main, so main’s version is what’s already there.

So always read the code, not the labels. Which side has the colleague’s changes, and which has yours?

What do we want here?

Both sides made a good change. The colleague wants find_peaks to return Peak objects, and you want to add your own option. We want both:

  • the colleague’s Peak class and the new docstring
  • your new parameter and your new filter, but building a Peak as the colleague did

In the demonstration, the instructor resolves the conflict in the merge editor, then commits the merge:

BASH

git commit --no-edit
git log --oneline --graph -8

OUTPUT

*   01eb097 Merge branch 'main' into feature-prominence
|\
| * 1c13652 Document Peak in the README
| * b83c177 Return Peak tuples from find_peaks
| * df97539 Bump version to 0.2.0
| * 25dbef6 Remove unused import from cli
| * e2c7538 Add mode option to normalise
| * 0b83055 Fix typo in README
* | a340483 Test min_prominence

There is the split and rejoin. We would rather not leave that in our history, so the instructor undoes the merge.

Undoing the merge

Before a merge, git remembered where it was in ORIG_HEAD (episode 4). That puts the branch back:

BASH

git reset --hard ORIG_HEAD
git log --oneline -4

OUTPUT

a340483 Test min_prominence
c8e1c74 Add min_prominence option to find_peaks
7c8cefd Add prominence function
1e81f27 Add plotting of the spectrum and its peaks

The three commits are back, exactly as they were. (If this ever doesn’t work, the reflog has the answer.)

Challenge

Challenge: rebase onto main

Now it’s your turn, the other way round. You’ve seen how a conflict gets resolved, so this time you do it, in a rebase. Switch to your feature branch, rebase it onto main, and resolve the conflict in the merge editor.

BASH

git switch feature-prominence        # or feature-widths
git rebase main

Git replays your three commits. It stops at the one that conflicts (your “Add … option to find_peaks” commit). Then:

  1. Open the Source Control view and resolve peaks.py in the merge editor. The result must have the colleague’s Peak tuple and your new option. There are two conflicts in the file, near the top and in the if inside the loop. (Hints are below.)
  2. Click Complete Merge. That stages the file.
  3. Tell git to carry on: git rebase --continue in the terminal. (VS Code’s Commit button also continues an in-progress rebase once everything is staged. An editor tab may open with the commit message. Just close it.)
  4. Run git log --oneline --graph -8: it should be a straight line, with your three commits on top of the colleague’s.
  5. Run the tests: pytest.

Predict first: what do you expect pytest to say? Then look.

Hints, for what the finished find_peaks needs:

  • Feature A (prominence): keep the colleague’s Peak class and docstring, add your min_prominence=0 parameter, and in the loop keep your if prominence(...) check, but append Peak(x[i], y[i]).
  • Feature B (widths): keep the colleague’s Peak class and docstring, add your with_widths=False parameter, and in the loop keep your if with_widths: branch. In the else branch append Peak(x[i], y[i]).

If it all goes wrong, git rebase --abort puts everything back as it was before you started. (In VS Code: Command Palette, Git: Abort Rebase.)

Feature A (the top of peaks.py, and the loop):

PYTHON

from typing import NamedTuple

import numpy as np


class Peak(NamedTuple):
    position: float
    height: float


def find_peaks(x, y, min_prominence=0):
    """Return a list of Peak tuples, one for each local maximum in y."""
    x = np.asarray(x)
    y = np.asarray(y)
    peaks = []
    for i in range(1, len(y) - 1):
        if y[i] > y[i - 1] and y[i] > y[i + 1]:
            if prominence(y, i) >= min_prominence:
                peaks.append(Peak(x[i], y[i]))
    return peaks

Feature B:

PYTHON

def find_peaks(x, y, with_widths=False):
    """Return a list of Peak tuples, one for each local maximum in y."""
    x = np.asarray(x)
    y = np.asarray(y)
    peaks = []
    for i in range(1, len(y) - 1):
        if y[i] > y[i - 1] and y[i] > y[i + 1]:
            if with_widths:
                peaks.append((x[i], y[i], peak_width(x, y, i)))
            else:
                peaks.append(Peak(x[i], y[i]))
    return peaks

(with the same Peak class above it.)

The commands:

BASH

git rebase main
# resolve peaks.py in the merge editor, then Complete Merge
git rebase --continue
git log --oneline --graph -8
pytest

OUTPUT

* 8c01021 Test min_prominence
* 706f2cd Add min_prominence option to find_peaks
* cdd94be Add prominence function
* 1c13652 Document Peak in the README
* b83c177 Return Peak tuples from find_peaks
* df97539 Bump version to 0.2.0
* 25dbef6 Remove unused import from cli
* e2c7538 Add mode option to normalise
* 0b83055 Fix typo in README
* 1e81f27 Add plotting of the spectrum and its peaks

A straight line: the colleague’s six commits, then your three.

What does pytest say? All your tests pass, but there is one failure:

OUTPUT

FAILED tests/test_normalise.py::test_normalise_runs_from_zero_to_one - assert...
1 failed, 8 passed

That’s not in your code. It’s in normalise, which you haven’t touched. Something has changed in the colleague’s commits that affects it, and we’ll find out what in the next episode.

Why can’t I push?


Your branch is on GitHub from yesterday, with the old versions of your commits. Try to push the new ones:

BASH

git push

OUTPUT

 ! [rejected]        feature-prominence -> feature-prominence (non-fast-forward)
error: failed to push some refs to 'github.com:...'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. If you want to integrate the remote changes,
hint: use 'git pull' before pushing again.

Git refuses, because the history on GitHub and the history on your computer have diverged. The remote has your three old commits, and you have three new ones that are replacements. It’s the picture from episode 2: a rebase makes new commits, and the old ones are still out there.

Callout

Don’t follow the hint!

Git suggests git pull. Don’t. That would try to combine your new commits with the old ones on the remote. You’d end up with each commit twice, or a mess of conflicts.

(We tried it. With git’s default, each of your commits ends up in the history twice, and you get a conflict. With pull.rebase true, git tries to replay the colleague’s commits on top of the old versions of yours and stops with conflicts. If you ever do it by accident, git merge --abort or git rebase --abort puts you back, and git reflog can help, as in episode 4.)

What we want is to replace the remote’s version with ours. That is a force push, and it’s the correct thing to do after a rebase, as long as the only person whose work you’re replacing is you. Use the safe version:

BASH

git push --force-with-lease

OUTPUT

 + a340483...36fc668 feature-prominence -> feature-prominence (forced update)

The difference from --force:

  • --force says: “Overwrite the remote, whatever is there.”
  • --force-with-lease says: “Overwrite the remote, but only if it’s still what I last saw.”

If a teammate had pushed something to the branch since you last fetched, --force-with-lease would refuse, instead of silently destroying their work. So always use it, and never plain --force.

Callout

The golden rule

Only rewrite history that nobody else is depending on.

  • Your own feature branch, before anyone has built on it: fine.
  • A branch with an open pull request: fine, with care. The reviewer must know. We’ll cover that in episode 11.
  • main, or any branch other people have pulled and are working on: never.

A word on linear history


Our main is a straight line, and so is our branch. Many teams like this because:

  • git log reads like a story
  • bisect, blame and cherry-pick are easier
  • a revert undoes one thing

When you merge a pull request on GitHub, there are three buttons. (The first, Create a merge commit, is the default, and a fine choice if that’s what your team does.)

Button What it does to main Keeps your carefully made commits?
Create a merge commit adds a merge commit with two parents yes, with a join in the history
Squash and merge squashes all your commits into one no, it throws the story away
Rebase and merge replays your commits on top of main yes, and the history stays straight

If you took the trouble to curate your commits, rebase and merge is usually what you want. Squash is a reasonable fallback for a branch that nobody tidied up. Each team has its own policy, and it’s worth finding out what yours is.

Callout

Your pull.rebase setting

You ran git config --global pull.rebase true in the setup. It makes a plain git pull rebase your local commits on top, instead of creating a merge commit. That’s a matter of taste (git’s default is to merge), but it keeps your branch a straight line.

Challenge

Knowledge check: is it safe to rebase?

Which of these are OK to rebase and force-push (with --force-with-lease)?

  1. main
  2. A branch where you and your partner both push commits
  3. Your own feature branch with an open pull request that nobody has reviewed yet
  1. No. Everyone’s work is based on it.
  2. Only if you tell your partner, and they know to fetch and reset, or rebase. Otherwise they’ll have the old commits and be confused. Better to agree a rule first.
  3. Yes. It’s your branch. If no one has started reviewing, there’s nothing to disturb. (If they have, tell them. See episode 11.)
Key Points
  • A fast-forward just moves a label, so main stays a straight line
  • Merge joins two tips with a merge commit. Rebase moves your branch’s base, and replays your commits as new ones
  • A conflict means both sides changed the same lines. Resolve it by editing the result to contain what you want. The VS Code merge editor makes this easy
  • In a rebase, “Current” is the branch you’re rebasing onto and “Incoming” is your commit
  • After a rebase, push with --force-with-lease. Never follow git’s hint to git pull
  • Only rewrite history that nobody else is depending on
  • For pull requests, “Rebase and merge” keeps your curated commits and a straight history

Content from Tracking Down a Bug: Blame and Bisect


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • Which commit last changed this line, and what was it for?
  • When did this test start failing?
  • How do I fix a bug I find, without tangling the fix into my own feature?

Objectives

  • Use blame in VS Code to see which commit changed a line
  • Use git bisect to find the commit where a test started failing
  • Fix a bug on a separate branch, merge it into main, and rebase your feature onto the result

One test is failing


At the end of the last episode we rebased onto main and one test failed. It isn’t in our code. Run it again:

BASH

pytest tests/test_normalise.py

OUTPUT

>       assert np.allclose(result, [0, 0.5, 1])
E       assert False
E        +  where False = <function allclose at 0x769723b210b0>(array([-1. , -0.6, -0.2]), [0, 0.5, 1])

normalise([1, 3, 5]) should give [0, 0.5, 1], but it gives [-1, -0.6, -0.2]. This test passed at v0.1.0, so something changed in the colleague’s six commits that affects it. Two questions: which commit changed normalise, and when did the test start failing?

Which commit changed this line? Blame


Open peakfinder/normalise.py in VS Code. The suspicious line is in the range branch. git blame tells you which commit last changed each line, and its author, so you know where to look and who to ask about what the change was for.

In VS Code:

  1. Open the Command Palette (Ctrl+Shift+P, or Cmd+Shift+P on a Mac).
  2. Run Git: Toggle Git Blame Editor Decoration. Each line now shows its commit at the end. (Git: Toggle Git Blame Status Bar Item shows the commit for the current line in the status bar instead.)
  3. Hover over the blame text to see the commit hash, message and author.

On the command line, the same information is:

BASH

git blame -L 5,12 peakfinder/normalise.py

OUTPUT

e2c75380 (Robin Researcher 2025-02-04 11:00:00 +0000  5)     """Scale y. mode is 'range' (0 to 1), 'max' (divide by max) or 'area'."""
b8055cf7 (Sam Scientist    2025-01-06 12:00:00 +0000  6)     y = np.asarray(y, dtype=float)
e2c75380 (Robin Researcher 2025-02-04 11:00:00 +0000  7)     if mode == "range":
e2c75380 (Robin Researcher 2025-02-04 11:00:00 +0000  8)         return (y - y.min()) / y.max() - y.min()
...

The suspicious line 8 comes from e2c75380. (-L 5,12 means lines 5 to 12.)

Callout

Other ways to look at history

  • Blame isn’t proof. It shows only the last change to a line. A later commit that merely re-indented the code would hide the real change. For when something broke, use bisect, below.
  • The Timeline view (in the Explorer sidebar, for the open file) lists the commits that changed it. The Source Control Graph lists the commits on your branch: select one to see its files, and a file to see the diff.
  • git log -S"text" -- <file> lists the commits that added or removed some text, and git log -L :<function>:<file> shows the history of one function.
  • The GitLens and Git History extensions add richer inline blame and file history, if you like them.

Bisect: find when it broke


Blame told us who last touched the line. What we really want is the first commit where the test fails, and git can find that for us, quickly. You know a commit where the test passed (v0.1.0) and one where it fails (main). git bisect does a binary search between them: it checks out the commit in the middle, tests it, and halves the range again.

flowchart LR
    accTitle: {Bisect narrows seven commits down to the first bad one}
    accDescr: {Seven commits in order from oldest to newest. The oldest, v0.1.0, is known good, shown in green. The newest, Document Peak, is known bad, shown in red. Bisect tests the middle commit first, Remove import, which is bad. It then tests Add mode option, which is bad, and then Fix typo, which is good. So Add mode option is the first bad commit.}
    A["v0.1.0<br/>GOOD"] --> B["Fix typo<br/>test 3: good"] --> C["Add mode option<br/>test 2: bad<br/>FIRST BAD"] --> D["Remove import<br/>test 1: bad"] --> E["Bump version"] --> F["Return Peak"] --> G["Document Peak<br/>BAD"]
    classDef good fill:#dfd,stroke:#080,color:#000
    classDef bad fill:#fdd,stroke:#c00,color:#000
    class A,B good
    class C,D,G bad

Time runs left to right. With six commits to check it takes three tests. With 1,000 commits, it takes about ten.

Even better, if the test can be run by a command, git can do the whole search by itself. The command should exit with 0 for “good” and non-zero for “bad”, which is exactly what pytest does:

BASH

git bisect start main v0.1.0
git bisect run pytest -q tests/test_normalise.py
git bisect reset

(git bisect start <bad> <good>: first the bad commit, then the good one. Always finish with git bisect reset, which puts you back on your own branch.)

OUTPUT

e2c7538061b16250b842ab506cac3c2ae25b20c2 is the first bad commit
commit e2c7538061b16250b842ab506cac3c2ae25b20c2
Author: Robin Researcher <robin.researcher@example.org>

    Add mode option to normalise
...
bisect found first bad commit
Callout

By hand: what bisect run is doing

Without run, you do the testing yourself. Your instructor will show this on screen:

BASH

git bisect start main v0.1.0       # git checks out a commit in the middle
pytest -q tests/test_normalise.py  # it fails...
git bisect bad                     # ...so tell git
pytest -q tests/test_normalise.py  # git moved to an older commit. It fails too...
git bisect bad
pytest -q tests/test_normalise.py  # older still. This one passes
git bisect good                    # git: "... is the first bad commit"
git bisect reset

At each step you’re on a detached HEAD (episode 2): not on any branch. That’s fine, as git bisect reset puts you back.

Callout

Why atomic commits matter here

Bisect names a commit. If that commit is small and atomic (“Add mode option to normalise”), you know almost exactly where the problem is. If it were a huge commit that changed 900 lines across ten files, bisect would tell you only that the problem is somewhere in there. This is the payoff of episode 3.

Challenge

Challenge: find the commit

  1. Run the three commands above to find the commit where test_normalise_runs_from_zero_to_one starts to fail.
  2. Open that commit (git show <hash>, or select it in the Source Control Graph). What exactly is wrong with the range line?
  3. Check you’re back on your feature branch: git branch --show-current.
  1. The first bad commit is Add mode option to normalise.
  2. In range mode, the code is (y - y.min()) / y.max() - y.min(). The brackets are wrong: it divides by y.max() only, and then subtracts y.min(). It should divide by (y.max() - y.min()). It only gives the right answer when the minimum is zero. The existing test would have caught it, but it looks as though the tests weren’t run, and nothing runs them automatically. (That is what we’ll fix in episode 12.)
  3. git bisect reset returns you to your branch.

If git bisect complains about local changes, you have uncommitted work. Stash it (see the reference page) or commit it, and try again.

Fix it, but not here


We know what’s wrong, and the fix is one line. The tempting thing is to fix it on the feature branch, as it’s right there. Don’t. The fix has nothing to do with your feature, so your pull request would mix two ideas. And if the fix is tangled up with your feature, nobody can use it without taking your feature too. We’ll need exactly that in episode 13.

So put the fix on its own branch from main:

BASH

git switch main
git switch -c fix/normalise

Fix the line in peakfinder/normalise.py:

PYTHON

        return (y - y.min()) / (y.max() - y.min())

Check it, and commit it with a message that explains why:

BASH

pytest
git commit -am "Fix 'range' mode of normalise for spectra that don't start at zero" -m "The division only applied to y.max(), not to (y.max() - y.min())."

On a real team you would open a pull request for this fix, and we’ll look at doing that well in the next episode. To keep moving, we’ll merge it straight into main now. Nothing has happened on main since we branched, so git can fast-forward it (episode 9):

BASH

git switch main
git merge --ff-only fix/normalise
git push
git branch -d fix/normalise

OUTPUT

Updating 1c13652..05c314d
Fast-forward
 peakfinder/normalise.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

Finally, your feature branch is based on a main that still has the bug. Rebase it again, as we did in the last episode:

BASH

git switch feature-prominence        # or feature-widths
git rebase main
pytest
git push --force-with-lease

OUTPUT

Successfully rebased and updated refs/heads/feature-prominence.
9 passed

This time there is no conflict, because the fix touched different lines from your feature, and every test passes.

Challenge

Challenge: fix the bug on its own branch

Do the whole thing yourself:

  1. Create fix/normalise from main, fix the bug, and commit it with a good message.
  2. Fast-forward main to it, push, and delete the branch.
  3. Rebase your feature branch onto the updated main, and push with --force-with-lease.
  4. Check: pytest passes everything, and git log --oneline -5 on your feature branch shows the fix underneath your three commits.

BASH

git switch main
git switch -c fix/normalise
# edit normalise.py: (y - y.min()) / (y.max() - y.min())
pytest
git commit -am "Fix 'range' mode of normalise for spectra that don't start at zero"

git switch main
git merge --ff-only fix/normalise
git push
git branch -d fix/normalise
git switch feature-prominence
git rebase main
pytest
git push --force-with-lease

OUTPUT

ab0c4ef Test min_prominence
b70cf77 Add min_prominence option to find_peaks
6eaff85 Add prominence function
b676f77 Fix 'range' mode of normalise for spectra that don't start at zero
1c13652 Document Peak in the README

(Your hashes will be different.)

Challenge

Knowledge check

  1. When might git blame point you at the wrong commit?
  2. Why does git bisect work best with small, atomic commits?
  3. Why did we fix the bug on a separate branch, and not on the feature branch?
  1. When a later commit changed the line without changing what it does, such as re-indenting, renaming a variable or reformatting. Blame shows only the last change, not the one that introduced the bug. (git blame -w ignores whitespace changes, and the VS Code setting git.blame.ignoreWhitespace does the same.)
  2. It names a single commit. If the commit is small and has one purpose, you know where the bug is. A giant commit leaves you searching inside it.
  3. A fix is a separate idea. Mixing it into the feature would give reviewers two things to understand at once, and anyone who wanted just the fix would have to take the feature too.
Key Points
  • Blame shows which commit last changed each line (in VS Code: Git: Toggle Git Blame Editor Decoration). It shows only the last change, so it isn’t proof of the cause
  • git bisect binary-searches history for the first commit where a test fails. git bisect run <command> automates it. Always finish with git bisect reset
  • Fix bugs you find on a branch of their own, so the fix is a single idea that can be reviewed and reused

Content from Pull Requests: Authoring and Reviewing


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • What makes a pull request easy to review?
  • How do I give a review that helps?
  • How do I change a pull request after feedback without confusing the reviewer?

Objectives

  • Check your own branch the way a reviewer will, before you open a pull request
  • Write a pull request description that a reviewer will thank you for
  • Review a pull request one commit at a time, and leave comments that help
  • Respond to feedback with --fixup commits, then autosquash before merging
  • Check that tidying your history didn’t change the code (in VS Code, or with git diff)

A pull request is a story


A pull request asks for your branch to be merged. But it is more than a button. It is the place where your work is read by another person, where automatic checks run (episode 12), and where the decision to merge is made.

When you open one, you are handing someone a small story: “Here is a change, here is why, here is how it was made.” Everything we have done so far, planning, atomic commits and a tidy history, exists to make that story easy to read.

A reviewer can read it in two ways:

  • all at once, in the Files changed tab, which is one big diff
  • one commit at a time, in the Commits tab, where each commit tells one part of the story

The second way is far easier, and it only works if your commits are atomic and well named. That is the payoff for the work we did on day 1.

Here is the life of a pull request, which is what we’ll do in this episode:

flowchart LR
    accTitle: {The life of a pull request}
    accDescr: {Open the pull request after reviewing your own branch. Your partner reviews it commit by commit. If they leave comments, you push a fixup commit and they review again. When they approve, you squash the fixups with autosquash, and then merge with Rebase and merge.}
    A["Open the PR<br/>(review your own<br/>branch first)"] --> B["Partner reviews<br/>commit by commit"]
    B -->|comments| C["You push a<br/>fixup commit"]
    C --> B
    B -->|approved| D["Squash the fixups<br/>(autosquash)"]
    D --> E["Rebase<br/>and merge"]
    classDef done fill:#dfd,stroke:#080,color:#000
    class E done

Today we’ll go as far as the approval. Squashing and merging are the last step, and you can do them now or later.

Before you open it: review your own branch


The cheapest review is your own. Before you ask anyone else, look at your branch as they will. Go through these:

Write a description a reviewer will thank you for


The title and description are the first things a reviewer reads. Tell them what they need to know:

  • What changed, in a sentence or two
  • Why: the problem it solves
  • How to check it: the commands they can run, or what to look at
  • Anything they should pay particular attention to, or that you aren’t sure about

For our prominence feature, that might be:

Add a min_prominence option to find_peaks

Our example data has 71 "peaks" and only three real ones, because noise makes lots of
little bumps. A peak's prominence is how far it stands out above the surrounding
valleys, so a minimum prominence removes the bumps on the slope of a real peak.

Three commits: the prominence helper, the new option, and a test. Read them in order.

To check it, run `pytest`. The new test is `test_min_prominence_ignores_bumps_on_a_slope`.

Not sure about: how this should behave for flat-topped peaks.
Callout

Pull request templates

Some repositories have a pull request template: a file called .github/pull_request_template.md that pre-fills the description box with headings (what changed, why, how to test, a checklist). If you see text already in the box when you open a pull request, that’s why. Fill it in rather than deleting it. A project without one can add its own, and it’s a good way for a team to agree what a description should contain.

Draft pull requests

If your work isn’t ready but you want early feedback, or you want automatic checks to run, open it as a draft (the arrow on the green button). Nobody will merge it by accident, and you can mark it Ready for review when it is.

Open the pull request


  1. Push your branch: git push. (It’s already on GitHub from day 1, so this should say everything is up to date.)
  2. On GitHub, open your fork, and click Compare & pull request next to your branch. (Or Pull requests, then New pull request.)
  3. Check the base repository. It must be your own fork (YOUR-USERNAME/peakfinder), with base branch main. Use the base repository dropdown to change it if needed. (See the warning below.)
  4. Write the title and description. Click Create pull request.
  5. In the right-hand sidebar, ask your partner for a review: Reviewers, then choose their username.

Look at the Commits tab. Each of your commits is there, one at a time. That’s what your reviewer will use.

Callout

Make sure the pull request is on your fork

Pull requests from a fork default to the project you forked from. If you create one against the original, you will be sending it to the course repository. Check the “base repository” line at the top of the page before you press the button. It should show your own username. From here on, every pull request in this workshop is on your own fork.

Giving a good review


Now swap. Your partner has opened a pull request in their fork. Open it (they’ll send you the link, or it will be in your notifications).

How to read it

  1. Read the description. Do you know what to expect?
  2. Go to the Commits tab. Read the commits one at a time, from the oldest. Does each one do what its message says?
  3. Look at each commit’s diff. Hover over a line in the diff and click the blue + to comment on that line.
  4. Ask yourself: Is this correct? Is it clear? Is anything missing, like a test?

What good comments look like

  • Be specific. “This loop is hard to follow” is less useful than “Could we name i as index? I had to scroll back to see what it was.”
  • Ask questions rather than giving orders. “What happens for a peak at the edge of the data?” invites a conversation, and might teach you something.
  • Mark the small things. Start optional, minor comments with nit: (short for nitpick) so the author knows they won’t block the merge.
  • Suggest the change. On a line comment, the Add a suggestion button writes your replacement code in the comment, and the author can apply it with one click.
  • Say what’s good. A review that is only complaints is hard to read. If something is neat, say so.
  • Review the code, not the person. “This doesn’t handle…” rather than “You forgot…”

When you’ve finished, click Review changes (top right of Files changed) and choose:

Choice Meaning
Comment feedback only
Approve looks good to merge
Request changes something must change first
Challenge

Challenge: swap and review

Review your partner’s pull request, one commit at a time, in the Commits tab. Leave exactly three comments:

  1. one nit: (short for nitpick: a small thing the author could improve)
  2. one question
  3. one suggestion, using the Add a suggestion button

Then submit the review as Comment (we’ll approve it in a moment).

No partner, or your partner isn’t ready? Review the example pull request your instructor shares instead.

Need an idea for something to comment on? Good first things to look at are the docstring of the helper function in the first commit, the names of variables in it, and what the test doesn’t cover (flat peaks, peaks at the edges, an empty list).

Responding to feedback


You’ve got a review, and you want to change something in an earlier commit, such as the docstring in your first commit. There are three common ways to do it, and each has a cost:

Approach What you do Easy for the reviewer? History afterwards The catch
“Address review” commits Add new commits on the end, e.g. PR: rename variable, and push normally Yes: each new commit is exactly what changed Messy, unless the pull request is squash-merged Fine if your team squash-merges anyway, because the commits vanish
Fixup commits, squashed before merging git commit --fixup <hash>, push normally. When approved, autosquash and --force-with-lease Yes: same as above Clean Someone has to autosquash before the merge. GitHub’s merge buttons won’t do it for you, so you tell the reviewer
Amend and force-push every round Fix the commit in place, --force-with-lease No: new hashes everywhere, so they re-read everything Clean Easy to lose track of what changed. Comments become “outdated”

Our recommendation: fixup commits, squashed when it’s approved. It’s the only one that is easy to review and leaves a clean history. The cost is one short bit of coordination: you say “approved, so I’m squashing the fixups now. The code won’t change, and I’ll check that.” If your team squash-merges every pull request, ignore all this: plain “address review” commits are fine, since the history is flattened anyway.

For a fixup, the steps are what you did yesterday, with one difference: you push it normally, with no force, because you only added a commit.

BASH

git log --oneline main..          # find the hash of the commit it belongs to
git commit --fixup <hash>
git push

OUTPUT

   ab0c4ef..9ae8b33  feature-prominence -> feature-prominence

Your reviewer opens the pull request and sees one small commit, fixup! Add prominence function, which contains exactly your change. There’s nothing to re-read.

Challenge

Challenge: respond and approve

  1. Address one of the comments you received, as a fixup of the commit it belongs to. Stage it in VS Code, then git commit --fixup <hash> in the terminal, and push it (a normal push).
  2. Reply to the comment: “Done, in <hash>.”
  3. As the reviewer, look at your partner’s fixup commit in the Commits tab. It should be small and obvious. If it’s right, approve their pull request: Review changes, then Approve.

BASH

git log --oneline main..
git add -u                                  # or stage in the Source Control view
git commit --fixup <hash-of-the-first-commit>
git push

Then reply on GitHub, and your partner approves from the Review changes button.

Finishing: squash and merge


When your pull request is approved, say so in a comment and tidy the history before merging. Do this now if there’s time, or later.

BASH

git rebase -i --autosquash main

Your fixup folds into the commit it belongs to, and the commits get new hashes. Before you push, check that nothing but the history changed:

  • In VS Code: in the Source Control Graph, right-click your newest commit and choose Compare with Remote. It compares your tidied branch with the version on GitHub, the one your reviewer approved. It should list no changed files.
  • On the command line: git diff @{u} HEAD should print nothing. (@{u} means “the branch on GitHub that this one tracks”.)

Then push the tidy version, safely (episode 9), and merge:

BASH

git push --force-with-lease

On GitHub, merge with Rebase and merge. Then update your local main:

BASH

git switch main
git pull

(For a per-commit comparison of the old and new series there is also git range-diff @{u}...HEAD, but the check above is usually all you need.)

Challenge

Knowledge check

  1. After autosquashing, git diff @{u} HEAD prints nothing, yet every commit has a new hash. How can both be true?
  2. When are plain “address review” commits a perfectly good choice?
  1. A diff compares files, and the files are identical. The commits are different, because squashing the fixup rewrote them (episode 2: a changed commit, or a changed parent, means a new hash). Same code, tidier history.
  2. When your team squash-merges every pull request. The commits are flattened into one anyway, so how tidy they were makes no difference.
Key Points
  • A pull request is a story. Review your own first: it should read well, each commit should pass, it should be up to date and contain only your change
  • Write a description that says what, why, and how to check it
  • Review one commit at a time. Be specific, ask questions, mark small things with nit:, suggest changes, and say what’s good
  • Respond to feedback with --fixup commits that you push as they are, and autosquash when it’s approved (say so first). If your team squash-merges, plain “address review” commits are fine
  • git diff @{u} HEAD printing nothing (or Compare with Remote in VS Code showing no files) proves that tidying the history didn’t change the code
  • Use Rebase and merge to keep your curated commits and a straight history
  • A pull request from a fork defaults to the original repository, so check the base repository is your own fork

Content from Catching Problems Early: Shift Left and CI


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • How can I catch problems before a reviewer has to?
  • What does “shift left” mean, and which checks belong where?
  • What is continuous integration, and how do I set it up with GitHub Actions?

Objectives

  • Explain “shift left”, and say where different kinds of check belong
  • Describe pre-commit hooks and their trade-offs
  • Read a GitHub Actions workflow, add one that runs the tests on every pull request, and read a failing run

The bug nobody ran a test for


In episode 10 we found a bug in the colleague’s commit. There was already a test that caught it. It failed the moment the change was made. It just wasn’t run.

We can’t rely on everyone remembering to run every check, every time, and a reviewer shouldn’t have to find problems a machine could. So let’s think about where each kind of check belongs.

Shift left


Picture a change moving from left to right, from the moment you type it to the moment users have it. At each stage, a problem can be noticed, but the later it’s noticed, the longer you wait to find out and the more it costs to fix.

flowchart LR
    accTitle: {Six stages a change passes through, and how long it takes to find a problem at each}
    accDescr: {From left to right: 1, in your editor, you find out as you type, instantly. 2, in a pre-commit hook, when you commit, in seconds. 3, running the tests yourself before you push, in seconds or minutes. 4, continuous integration after you push, in a few minutes. 5, code review, in hours or days. 6, released to users, in weeks. Problems are cheap to fix on the left and expensive on the right.}
    A["<b>1. Editor</b><br/>as you type<br/>(instant)"] --> B["<b>2. Pre-commit</b><br/>when you commit<br/>(seconds)"] --> C["<b>3. Your tests</b><br/>before you push<br/>(seconds to minutes)"] --> D["<b>4. CI</b><br/>after you push<br/>(minutes)"] --> E["<b>5. Review</b><br/>(hours to days)"] --> F["<b>6. Users</b><br/>after release<br/>(weeks)"]
    classDef cheap fill:#dfd,stroke:#080,color:#000
    classDef mid fill:#ffd,stroke:#a80,color:#000
    classDef dear fill:#fdd,stroke:#c00,color:#000
    class A,B,C cheap
    class D,E mid
    class F dear

Green: cheap and fast to fix. Red: slow and expensive. Time runs left to right.

“Shift left” means moving each check as far left as it sensibly can go. The rule of thumb is to push a check left until it becomes too slow or too annoying to run there:

Stage What belongs there Why
1. Editor formatting, lint warnings, typos, type errors instant, and you never see them again
2. Pre-commit the same fast checks, enforced optional, and only if it stays fast
3. Before you push the tests too slow for every keystroke, but cheap to run now and then
4. CI the tests again, on a clean machine, plus slower checks (other Python versions, building the docs) nobody can skip it
5. Review design, naming, “is this the right change?” the things only a person can judge

So formatting goes as far left as it can: set up your editor so it’s fixed before you ever commit. The tests are slower and more costly, so you run them yourself before pushing, and CI runs them for everyone, regardless. The point of the earlier stages is that review, and the users, only get to see changes that have already passed everything a machine can check.

Stage 1: your editor


The earliest check is the one you don’t have to think about. A linter finds likely mistakes without running your program, such as unused imports, undefined names and unreachable code. A formatter fixes layout. ruff is a fast tool that does both for Python, and the Ruff extension for VS Code shows its findings as you type and can format when you save (turn on Format on Save in VS Code’s settings).

On the command line, you can ask it the same question. In the original peakfinder, it finds the unused import sys that the colleague later removed:

BASH

ruff check .

OUTPUT

F401 [*] `sys` imported but unused
 --> peakfinder/cli.py:2:8
  |
1 | import argparse
2 | import sys
  |        ^^^
  |
help: Remove unused import: `sys`

This is the cheapest feedback there is, and it needs no workshop to set up. (How you configure these tools varies between projects, so look at what yours uses.)

Stage 2: pre-commit hooks


Git can run a script just before each commit, called a hook. The pre-commit tool manages these for you. You list the checks in a .pre-commit-config.yaml file:

YAML

repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: <a version>        # `pre-commit autoupdate` fills in the latest
    hooks:
      - id: ruff

Each person runs pip install pre-commit and pre-commit install once. From then on, git commit runs the checks on the files you’re committing, and refuses to commit if one fails.

Pros Cons
Finds problems in seconds, before they’re committed Every contributor has to install it, and it is not on by default
Keeps everyone’s formatting the same Slow hooks interrupt every commit
Can fix things automatically (formatting) Gets in the way of messy work-in-progress commits, which we may want to make and tidy up later
Can be skipped: git commit --no-verify

Opinions differ, and several of us find hooks more annoying than helpful. If you like them, use them and keep the hooks fast (formatting and linting, not the whole test suite). Never rely on them alone, because they can be skipped.

Stage 3: run the tests before you push


Nothing clever here: run pytest before you push. For a quick check of every commit on your branch (not just the last), as we did in episode 7:

BASH

git rebase main --exec "pytest -q"

It stops at the first commit where the tests fail. That’s how you confirm each commit is atomic, with the tests passing at every step.

Stage 4: continuous integration


You can skip any of the stages above, and sometimes you will. Continuous integration (CI) is the one you can’t skip, so it’s the backstop for everything. Every time someone proposes a change, a computer automatically builds the project and runs the checks, on a clean machine, and reports back.

  • A reviewer sees a green tick or a red cross on the pull request, before they’ve read a line.
  • It runs in a fresh environment, so “it works on my machine” can’t hide a missing dependency.
  • It runs every time, whether or not anyone remembers.

GitHub Actions is GitHub’s built-in way to do this, and it’s free for public repositories. You describe what to run in a workflow file, a small YAML file in the .github/workflows/ folder of your repository:

YAML

name: Tests                          # what this workflow is called

on:                                  # WHEN to run it
  pull_request:                      #   on every pull request
  push:
    branches: [main]                 #   and on every push to main

jobs:
  test:                              # a job: a list of steps on one machine
    runs-on: ubuntu-latest           # GitHub gives us a fresh Linux machine
    steps:
      - uses: actions/checkout@v7    # use a ready-made action: get our code

      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
          cache: pip

      - name: Install the requirements
        run: pip install -r requirements.txt   # run a command

      - name: Run the tests
        run: pytest

Read it from the top: when it runs (on), where (runs-on), then the steps. A step either uses a ready-made action, or runs a command. The commands are the ones you’d type yourself: the same pip install and pytest as in our setup page.

Callout

YAML is fussy

YAML uses indentation to show structure. Use spaces, never tabs, and keep the indentation exactly as shown. A step that’s one space out will fail with a confusing error. VS Code shows the indentation guides, which helps.

Add CI, and watch it catch a mistake


We’ll do this in one pull request: add the workflow, see it go green, then make a plausible mistake and watch CI catch it. The mistake is renaming something in the code but forgetting to update its test, and pushing without running the tests. (We’re skipping stage 3 on purpose. In real life, it happens by accident.)

Challenge

Challenge: add CI, then break it and fix it

Your fork needs Actions switched on. Open the Actions tab of your fork. If it offers a button saying “I understand my workflows, go ahead and enable them”, click it. (You did this in the setup. This is where we find out if it worked.)

Callout

If Actions won’t run for you

GitHub Actions is the one part of today that depends on GitHub doing something at the right moment, and sometimes it’s slow, or switched off. If your checks don’t appear or you’re stuck waiting, don’t wait. Watch the instructor’s prepared run on screen, and carry on with the git steps, which are the same either way: the commits, the fixup and the autosquash all work without Actions. You’ll still see the point of CI.

Part 1: add the workflow.

  1. Update main and make a branch:

    BASH

    git switch main
    git pull
    git switch -c add-ci
  2. Create the file .github/workflows/tests.yml (in VS Code: create a folder .github, with a folder workflows inside it, and a file tests.yml) containing the workflow above.

  3. Commit it with a clear message, and push:

    BASH

    git add .github/workflows/tests.yml
    git commit -m "Run the tests on every pull request"
    git push
  4. Open a pull request in your own fork (check the base repository!) from add-ci into main.

  5. Scroll to the bottom of the pull request. In the checks section, you’ll see your Tests job running (a yellow dot), then a green tick. Click Details to read the log, which shows each step.

Part 2: break it, on the same pull request.

  1. In peakfinder/normalise.py, rename the mode "max" to "maximum" (the line if mode == "max":). Only the code. Commit and push, without running pytest:

    BASH

    git commit -am "Rename the normalise mode 'max' to 'maximum'"
    git push
  2. Go back to the pull request. The checks run again, and this time they fail: a red cross. Click Details, open the Run the tests step, and find the error. Is it the same as you would see locally?

Part 3: fix it where it belongs, and merge.

  1. The test should have been part of the same commit. In tests/test_normalise.py, change mode="max" to mode="maximum", then make it a fixup of the rename commit, and tidy up:

    BASH

    git log --oneline -3
    git add -u
    git commit --fixup <hash of the rename commit>
    git rebase -i --autosquash main
    git push --force-with-lease
  2. Watch the pull request: the checks run again, and go green.

  3. Merge it with Rebase and merge (the rename is harmless, so we’ll keep it), then update your local main: git switch main, then git pull.

If the job doesn’t start at all, check the Actions tab is enabled, and that the file is in exactly .github/workflows/.

The workflow file is the one on this page. The finished steps:

BASH

git switch main
git pull
git switch -c add-ci
# create .github/workflows/tests.yml
git add .github/workflows/tests.yml
git commit -m "Run the tests on every pull request"
git push
# open the pull request on GitHub (base: your fork's main). Wait for the tick

# edit normalise.py: if mode == "max" -> "maximum"
git commit -am "Rename the normalise mode 'max' to 'maximum'"
git push                                  # CI runs, and fails

# edit tests/test_normalise.py: mode="max" -> mode="maximum"
git log --oneline -3
git add -u
git commit --fixup <hash of the rename commit>
git rebase -i --autosquash main
git push --force-with-lease               # CI runs again, and passes

# Rebase and merge on GitHub, then
git switch main
git pull

In step 7 the log shows:

OUTPUT

FAILED tests/test_normalise.py::test_normalise_max_mode - ValueError: unknown mode: max
1 failed, 7 passed

which is exactly what pytest would print on your own computer. After the autosquash, the pull request has two commits, each one passing: the workflow, and the rename with its test. The fixup workflow kept the mistake out of the history.

OUTPUT

28171b1 Rename the normalise mode 'max' to 'maximum'
7ba3c1f Run the tests on every pull request

(Your hashes will be different.)

Going further: more checks in CI

A good CI job is the list of things you’d want a careful reviewer to check by hand. The linter from stage 1 is easy to add. Append one more step (indented to match the others):

YAML

      - name: Check the code for common mistakes
        run: |
          pip install ruff
          ruff check .

The same idea works for formatting (ruff format --check .), type checks, and building the documentation. Anything that’s too slow to run in your editor, but worth running on every change, belongs here.

How this connects to history


CI and everything else we have learned reinforce each other:

  • Each commit should pass, but CI usually only checks the tip. The rename commit failed CI because its test was missing, and we fixed it in the commit, so every commit passes. git rebase main --exec "pytest -q" checks all of them.
  • Bisect uses the same test command. CI keeps the commands you’d bisect with working.
  • Merging can be made conditional. Repositories can require the checks to pass before the merge button works (Settings, then Rules or Branches). Then a failing change can’t reach main, even by accident.
  • The reviewer sees the result. A green tick means they can spend their time on the design, which is the one thing only they can do.
Challenge

Knowledge check

Where would you put each of these checks, and why?

  1. Fixing the formatting of your code
  2. A test suite that takes ten minutes
  3. Running the tests on three different versions of Python
  4. Deciding whether a function has a good name
  1. Your editor (format on save): it’s instant, and you never see the problem again.
  2. CI, and run a quick subset yourself before you push. A ten-minute check on every commit would be painful, but CI can run it in the background while you carry on.
  3. CI. You’d rarely have three versions of Python to hand locally, and CI can run them in parallel on clean machines.
  4. Code review. Only a person can judge it, and it’s what review is for.
Key Points
  • “Shift left”: find problems as early, cheaply and quickly as you can. Push each check left until it becomes too slow or annoying to run there
  • Formatting and linting belong in your editor. Tests you run yourself before pushing, and CI runs them again for everyone, plus anything slower
  • Pre-commit hooks are an optional personal convenience, and can be skipped. CI is the shared gate that can’t
  • A GitHub Actions workflow is a YAML file in .github/workflows/: when to run, where, and a list of steps
  • Fix a failing check in the commit it belongs to (--fixup, then autosquash), so that every commit passes

Content from Releases: Versions, Tags and Cherry-pick


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • What does the life of a released project look like?
  • How do I mark a release, and fix a bug in a version that’s already out?
  • How do I copy a single commit onto another branch?

Objectives

  • Describe a simple lifecycle for a released project, and what a version number tells you
  • Explain how a tag differs from HEAD and from a branch
  • Choose between “fix on main and release again” and “patch an old release”
  • Cherry-pick a commit onto a release branch, and tag and push a release

The life of a released project


So far we’ve worked towards getting changes into main. But a project doesn’t end there. Here is the simplified life of most software:

  1. You develop on main, through small branches and pull requests.
  2. At some point you release: you pick a version number and mark that commit.
  3. Users run that version, and find bugs.
  4. You fix them on main, and release again.

In git, that looks like a line of commits with a tag at each release:

gitGraph
    accTitle: {A project's history with a tag at each release}
    accDescr: {A single line of commits on the main branch, from oldest on the left to newest on the right. Three of the commits carry release tags: v0.1.0, v0.2.0 and v0.3.0. Between the tags are the ordinary commits made while developing.}
    commit id: "First commit"
    commit id: "Add normalise"
    commit id: "Add plotting" tag: "v0.1.0"
    commit id: "Add modes"
    commit id: "Return Peak" tag: "v0.2.0"
    commit id: "Add prominence"
    commit id: "Add widths" tag: "v0.3.0"

That is the whole model. Bigger projects add more branches and ceremony (you may hear the name git flow), but most research software gets by with this. The one extra wrinkle is what to do when a bug is found in a version that’s already out, which we’ll come to.

Version numbers


A release needs a name, and a version number is how people refer to it. Most projects use semantic versioning, three numbers, MAJOR.MINOR.PATCH:

Change Which number goes up Example
Bug fixes only PATCH 0.2.0 to 0.2.1
New features that don’t break existing use MINOR 0.2.1 to 0.3.0
Changes that may break existing use MAJOR 0.3.0 to 1.0.0

So the version tells a user what to expect before they upgrade: a patch should be safe to take, and a major release may need them to change something.

Tags: names for releases


Git needs a way to say “this exact commit is version 0.2.1”, and a tag is that. It helps to compare the three kinds of label git has:

Label Points at Does it move?
HEAD where you are right now Yes: every time you switch or commit
A branch (main, release/0.2) the latest commit of a line of work Yes: every time you commit on it
A tag (v0.2.1) one specific commit Never: that’s the point

Because a tag never moves, “version 0.2.1” always means exactly the same code.

There are two kinds of tag:

Created with What it is
Lightweight git tag v0.2.1 just a label on a commit
Annotated git tag -a v0.2.1 -m "message" a label plus a small object that records who tagged it, when, and a message

Use annotated tags for releases. git show v0.2.1 shows the message. Two more things to know:

  • Tags aren’t pushed by default. You send one explicitly: git push origin v0.2.1.
  • A tag is on a commit, not a branch. git switch -c release/0.2 v0.2.0 makes a branch that starts at the tagged commit.

A bug in a released version


Our version 0.2.0 was released with the normalise bug in it, and people are using it. We’ve fixed the bug on main, but main has moved on since then, and also contains new, unreleased features.

You have two options, from the lifecycle:

  • Fix on main and release a new version (0.3.0). This is the simplest, and the right answer when users can upgrade. Do this if you can.
  • Make a patch release (0.2.1) of the old version. This is for when users can’t just upgrade: perhaps 0.3.0 changes something they depend on, or it isn’t ready. We want to give them just the fix.

For the second option, we make a release branch that starts from the old version’s tag, and bring the fix across. We don’t want the whole of main, only that one commit. How do we copy a single commit?

Cherry-pick


git cherry-pick <commit> takes one commit from anywhere in the repository and replays its change on top of your current branch, as a new commit. This is the “commit as a change” way of thinking from episode 2: git works out what that commit changed, and applies the same change here.

BASH

git switch <the branch you want to put it on>
git cherry-pick <hash of the commit to copy>
gitGraph
    accTitle: {A bug fix copied onto a release branch}
    accDescr: {The main branch has the version 0.2.0 release. A release branch for 0.2 is created from that point. Meanwhile main gains new commits, including the fix for the normalise bug, a new feature and more work. The fix is cherry-picked onto the release branch, which is then given a version bump and the tag v0.2.1. The feature and later work stay on main only.}
    commit id: "Release 0.2.0" tag: "v0.2.0"
    branch release/0.2
    checkout main
    commit id: "Fix"
    commit id: "Feature"
    checkout release/0.2
    cherry-pick id: "Fix"
    checkout main
    commit id: "More work"
    checkout release/0.2
    commit id: "Bump version" tag: "v0.2.1"

It makes a new commit with a new hash, as the parent is different. So the original and the copy are two separate commits with the same change. The option -x records where it came from, in the message:

(cherry picked from commit 05c314d857072a26b300c8be5ce6a350126c3000)

That makes it easy to see later that two commits are the same fix. Use -x whenever you cherry-pick onto a shared branch, such as a release.

Callout

This only works because of atomic commits

Our fix is one small commit that does one thing. It can be copied cleanly, and the result is a sensible release.

If the fix had been bundled into a larger commit along with a new feature, cherry-picking it would drag half the feature along, or fail with conflicts because the feature depends on code the release branch doesn’t have. That’s the episode 3 payoff again: atomic commits are what make cherry-pick safe.

Callout

In VS Code

In the Source Control Graph, right-click a commit and choose Cherry Pick to apply it to the branch you have checked out. (If you can’t see the commit, change which branches the graph is showing.) If there’s a conflict, resolve it in the merge editor as before, then finish with git cherry-pick --continue in the terminal. To give up, run Git: Abort Cherry Pick from the Command Palette, or git cherry-pick --abort.

Challenge

Challenge: release the fix as version 0.2.1

Work in your clone, with your virtual environment active.

1. Make a release branch and bring the fix across. First find the fix on main: it has the message Fix ‘range’ mode of normalise…. (You deleted your fix/normalise branch, so look it up by its message.) Then branch from the old tag, check the bug is there, and cherry-pick:

BASH

git switch main
git pull
git log --oneline --grep="Fix 'range' mode"

git switch -c release/0.2 v0.2.0
pytest tests/test_normalise.py           # fails: the bug is in 0.2.0
git cherry-pick -x <hash of the fix>
pytest                                   # passes

2. Bump the version, tag it, and push. Change the version to 0.2.1 in two places, __version__ in peakfinder/__init__.py and version in pyproject.toml (edit them in VS Code). Then:

BASH

git commit -am "Bump version to 0.2.1"
git tag -a v0.2.1 -m "Version 0.2.1: fix the 'range' mode of normalise"
git push -u origin release/0.2 v0.2.1

3. Check it:

BASH

git log --oneline --graph --all --decorate -8

You should see v0.2.1 on release/0.2, with the cherry-picked fix just below it, and the new features only on main.

Optional: publish a GitHub release. On your fork’s page, click Releases, then Create a new release. Choose the tag v0.2.1, click Generate release notes, and then Publish release.

BASH

git switch main
git pull
git log --oneline --grep="Fix 'range' mode"      # note the hash

git switch -c release/0.2 v0.2.0
pytest tests/test_normalise.py                  # fails
git cherry-pick -x <hash>
pytest                                          # passes

# edit __version__ in peakfinder/__init__.py and version in pyproject.toml to 0.2.1
git commit -am "Bump version to 0.2.1"
git tag -a v0.2.1 -m "Version 0.2.1: fix the 'range' mode of normalise"
git push -u origin release/0.2 v0.2.1

The cherry-pick:

OUTPUT

[release/0.2 9bbd943] Fix 'range' mode of normalise for spectra that don't start at zero
 Author: Sam Scientist <sam.scientist@example.org>
 1 file changed, 1 insertion(+), 1 deletion(-)

and the picture afterwards (hashes will differ):

OUTPUT

* fe33fcc (HEAD -> release/0.2, tag: v0.2.1, origin/release/0.2) Bump version to 0.2.1
* 9bbd943 Fix 'range' mode of normalise for spectra that don't start at zero
| * 05c314d (origin/main, main) Fix 'range' mode of normalise for spectra that don't start at zero
...
* df97539 (tag: v0.2.0) Bump version to 0.2.0

The same fix is on both branches, as two different commits. release/0.2 has the fix and none of the new features.

Callout

Releases and research software

A tagged release is what people cite and reproduce. If you link your GitHub repository to Zenodo, every GitHub release gets its own DOI, a permanent citable identifier for exactly that version. A CITATION.cff file in the repository tells people how to cite you. Tags and releases turn “the code I used in the paper” into something others can find.

Challenge

Knowledge check

  1. A bug is found in 0.2.0, and 0.3.0 has just been released. Users can upgrade without trouble. Do you need a release branch?
  2. Which of HEAD, a branch and a tag will still point at the same commit tomorrow, whatever you do?
  3. Why does the cherry-picked fix have a different hash from the original?
  4. A teammate cherry-picks a commit that adds a feature, and it fails with a conflict. What is the likely reason?
  1. No. Fix it on main, and release 0.3.1 (or whatever comes next). A release branch is only needed when users can’t move to the new version.
  2. The tag. HEAD and branches move when you switch or commit.
  3. A commit’s hash depends on its parent (and the other contents). The copy sits on a different parent, so it’s a new commit, even though its change is the same. -x records where it came from.
  4. The commit depends on earlier commits that the target branch doesn’t have, such as a helper function the feature uses. A commit that is a self-contained change copies cleanly. That’s why atomic commits matter.
Key Points
  • Most projects follow a loop: develop on main, release with a version number and a tag, fix bugs on main, and release again
  • Semantic versioning (MAJOR.MINOR.PATCH) tells users what to expect from an upgrade
  • A tag is a label that never moves, unlike HEAD and branches. Use annotated tags (git tag -a) for releases, and push them explicitly
  • If users can upgrade, fix on main and release again. If they can’t, patch the old release on a release branch
  • git cherry-pick -x <commit> replays one commit’s change as a new commit, and atomic commits are what make it safe

Content from Tooling and Wrap-up


Last updated on 2026-11-02 | Edit this page

Overview

Questions

  • What small things make these habits quicker?
  • Which VS Code features match what we did in the terminal?
  • What should I take away and try on Monday?

Objectives

  • Create useful git aliases, and know a few settings worth turning on
  • Match the commands from the workshop to VS Code’s source control features
  • Pick one habit to adopt first

Make the good habits quicker


This episode is a menu, not a to-do list. Skim it, or read it after the workshop. Everything here is a personal choice.

An alias is a nickname for a git command. Plenty of people use none at all, and typing the full command is perfectly fine. These are some of the ones that are commonly shared, if you’d like a few:

BASH

git config --global alias.st "status -sb"
git config --global alias.lg "log --oneline --graph --decorate"
git config --global alias.unstage "restore --staged"
git config --global alias.last "log -1 --stat"
Type It runs You’d use it to
git st git status -sb a short status, with the branch
git lg git log --oneline --graph --decorate see the history as a picture
git unstage <file> git restore --staged <file> take a file out of the next commit
git last git log -1 --stat see what the last commit changed

They’re stored in your ~/.gitconfig file. Change them, add your own, and delete the ones you don’t use. (VS Code covers a lot of this already, so you may not need any.)

A word on settings

Git’s defaults are the defaults for good reasons, and a lot of the advice about settings online is one person’s preference. Change a setting when you’ve hit the problem it solves, not before. The three we asked you to set in the setup (pull.rebase, rebase.autoSquash and push.autoSetupRemote) suit the workflow in this workshop, but they are preferences too, and many people never change them.

If you want to try something, these three are widely recommended and low-risk:

Setting What it does
fetch.prune true removes your copies of branches that were deleted on GitHub, so your branch list stays tidy
rebase.autoStash true stashes uncommitted changes before a rebase, and puts them back afterwards
merge.conflictStyle zdiff3 conflict markers also show the original version, which makes conflicts easier to understand (needs Git 2.35 or newer)

Set one with git config --global <setting> <value>, and undo it with git config --global --unset <setting>.

VS Code and the terminal


We used both. This table matches what we did to what VS Code offers, so you can use whichever you prefer.

What we did In VS Code
Stage part of a file (ep 5) In the diff editor, select lines and use the gutter Stage button, or right-click Stage Selected Ranges
Unstage, or discard changes the - icon, or right-click Discard Changes
Amend the last commit (ep 5) the dropdown on the Commit button, then Commit (Amend)
Undo the last commit (ep 5) ..., then Commit, then Undo Last Commit
Read your branch like a reviewer (ep 7) the Source Control Graph: select a commit, then a file
History of one file (ep 10) the Timeline view in the Explorer
Blame (ep 10) Git: Toggle Git Blame Editor Decoration in the Command Palette
Compare with a branch or tag right-click a commit in the graph, then Compare with… (or Compare with Merge Base)
Resolve a conflict (ep 9) Resolve in Merge Editor, then Complete Merge
Stash and restore Git: Stash, Git: Pop Latest Stash in the Command Palette
Cherry-pick (ep 13) right-click a commit in the graph, then Cherry Pick
Give up on a merge, rebase or cherry-pick Git: Abort Merge / Abort Rebase / Abort Cherry Pick

And the things that have no button, so you use the terminal: --fixup commits, interactive rebase and --autosquash, the reflog, bisect, range-diff, and --force-with-lease. (The GitLens extension adds an editor for interactive rebase and more, if you want a graphical version of those.)

Things we only mentioned


Stash. Real work gets interrupted. You’re halfway through an edit, and a colleague asks you to look at something on another branch. You can’t switch branches with half-finished changes in the way, and you don’t want to make a messy commit. Stash puts your uncommitted changes in a drawer and gives you a clean working directory:

BASH

git stash push -m "README scratch note"     # put them away, with a label
git stash list                              # what's in the drawer?
git switch main                             # do the other thing...
git switch my-feature                       # ...and come back
git stash pop                               # take the changes out again

OUTPUT

Saved working directory and index state On my-feature: README scratch note
stash@{0}: On my-feature: README scratch note

Some variations: git stash push -u also stashes new, untracked files, git stash apply is like pop but keeps the stash in the drawer, and git stash drop throws one away. In VS Code, run Git: Stash (it asks for an optional message) and Git: Pop Latest Stash from the Command Palette. Git: Stash Staged stashes only what’s staged, which is git stash push --staged and needs Git 2.35 or newer.

Worktrees. Sometimes you want two branches checked out at once, such as a release branch for a quick fix while your feature is in the middle of a change. Instead of stashing and switching, make a second folder for the same repository:

BASH

git worktree add ../peakfinder-hotfix release/0.2

You get a new folder with release/0.2 checked out. Work there, commit, and delete it when you’re finished (git worktree remove ../peakfinder-hotfix). VS Code can manage worktrees too.

The merge base. The merge base of two branches is the commit where they diverged: git merge-base main my-feature. It’s what git range-diff and VS Code’s Compare with Merge Base compare against.

Take-aways


Nobody does all of this at once. Here are the habits we’ve covered, roughly in order of how much they give back:

  1. Plan the change, then the commits.
  2. Make commits atomic, with messages that say why.
  3. Use fixup for mistakes in earlier commits, and autosquash before you share.
  4. Rebase onto main rather than merging main into your branch. Push with --force-with-lease.
  5. Review your own branch first, then ask for review.
  6. Let CI check what a person shouldn’t have to.
Challenge

Challenge: your first step

  1. If you like, add an alias or two from the list above, and try them in your peakfinder clone. (Or skip this: it’s optional.)
  2. Decide one habit from the take-aways that you’ll try on your own work next week. Tell your partner, and say what might get in the way.

Keep it small. One habit that you actually use is worth more than six that you don’t.

There’s no single answer. A popular first choice is fixup and autosquash, because you can start with it today, on any branch, without anyone else changing what they do.

If you’re not sure, try this on your next piece of work: write the commit plan first, make each commit one idea, and run git lg before you ask for review to check that it reads like a story.

Where next


  • Pro Git, the free book, at git-scm.com/book. Chapters 3 (branching), 7 (tools) and 10 (internals) go deeper on everything here.
  • Learn Git Branching, an interactive game that draws the graphs as you type: learngitbranching.js.org.
  • Conventional Commits, if you want a commit message convention: conventionalcommits.org.
  • The reference page in this lesson has a cheat sheet of the commands and a glossary.
  • The extras page has a short guided peek inside .git (blobs, trees and packfiles), and reading on how git works, on branching models such as git flow, and on the topics in this workshop.

Thank you


We’d love to hear what worked and what didn’t.

Key Points
  • Aliases and settings are personal choices: git’s defaults are fine, and you only need to change what’s bothering you
  • VS Code covers staging, amending, history, blame, conflicts, stash and cherry-pick. Fixup, interactive rebase, the reflog, bisect and range-diff need the terminal
  • Pick one habit to adopt first. Atomic commits and fixup with autosquash give the most for the least effort