---
title: "Version Control with Git"
book: "University Computer Science — Year 1"
subject: computer-science
language: en
chapter: 9
exercises: 12
source: https://one-course.com/books/computer-science/3/en/chapter/9-version-control-with-git
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 9 — Version Control with Git

Yesterday the library’s catalogue program worked; today its test fails, and forty edits were made in between, some by you, some by a colleague. Which one broke it? Copies named `catalogue_old.py` and `catalogue_final2.py` do not answer. A [version control system](#def-b1-version-control-repository) does: it keeps every recorded state of the project, says who changed what and why, [merges](#def-b1-version-control-merge) the work of several people, and can search its own history for the change that broke a test, in six runs of that test where forty would seem needed. This chapter teaches the one used almost everywhere, Git, through sessions run on a small catalogue.

**You already know.**

A file holds bytes and is named by a path in a tree of folders. A test runs a piece of a program on chosen inputs and compares the result with the expected one; its [exit status](https://one-course.com/books/computer-science/3/en/chapter/8-the-shell#def-b1-the-shell-exit-status) says whether it passed ([Chapter 8](https://one-course.com/books/computer-science/3/en/chapter/8-the-shell#ch-b1-the-shell)).

## 9.1 Snapshots and commits

**Definition 9.1 (Version control system, repository).**

A *version control system* records the successive states of the files of a project, with their authors, dates and reasons, and can restore or compare any of them. The recorded history of a project is its *repository*; with Git it is kept in a hidden folder `.git` at the top of the project.

**Definition 9.2 (Commit, snapshot).**

A *commit* is one recorded state of the project: a *snapshot* of every tracked file as it was when the commit was made, together with an author, a date, a message, and the identifiers of its *parent* commits, the commits it was made from: none for the first commit, one usually, two for a [merge](#def-b1-version-control-merge).

**History — Git.**

Git was born in 2005 in the community that develops the Linux kernel. The kernel had used a proprietary system for three years, whose free licence was then withdrawn; its developers, Linus Torvalds in particular, wrote their own. Its aims were speed, a simple design, thousands of parallel [branches](#def-b1-version-control-branch), and full distribution: every copy holds the whole history.

```
$ git init -q -b main catalogue
$ cd catalogue
$ printf 'The Silent Code,2002\nThe Paper Forest,1996\n' > books.csv
$ git add books.csv
$ git commit -q -m "Start the catalogue with two books"
$ printf 'Harbour Lights,2011\n' >> books.csv
$ git commit -q -am "Add Harbour Lights"
$ git log
commit 8da0a4433b74113ff0e129e56581f29ef6afdd75
Author: Ada Lovelace <ada@example.org>
Date:   Mon Jan 5 09:00:00 2026 +0000

    Add Harbour Lights

commit 3e494d142e1c6bfdab3f2c6a39315040b0336200
Author: Ada Lovelace <ada@example.org>
Date:   Mon Jan 5 09:00:00 2026 +0000

    Start the catalogue with two books
$ git log --oneline
8da0a44 Add Harbour Lights
3e494d1 Start the catalogue with two books
$ git show --stat HEAD
commit 8da0a4433b74113ff0e129e56581f29ef6afdd75
Author: Ada Lovelace <ada@example.org>
Date:   Mon Jan 5 09:00:00 2026 +0000

    Add Harbour Lights

 books.csv | 1 +
 1 file changed, 1 insertion(+)
```

***Output 9.1.** A [repository](#def-b1-version-control-repository), two [commits](#def-b1-version-control-commit), and its history.*

The session pins the author, `Ada Lovelace`, and the date, so that it reruns identically; in daily use Git takes both from the configuration and the clock. `git add` chooses what goes into the next [commit](#def-b1-version-control-commit), `git commit` records it, `-a` adding every tracked file that changed. The long hexadecimal number after `commit` is the [commit](#def-b1-version-control-commit)’s identifier, which `--oneline` abbreviates to its first seven digits.

Git stores the project as objects of three kinds: a *blob* holds the content of a file, a *tree* lists the names of a folder with the objects they stand for, and a [commit](#def-b1-version-control-commit) points to the tree of the top folder. Each object is named by a hash of its content: a 40-digit hexadecimal number computed from the type, the length and the bytes of the object, by the function SHA-1 (a newer format uses SHA-256 and 64 digits; hash functions are studied in the Year 3 volume).

```
$ git cat-file -p HEAD
tree 525ef202ac0c29c3522cd0e13a613e90d1a9dd9b
parent 3e494d142e1c6bfdab3f2c6a39315040b0336200
author Ada Lovelace <ada@example.org> 1767603600 +0000
committer Ada Lovelace <ada@example.org> 1767603600 +0000

Add Harbour Lights
$ git cat-file -p HEAD^{tree}
100644 blob d343e221360398b3292388f1abfb19f0b775809d	books.csv
$ git cat-file -p HEAD:books.csv
The Silent Code,2002
The Paper Forest,1996
Harbour Lights,2011
$ git hash-object books.csv
d343e221360398b3292388f1abfb19f0b775809d
$ { printf 'blob %d\0' "$(wc -c < books.csv)"; cat books.csv; } | sha1sum
d343e221360398b3292388f1abfb19f0b775809d  -
$ git cat-file -t 3e494d1
commit
```

***Output 9.2.** Inside the last [commit](#def-b1-version-control-commit): its tree, the blob of `books.csv`, and the blob’s name computed by hand.*

Two consequences follow from naming by content. Identical files are stored once, under one name. And a [commit](#def-b1-version-control-commit) names its parent by the parent’s hash, so changing anything in an old [commit](#def-b1-version-control-commit), a single byte of a file or of a message, changes its name, then the name of every [commit](#def-b1-version-control-commit) after it: a history cannot be altered without the change showing.

## 9.2 The staging area

**Definition 9.3 (Working tree, staging area).**

The *working tree* is the folder of the project, the files as you edit them. The *staging area* (also called the *index*) holds the [snapshot](#def-b1-version-control-commit) that the next [commit](#def-b1-version-control-commit) will record; `git add` copies a file of the working tree into it, and `git commit` records it in the [repository](#def-b1-version-control-repository).

![The three places a file lives in. git add and git commit move changes to the right; git restore brings a file back from the staging area, and git restore --staged unstages it. Each diff compares two neighbouring places.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-version-control/fig-af163faf4de0.svg)

*The three places a file lives in. `git add` and `git commit` move changes to the right; `git restore` brings a file back from the [staging area](#def-b1-version-control-staging), and `git restore --staged` unstages it. Each `diff` compares two neighbouring places.*

```
$ printf 'Stone Bridge,1987\n' >> books.csv
$ printf '# Catalogue\nOne line per book: title,year.\n' > README.md
$ git status --short
 M books.csv
?? README.md
$ git add README.md
$ git status --short
A  README.md
 M books.csv
$ git diff
diff --git a/books.csv b/books.csv
index d343e22..248ecd5 100644
--- a/books.csv
+++ b/books.csv
@@ -1,3 +1,4 @@
 The Silent Code,2002
 The Paper Forest,1996
 Harbour Lights,2011
+Stone Bridge,1987
$ git diff --staged
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..08a2228
--- /dev/null
+++ b/README.md
@@ -0,0 +1,2 @@
+# Catalogue
+One line per book: title,year.
$ git commit -q -m "Explain the file format"
$ git status --short
 M books.csv
$ git restore books.csv
$ git status --short
```

***Output 9.3.** Two changes, one staged: `status`, `diff` and `diff --staged` each see a different part.*

In `git status --short`, the first column describes the [staging area](#def-b1-version-control-staging) against the last [commit](#def-b1-version-control-commit) and the second the [working tree](#def-b1-version-control-staging) against the [staging area](#def-b1-version-control-staging): `A` added, `M` modified, `??` untracked. A *diff* shows changed lines with `-` and `+` and a few lines of context around them; the header `@@ -1,3 +1,4 @@` says that lines 1 to 3 of the old version became lines 1 to 4 of the new. The last `git restore` threw the unstaged line away: Git never saw it, so nothing can bring it back. Stage or [commit](#def-b1-version-control-commit) what you want to keep.

**Method 9.4 (A good commit).**

1. One change per [commit](#def-b1-version-control-commit) : a fix, a feature, a rename, not three of them mixed. Stage the files, or the parts of files, that belong to it, and leave the rest for the next [commit](#def-b1-version-control-commit) .
2. The tests pass at every [commit](#def-b1-version-control-commit) , so that any [commit](#def-b1-version-control-commit) can be checked out and used.
3. A message whose first line says what the [commit](#def-b1-version-control-commit) does, in fewer than 60 characters, and whose body says why.
4. Nothing generated: compiled files, outputs and temporary files are listed in a file `.gitignore` and never committed.

## 9.3 Branches and merges

**Definition 9.5 (Commit graph, ancestor).**

The [commits](#def-b1-version-control-commit) of a [repository](#def-b1-version-control-repository) and the links from each [commit](#def-b1-version-control-commit) to its parents form the *commit graph*. A [commit](#def-b1-version-control-commit) $a$ is an *ancestor* of a [commit](#def-b1-version-control-commit) $c$ if $a$ can be reached from $c$ by following parent links, $c$ itself included. No [commit](#def-b1-version-control-commit) is its own ancestor through one link or more, since a [commit](#def-b1-version-control-commit)’s name depends on its parents’ names, which must exist before it: the graph has no cycle (graphs are studied in [Chapter 24](https://one-course.com/books/computer-science/3/en/chapter/24-graphs-and-traversals#ch-b1-graph-traversals)).

**Definition 9.6 (Branch).**

A *branch* is a name that points to a [commit](#def-b1-version-control-commit), its *tip*. Committing on a branch makes a new [commit](#def-b1-version-control-commit) whose parent is the tip and moves the name to it. `HEAD` names the current branch. A branch contains the [commits](#def-b1-version-control-commit) that are [ancestors](#def-b1-version-control-commit-graph) of its tip.

**Definition 9.7 (Merge, merge base).**

To *merge* a [branch](#def-b1-version-control-branch) $b$ into the current [branch](#def-b1-version-control-branch) $a$ is to make $a$ contain the [commits](#def-b1-version-control-commit) of $b$. The *merge base* of two [commits](#def-b1-version-control-commit) is their best common [ancestor](#def-b1-version-control-commit-graph): a common [ancestor](#def-b1-version-control-commit-graph) of which no other common [ancestor](#def-b1-version-control-commit-graph) is a descendant. If the tip of $a$ is itself the merge base, $a$ is simply moved to the tip of $b$: a *fast-forward merge*. Otherwise Git makes a *three-way merge*: it compares each file in the merge base, in $a$ and in $b$, keeps every change made on either side, and records the result in a merge [commit](#def-b1-version-control-commit) with two parents.

```
$ git switch -q -c genres
$ sed -i 's/$/,mystery/' books.csv
$ git commit -q -am "Add a genre column"
$ git switch -q main
$ git merge genres
Updating 8da0a44..9fdd4a5
Fast-forward
 books.csv | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
$ git switch -q -c sort-by-year
$ sort -t, -k2,2n books.csv > sorted.csv && mv sorted.csv books.csv
$ git commit -q -am "Sort the books by year"
$ git switch -q main
$ printf 'Stone Bridge,1987,history\n' >> books.csv
$ git commit -q -am "Add Stone Bridge"
$ git merge-base main sort-by-year
9fdd4a5e8613c2ab66981f2fe27010d3f2bb6bef
$ git merge --no-edit sort-by-year
Auto-merging books.csv
Merge made by the 'ort' strategy.
 books.csv | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
$ git log --graph --oneline --all
*   58e34f4 Merge branch 'sort-by-year'
|\  
| * 346e84d Sort the books by year
* | 88f4716 Add Stone Bridge
|/  
* 9fdd4a5 Add a genre column
* 8da0a44 Add Harbour Lights
* 3e494d1 Start the catalogue with two books
$ cat books.csv
The Paper Forest,1996,mystery
The Silent Code,2002,mystery
Harbour Lights,2011,mystery
Stone Bridge,1987,history
```

***Output 9.4.** A fast-forward, then a [three-way merge](#def-b1-version-control-merge), and the graph drawn by `log --graph`.*

![The commit graph of , each arrow going from a commit to its parent. The fast-forward only moved the name main; the three-way merge made commit 58e3, whose two parents are the tips of the two branches, and whose content combines both changes made since the merge base 9fdd.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-version-control/fig-f04363cb352a.svg)

*The [commit graph](#def-b1-version-control-commit-graph) of [Output 9.4](#out-b1-version-control-branches), each arrow going from a [commit](#def-b1-version-control-commit) to its parent. The fast-forward only moved the name `main`; the [three-way merge](#def-b1-version-control-merge) made [commit](#def-b1-version-control-commit) 58e3, whose two parents are the tips of the two [branches](#def-b1-version-control-branch), and whose content combines both changes made since the [merge base](#def-b1-version-control-merge) 9fdd.*

The [three-way merge](#def-b1-version-control-merge) kept the order of `sort-by-year` and the line added on `main`: each side changed a different part of the file. Comparing with the [merge base](#def-b1-version-control-merge) is what makes this possible: a line that differs between the two tips is taken from the side that changed it since the base. Another way to combine [branches](#def-b1-version-control-branch), *rebasing*, replays the [commits](#def-b1-version-control-commit) of one [branch](#def-b1-version-control-branch) on top of the other, producing new [commits](#def-b1-version-control-commit) with new names and a straight history; it should not be used on [commits](#def-b1-version-control-commit) that others already have.

## 9.4 Conflicts and remotes

**Definition 9.8 (Merge conflict).**

A *merge conflict* arises when both sides of a [three-way merge](#def-b1-version-control-merge) changed the same lines of a file differently since the [merge base](#def-b1-version-control-merge). Git then stops before committing, writes both versions into the file between the markers `<<<<<<<`, `=======` and `>>>>>>>`, and waits for a person to write the right result, stage it with `git add` and [commit](#def-b1-version-control-commit).

```
$ git switch -q -c rename
$ sed -i 's/The Paper Forest/The Paper Forest (2nd ed.)/' books.csv
$ git commit -q -am "Name the second edition"
$ git switch -q main
$ sed -i 's/The Paper Forest,1996/The Paper Forest,1997/' books.csv
$ git commit -q -am "Fix the year of The Paper Forest"
$ git merge rename
Auto-merging books.csv
CONFLICT (content): Merge conflict in books.csv
Automatic merge failed; fix conflicts and then commit the result.
$ git status --short
UU books.csv
$ cat books.csv
The Silent Code,2002
<<<<<<< HEAD
The Paper Forest,1997
=======
The Paper Forest (2nd ed.),1996
>>>>>>> rename
Harbour Lights,2011
$ printf 'The Silent Code,2002\nThe Paper Forest (2nd ed.),1997\nHarbour Lights,2011\n' > books.csv
$ git add books.csv
$ git commit -q --no-edit
$ git log --oneline --graph
*   4cac20f Merge branch 'rename'
|\  
| * a9d83f7 Name the second edition
* | 17dfc05 Fix the year of The Paper Forest
|/  
* 8da0a44 Add Harbour Lights
* 3e494d1 Start the catalogue with two books
```

***Output 9.5.** Two changes to the same line: the conflict, its markers, and a resolution that keeps both changes.*

![A conflict. Each side changed line 2 of the merge base, in a different way; the lines that only one side changed, or neither, are merged without a question.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-version-control/fig-204e6f0663dc.svg)

*A conflict. Each side changed line 2 of the [merge base](#def-b1-version-control-merge), in a different way; the lines that only one side changed, or neither, are merged without a question.*

A conflict is not an error of Git: it is a question only a person can answer, since Git cannot know that the two changes are compatible. Small, frequent [merges](#def-b1-version-control-merge) keep conflicts small.

**Definition 9.9 (Remote repository, clone).**

A *remote repository* is another [repository](#def-b1-version-control-repository) of the same project, named in the local one (usually `origin`). A *clone* is a complete copy of a [repository](#def-b1-version-control-repository), history included, made by `git clone`. `git push` sends local [commits](#def-b1-version-control-commit) to a remote and moves its [branch](#def-b1-version-control-branch); `git fetch` brings the remote’s new [commits](#def-b1-version-control-commit) without merging them; `git pull` fetches and [merges](#def-b1-version-control-merge).

```
$ cd ..
$ git init -q --bare -b main shared.git
$ cd catalogue
$ git remote add origin ../shared.git
$ git push -q origin main
$ cd ..
$ git clone -q shared.git colleague
$ cd colleague
$ printf 'Stone Bridge,1987\n' >> books.csv
$ git commit -q -am "Add Stone Bridge"
$ git push -q origin main
$ cd ../catalogue
$ git log --oneline
8da0a44 Add Harbour Lights
3e494d1 Start the catalogue with two books
$ git pull -q origin main
$ git log --oneline
1b63ead Add Stone Bridge
8da0a44 Add Harbour Lights
3e494d1 Start the catalogue with two books
$ git branch -a
* main
  remotes/origin/main
```

***Output 9.6.** A shared [repository](#def-b1-version-control-repository) on the same disk, two [clones](#def-b1-version-control-remote), and a change travelling from one to the other.*

The shared [repository](#def-b1-version-control-repository) here is *bare*, a [repository](#def-b1-version-control-repository) with no [working tree](#def-b1-version-control-staging), as on a server: nobody edits in it, all push to it. In a team, the shared [repository](#def-b1-version-control-repository) lives on a server reached through the network, but the commands are the same; nothing in this session left the machine. A push that would lose [commits](#def-b1-version-control-commit) on the remote, because someone pushed first, is refused: the pusher must pull, [merge](#def-b1-version-control-merge), and push again.

![Four people changing the same program at the same time, each in a clone of the repository: their commits meet only when they push and pull, and most merges then need no one.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-version-control/img-576ee6a83182.jpg)

*Four people changing the same program at the same time, each in a [clone](#def-b1-version-control-remote) of the [repository](#def-b1-version-control-repository): their [commits](#def-b1-version-control-commit) meet only when they push and pull, and most [merges](#def-b1-version-control-merge) then need no one.*

## 9.5 Searching history

```
$ git log --oneline
bc8f464 Fix a year
1b63ead Add Stone Bridge
8da0a44 Add Harbour Lights
3e494d1 Start the catalogue with two books
$ git log -S"1996" --oneline
bc8f464 Fix a year
3e494d1 Start the catalogue with two books
$ git blame books.csv
^3e494d1 (Ada Lovelace 2026-01-05 09:00:00 +0000 1) The Silent Code,2002
bc8f4648 (Ada Lovelace 2026-01-05 09:00:00 +0000 2) The Paper Forest,1997
8da0a443 (Ada Lovelace 2026-01-05 09:00:00 +0000 3) Harbour Lights,2011
1b63ead6 (Ada Lovelace 2026-01-05 09:00:00 +0000 4) Stone Bridge,1987
```

***Output 9.7.** `log -S` lists the [commits](#def-b1-version-control-commit) that changed the number of occurrences of a string; `blame` shows, for each line, the last [commit](#def-b1-version-control-commit) that changed it.*

These commands answer “when did this text appear or disappear” and “who last touched this line”. They do not answer “which [commit](#def-b1-version-control-commit) broke the test”, since the [commit](#def-b1-version-control-commit) that breaks a program may change lines far from where the failure shows. That question has a better answer.

**Definition 9.10 (Bisection of a history).**

Given a [commit](#def-b1-version-control-commit) known to be *good* (a test passes) and a later one known to be *bad* (it fails), the *bisection* of the history between them tests a [commit](#def-b1-version-control-commit) near the middle of the candidates, those that are [ancestors](#def-b1-version-control-commit-graph) of the bad [commit](#def-b1-version-control-commit) and not of the good one; if it is bad, the culprit is among its [ancestors](#def-b1-version-control-commit-graph); if good, among the others. It repeats until a single [commit](#def-b1-version-control-commit) remains: the first bad [commit](#def-b1-version-control-commit), whose parents are all good. `git bisect run` automates it with a test command whose [exit status](https://one-course.com/books/computer-science/3/en/chapter/8-the-shell#def-b1-the-shell-exit-status) is the verdict: 0 for good, 1 to 127 for bad, except 125, which means “cannot test this [commit](#def-b1-version-control-commit), skip it”.

The session below generates a history of 64 [commits](#def-b1-version-control-commit) of the catalogue ([Listing 9.3](#lst-b1-version-control-make-history), in the problem), on two [branches](#def-b1-version-control-branch) merged at the end. The test `check.py` of the last [commit](#def-b1-version-control-commit) fails. [Bisection](#def-b1-version-control-bisection) finds why.

```
$ python3 make_history.py repo
$ cd repo
$ git rev-list --count HEAD
64
$ python3 check.py; echo "exit status $?"
FAIL: oldest() returned ('Harbour Lights', 2011)
exit status 1
$ git bisect start HEAD $(git rev-list --max-parents=0 HEAD)
Bisecting: 31 revisions left to test after this (roughly 5 steps)
[80502c470b5390380cd334fb70760f85c107d666] Add The Amber Map
$ git bisect run python3 check.py
running 'python3' 'check.py'
FAIL: oldest() returned ('Harbour Lights', 2011)
Bisecting: 15 revisions left to test after this (roughly 4 steps)
[47d1d75da0502e80dd6d3aec701ebe986254b856] Add The Amber Lights
running 'python3' 'check.py'
ok
Bisecting: 7 revisions left to test after this (roughly 3 steps)
[2641214f8b5afcde03e0d5b6892ebffb2c7acbf3] Add The Quiet Map
running 'python3' 'check.py'
ok
Bisecting: 3 revisions left to test after this (roughly 2 steps)
[97caf497aeca0d499ce31307e1fd9e341bf3c99f] Add The Northern Letter
running 'python3' 'check.py'
ok
Bisecting: 1 revision left to test after this (roughly 1 step)
[2a55f3ceb0e0f517a4715207fce1cd1a74bd1e53] Add The Copper River
running 'python3' 'check.py'
ok
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[6bdea1a8873d3675ca64d18fff04a6dde1960af6] Tidy the catalogue functions
running 'python3' 'check.py'
FAIL: oldest() returned ('Harbour Lights', 2011)
6bdea1a8873d3675ca64d18fff04a6dde1960af6 is the first 'bad' commit
commit 6bdea1a8873d3675ca64d18fff04a6dde1960af6
Author: Ada Lovelace <ada@example.org>
Date:   Mon Jan 5 09:31:00 2026 +0000

    Tidy the catalogue functions

 catalogue.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
bisect found first 'bad' commit
$ git bisect reset
Previous HEAD position was 6bdea1a Tidy the catalogue functions
Switched to branch 'main'
```

***Output 9.8.** [Bisection](#def-b1-version-control-bisection) over 64 [commits](#def-b1-version-control-commit): six runs of the test, and the culprit.*

![Bisection on a linear history of 64 commits, the first known good, the last known bad: a schematic run, whose verdicts are not those of . The shaded interval holds the commits that may still be the first bad one; each test (red line) halves it, so that six tests leave one commit, where testing all of them in turn could take 62.](https://one-course.com/images/onecourse/chapters/computer-science-3/b1-version-control/fig-45777b9bfa00.svg)

*[Bisection](#def-b1-version-control-bisection) on a linear history of 64 [commits](#def-b1-version-control-commit), the first known good, the last known bad: a schematic run, whose verdicts are not those of [Output 9.8](#out-b1-version-control-bisect). The shaded interval holds the [commits](#def-b1-version-control-commit) that may still be the first bad one; each test (red line) halves it, so that six tests leave one [commit](#def-b1-version-control-commit), where testing all of them in turn could take 62.*

Each test at least halves the number of candidates, so $n$ candidates need at most $\lceil \log_2 n \rceil$ tests on a linear history ([Exercise 9.10](#exo-b1-version-control-10)): six for 63 candidates, ten for a thousand, twenty for a million. The method needs a test that decides automatically and a history whose [commits](#def-b1-version-control-commit) each build and run, which is one more reason for the good [commits](#def-b1-version-control-commit) of [Method 9.4](#met-b1-version-control-good-commit).

**Safe use.**

A [repository](#def-b1-version-control-repository) is a history, not a backup unless it is copied elsewhere: push to a second machine. Never [commit](#def-b1-version-control-commit) passwords or keys: removing them in a later [commit](#def-b1-version-control-commit) leaves them in the history, readable by anyone with a [clone](#def-b1-version-control-remote). Commands that rewrite history (`rebase`, `reset --hard`, `push --force`) can lose work; use them only on [commits](#def-b1-version-control-commit) nobody else has.

## 9.6 Exercises

**Exercise 9.1 ★.**

In the catalogue of [Output 9.1](#out-b1-version-control-first), with nothing changed since the last [commit](#def-b1-version-control-commit), the commands below are run. What does `git status --short` print?

```bash
printf 'Stone Bridge,1987\n' >> books.csv
git add books.csv
printf 'Winter Map,2019\n' >> books.csv
printf 'draft\n' > notes.txt
git status --short
```

***Listing 9.1.** Edits and adds code/bachelor-1/09-version-control/listings/exo_status.sh*

**Solution of Exercise 9.1.**

```
$ git status --short
MM books.csv
?? notes.txt
```

***Output 9.11.** The status. Some lines are left out.*

`books.csv` is modified in the [staging area](#def-b1-version-control-staging) (the Stone Bridge line, first column `M`) and modified again in the [working tree](#def-b1-version-control-staging) since it was staged (the Winter Map line, second column `M`). `notes.txt` was never added: untracked.

**Exercise 9.2 ★.**

In the graph of [Output 9.4](#out-b1-version-control-branches), list the [commits](#def-b1-version-control-commit) that the [branch](#def-b1-version-control-branch) `sort-by-year` contains, those that `genres` contains, and those that `main` contains after the [merge](#def-b1-version-control-merge).

**Solution of Exercise 9.2.**

`sort-by-year`: 346e, 9fdd, 8da0, 3e49. `genres`: 9fdd, 8da0, 3e49 (the fast-forward did not create a [commit](#def-b1-version-control-commit)). `main` after the [merge](#def-b1-version-control-merge): all six, 58e3, 88f4, 346e, 9fdd, 8da0 and 3e49, since every one is an [ancestor](#def-b1-version-control-commit-graph) of 58e3.

**Exercise 9.3 ★.**

Does each [merge](#def-b1-version-control-merge) fast-forward? (a) `main` at [commit](#def-b1-version-control-commit) $X$, [branch](#def-b1-version-control-branch) `fix` made from $X$ with two [commits](#def-b1-version-control-commit), nothing committed on `main` since; `git merge fix` on `main`. (b) The same after one [commit](#def-b1-version-control-commit) on `main`. (c) `git merge main` on `fix` in case (a). Justify with the [merge base](#def-b1-version-control-merge).

**Solution of Exercise 9.3.**

(a) The [merge base](#def-b1-version-control-merge) of `main` and `fix` is $X$, the tip of `main`: fast-forward, `main` moves to the tip of `fix`. (b) The [merge base](#def-b1-version-control-merge) is still $X$, but the tip of `main` is now a later [commit](#def-b1-version-control-commit): a [three-way merge](#def-b1-version-control-merge), with a [merge](#def-b1-version-control-merge) [commit](#def-b1-version-control-commit). (c) The [merge base](#def-b1-version-control-merge) is $X$, the tip of `main` being an [ancestor](#def-b1-version-control-commit-graph) of `fix`: `fix` already contains every [commit](#def-b1-version-control-commit) of `main`, and Git answers “Already up to date” without changing anything.

**Exercise 9.4 ★.**

After the commands below, run on the catalogue of [Output 9.1](#out-b1-version-control-first), which change does `git diff --staged` show, and which does `git diff` show? What would `git commit` record?

```bash
sed -i 's/1996/1997/' books.csv
git add books.csv
sed -i 's/2011/2012/' books.csv
```

***Listing 9.2.** A staged change and another one code/bachelor-1/09-version-control/listings/exo_staged.sh*

**Solution of Exercise 9.4.**

```
$ git diff --staged | grep '^[-+][A-Z]'
-The Paper Forest,1996
+The Paper Forest,1997
$ git diff | grep '^[-+][A-Z]'
-Harbour Lights,2011
+Harbour Lights,2012
```

***Output 9.12.** The two diffs. Some lines are left out.*

`git add` copied the file with the year 1997 into the [staging area](#def-b1-version-control-staging); the change to 2012 came after, in the [working tree](#def-b1-version-control-staging) only. `git commit` records the [staging area](#def-b1-version-control-staging): the year 1997 and Harbour Lights still dated 2011.

**Exercise 9.5 ★★.**

The [working tree](#def-b1-version-control-staging) holds two unrelated changes to the same file: a corrected year and a new book. Using only commands of this chapter and of the [shell](https://one-course.com/books/computer-science/3/en/chapter/8-the-shell#def-b1-the-shell-shell), without an editor, make two [commits](#def-b1-version-control-commit), one per change.

```
$ git diff
diff --git a/books.csv b/books.csv
index d343e22..f42aad8 100644
--- a/books.csv
+++ b/books.csv
@@ -1,3 +1,4 @@
 The Silent Code,2002
-The Paper Forest,1996
+The Paper Forest,1997
 Harbour Lights,2011
+Stone Bridge,1987
```

***Output 9.9.** The two changes. Some lines are left out.*

**Solution of Exercise 9.5.**

Keep a copy of the file with both changes, remove the new last line, [commit](#def-b1-version-control-commit) the year, then put the copy back and [commit](#def-b1-version-control-commit) the book.

```
$ cp books.csv both.csv
$ sed -i '$d' books.csv
$ git commit -q -am "Fix the year of The Paper Forest"
$ mv both.csv books.csv
$ git commit -q -am "Add Stone Bridge"
$ git log --oneline --stat -2
2d0db63 Add Stone Bridge
 books.csv | 1 +
 1 file changed, 1 insertion(+)
17dfc05 Fix the year of The Paper Forest
 books.csv | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
```

***Output 9.13.** Two [commits](#def-b1-version-control-commit) of one change each. Some lines are left out.*

With an editor, one would stage a part of the file with `git add -p`, which asks, for each changed block, whether to stage it.

**Exercise 9.6 ★★.**

In the conflict of [Output 9.5](#out-b1-version-control-conflict), a hurried colleague types `git commit -am "Merge rename"` right after `git merge rename`. Does Git accept it? What does the [commit](#def-b1-version-control-commit) contain, which problems does it cause, and how can such a [commit](#def-b1-version-control-commit) be detected?

**Solution of Exercise 9.6.**

```
$ git merge rename > /dev/null
$ git commit -q -am "Merge rename"
$ cat books.csv
The Silent Code,2002
<<<<<<< HEAD
The Paper Forest,1997
=======
The Paper Forest (2nd ed.),1996
>>>>>>> rename
Harbour Lights,2011
$ git diff --check HEAD^1 HEAD; echo "exit status $?"
books.csv:2: leftover conflict marker
books.csv:4: leftover conflict marker
books.csv:6: leftover conflict marker
exit status 2
```

***Output 9.14.** The [commit](#def-b1-version-control-commit) Git accepted.*

Git accepts it: `-a` stages the file as it is, markers included, and staging is how a conflict is declared resolved. The [commit](#def-b1-version-control-commit) records a file of seven lines, three of them markers, and two versions of the same book: any program that reads the catalogue now fails or counts the book twice, on every [branch](#def-b1-version-control-branch) that [merges](#def-b1-version-control-merge) this one. `git diff --check` between the [merge](#def-b1-version-control-merge) and its first parent reports the markers, with an [exit status](https://one-course.com/books/computer-science/3/en/chapter/8-the-shell#def-b1-the-shell-exit-status) of 2; a test of the file’s format would also catch them.

**Exercise 9.7 ★★.**

Write a test script `bisect_test.sh` for `git bisect run` on the catalogue: exit 0 if `check.py` passes, 1 if it fails, and 125 if the [commit](#def-b1-version-control-commit) cannot be tested because `catalogue.py` does not even parse. Why is 125 needed, when a Python program that does not parse stops with an [exit status](https://one-course.com/books/computer-science/3/en/chapter/8-the-shell#def-b1-the-shell-exit-status) of 1 anyway?

**Solution of Exercise 9.7.**

```bash
#!/bin/bash
# bisect_test.sh: the test for `git bisect run`: 0 good, 1 bad, 125 untestable.
if ! python3 -c 'import ast; ast.parse(open("catalogue.py").read())' 2> /dev/null; then
    exit 125                # the program does not even parse: no verdict, skip
fi
python3 check.py > /dev/null 2>&1
status=$?
case $status in
    0) exit 0 ;;            # the test passes: good
    1) exit 1 ;;            # the test fails: bad
    *) exit 125 ;;          # anything else is not a verdict on the bug
esac
```

*A test with three verdicts code/bachelor-1/09-version-control/exercises/bisect_test.sh*

A program that does not parse stops before running the test, with a status of 1, which `bisect run` would read as “bad”: [bisection](#def-b1-version-control-bisection) would then blame a [commit](#def-b1-version-control-commit) for a failure unrelated to the bug it is looking for, and conclude wrongly. The status 125 says “no verdict”, and [bisection](#def-b1-version-control-bisection) tests a neighbouring [commit](#def-b1-version-control-commit) instead. Statuses above 127 abort the [bisection](#def-b1-version-control-bisection), which is why the script maps any unexpected status to 125. The test `tests/test_history.py` runs the script on the four cases.

**Exercise 9.8 ★★.**

A history has [commits](#def-b1-version-control-commit) $A$ to $H$. $A$ is the first; $B$’s parent is $A$, $C$’s is $B$, $D$’s is $C$, $E$’s is $C$, $F$’s is $E$; $G$ is a [merge](#def-b1-version-control-merge) with parents $D$ and $F$; $H$’s parent is $E$. Give the [merge base](#def-b1-version-control-merge) of $G$ and $H$, and of $D$ and $H$. Which [commits](#def-b1-version-control-commit) would a [merge](#def-b1-version-control-merge) of $H$ into $G$ compare?

**Solution of Exercise 9.8.**

The [ancestors](#def-b1-version-control-commit-graph) of $G$ are $G, D, F, C, E, B, A$; those of $H$ are $H, E, C, B, A$. The common [ancestors](#def-b1-version-control-commit-graph) are $E, C, B, A$, and $C$, $B$, $A$ are [ancestors](#def-b1-version-control-commit-graph) of $E$: the [merge base](#def-b1-version-control-merge) is $E$, not $C$. For $D$ and $H$, the common [ancestors](#def-b1-version-control-commit-graph) are $C, B, A$, and the [merge base](#def-b1-version-control-merge) is $C$. A [merge](#def-b1-version-control-merge) of $H$ into $G$ compares each file in $E$, in $G$ and in $H$: what $F$ and $D$ changed since $E$ is kept from the side of $G$, what $H$ changed from the side of $H$.

**Exercise 9.9 ★★.**

From the catalogue of [Output 9.1](#out-b1-version-control-first), three [branches](#def-b1-version-control-branch) are made from its last [commit](#def-b1-version-control-commit): on `a`, one [commit](#def-b1-version-control-commit) A1; on `b`, one [commit](#def-b1-version-control-commit) B1; on `main`, one [commit](#def-b1-version-control-commit) M1. Then, on `main`, `git merge a` and `git merge b`. Draw the [commit graph](#def-b1-version-control-commit-graph), with its [merge](#def-b1-version-control-merge) [commits](#def-b1-version-control-commit) and their parents.

**Solution of Exercise 9.9.**

```
$ git log --graph --oneline
*   78ddb07 Merge branch 'b'
|\  
| * e197476 B1
* |   37358c0 Merge branch 'a'
|\ \  
| * | 4b809e1 A1
| |/  
* / 6512b81 M1
|/  
* 8da0a44 Add Harbour Lights
* 3e494d1 Start the catalogue with two books
```

***Output 9.15.** The graph after two [merges](#def-b1-version-control-merge). Some lines are left out.*

The first [merge](#def-b1-version-control-merge) [commit](#def-b1-version-control-commit) has parents M1 and A1; the second has parents the first [merge](#def-b1-version-control-merge) and B1. Every [branch](#def-b1-version-control-branch) was made from 8da0, which is the [merge base](#def-b1-version-control-merge) of both [merges](#def-b1-version-control-merge).

**Exercise 9.10 ★★★.**

A linear history has $n + 1$ [commits](#def-b1-version-control-commit) $c_0, \dots, c_n$, $c_0$ good and $c_n$ bad, and once a [commit](#def-b1-version-control-commit) is bad all later ones are. Prove that [bisection](#def-b1-version-control-bisection), testing the middle candidate each time, finds the first bad [commit](#def-b1-version-control-commit) in at most $\lceil \log_2
n \rceil$ tests, and that no method that only tests [commits](#def-b1-version-control-commit) can do better in the worst case.

**Solution of Exercise 9.10.**

Call the candidates $c_1, \dots, c_n$: the first bad [commit](#def-b1-version-control-commit) is one of them, since $c_0$ is good and $c_n$ bad. Let $T(m)$ be the largest number of tests [bisection](#def-b1-version-control-bisection) needs when $m$ consecutive candidates remain, the last of them known bad. $T(1) = 0$. For $m \geq 2$, testing the candidate of position $\lfloor m / 2 \rfloor$ leaves the first $\lfloor m / 2
\rfloor$ candidates if it is bad and the last $\lceil m / 2 \rceil$ if it is good: $T(m) \leq 1 + T(\lceil m / 2
\rceil)$. By induction, $T(m) \leq \lceil \log_2 m \rceil$, since for $m \geq 2$, $\lceil \log_2 \lceil m / 2 \rceil
\rceil = \lceil \log_2 m \rceil - 1$. Lower bound: a method that makes at most $t$ tests, each with two answers, can end in at most $2^t$ different ways, and it must name $n$ different culprits for the $n$ possible histories: $2^t \geq n$, so $t \geq \lceil \log_2 n \rceil$. The test `tests/test_history.py` checks the recurrence for $n < 300$.

**Exercise 9.11 ★★★.**

In a history with [merges](#def-b1-version-control-merge), a test of a [commit](#def-b1-version-control-commit) $x$ that says “bad” keeps as candidates the [ancestors](#def-b1-version-control-commit-graph) of $x$, and one that says “good” removes $x$ and its [ancestors](#def-b1-version-control-commit-graph). Show that [bisection](#def-b1-version-control-bisection) still ends. Then take a good [commit](#def-b1-version-control-commit) $R$, $k$ [branches](#def-b1-version-control-branch) of one [commit](#def-b1-version-control-commit) each, $C_1, \dots, C_k$, all made from $R$, and one [merge](#def-b1-version-control-merge) $M$ of all of them, bad. How many tests are needed in the worst case? Compare with $\lceil \log_2 (k + 1) \rceil$.

**Solution of Exercise 9.11.**

Let the candidates be the [ancestors](#def-b1-version-control-commit-graph) of the known bad [commit](#def-b1-version-control-commit) $b$ that are not [ancestors](#def-b1-version-control-commit-graph) of a good [commit](#def-b1-version-control-commit), $b$ included; the test picks a candidate $x \neq b$. If $x$ is bad, the candidates become those that are [ancestors](#def-b1-version-control-commit-graph) of $x$, and $b$, which is not an [ancestor](#def-b1-version-control-commit-graph) of $x$ (the graph has no cycle), leaves; if $x$ is good, $x$ leaves. The set loses at least one [commit](#def-b1-version-control-commit) at each test, so [bisection](#def-b1-version-control-bisection) ends, with $b$ alone. In the example, the candidates are $C_1, \dots, C_k$ and $M$, and each $C_i$ has no candidate among its [ancestors](#def-b1-version-control-commit-graph) but itself: a “good” verdict removes one [commit](#def-b1-version-control-commit) only. If the culprit is $M$, every $C_i$ must be tested: $k$ tests in the worst case, against $\lceil \log_2 (k + 1) \rceil$ on a linear history of as many candidates (3 instead of 7 for $k = 7$). [Merges](#def-b1-version-control-merge) of many short [branches](#def-b1-version-control-branch) make [bisection](#def-b1-version-control-bisection) slower.

**Exercise 9.12 ★★★.**

Write a script `touch_count.sh [REPO]` that prints, for each file of a [repository](#def-b1-version-control-repository), the number of [commits](#def-b1-version-control-commit) that changed it, the most changed first, [merge](#def-b1-version-control-merge) [commits](#def-b1-version-control-commit) excluded. Run it on the generated history of the problem: which counts can you predict from the generator alone?

**Solution of Exercise 9.12.**

```bash
#!/bin/bash
# touch_count.sh [REPO]: for each file, the number of commits that changed it.
set -euo pipefail
cd "${1:-.}"
git log --format= --name-only --no-merges |
    grep -v '^$' |
    sort | uniq -c |
    sort -k1,1rn -k2,2
```

*[Commits](#def-b1-version-control-commit) per file code/bachelor-1/09-version-control/listings/touch_count.sh*

```
$ python3 make_history.py repo
$ bash touch_count.sh repo
     39 books.csv
     23 covers.csv
      2 catalogue.py
      1 check.py
```

***Output 9.16.** The counts on the generated history.*

`--name-only` lists the files changed by each [commit](#def-b1-version-control-commit) and `--format=` prints nothing else, leaving blank lines that `grep` removes; `--no-merges` skips the [merge](#def-b1-version-control-merge), which would otherwise count again files brought from the [branch](#def-b1-version-control-branch). All four counts follow from the generator: `books.csv` is created by the first [commit](#def-b1-version-control-commit) and extended by 38 of the next 39 main [commits](#def-b1-version-control-commit), the other one being the bad [commit](#def-b1-version-control-commit): 39; `covers.csv` 23, one per [branch](#def-b1-version-control-branch) [commit](#def-b1-version-control-commit); `catalogue.py` 2, its creation and the bad [commit](#def-b1-version-control-commit); `check.py` 1. The test `tests/test_history.py` checks them from the generator’s constants.

## 9.7 Problem: Who broke the catalogue?

**Problem 9.1.**

Weekend problem — Who broke the catalogue?

The program below writes the history of a small catalogue program: 40 [commits](#def-b1-version-control-commit) on `main`, a [branch](#def-b1-version-control-branch) `covers` made after the twentieth with 23 [commits](#def-b1-version-control-commit) of its own, and a [merge](#def-b1-version-control-merge). One [commit](#def-b1-version-control-commit) of `main` breaks the function `oldest`, which then returns the newest book; the test `check.py` detects it. The session reads the graph; [Output 9.8](#out-b1-version-control-bisect) bisected the same history.

```python
WORDS = ["Silent", "Paper", "Stone", "Harbour", "Winter",
         "Copper", "Hidden", "Northern", "Quiet", "Amber"]
NOUNS = ["Code", "Forest", "Bridge", "Lights", "Garden",
         "River", "Letter", "Map", "Tower", "Orchard"]
MAIN, BRANCH = 40, 23  # commits on main (before the merge), commits on the branch
FORK, BAD = 20, 31  # the branch starts after main commit 20; main commit 31 is bad
    git("init", "-q", "-b", "main")
    write("catalogue.py", CATALOGUE.format(fn="min"))
    write("check.py", CHECK)
    write("books.csv", a_book())
    git("add", ".")
    git("commit", "-q", "-m", "Start the catalogue")
    for i in range(2, MAIN + 1):
        if i == BAD:
            write("catalogue.py", CATALOGUE.format(fn="max"))
            git("commit", "-q", "-am", "Tidy the catalogue functions")
        else:
            title = a_book()
            write("books.csv", title, "a")
            git("commit", "-q", "-am", f"Add {title.rsplit(',', 1)[0]}")
        if i == FORK:
            git("branch", "covers")
    git("switch", "-q", "covers")
    for _ in range(BRANCH):
        line = f"{rng.randint(1, 40)},cover-{rng.randint(100, 999)}.jpg\n"
        write("covers.csv", line, "a")
        git("add", "covers.csv")
        book = line.split(",")[0]
        git("commit", "-q", "-m", f"Add a cover for book {book}")
    git("switch", "-q", "main")
    git("merge", "-q", "--no-edit", "covers")
```

***Listing 9.3.** The history generator (excerpt) code/bachelor-1/09-version-control/listings/make_history.py*

```
$ python3 make_history.py repo
$ cd repo
$ git rev-list --count HEAD
64
$ git log --graph --oneline | sed -n '1,3p;25,27p;34,36p;45,48p;65,66p'
*   8424896 Merge branch 'covers'
|\  
| * ebc93ee Add a cover for book 33
| * 5a5e47f Add a cover for book 16
* | cc84672 Add The Winter Bridge
* | 353818a Add The Northern Code
* | 80502c4 Add The Amber Map
* | 6bdea1a Tidy the catalogue functions
* | 2a55f3c Add The Copper River
* | abade2e Add The Northern River
|/  
* 66ce86b Add The Copper Map
* a9689ed Add The Northern Tower
* e413575 Add The Paper Tower
* bafeea4 Start the catalogue
$ git log --oneline --merges
8424896 Merge branch 'covers'
$ git rev-list --count --first-parent HEAD
41
$ git rev-list --count covers
43
$ git log --oneline -1 $(git merge-base HEAD^1 HEAD^2)
66ce86b Add The Copper Map
$ git rev-list --count HEAD ^covers
21
$ git rev-list --count covers ^HEAD^1
23
$ git log --oneline -1 -- catalogue.py
6bdea1a Tidy the catalogue functions
$ git diff HEAD~11 HEAD~10 -- catalogue.py | grep -E '^[-+] '
-    return min(books, key=lambda book: book[1])
+    return max(books, key=lambda book: book[1])
```

***Output 9.10.** Reading the generated history; the `sed` keeps a few lines of the long graph.*

**Part I — Reading the graph.**

1. How many [commits](#def-b1-version-control-commit) does the history hold? Check the number against the generator.
2. Which [commit](#def-b1-version-control-commit) has two parents? How does `log --graph` show where the [branch](#def-b1-version-control-branch) starts and where it is merged?
3. `rev-list --count --first-parent HEAD` prints 41. Which [commits](#def-b1-version-control-commit) does it count?
4. Why does `rev-list --count covers` print 43?
5. Is the [commit](#def-b1-version-control-commit) “Tidy the catalogue functions” an [ancestor](#def-b1-version-control-commit-graph) of the tip of `covers` ? Of `HEAD` ?
6. The generator dates its [commits](#def-b1-version-control-commit) a minute apart. If it gave them all the same date, would the history still be well defined? Would the identifiers change from run to run?

**Part II — Merge base and merge.**

7. Which [commit](#def-b1-version-control-commit) is the [merge base](#def-b1-version-control-merge) of the two parents of the [merge](#def-b1-version-control-merge) ? Which line of the generator decides it?
8. `rev-list --count HEAD ^covers` prints 21. Which [commits](#def-b1-version-control-commit) are they?
9. `rev-list --count covers ^HEAD^1` prints 23. What does that number say about the [merge](#def-b1-version-control-merge) ?
10. For each of `catalogue.py` , `books.csv` and `covers.csv` , say which sides changed the file since the [merge base](#def-b1-version-control-merge) , and what the [three-way merge](#def-b1-version-control-merge) kept.
11. Why did the [merge](#def-b1-version-control-merge) produce no conflict?
12. Does the tip of `covers` pass the test? Does the [merge](#def-b1-version-control-merge) ? Why?

**Part III — Finding the culprit.**

13. The last [commit](#def-b1-version-control-commit) that changed `catalogue.py` is the culprit here. Why can `log -- catalogue.py` not replace [bisection](#def-b1-version-control-bisection) in general?
14. Explain, from the diff, what the bad [commit](#def-b1-version-control-commit) changed, and why the test prints `Harbour Lights` .
15. `git bisect start HEAD` followed by the first [commit](#def-b1-version-control-commit) says what? How many [commits](#def-b1-version-control-commit) are candidates?
16. In [Output 9.8](#out-b1-version-control-bisect) , list the six verdicts and the number of candidates left after each test.
17. The covers [commits](#def-b1-version-control-commit) are candidates at the start, yet none was tested. Why?
18. Had `catalogue.py` failed to parse at some [commit](#def-b1-version-control-commit) of the [branch](#def-b1-version-control-branch) , how would `check.py` have exited, and what would [bisection](#def-b1-version-control-bisection) have concluded? What does `bisect_test.sh` ( [Exercise 9.7](#exo-b1-version-control-7) ) change?

**Part IV — The logarithmic bound.**

19. Show that after $k$ tests that each halve the candidates, at most $\lceil n / 2^k \rceil$ remain.
20. Deduce the number of tests needed for $n = 63$ candidates.
21. Testing the [commits](#def-b1-version-control-commit) one by one, from the oldest, how many tests would find this culprit? In the worst case?
22. Git announced “roughly 5 steps” after choosing the first [commit](#def-b1-version-control-commit) to test, then ran the test six times. Explain both numbers.
23. The history has a [merge](#def-b1-version-control-merge) . Why did the bound still hold in this run? Use [Exercise 9.11](#exo-b1-version-control-11) .
24. State the named result of the problem, *[bisection](#def-b1-version-control-bisection) finds the culprit among 64 [commits](#def-b1-version-control-commit) in at most 6 tests* .

**Solution of Problem 9.1.**

**1.** 64: 40 [commits](#def-b1-version-control-commit) on `main`, 23 on the [branch](#def-b1-version-control-branch), and the [merge](#def-b1-version-control-merge).

**2.** The [merge](#def-b1-version-control-merge), 8424896. `|\` under it opens a second column, its second parent’s line; the `|/` near the bottom joins that column to the [commit](#def-b1-version-control-commit) the [branch](#def-b1-version-control-branch) was made from.

**3.** The [commits](#def-b1-version-control-commit) reached from `HEAD` through first parents only: the [merge](#def-b1-version-control-merge) and the 40 [commits](#def-b1-version-control-commit) of `main`.

**4.** The tip of `covers` has as [ancestors](#def-b1-version-control-commit-graph) its 23 [commits](#def-b1-version-control-commit) and the first 20 [commits](#def-b1-version-control-commit) of `main`: 43.

**5.** No: it is the 31st [commit](#def-b1-version-control-commit) of `main`, made after the [branch](#def-b1-version-control-branch) left at the 20th. Yes for `HEAD`, which is reached from it through the [merge](#def-b1-version-control-merge)’s first parent.

**6.** The graph would be the same, since it is made of parent links, not dates. The identifiers are the same at each run anyway, since they are hashes of contents, names, dates and parents that the seed and the fixed dates determine; with dates taken from the clock, they would change at every run.

**7.** 66ce86b, “Add The Copper Map”, the 20th [commit](#def-b1-version-control-commit) of `main`: the test `if i == FORK:` of the loop makes the [branch](#def-b1-version-control-branch) just after it.

**8.** The [commits](#def-b1-version-control-commit) reachable from `HEAD` and not from `covers`: the 20 [commits](#def-b1-version-control-commit) 21 to 40 of `main`, and the [merge](#def-b1-version-control-merge).

**9.** The 23 [commits](#def-b1-version-control-commit) of the [branch](#def-b1-version-control-branch) are not [ancestors](#def-b1-version-control-commit-graph) of the first parent of the [merge](#def-b1-version-control-merge): the [merge](#def-b1-version-control-merge) brought exactly them into `main`.

**10.** `catalogue.py`: changed on `main` only (`min` to `max`), so the [merge](#def-b1-version-control-merge) keeps `max`. `books.csv`: on `main` only, so `main`’s version. `covers.csv`: created on the [branch](#def-b1-version-control-branch) only, so the [branch](#def-b1-version-control-branch)’s version.

**11.** No file was changed on both sides since the [merge base](#def-b1-version-control-merge).

**12.** The tip of `covers` has the catalogue of [commit](#def-b1-version-control-commit) 20, with `min`: it passes. The [merge](#def-b1-version-control-merge) has `max`: it fails.

**13.** A program can break through a change to another file (the data, a library, a configuration), and a file may be changed by dozens of [commits](#def-b1-version-control-commit), of which `log` cannot say which one broke the test.

**14.** `min` became `max`: `oldest` returns the book with the largest year, and among the three books of the test that is Harbour Lights, 2011.

**15.** That `HEAD` is bad and the first [commit](#def-b1-version-control-commit) good. The candidates are the [ancestors](#def-b1-version-control-commit-graph) of `HEAD` that are not [ancestors](#def-b1-version-control-commit-graph) of the first [commit](#def-b1-version-control-commit): 63 [commits](#def-b1-version-control-commit).

**16.** Bad, good, good, good, good, bad. Git announces 31, 15, 7, 3, 1 and 0 [commits](#def-b1-version-control-commit) left to test after each choice: the candidates halve at every test.

**17.** The first test, at “Add The Amber Map”, the 32nd [commit](#def-b1-version-control-commit) of `main`, was bad: the candidates became its [ancestors](#def-b1-version-control-commit-graph), among which no [commit](#def-b1-version-control-commit) of the [branch](#def-b1-version-control-branch).

**18.** With a syntax error, Python stops with status 1 before running the test, and `bisect run` reads “bad”. Had such a [commit](#def-b1-version-control-commit) been tested, [bisection](#def-b1-version-control-bisection) would have treated it as broken by the bug: had it been on the [branch](#def-b1-version-control-branch), before the first test removed the [branch](#def-b1-version-control-branch), it could have been named the first bad [commit](#def-b1-version-control-commit). `bisect_test.sh` returns 125 for it, and the [commit](#def-b1-version-control-commit) is skipped.

**19.** By induction: after the test $k + 1$, at most $\lceil m_k / 2 \rceil$ candidates remain, and $\lceil \lceil n / 2^k \rceil / 2 \rceil = \lceil n / 2^{k + 1} \rceil$.

**20.** $\lceil 63 / 2^5 \rceil = 2$ and $\lceil 63 / 2^6 \rceil = 1$: six tests.

**21.** Along `main` from the oldest, the [commits](#def-b1-version-control-commit) 2 to 31: 30 tests, the last one bad. In the worst case, 62 tests for 63 candidates, since the last candidate need not be tested.

**22.** After choosing the first [commit](#def-b1-version-control-commit), 31 candidates remain whatever its verdict, and about $\log_2 31 \approx 5$ tests are still needed after this one: five, plus the one about to run, make six.

**23.** The bad [commit](#def-b1-version-control-commit) lies on `main` after the fork, and the first test, bad, left only [commits](#def-b1-version-control-commit) of `main`: from then on the candidates formed a linear history, on which each test halves them ([Exercise 9.10](#exo-b1-version-control-10)). Had the first verdict been good, the [branch](#def-b1-version-control-branch) would have stayed, with the risk shown in [Exercise 9.11](#exo-b1-version-control-11).

**24.** *[Bisection](#def-b1-version-control-bisection) finds the culprit among 64 [commits](#def-b1-version-control-commit) in at most 6 tests.* With the first [commit](#def-b1-version-control-commit) good and the last bad, the 63 candidates halve at each test, so $\lceil \log_2 63 \rceil = 6$ tests suffice; the captured run of `git bisect run` took exactly six, and named “Tidy the catalogue functions”, the [commit](#def-b1-version-control-commit) that changed `min` into `max`, which the chapter’s test confirms by running `check.py` on all 64 [commits](#def-b1-version-control-commit).
