Lesson 12 of 18Your tools
Git Basics
Save snapshots of your work, read diffs and history, branch and merge safely, undo local mistakes, and share code through GitHub.
Every software team on earth uses version control, and almost all of them use Git. It is how you undo a bad change from last Tuesday, how five people edit the same project without overwriting each other, and how your code gets reviewed before it ships. Your GitHub profile is also the first thing many recruiters look at, so a tidy history of real commits is part of your CV.
Why version control
Without it, projects end up as final.py, final-v2.py, final-v2-REAL.py. You cannot tell what changed between them, and two people editing at once means someone's work gets lost.
Version control records the history of a project as a series of snapshots. Each snapshot is a commit: the full state of every tracked file at one moment, plus who made it, when, and a message saying why. You can look at any old commit, compare two of them, or go back.
Git is distributed: every copy of a project (a repository, or repo) has the complete history, so you can work offline and nothing depends on one central computer. GitHub (and GitLab, Bitbucket) is a website that hosts a shared copy of your repo and adds collaboration tools on top. Git is the tool; GitHub is a place to put Git repos.
The three areas
Git keeps your work in three places on your machine, and a fourth online:
The working tree is the normal folder you edit. Git notices changes but does not save anything yet.
Why a staging area? It lets you commit part of your work. Say you fixed a bug and also started a new feature. You stage and commit just the bug fix with a clear message, and keep working on the feature. Small, focused commits are much easier to review and to undo.
Your first commits
Tell Git who you are, once per machine:
git config --global user.name "Ada Example"git config --global user.email "ada@example.com"git config --global init.defaultBranch mainThen, inside a project folder:
git init # start tracking this folder (creates .git/)git status # what changed? what is staged? (run this constantly)git add main.py # stage one filegit add . # stage every change in this foldergit commit -m "Add note saving" # snapshot what is stagedgit log --oneline # list commits, newest firstgit diff # changes not yet stagedgit diff --staged # changes staged for the next commitgit restore main.py # throw away unstaged edits to a file (careful)git status is your best friend. It tells you what is modified, what is staged, and usually suggests the next command.
You edited main.py in a brand new project. Put the commands in order to make your first commit and see it.
- Tap the steps below in the right order.
Configure Git once, properly
The three git config lines above are the minimum. A few more save real pain, and knowing where settings live helps when something behaves oddly.
Git reads settings from three levels, and the most specific wins: system (for every user on the machine), global (you, in ~/.gitconfig), and local (one repo, in .git/config). --global writes to your file; leaving it out writes to the current repo only.
git config --global core.editor "code --wait" # open VS Code for messages, not Vimgit config --global init.defaultBranch main # new repos start on main, not mastergit config user.email "ada@company.com" # this repo only: your work emailgit config --list --show-origin # every setting and the file it came from--wait matters: it tells VS Code not to return until you close the tab, so Git waits for your message. Without it Git sees an empty message and aborts the commit. The per-repo email is how you keep work commits under your work address while personal projects use your own.
Why set init.defaultBranch? Plain git init still names the first branch master unless you configure it, while GitHub creates main. Mixing the two is how people end up pushing a branch nobody expected.
Line endings are the one setting that differs on Windows. Windows text files end lines with \r\n, macOS and Linux with \n. Git for Windows' installer usually sets core.autocrlf true, which converts on the way in and out. Inside WSL, leave it unset, because you are on Linux. The more reliable fix lives in the repo, so it applies to everyone regardless of their settings:
* text=auto eol=lf
*.png binaryIf you have ever opened a pull request where every line of a file shows as changed but nothing looks different, mismatched line endings were the cause.
Commits Your Teammates Thank You For (in Engineering at Work) adds the settings experienced engineers turn on next, such as pull.rebase, push.autoSetupRemote and rerere, and explains each one.
What a commit really is
Each commit gets an ID: a 40-character hash like a1b2c3d…, usually shortened to the first 7. Git computes it from the contents, so the same content always produces the same hash and any change produces a completely different one. You can reproduce Git's hash of a file containing hello yourself:
Press Run (⌘ Enter) to see what happens.Every commit also stores the hash of its parent, the commit before it. That chain of parents is your history. git log simply starts at the newest commit and follows the parents back:
Press Run (⌘ Enter) to see what happens.HEAD is Git's name for "where you are right now", usually the newest commit on your current branch.
Seeing what changed: status, diff, log, show
Before you commit, you should know exactly what you are committing. Before you debug, you should know what changed since it last worked. Four commands answer both.
git status --short packs the full status into two columns. The left column is the staging area, the right column is the working tree:
MM app.py # staged changes AND more unstaged edits on top
A test.py # a new file, staged
?? notes.txt # untracked: Git has never seen itM is modified, A added, D deleted, and ?? untracked. MM is the case that surprises people: you staged app.py, then kept editing. The commit will contain the staged version, not what is on screen now.
git diff compares two of the three areas, and which two depends on the flag:
| Command | Compares | Answers |
|---|---|---|
git diff | working tree vs staging area | What have I not staged yet? |
git diff --staged | staging area vs last commit | What will this commit contain? |
git diff HEAD | working tree vs last commit | Everything I changed since the last commit |
git diff main...feature | a branch vs where it split from main | What does this branch add? (what a PR shows) |
Add --stat to any of them for a per-file summary instead of every line.
A diff is a standard text format, and once you can read it you can review code anywhere: in a terminal, on GitHub, or in a patch someone pasted into a chat. Python's difflib produces exactly the same format, so you can experiment:
Press Run (⌘ Enter) to see what happens.Lines starting with - were removed, + were added, and a space means unchanged context. The hunk header @@ -1,2 +1,5 @@ says "this chunk covers 2 lines starting at line 1 in the old file, and 5 lines starting at line 1 in the new one". A change to one line shows as a removal plus an addition.
In the hunk header @@ -10,4 +10,6 @@, how many lines longer is the new version of this chunk?
old_start, old_len = 10, 4 new_start, new_len = 10, 6 print(new_len - old_len)
git log reads history, and a few flags make it far more useful:
git log --oneline --graph --all # every branch as a drawinggit log --oneline -- app.py # only commits that touched this filegit log -p -2 # the last 2 commits with their full diffsgit show 9cf0917 # one commit: message plus its diffgit show HEAD~1:app.py # a file as it was one commit agoThis is real output of git log --oneline --graph --all from a repo where a search branch was merged into main:
* 3de3a9c Merge branch 'search'
|\
| * 9cf0917 Add search stub
* | ef85ea7 Add README
|/
* 1bd78ee Use an f-string
* 6bec053 Add greetRead it from the bottom up. Two commits on main, then the history splits: one line has the branch's commit, the other a commit made on main meanwhile. The merge commit at the top has two parents and joins them.
HEAD~1 means "one commit before HEAD", HEAD~3 three before, following the first parent each time. On a merge commit the first parent is the branch you merged into, so HEAD~1 above is ef85ea7, not the branch's commit. HEAD^2 is the second parent, the branch that was merged in.
git status --short shows MM config.py. You run git commit -m "Update config" with no other commands. What gets committed?Small commits and staging part of a file
The staging area exists so a commit can be one logical change: one bug fix, one refactor, one feature step, each building on its own. Small commits are easier to review, easier to revert, and make tools like git bisect useful later.
Often you have two changes mixed in one file. git add -p (patch mode) walks through each changed chunk and asks whether to stage it: y yes, n no, s split it smaller, q quit. Stage the bug fix, commit, then stage the rest. Run git diff --staged before every commit to check what you are about to save.
Commits Your Teammates Thank You For goes deeper: splitting work into commits, writing messages that explain why, and tidying history before you push.
Branches and merging
A branch is a movable label pointing at a commit. When you commit on a branch, the label moves forward to the new commit. The default branch is usually called main. You make a new branch to work on something without disturbing main, then merge it back when it is ready.
git switch -c search-feature # create a branch and switch to it# ...edit, add, commit as usual...git switch main # go back to maingit merge search-feature # bring the branch's commits into maingit branch # list branches (* marks the current one)git branch -d search-feature # delete the label once mergedTwo commits on main. The main label points at B. Arrows show time going forward.
git switch and git restore: the modern verbs
For years one command, git checkout, did two unrelated jobs: moving between branches and overwriting files. A typo could silently throw away your edits. Git 2.23 (2019) split it into two clearer commands, and they are now standard. Older tutorials and Stack Overflow answers still use checkout, so you need to recognise both.
| Job | Modern | Older equivalent |
|---|---|---|
| Go to a branch | git switch main | git checkout main |
| Create a branch and go to it | git switch -c fix-login | git checkout -b fix-login |
| Back to the previous branch | git switch - | git checkout - |
| Throw away unstaged edits to a file | git restore app.py | git checkout -- app.py |
| Unstage a file, keep the edits | git restore --staged app.py | git reset app.py |
| Bring back a file from an older commit | git restore --source=HEAD~2 app.py | git checkout HEAD~2 -- app.py |
git restore moves content between the areas you saw earlier, in the direction that undoes your work:
You edited app.py, staged it, then edited it again. All three areas now hold different versions.
Detached HEAD. If you switch to a commit instead of a branch, for example git checkout 1bd78ee to see old code, Git warns that you are in "detached HEAD" state. It only means HEAD points at a commit directly, with no branch label to move forward. Looking around is perfectly safe. The risk is committing there: those commits belong to no branch, and once you switch away they are easy to lose. git switch - takes you back, and git switch -c rescue turns where you are into a real branch. The modern command makes this explicit: git switch refuses a bare commit unless you add --detach.
Mistakes in committed history, like a bad commit, a deleted branch or a botched merge, need different tools: git revert, git reset and the reflog. Git Archaeology: Bisect, Blame and Reflog has a full undo table for exactly those situations.
You find these older commands in a tutorial. Match each to its modern equivalent.
Merge conflicts
Usually Git merges automatically, even when both branches changed the same file, as long as they changed different lines. When both changed the same lines, Git cannot know which version you want, so it stops and marks a merge conflict in the file:
<<<<<<< HEAD
greeting = "Hello"
=======
greeting = "Hi there"
>>>>>>> featureEverything between <<<<<<< and ======= is your current branch's version. Everything between ======= and >>>>>>> is the incoming branch's version. To resolve it:
- Edit the file so it says what it should say (one version, the other, or a mix) and delete all three marker lines.
git addthe file to mark it resolved.git committo finish the merge.
Conflicts are normal, not a sign you broke something. Editors like VS Code show buttons for "accept current", "accept incoming" and "accept both". Pulling often and keeping branches short-lived keeps them small.
Remotes, GitHub and pull requests
A remote is another copy of the repo that you sync with, usually on GitHub and named origin.
git clone https://github.com/someone/project.git # copy a repo from GitHubgit remote add origin git@github.com:you/notes-app.git # link an existing repogit push -u origin main # upload main and remember the link (-u)git push # later pushes need nothing elsegit pull # fetch and merge others' new commitsOn a team, nobody pushes straight to main. Instead you push a branch and open a pull request (PR; GitLab calls it a merge request) on GitHub. A PR shows the diff, runs automatic checks (tests, linters), and lets teammates comment and approve. When it is approved, it is merged into main on GitHub, and everyone pulls it.
Put a typical team workflow in order.
- Tap the steps below in the right order.
fetch vs pull
git pull is really two commands: git fetch downloads new commits from the remote, then Git combines them into your current branch with a merge (or a rebase, if you configured that). Knowing the difference lets you look before you leap:
git fetch # download only; your files and branches do not changegit log --oneline main..origin/main # commits on the remote you do not have yetgit status # "Your branch is behind 'origin/main' by 3 commits"git pull # now combine themorigin/main is a remote-tracking branch: your local, read-only copy of where main was on GitHub the last time you fetched. It only moves when you fetch or pull, so git status saying "up to date" means "up to date with my last fetch", not with GitHub right now.
On a team, keeping your feature branch current with main is a daily job, and teams disagree about whether to merge or rebase. Rebase, Merge and Squash in Engineering at Work covers both, and when rewriting history is safe.
.gitignore and good commit messages
Some files should never be committed: installed packages (node_modules/, .venv/), build output, editor clutter, and above all secrets like API keys and passwords. List them in a .gitignore file at the project root:
# dependencies
node_modules/
.venv/
# build output and caches
dist/
__pycache__/
# secrets and local settings
.env
.DS_StoreA good commit message helps the next person (often you in six months) understand why something changed. The common convention:
- A subject line of 50 characters or fewer, starting with a capital letter, in the imperative ("Add search", not "Added search" or "adds search"), with no full stop. A handy test: it should finish the sentence "If applied, this commit will…".
- A blank line, then an optional body explaining why, wrapped at about 72 characters.
Fix crash when a note has no title
Notes imported from the old app can have an empty title, and the
list view called .upper() on None. Fall back to "Untitled".Messages like stuff, wip or fixed it tell nobody anything.
Check a commit subject line
Teams often check commit messages automatically. Write a function that returns True/true if a commit subject line follows these house rules, and False/false otherwise:
- It is between 1 and 50 characters long.
- It starts with an uppercase letter.
- It does not end with a period.
"Add login form" → true
"fix bug" → false (lowercase start)
"Update the README." → false (ends with a period)
"" → false (empty)- commit
- A snapshot of all tracked files, with an author, a message, and a pointer to its parent commit.
- staging area
- Where you collect the changes that will go into the next commit, using
git add. - branch
- A movable label pointing at a commit, used to work on something without touching
main. - merge conflict
- Two branches changed the same lines. Git marks them and you choose the final version.
- remote
- Another copy of the repo you push to and pull from, usually on GitHub and named
origin. - pull request
- A request to merge your branch, where teammates review the diff and automatic checks run.
- diff
- A text listing of changed lines:
-removed,+added, grouped into hunks with@@headers. - detached HEAD
- HEAD points straight at a commit instead of a branch. Safe to look around; commits made there belong to no branch.
- remote-tracking branch
- Your local copy of where a remote branch was at your last fetch, like
origin/main.