Branches

A branch is a movable label, not a copy

ABCmainHEADoldestnewestfeaturegit branch featureadds one label. No file is copied.A branch is a movable label on a commit, not a copy of the project.Creating one writes a 41-byte file that holds a commit id. That is why branching in Git is instant,and why teams make a branch for every change. HEAD is a label as well: it names the branch you are on,which is where the next commit will be added.

A branch is a label on a commit. HEAD names the branch you are on.

Branches · Going deeper

What is inside the .git folder

HEADref: refs/heads/mainrefs/heads/main9f3c2e1...commit 9f3c2e1tree 4b825dcparent 1a2b3c4tree 4b825dcapp.pyREADME.mdblobbloblabels: tiny text filesobjects: stored under the hash of their contentsEverything in Git is one of three objects, or a label that names one.A blob holds the contents of one file. A tree lists names and the blobs behind them: a directory. Acommit names one tree and its parent commits. All of it lives in the .git folder. Copy that folder andyou have the entire repository and its history; delete it and the history is gone.

Blobs, trees and commits, plus labels that name them.

The graph

Committing moves your branch; switching moves HEAD

1git switch -c featureABmainfeatureHEAD2git commitABCmainfeatureHEAD3git commitABCDmainfeatureHEAD4git switch mainABCDmainfeatureHEAD5git commitABCDEmainfeatureHEADCommitting moves the branch you are on. Switching moves only HEAD.Follow the purple: each command changes one thing. Switching also rewrites the files in the workingdirectory to match the commit you land on. After the fifth command main and feature have diverged:each holds work the other lacks. Bringing them together is the next page.

Each command moves one label or adds one commit.

Fast-forward

If main has not moved, a merge just slides the label

BeforeABCDmainfeaturemergeAftergit merge featureABCDmainfeatureWhen main has not moved, merging only slides its label forward.This is a fast-forward. feature already contains everything main has, so there is nothing to combineand no new commit is made. History stays a straight line. You run the merge from the branch thatshould receive the work: switch to main first, then merge feature into it.

Nothing to combine, so no new commit: main simply moves forward.

Merge commits

A merge commit joins two histories and has two parents

BeforeABCDEmainfeaturecommonancestormergeAftergit merge featureABCDEMmainfeaturetwo parentsWhen both branches have new commits, Git creates a merge commit with two parents.It compares three snapshots: the two branch tips, D and E, and their common ancestor, B. A changemade on one side only is taken automatically. Git needs you only where both sides changed the samelines. Nothing is rewritten: C, D and E keep their ids.

Git compares both tips with their common ancestor and creates one commit.

Conflicts

A conflict is Git asking a question it cannot answer

Common ancestorport = 8080On mainport = 80On featureport = 443config.py after git merge feature<<<<<<< HEADport = 80=======port = 443>>>>>>> featurethe version on your branchthe version coming inTo resolveEdit the file to what it should be,and delete the three marker lines.git add config.pygit commitTo back outgit merge --abortA conflict is Git asking a question that it cannot answer.Both branches changed the same line in different ways, and only a person knows which is right. Gitstops, marks the place in the file and waits. Nothing is lost, and the merge can always be aborted.

The same line changed both ways. Git marks it and waits for you.

Merge or rebase

Merge records what happened; rebase straightens it

The same forkABCDEmainfeatureMergeon main: git merge featureABCDEMmainfeaturehistory as it happenedadds one merge commitno commit changes its idRebaseon feature: git rebase mainABECDC′D′mainfeaturehistory as a straight lineno merge commitC and D are replaced by C′ and D′Merge records what happened. Rebase rewrites it into a straight line.Rebase replays your commits one at a time on top of the new base, and each replayed commit gets anew id. Use it to tidy a branch that only you have. Never rebase commits that others have alreadypulled: their copies still hold the old ids, and the two histories no longer fit together.

Merge keeps every commit. Rebase replays yours with new ids.

Pushing a rebase · Going deeper

After a rebase, push with --force-with-lease, never plain --force

On GitHub: featureACXfeatureX: pushed by benYour clone, after git rebase mainAEC′featureyou do not have Xgit 2.43, two clones of one repository$ git push ! [rejected] feature -> feature (fetch first)1$ git push --force-with-lease ! [rejected] feature -> feature (stale info)2$ git pull --rebase...$ git push --force-with-lease b393cf5..88f8eca feature -> feature31A rebase changed your ids, so a plain push is refused2The lease check saved X: the remote had moved since your last fetch3With ben's commit brought in, the push goes throughAfter rebasing a pushed branch, use --force-with-lease. Plain --force would have erased X without a word.--force-with-lease overwrites the remote branch only if it is still where your last fetch saw it. A fetch you did notlook at defeats the check, and editors fetch in the background: add --force-if-includes (Git 2.30 or later) to demandthat what you overwrite was actually brought into your branch. On a branch others share, do not rebase at all.

--force-with-lease refuses to overwrite commits you have not seen.

Undoing

Rewind private work; add a commit to undo shared work

Not committed yetgit restore app.pythrows the edits away,and they cannot be recoveredgit restore --staged app.pyun-adds it and keeps the editsCommitted, not sharedgit reset --hard BABCmainmoves the label back: C is droppedAlready sharedgit revert CABCRmainadds R, which undoes what C didUndo by rewinding while the work is private, and by adding once it is shared.reset moves the branch label back, so the commit vanishes from history; with --soft the changesstay staged, with --hard they are discarded. revert leaves history intact and adds a new commit thatreverses an old one, so nobody else's copy is broken. git commit --amend replaces the last commit.

restore for edits, reset for private commits, revert for shared ones.

Undoing · Going deeper · 1 of 2

The reflog: your safety net

git reflog9f3c2e1 HEAD@{0}: reset: moving to HEAD~14b825dc HEAD@{1}: commit: add the test9f3c2e1 HEAD@{2}: commit: fix the portthe commit that the reset droppedis still in the repositorygit reset --hard 4b825dcputs the branch back on itGit keeps a private log of everywhere HEAD has been.So a commit that was reset or rebased away is rarely gone: find its id in the reflog and point abranch at it again. Entries are kept for at least 30 days by default. The reflog is local and isnever pushed, and it cannot bring back edits that were never committed.

The reflog remembers where HEAD was. Dropped commits can come back.

reset modes · Going deeper · 2 of 2

reset always moves the branch; the mode decides what else is rewound

CommandBranch labelStaging areaWorking filesgit status -sBeforeA, B, C committed; nothing editedCCC(clean)git reset --soft HEAD~1to rewrite the last commitBCCM f.txtgit reset HEAD~1--mixed, the default: to choose again what to stageBBC M f.txtgit reset --hard HEAD~1to throw the work awayBBB(clean)Every reset moves the branch label. The mode decides whether the staging area and the files follow it.After --soft and --mixed nothing is lost: the changes made in C are still in your files, ready to commit differently.--hard also overwrites edits you had not committed, and those were never stored anywhere. The dropped commit C canstill be found with git reflog for a while. The status column is real output from a three-commit repository.

--soft keeps everything staged, the default unstages, --hard destroys the edits.

Lesson complete

You finished “Branching and merging”

Nicely done.

Open in a new tab