Tutorial Goals

In this tutorial, we will learn the basics of using Git via the command line.
We’ve already been using this under the hood in CS1010, so now we’ll reveal the magic!
We’ll first start by going through the everyday workflow of using Git, then we’ll explore the
underlying mental model of Git, to handle more complex situations with confidence.
We promise you that this will be helpful for the rest of your careers.

At the end of the tutorial, you should be able to:

  1. Perform everyday Git operations using the command line
  2. Use commits and branches to find and recover saved work
  3. Push the intended branch and verify the result

Work through the required path and graded task first. The optional sections afterwards
explore Git’s objects, three-way merges, and remote branches in more detail.

A horror story

John just spent hours working on his assignment.
He finally pushed to GitHub to show his TA…
but his changes weren’t there.

Confused, John asked an AI agent for help,
but he couldn’t explain what had gone wrong.
The agent did exactly what he asked,
and soon his code was gone from his computer too.
Defeated, he started rewriting everything from scratch.
Little did he know
that his code was there all along.

Anyone can memorize add/commit/push.
But the day Git does something you didn’t expect,
memorized commands won’t save you.
You’ll end up like John.
Don’t be like John.
Understanding how Git actually works
is what lets you stay calm and find your code.
That’s what this tutorial is about.
By the end, you’ll know exactly what happened to John,
and you’ll fix it yourself.

Introduction

Warning

This tutorial shows you what Git can do,
not necessarily what you should do.
The emphasis here is on conceptual understanding and technical capability,
not organisational best practices.
Those best practices will be covered in your Software Engineering modules later on.

In CS1010, we’ve already been using Git and GitHub!
GitHub stores all your Volume code,
and the cs1010 TUI runs the Git commands that save and submit your work.
Git is good for managing code
because it allows us to keep track of changes
and revert to previous versions if needed.

Git vs GitHub

Git vs GitHub is just like… videos vs YouTube.1
Git is a version control system that runs on your computer.
GitHub is a web-based platform that hosts Git repositories.
You can use Git without GitHub,
but you can’t use GitHub without Git.

I only want to save changes to a file, so why is Git so complicated?

assets/git/git.png

Many people only learn a small subset of Git commands
(init/clone/add/commit/push + branch/switch/merge/rebase).
That’s enough for common cases.
However, when things go wrong,
if you only memorize the basics, you’ll be stuck.
By understanding Git’s underlying model,
you’ll have the tools to handle the tricky 20% of situations with confidence.

Resource

If you’re satisfied with just learning the commands,
you may find the following resource handy: https://ohshitgit.com

Getting Started

Go to https://code.cs1010.org, and use the CS1010 WebTop environment,
not Tut 10: Git.
The exercises push to GitHub,
which only the CS1010 WebTop can reach.

Clone your tutorial repository,
replacing <your-username> with your GitHub username
(for example, tutorial-10-WhyAre):

git clone https://github.com/cs1010-ay2627/tutorial-10-<your-username>.git
cd tutorial-10-<your-username>

Before you start

Check that you are inside your tutorial repository, not another project:

pwd
git status
git remote -v

If cloning fails, or Git asks for credentials or an identity you have not set up,
ask your TA to check the environment. Do not paste tokens into commands or change
unrelated repositories to make the exercise work.

Basic workflow

Here is how you would typically use Git in your daily development:

  1. Make changes to files
  2. Create a save point (git add + git commit)
  3. (Optional) Push (git push) the commit to a remote repository

Creating commits

We’ll first start by learning how to create commits.
Commits are like save points in a game.
They are useful for saving your progress, so that you can revert to them later if needed.

Creating commits is a two-step process:

  1. Decide which file (or part of a file) to include in the commit
  2. Create the commit

Three places, three different states

Your working tree is the files you are editing.
The index holds the versions you have selected for the next commit.
A commit records a saved snapshot.
Editing a file after git add does not automatically change the staged version:
use git diff for unstaged changes and git diff --staged for staged changes.

Deciding what to include in the commit

Before creating a commit, we need to decide which files (or parts of files) to include in the
commit.
This is done by adding files to the staging area, more formally known as the index.

An Analogy

You can think of the index as a shopping cart. You can add items (files) to your cart (index), review them, and then proceed to “pay” (create the commit).

The command to add files to the staging area is git add. The syntax is as follows:

git add <files...>

You can specify multiple files separated by spaces:

git add file1.txt file2.txt

  1. Fix main.c by adding #include <stdio.h> to the top of the file

  2. Add main.c to the index
    (this tells Git to include main.c in the next commit):

    git add main.c
  3. Verify that main.c is staged using:

    git status
  4. View the staged changes using:

    git diff --staged
  5. (Optional) If you made a mistake, you can unstage the file using:

    git restore --staged main.c

Please always verify what you’re about to commit using git status and git diff --staged.

Warning

Please be very very very very careful when restoring files.
git restore --staged main.c unstages the file without changing your working copy.
Without --staged, git restore main.c replaces your working copy with the version in the index,
discarding any unstaged changes to that file.
A change you have already staged is not automatically lost by this command.
Read git status and git diff first: Git cannot reliably recover work it never saved.

Note

There are a lot of people who will mindlessly type this:

git add .

This is a surefire way to commit unwanted files. It’s okay to use this command, just verify what you’re about to commit first.

Creating the commit

Once you have staged the files you want to include in the commit, you can create the commit using
git commit. The syntax is as follows:

git commit -m "<commit-message>"

The commit message is just a short description of what changes were made in this commit, so that
you (and other developers) can understand it later.

Once you have staged (and verified) the files you want to include in the commit,
create the commit:

git commit -m "Update main.c"

View the commit you just created:

git log

Tip

There are some conventions to writing “good” commit messages.

  1. https://cbea.ms/git-commit
  2. Conventional commits: https://www.conventionalcommits.org/en/v1.0.0/

Push the commit to a remote repository

Once you have created a commit, you may want to push it to a remote repository (e.g., GitHub).
This is done using git push.

We’ll explore the various options of git push later on.
For now, push your commit to the remote repository:

git push origin main

Verify the commit is in the remote repository by visiting the GitHub page for your repository.

Checkpoint: saved here or on GitHub?

What is the difference between editing a file, committing it, and pushing it?
Before moving on, verify your new commit on GitHub. A successful local commit
alone does not mean that GitHub has it.

If git log opens a pager, press q to return to the terminal.

Directed Acyclic Graph… what?

Let’s explore how Git stores our save points (commits) under the hood.
It is inevitable that you will encounter the term “DAG” when reading about Git.
DAG stands for Directed Acyclic Graph.
For the purposes of understanding Git, it is not necessary to know what a DAG is.

You can think of a DAG as a linked list, but each node can point to multiple parent nodes.
In Git, each node represents a commit, and each commit points to its parent commit(s).

Tip

Since each commit points to its parent commit(s), the arrows point in the opposite direction of time.

Let’s observe the DAG for ourselves:

Run the following command (the mnemonic is “ago”):

git log --all --graph --oneline

(The graph you see may look different from the one above)

For now, focus on the commits and the branch names beside them.
You don’t need to inspect Git’s internal objects to recover a commit;
we’ll explore those in the optional section.

Branches

The hash of a commit is not very memorable.
To make things easier, we use branches as human-friendly names for commits.
In this tutorial, the default branch is called main.
You may see master in older repositories; branch names are not fixed by Git.

Branches also allow for parallel development.
You may want to experiment on some feature without affecting the main codebase.

Where you currently are: HEAD

HEAD is a special pointer that refers to your current position in the DAG.
Usually, HEAD refers to the current branch, which points to its latest commit.
When you commit, that branch moves forward. Other branches do not automatically move with it.

You can use HEAD in-place of a commit hash.

Try:

git cat-file -p HEAD

Creating and switching branches

You can create a new branch using git branch.
The following command creates a new branch called <branch-name> that refers to the commit at
<commit>:

git branch <branch-name> <commit>

If the <commit> is omitted, the new branch will refer to HEAD.

You can use git switch to switch branches.
The syntax is as follows:

git switch <branch-name>

Tip

Some older tutorials may suggest using git checkout to switch branches.
While it works, the modern and more aptly named command is git switch.

  1. Create a new branch called feature:

    git branch feature
  2. Switch to the feature branch:

    git switch feature

You can create and switch to a new branch in one command using the -c flag:

git switch -c another-feature

Merging changes

Your history diverges when you work with multiple machines,
or when a teammate commits alongside you.

Fast-forward merge

The first type of merge is known as the fast-forward merge.
This happens when the latest common ancestor is the same as the latest commit of one of the
branches.
The diagram below shows a fast-forward merge of B1 into the current branch (denoted by HEAD).

The syntax of the command is as follows:

git merge <branch-name>

In the case of a fast-forward merge, git will simply make the current branch point to the latest
commit of the other branch.

  1. Make sure you’re on the feature branch
    (the previous exercise left you on another-feature):

    git switch feature

    Then make a small change to main.c,
    such as adding a comment at the top of the file

  2. Stage and commit the change, as you did earlier:

    git add main.c
    git commit -m "Update main.c on feature"

    This moves feature one commit ahead of main,
    which is the situation in the diagram above

  3. Switch back to the main branch:

    git switch main
  4. View the DAG:

    git log --all --graph --oneline
  5. Merge the feature branch into main:

    git merge feature
  6. View the DAG again to observe the changes:

    git log --all --graph --oneline

Checkpoint: which branch are you pushing?

Suppose you commit on feature, but run git push origin main.
Does that send your new feature commit? Find both branch names in the graph
before answering.

A push names the branch to send; it does not mean “send whatever I am looking at”.
After merging into main, push main and verify the result on GitHub.

When things don’t go as expected

Start with inspection, not with commands that throw work away:

git status
git log --all --graph --oneline
git remote -v
  • Git refuses to switch or merge because of local changes: inspect git diff.
    Preserve work you care about before proceeding. Ask your TA if you are unsure.
  • A push is rejected: this does not mean your local commits disappeared.
    Do not force-push to make the error go away. Ask your TA, or work through the
    optional remote-branches exercise below.
  • A merge reports conflicts: do not guess at a destructive fix.
    If you started with a clean working tree, git merge --abort is the way to
    abandon an in-progress conflicted merge. Ask your TA before continuing.
  • An editor opens for a commit message: save and exit the editor to finish.
    If you do not recognise the editor, ask your TA rather than closing the whole environment.

Graded Task(s)

Remember John?
Just like John, Bob yeeted his argmax implementation in a similar way.
John managed to vibe his code back,
so he has no idea how he did it and can’t help.

Now Bob is sadly rewriting his code from scratch.
You walk past and see him coding it all again.
After this tutorial, you know exactly how to get his code back.

You may be tempted to just fix Bob's code

There is a correct version of the code somewhere in the Git logs;
you just have to find it.
This is a disposable recovery exercise: Bob’s current uncommitted attempt is deliberately incomplete.
Inspect it with git diff before deciding to discard it. Do not apply that advice
to your own unsaved work in other repositories.

Switch to the Tut 10: Git Environment

Go to https://code.cs1010.org, and use the environment Tut 10: Git.
Then navigate to the Git repository at ~/tutorial-graded before starting.
Unlike the earlier GitHub practice repository, this exercise uses a local bare
repository as its remote. Check git remote -v: a remote does not have to be on GitHub.

  1. Find the existing commit containing Bob’s working implementation of argmax
  2. Recover that snapshot on main, without rewriting the implementation
  3. Push the recovered main to the remote

The checker expects the same complete tracked-file snapshot as the recovered commit.
Do not reformat the code, edit other tracked files, or add extra tracked files.
This is a Git recovery task, not another C programming task.

Before you leave: verify your progress

Run this command inside your Tutorial environment:

progress

It shows whether you have successfully completed the tutorial and which
individual tasks have been recorded as complete.

The progress command is available only inside a Tutorial environment, not in
the general CS1010 WebTop environment.

Before you leave: explain the recovery

Where was Bob’s code? Why did his earlier push not send it?
What changed on main, and what evidence shows the recovery reached the remote?

If the push succeeds but progress is incomplete, read the checker output.
A successful push and a correct recovery are two different things; ask your TA
if the expected snapshot is unclear.

Optional: looking further under the hood

The required recovery task is complete. The following sections extend the model;
they are not prerequisites for the graded task.

Return to CS1010 WebTop and your original tutorial-10-<your-username>
practice repository, not ~/tutorial-graded. Start on main, with no uncommitted
changes. The three-way merge and remote exercises continue from the fast-forward
merge above, so work through them in order if you choose to do them.

Everything is an object (Extra)

Just like how every variable in C has a memory address, every piece of data in Git has a hash.
Once again, you don’t need to understand how hashing works for now, but just know that the hash is
a unique identifier for that piece of data.

You can use git cat-file -p to view the contents of any Git object. The syntax is as follows:

git cat-file -p <hash>

Commits

Now, let’s explore what a commit actually stores.
We’ll use git cat-file -p to view the contents of a commit.

Assume that the commit hash is 9439e85.
The output of the following command:

git cat-file -p 9439e85

may look something like this:

tree c4acbb0c9423ce24ea821ca1df14e8b77b39fbcd
parent 3929f247f68da95410694caad3ba85b29b618dff
author John <john@iusenano.com> 1761550724 +0800
committer John <john@iusenano.com> 1761550724 +0800

This is a commit message
  1. tree: Directory listing of files in this commit (State of the project at this commit)
  2. parent: Parent commit (previous save point)
  3. author/committer: Who made the commit and when
  4. Commit message

As we’ve mentioned earlier, you can use git cat-file -p to view Git objects.

  1. View the latest commit hash (e.g., 9439e85):

    git log --oneline
  2. Run the following on the latest commit hash to view its contents:

    git cat-file -p <hash>
  3. Run the same command on the tree hash
    to view the directory listing of files in this commit

  4. Run the same command on the files in the directory listing to view their contents

Commits are snapshots, not diff (Extra)

For those that have interacted with Git before, it may feel like Git is storing diffs between
files.
But in reality, Git stores snapshots of the entire project.

You should really be associating commits to zip files of your project at that point in time.
There’s this really nice blogpost by GitHub:
https://github.blog/open-source/git/commits-are-snapshots-not-diffs/

Three-way merge (Extra)

The second type of merge is known as the three-way merge.
It generalises the fast-forward merge to handle the case where both branches have diverged.

The command to do a three-way merge is the same as fast-forward merge, the type of merge is
determined by the state of the DAG.

A three-way merge will create a new commit that combines the changes from both branches.
Looking at the diagram above, this new commit will be pointing to two commits.
This is known as a merge commit.

  1. You’re still on main from the previous exercise.
    Make a small change to main.c,
    such as editing the comment you added

  2. Stage and commit the change:

    git add main.c
    git commit -m "Update main.c on main"
  3. Switch to the feature branch:

    git switch feature
  4. Make a small change to README.md.
    Use a different file from step 1
    so that Git can combine the two changes without a conflict

  5. Stage and commit the change:

    git add README.md
    git commit -m "Update README.md on feature"

    main and feature now each have a commit the other doesn’t,
    which is the situation in the diagram above

  6. Switch to the main branch:

    git switch main
  7. View the DAG:

    git log --all --graph --oneline
  8. Merge the feature branch into main:

    git merge feature

    (An editor may pop up to ask for a commit message for the merge commit;
    just save and exit the editor to proceed)

  9. View the DAG again to observe the changes:

    git log --all --graph --oneline

If git merge results in a fast-forward merge, can you force it to do a three-way merge instead?

Tip

(Some implementation detail about three-way merges) In a three-way merge, Git looks at the latest common ancestor of the two branches being merged, and compares the changes made in each branch since that ancestor (remember a commit stores the state of the repository, and not changes). It then combines these changes to create a new commit using an algorithm.

(The word “algorithm” is used when programmers don’t want to explain what they did.)

Rebase (Extra)

Rebase is a way of combining changes, which results in a linear history.

The syntax of the command is as follows:

git rebase <branch-name>

Rebase works by replaying the commits (by converting snapshots into diffs) from one branch onto
another branch.
It is very important to understand that new commits are created during a rebase, as opposed to
moving existing commits.
In the diagram above, the commits A and A' are different commits, even though they contain
the same changes
.

Tip

It is confusing to know which branch will be at the base after the rebase.
The branch specified in the command will be at the base,
and the current branch will be replayed on top of it.

In the diagram above, HEAD is on the branch with commit A,
and we run git rebase B1.
B1 stays where it is,
and A is replayed on top of B1 as A'.

Similarly, if you are on feature and run git rebase main,
main stays where it is,
and the commits on feature are replayed on top of main.

Interacting with remote repositories (Extra)

Just more branches

At its core, you’re just dealing with more branches.
fetch and push sync branches between your repository and the remote.
Everything else is the same branch work you’ve already done locally.

A remote is a version of your repository hosted on the Internet or network.
In our course, we’re using GitHub.
There are other Git hosting services such as GitLab and Bitbucket.

Just like how branches are human-friendly names for commits, remotes are human-friendly names for
URLs of remote repositories.
By convention, the name of a remote is called origin.

View your remotes using:

git remote -v

Type of branches

Up to now, we haven’t distinguished between the different types of branches.
However, it is important to do so when dealing with remote repositories.

There are three types of branches to be aware of:

  • Local branches: These are the branches we were using so far
  • Remote branches: Branches in the remote repository
  • Remote-tracking branches: These are local references recording the last-known positions of remote branches

View all branches (including remote-tracking branches) using:

git branch -av

The branches prefixed with remotes/origin/ are remote-tracking branches, and the rest are local branches. You can’t directly see the remote branches.

Can you identify the remote-tracking branches in the DAG?

Fetch

git fetch copies GitHub’s new commits into your graph,
then moves your remote-tracking branches to match GitHub’s branches.

One of the rare times you’ll interact with the remote repository using GitHub.

  1. Go to your repository on GitHub and open main.c.
    Edit it with the pencil icon,
    then commit the change directly to main.
    GitHub’s main now has a commit that your repository doesn’t know about

  2. Back in your terminal, check your status:

    git status

    Git says your branch is ahead of origin/main,
    and says nothing about the commit you just made on GitHub.
    That’s because git status only compares against your snapshot of GitHub,
    and that snapshot is out of date

  3. View the DAG:

    git log --all --graph --oneline

    Notice that your remote-tracking branch (origin/main) has not moved

  4. Update your remote-tracking branches:

    git fetch
  5. View the DAG again:

    git log --all --graph --oneline

    Notice that origin/main now points to the commit you made on GitHub.
    main and origin/main have diverged,
    just like main and feature did before the three-way merge

  6. Check your status again:

    git status

    Git now says your branch and origin/main have diverged

Push

A push transfers the needed objects and asks the remote to update the named branch.
Normally, updating an existing remote branch is allowed only if it is a fast-forward:
its current commit must be an ancestor of the commit you are sending.
The remote does not create a merge commit for you.

The syntax of the command is as follows:

git push <remote-name> <branch-name>

Tip

Previously, you pushed your commit to the remote repository using:

git push origin main

Hopefully you now understand what that command does in more detail.

If you’ve been playing along, push your changes to the remote repository using:

git push origin main

It should fail.

Can you figure out why it failed?
How do you reconcile the differences?

Pull

Pull fetches and then integrates changes. Depending on options and configuration,
it may merge, rebase, or allow only a fast-forward. Do not assume that every
git pull uses the same integration method.

For this exercise, use the two steps we have already explored explicitly:

git fetch origin
git merge origin/main

Start with a clean working tree. If the merge reports a conflict, ask your TA;
git merge --abort abandons the in-progress merge. Once the merge succeeds,
push main again and verify the result on GitHub.

The syntax of the command is similar to git push:

git pull <remote-name> <branch-name>

Going Further (Extra)

  • Practise branching and merging at https://learngitbranching.js.org/
  • Try a TUI Git client such as lazygit,
    gitui, or tig
  • Rewrite history with interactive rebase
  • Copy commits from another branch with cherry-pick
  • Check out multiple branches at once with worktrees

Footnotes

  1. Thought it was going to be something else? ↩