Objectives: LO-10.1, LO-10.2, LO-10.3, LO-10.4
Prerequisites: the Module 10 reading,
Lab 9, and Git installed, as
Setting up your computer describes
Time: about 2 hours
In this lab you build the history of a small project, a shopping list script, from its first
commit to a merged branch: you commit, predict what git status reports, read the history,
ignore generated files, write a commit message and a README, push to a remote, undo mistakes,
and merge a branch. As before, each exercise ends with a check cell that prints passed or
says what is wrong, and fails until you answer.
Each section builds on the one before it, so run the cells in order. If the repository gets into a state you can’t fix, run the setup cell again, which deletes it and starts over, and then run each cell after it again in order.
Setup¶
Run the next cell first. It prints the versions of Python and Git, deletes anything an earlier
run left in scratch, and makes the folder scratch/lab10 with the project’s first files. It
also defines a helper, git, which runs a Git command in that folder and prints what Git
prints. Type the command as you would after git in a terminal: git("status") runs
git status, and git('commit -m "Add a list"') runs git commit -m "Add a list". Put
single quotes around a command that has double quotes in it, as that one does.
The helper changes three things from a terminal, so that the lab works the same on every computer:
It never opens an editor. Give every commit a message with
-m; a merge or a revert uses the message Git writes for it.It records commits as “PY101 Learner”, not with the name and address you set with
git config.It only finds repositories inside
scratch, so a mistake here can’t reach any other repository on your computer.
import os
import shlex
import shutil
import stat
import subprocess
import sys
print("Python", sys.version.split()[0])
GIT = shutil.which("git")
if GIT is None:
raise RuntimeError(
"This notebook can't find Git. Install it as 'Setting up your computer' describes, "
"then close JupyterLab and start it again."
)
print(subprocess.run([GIT, "--version"], capture_output=True, text=True).stdout.strip())
SCRATCH = os.path.abspath("scratch")
REPO = os.path.join(SCRATCH, "lab10") # the project's repository
REMOTE = os.path.join(SCRATCH, "lab10-remote.git") # stands in for GitHub, in section 7
CLONE = os.path.join(SCRATCH, "lab10-clone") # a stranger's copy, in section 7
ENVIRONMENT = dict(
os.environ,
GIT_EDITOR=":", # ":" tells Git not to open an editor
GIT_TERMINAL_PROMPT="0", # never wait for a password
GIT_CEILING_DIRECTORIES=SCRATCH, # never look for a repository above scratch
GIT_AUTHOR_NAME="PY101 Learner",
GIT_AUTHOR_EMAIL="[email protected]",
GIT_COMMITTER_NAME="PY101 Learner",
GIT_COMMITTER_EMAIL="[email protected]",
)
OPTIONS = ["-c", "color.ui=never", "-c", "init.defaultBranch=main", "-c", "commit.gpgSign=false"]
def run_git(command, folder=REPO):
"""Run a Git command in folder, and return its output and exit status.
command is what you would type after "git", as a string, or a list of its arguments.
"""
arguments = shlex.split(command) if isinstance(command, str) else list(command)
result = subprocess.run(
[GIT, *OPTIONS, *arguments], cwd=folder, env=ENVIRONMENT, timeout=60,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8",
errors="replace",
)
return result.stdout, result.returncode
def git(command, folder=REPO):
"""Run a Git command as a terminal would, and show its output, and its status if not 0."""
output, status = run_git(command, folder)
print(output, end="")
if status != 0:
print(f"(exit status {status})")
def git_output(command, folder=REPO):
"""Run a Git command, and return what it printed."""
return run_git(command, folder)[0]
def write(name, text):
"""Write text to the file name in the repository's folder, making folders as needed."""
path = os.path.join(REPO, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as file:
file.write(text)
def read(name):
"""Return the text of the file name in the repository's folder."""
with open(os.path.join(REPO, name), encoding="utf-8") as file:
return file.read()
def remove(folder):
"""Delete folder and everything in it, including the files Git marks read-only."""
def make_writable_and_retry(function, path, error):
os.chmod(path, stat.S_IWRITE)
function(path)
if os.path.exists(folder):
shutil.rmtree(folder, onexc=make_writable_and_retry)
SHOPPING = '''"""Print a shopping list in alphabetical order, and count the items."""
ITEMS = ["milk", "eggs", "bread"]
for item in sorted(ITEMS):
print("-", item)
print(len(ITEMS), "items")
'''
for folder in [REPO, REMOTE, CLONE]:
remove(folder)
os.makedirs(REPO)
write("shopping.py", SHOPPING)
write("notes.txt", "Ask whether we need more milk.\n")
run_git("init --bare lab10-remote.git", folder=SCRATCH)
print("Ready.")1. A repository and its first commit¶
scratch/lab10 holds two files: shopping.py, the program, and notes.txt, your own notes,
which don’t belong in the project. Run the next cell. Git can’t report anything yet, because
the folder isn’t a repository, and the command fails with exit status 128.
print(sorted(os.listdir(REPO)))
git("status")Exercise L10.1 (LO-10.1, ★, about 10 minutes)¶
In the next cell, make the folder a repository, and record shopping.py, and only
shopping.py, in its first commit, with the message Add a shopping list script. Use one
git(...) line for each command, and add git("status") lines between them to watch what
each one does.
Hint
Three commands: init, then add with the file’s name, then commit with -m and the message in double quotes.
# Write your git(...) lines here.assert os.path.isdir(os.path.join(REPO, ".git")), "Make the folder a repository with init."
log = git_output("log --format=%s").splitlines()
assert log, "The repository has no commits yet: stage shopping.py with add, then commit."
assert log[-1] == "Add a shopping list script", (
f"The first commit's message is {log[-1]!r}, not 'Add a shopping list script'."
)
tracked = git_output("ls-files").split()
assert "shopping.py" in tracked, "Stage shopping.py with add before you commit."
assert "notes.txt" not in tracked, (
"notes.txt is committed too. Run the setup cell again, and add only shopping.py."
)
print("passed")2. What Git reports¶
Git reports each file in one of four states, which this lab names like this:
"untracked": in the folder, but never added;"modified": changed since the last commit, and not staged;"staged": its changes are in the staging area, ready for the next commit;"unchanged": the same as in the last commit (git statusdoesn’t list it).
Exercise L10.2 (LO-10.1, ★★, about 10 minutes)¶
The cell after the check takes these four steps, in order:
It adds
"apples"toITEMSinshopping.py, and saves the file.It runs
git add shopping.py.It adds
"rice"toITEMS, and saves the file again.It creates a new file,
prices.txt.
Without running it, predict:
s1: the state ofshopping.pyafter step 1.s2: the state ofshopping.pyafter step 2.s3: after step 3, agit commitwould recordshopping.pywith which new items? Answer"apples"or"apples and rice".s4: the state ofprices.txtafter step 4.
s1 = "..."
s2 = "..."
s3 = "..."
s4 = "..."assert s1 == "modified", "s1: the file has changed since the last commit, and isn't staged."
assert s2 == "staged", "s2: git add copies the file as it is now into the staging area."
assert s3 == "apples", (
"s3: git add staged the file as it was then. A commit records the staging area, not the "
"file's later changes."
)
assert s4 == "untracked", "s4: Git hasn't been told about prices.txt."
print("passed")Now run the next cell, which takes the four steps and shows git status --short after each.
--short prints one line for each file Git lists, with two columns of codes before the name:
the first column for the staging area and the second for the working tree. M means
modified, and ?? means untracked. After step 3, MM says that shopping.py has a staged
change and another change that isn’t staged.
write("shopping.py", SHOPPING.replace('"bread"]', '"bread", "apples"]'))
print("After step 1:")
git("status --short")
git("add shopping.py")
print("After step 2:")
git("status --short")
write("shopping.py", SHOPPING.replace('"bread"]', '"bread", "apples", "rice"]'))
print("After step 3:")
git("status --short")
write("prices.txt", "apples 0.50\neggs 0.30\nmilk 1.20\nrice 2.00\n")
print("After step 4:")
git("status --short")3. Reading the history¶
Run the next cell. It commits both changes to shopping.py, then makes three more commits, as
someone else working on the project might have.
git("add shopping.py")
git('commit -m "Add apples and rice to the list"')
git("add prices.txt")
git('commit -m "Add a price list"')
write("shopping.py", read("shopping.py").replace('"eggs", "bread", ', '"eggs", '))
git("add shopping.py")
git('commit -m "Remove an item that is already at home"')
write("shopping.py", read("shopping.py").replace(
'print(len(ITEMS), "items")', 'print(f"You need {len(ITEMS)} items.")'
))
git("add shopping.py")
git('commit -m "Count the items in a sentence"')Exercise L10.3 (LO-10.1, ★★, about 10 minutes)¶
Use git log --oneline, git show with a commit’s hash, and git show HEAD (HEAD is the
latest commit on your branch) in the next cell to find:
h1: how many commits the repository has.h2: the item that the commit “Remove an item that is already at home” removed, as a string such as"milk".h3: how many lines the latest commit added, andh4: how many it removed.
git("log --oneline")h1 = 0
h2 = "..."
h3 = 0
h4 = 0commits = len(git_output("log --oneline").splitlines())
assert h1 == commits, f"h1: count the lines of git log --oneline; there are {commits}, not {h1}."
assert h2 == "bread", "h2: run git show on that commit, and find the item on its - line."
assert (h3, h4) == (1, 1), (
"h3 and h4: git show HEAD shows one line removed (-) and one added (+), as a changed line."
)
print("passed")4. Ignoring files¶
Run the next cell. It makes the kinds of files that collect in a project folder: Python’s
cache, a virtual environment, and two logs, one of them in a folder. (They are stand-ins, with
almost nothing in them.) --untracked-files=all makes git status list every file inside an
untracked folder, not only the folder.
write("__pycache__/shopping.cpython-312.pyc", "(stand-in for a cache file)\n")
write(".venv/pyvenv.cfg", "(stand-in for an environment)\n")
write("debug.log", "(stand-in for a log)\n")
write("logs/monday.log", "(stand-in for a log)\n")
git("status --short --untracked-files=all")Exercise L10.4 (LO-10.2, ★★, about 15 minutes)¶
In the first cell below, write the repository’s
.gitignore, so that Git ignores every__pycache__folder, the.venvfolder, every file whose name ends in.log, wherever it is, andnotes.txt. Running the cell saves the file.In the second cell, stage
.gitignore, and commit it with a message of your own.
When you are done, git status reports nothing to commit.
Hint
Four lines: a folder’s name ends with /, and * matches any characters. git check-ignore -v followed by a path tells you which line ignores it.
%%writefile scratch/lab10/.gitignore
# Write the patterns here, in place of this line.# Write your git(...) lines here.for path in ["__pycache__/shopping.cpython-312.pyc", ".venv/pyvenv.cfg", "debug.log",
"logs/monday.log", "notes.txt"]:
assert run_git(["check-ignore", "--no-index", "-q", path])[1] == 0, f"{path} isn't ignored yet."
for path in ["shopping.py", "prices.txt", ".gitignore"]:
assert run_git(["check-ignore", "--no-index", "-q", path])[1] == 1, (
f"{path} is ignored, but it belongs in the project. Make the patterns narrower."
)
assert ".gitignore" in git_output("ls-files").split(), "Stage and commit .gitignore."
assert git_output("status --porcelain") == "", (
"git status lists changes still to commit:\n" + git_output("status --short")
)
print("passed")5. A commit message¶
The list’s last line says You need 1 items. when the list has one item. The cell after the
check fixes that line, so it says You need 1 item. for one item and You need 4 items. for
four, and commits the fix with the message you write here.
Exercise L10.5 (LO-10.2, ★★, about 10 minutes)¶
Write the commit’s message as two strings, following the conventions in the reading:
summary: what the commit does, as an instruction (“Fix …”, “Say …”), in 50 characters or fewer, without a period at the end;body: a sentence or two on why the change was needed, which the summary doesn’t say.
summary = "..."
body = "..."words = summary.split()
assert len(words) >= 3, "summary: say what changed, in at least three words."
assert len(summary) <= 50, f"summary: keep it to 50 characters; it has {len(summary)}."
assert not summary.endswith("."), "summary: leave out the period at the end."
first = words[0].lower()
not_instructions = {"fixes", "adds", "changes", "makes", "says", "prints", "corrects", "updates"}
assert not first.endswith(("ed", "ing")) and first not in not_instructions, (
f"summary: start with an instruction, such as 'Fix' or 'Say', not {words[0]!r}."
)
assert "item" in summary.lower(), "summary: name what it fixes: the count of items."
assert len(body.split()) >= 8, "body: explain why, in at least a full sentence."
assert body != summary, "body: say why, which the summary doesn't."
print("passed")Run the next cell. It makes the change, commits it with your message, and shows the commit.
Git puts a blank line between the summary and the body, as it does for two -m options in a
terminal.
write("shopping.py", read("shopping.py").replace(
'print(f"You need {len(ITEMS)} items.")',
'if len(ITEMS) == 1:\n'
' print("You need 1 item.")\n'
'else:\n'
' print(f"You need {len(ITEMS)} items.")',
))
git(["commit", "-a", "-m", summary, "-m", body])
git("show HEAD")6. A README¶
Run the next cell to see what the program prints now. It runs shopping.py from the
repository’s folder, as python shopping.py would in a terminal there.
PRINTED = subprocess.run([sys.executable, "shopping.py"], cwd=REPO, capture_output=True,
text=True).stdout
print(PRINTED, end="")Exercise L10.6 (LO-10.3, ★★, about 15 minutes)¶
In the first cell below, write a
README.mdfor the project that tells a stranger what it does and how to run it. It needs:a
#title on its first line;a sentence that says what the program does;
a
##section whose heading has the word “run” in it, such as## How to run, with the commandpython shopping.pyin a fenced code block, and then a second fenced block with what it prints, copied from the cell above.
In the second cell, stage and commit it.
Markdown needs a blank line before each heading’s text, each list, and each fenced block.
%%writefile scratch/lab10/README.md
# Write the README here, in place of this line.# Write your git(...) lines here.readme = read("README.md")
lines = readme.splitlines()
assert lines and lines[0].startswith("# "), "Start the README with a title: # and a space."
assert len(lines) > 1 and any(len(line.split()) >= 5 and not line.startswith(("#", "`"))
for line in lines), "Add a sentence that says what it does."
sections = [line for line in lines if line.startswith("## ") and "run" in line.lower()]
assert sections, "Add a section whose heading, starting with ##, has the word run in it."
blocks = readme.split("```")[1::2]
assert any("python shopping.py" in block for block in blocks), (
"Put the command python shopping.py in a fenced block: a line of three backticks before "
"it, and one after."
)
for line in PRINTED.splitlines():
assert any(line in block for block in blocks), (
f"Show what the program prints in a fenced block; {line!r} is missing."
)
assert "README.md" in git_output("ls-files").split(), "Stage and commit README.md."
assert git_output("status --porcelain") == "", (
"git status lists changes still to commit:\n" + git_output("status --short")
)
print("passed")7. Pushing to a remote¶
The setup cell made scratch/lab10-remote.git, a bare repository: one with a history but no
working tree, which is the kind GitHub keeps. It stands in for GitHub here, so you can push
without an account or a network connection; the commands are the same. Its address, from the
project’s folder, is the relative path ../lab10-remote.git.
Exercise L10.7 (LO-10.3, ★, about 10 minutes)¶
In the next cell, add the bare repository as a remote named origin, and push main to it, so
that later pushes need no names. Then list the remotes, to check the address.
# Write your git(...) lines here.url = git_output("remote get-url origin").strip()
assert url.replace("\\", "/").endswith("lab10-remote.git"), (
"Add the remote with remote add, the name origin, and the address ../lab10-remote.git."
)
local = git_output("rev-parse main").strip()
remote = git_output("rev-parse main", folder=REMOTE).strip()
assert local == remote, "The remote doesn't have your latest commit yet: push main to origin."
assert git_output("rev-parse --abbrev-ref main@{upstream}").strip() == "origin/main", (
"Push with -u, so that main remembers origin/main and a plain git push works later."
)
print("passed")Run the next cell. It clones the remote, as a stranger would clone your repository from GitHub, and lists what they get: every committed file, and none of the ignored ones.
git("clone lab10-remote.git lab10-clone", folder=SCRATCH)
print(sorted(name for name in os.listdir(CLONE) if name != ".git"))
git("log --oneline", folder=CLONE)8. Undoing mistakes¶
Run the next cell. It makes two mistakes: it saves shopping.py with almost everything in it
deleted, and it replaces the README with the word “TODO” and stages that.
write("shopping.py", "ITEMS = []\n")
write("README.md", "TODO\n")
git("add README.md")
git("status")Exercise L10.8 (LO-10.4, ★★, about 10 minutes)¶
Neither mistake was committed. In the next cell, put both files back as they are in the last
commit. Read the hints that git status printed above.
# Write your git(...) lines here.assert git_output("diff --staged --name-only") == "", (
"A change is still staged. Take it out of the staging area with restore --staged."
)
assert git_output("diff --name-only") == "", (
"A file still differs from the last commit. Discard the change with restore."
)
print("passed")Run the next cell. It commits a change that lists the items from Z to A, and pushes it, before anyone notices that the list is harder to use that way.
write("shopping.py", read("shopping.py").replace("sorted(ITEMS)", "sorted(ITEMS, reverse=True)"))
git('commit -a -m "List the items from Z to A"')
git("push")Exercise L10.9 (LO-10.4, ★★, about 10 minutes)¶
The commit is pushed, so undo it with a new commit that reverses it, using Git’s message for that commit, and push the result.
# Write your git(...) lines here.messages = git_output("log --format=%s").splitlines()
assert messages[0] == 'Revert "List the items from Z to A"', (
"The latest commit should be the one revert makes, with Git's message."
)
assert "List the items from Z to A" in messages, "The history should keep the commit you undid."
assert "reverse=True" not in read("shopping.py"), "shopping.py still sorts from Z to A."
pushed = git_output("rev-parse main", folder=REMOTE).strip()
assert git_output("rev-parse main").strip() == pushed, "Push the revert, so the remote has it too."
print("passed")9. A branch¶
The next change gives each item a quantity: two eggs, six apples. You’ll make it on a branch,
so that main keeps working until the change is finished.
Exercise L10.10 (LO-10.4, ★★★, about 15 minutes)¶
This exercise has three cells for your commands, with a cell of ours between each two.
In the first cell, create a branch named
quantitiesand switch to it. The cell after it writes the newshopping.py.In the second, commit the change on your branch, with a message of your own, and switch back to
main. The cell after it makes a commit onmainthat adds a line to the README, so the two branches have each moved on.In the third, merge
quantitiesintomain, and delete the branch, which is no longer needed.
# Write your git(...) lines here.write("shopping.py", '''"""Print a shopping list, with quantities, and count the items."""
ITEMS = {"apples": 6, "eggs": 2, "milk": 1, "rice": 1}
for item in sorted(ITEMS):
print("-", ITEMS[item], item)
if len(ITEMS) == 1:
print("You need 1 item.")
else:
print(f"You need {len(ITEMS)} items.")
''')
git("status --short")# Write your git(...) lines here.git("branch --show-current")
write("README.md", read("README.md") + "\nThe program needs only Python's standard library.\n")
git("add README.md")
git('commit -m "Say that the list needs no packages"')# Write your git(...) lines here.assert git_output("branch --show-current").strip() == "main", "Switch back to main."
assert '"apples": 6' in read("shopping.py"), (
"shopping.py on main doesn't have the quantities: commit them on the branch, then merge it."
)
assert "needs only Python's standard library" in read("README.md"), (
"The README lost the commit made on main. Run the setup cell again and start over."
)
parents = git_output("rev-list --parents -n 1 HEAD").split()
assert len(parents) == 3, (
"The latest commit should be a merge commit, with two parents: merge quantities into main."
)
assert git_output("log -1 --format=%s").strip() == "Merge branch 'quantities'", (
"Use the message Git writes for the merge."
)
assert git_output("branch --list quantities") == "", "Delete the branch with branch -d."
print("passed")Run the next cell to see the shape of the history: the branch’s commit and the README’s commit, joined by the merge commit at the top.
git("log --oneline --graph")Summary¶
In this lab you:
made a repository, and chose what went into its first commit with
git add;predicted whether a file was untracked, modified, or staged, and saw that a commit records the staging area;
read a project’s history with
git logandgit show;ignored generated files and personal notes with
.gitignore;wrote a commit message with a summary and a body;
wrote a README that tells a stranger what the project does and how to run it;
pushed to a remote, and cloned it as a stranger would;
restored a file, unstaged a change, and reverted a pushed commit; and
made a change on a branch and merged it into
main.
Next, the Module 10 practice has you do the same in a real terminal, and publish a project on GitHub.