Introduction
Without version control, a project's history lives in folders named final, final2 and final-really. Mistakes are hard to undo, and two people editing the same files overwrite each other's work. Version control records every saved version of every file, with who changed it and why, so you can compare versions, go back to one that worked, and combine the work of many people safely. Git is the version control system used by almost every software project, and GitHub is the most popular place to share Git repositories.
This course teaches the Git commands and, in every exercise, the ideas behind them, which you write as small Python programs: you will compute real Git object hashes, diffs, merges and rebases yourself.
How it works
A repository is a project folder plus its history. Git keeps the history in a hidden .git folder inside the project; the files you see and edit are the working tree.
A commit is a snapshot of the whole project at one moment, with an author, a date and a message. Git does not store "what changed"; it stores the full snapshot and works out the differences when you ask. Commits form a history: each one remembers the commit before it, its parent.
Git is distributed: every copy of a repository, on every developer's computer, contains the full history. You can commit, compare and browse without a network, and any copy can restore the others.
The first commands:
git config --global user.name "Ada Lovelace"
git config --global user.email "ada@example.com" # recorded in every commit you make
git init # turn the current folder into a repository
git status # what has changed since the last commit?
git log --oneline # the history, newest first, one line per commit
A good commit message has a short first line (the subject), around 50 characters or fewer, written as a command: "Add search to the notes page", not "added stuff". If more explanation is needed, leave a blank line and write a body, wrapped at about 72 characters, saying why the change was made.
Example
history = []
def commit(files, message):
history.append({"files": dict(files), "message": message})
print(f"commit {len(history)}: {message} ({len(files)} file{'s' if len(files) != 1 else ''})")
def changes(old, new):
added = sorted(set(new) - set(old))
removed = sorted(set(old) - set(new))
modified = sorted(f for f in set(old) & set(new) if old[f] != new[f])
return added, removed, modified
project = {"README.md": "# Notes\n"}
commit(project, "Start the project")
project["tasks.txt"] = "buy milk\n"
commit(project, "Add a to-do list")
project["tasks.txt"] = "buy milk\nwrite report\n"
commit(project, "Add a task")
del project["README.md"]
commit(project, "Remove the readme")
print("history, newest first:")
for number in range(len(history), 0, -1):
print(f" {number} {history[number - 1]['message']}")
version2 = history[1]["files"]
print("files in commit 2:", sorted(version2))
print("tasks.txt in commit 2:", repr(version2["tasks.txt"]))
added, removed, modified = changes(history[1]["files"], history[3]["files"])
print("from commit 2 to commit 4: added", added, "removed", removed, "modified", modified)Line by line
commitstores a copy of all the project's files with a message, like a Git commit.- Four commits record the project growing and then losing its README.
- The history is printed newest first, the way
git logshows it. - Any old snapshot can be looked at in full: commit 2 had two files.
- Comparing two snapshots tells us what was added, removed or modified between them.
Expected result
commit 1: Start the project (1 file)
commit 2: Add a to-do list (2 files)
commit 3: Add a task (2 files)
commit 4: Remove the readme (1 file)
history, newest first:
4 Remove the readme
3 Add a task
2 Add a to-do list
1 Start the project
files in commit 2: ['README.md', 'tasks.txt']
tasks.txt in commit 2: 'buy milk\n'
from commit 2 to commit 4: added [] removed ['README.md'] modified ['tasks.txt']
In the real world
Git was written in 2005 by Linus Torvalds to manage the Linux kernel, which now has over a million commits from tens of thousands of people. Companies keep all their code, and often their documentation and configuration, in Git. GitHub, GitLab and Bitbucket host repositories and add code review, issue tracking and automation on top.
Common mistakes
- Committing with a vague message such as "update", which makes the history useless later.
- Forgetting to set user.name and user.email, so commits carry the wrong identity.
- Running git init inside a folder that is already part of a repository, creating a confusing nested repository.
- Saving many unrelated changes in one commit, which makes them hard to review or undo separately.
Best practices
- Run
git statusoften; it tells you exactly what Git sees. - Commit small, complete steps, each with a clear message.
- Write the subject line as a command in the present tense: "Fix", "Add", "Remove".
Summary
Version control keeps the full history of a project. Git stores it in the repository's .git folder as commits, each a snapshot of the whole project with an author and a message, linked to its parent. git init creates a repository, git status shows what has changed, and git log shows the history.
Quick check
Key takeaways
- Git saves snapshots of the whole project, called commits, each with a message explaining it.
- git status tells you what has changed; git log shows the history.
- Good commit messages say what changed and why, in a short first line.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.