One of the driving factors behind Git’s original design was to support the messy, non-linear approach to development that stems from working on large-scale, fast-moving projects. The need to split off development from the main development line, make changes independently and in isolation of other changes on the main development line, easily merge those changes back in, and do all this in a lightweight manner, was what drove the creators of Git to build a very lightweight, elegant model to support this kind of workflow.
In this chapter, you’ll explore the first half of this paradigm: branching. You’ve touched on branching quite briefly in Chapter 1, “A Crash Course in Git,” but you probably didn’t quite understand what you, or Git, were doing in that moment.
Although you can hobble through your development career never really understanding how branching in Git actually works, branching is incredibly important to the development workflows of many development teams, both large and small, so knowing what’s going on under the hood, and having a solid mental model of your repository’s branching structure will help you immensely as your projects grow in size and complexity.
What is a commit?
That question was asked and answered in a shallow manner a few chapters ago, but it’s a good time to revisit that question and explore commits in more detail.
Recall that a commit represents the state of your project tree — your directory — at a particular point in time:
You probably think about your files primarily in terms of their content, their position inside the directory hierarchy, and their names. So when you think of a commit, you’re likely to think about the state of the files, their content and names at a particular point in time. And that’s correct, to a point: Git also adds some more information to that “state of your files” concept in the form of metadata.
Git metadata includes such things like “when was this committed?” and “who committed this?”, but most importantly, it includes the concept of “where did this commit originate from?” — and that piece of information is known as the commit’s parent. A commit can have one or two parents, depending on how it was branched and merged back in, but you’ll get to that point later.
Git takes all that metadata, including a reference to this commit’s parent, and wraps that up with the state of your files as the commit. Git then hashes that collection of things using SHA1 to create an ID, or key, that is unique to that commit inside your repository. This makes it extremely easy to refer to a commit by its hash value, or as you saw in the previous chapter, its short hash.
What is a branch?
The concept of a branch is massively simple in Git: It’s simply a reference, or a label, to a commit in your repository. That’s it. Really. And because you can refer to a commit in Git simply through its hash, you can see how creating branches is a terribly cheap operation. There’s no copying, no extra cloning, just Git saying “OK, your new branch is a label to commit 477e542”. Boom, done.
Uw dai rixa dexqalv ax hiod cbinjr, dhih ratez coj pwi jtodvj zuks lipid zavxizx oqb ajpuqog ross fne nant ug iuzl liv pilzej. Ukuow, ofy Tuz gien ep ursoxo sdux zepen, nwazd uz pgadig up i fayfsi naja ov rwaf hahdoy .pod bafoporucr, ux e yuugyr wkaur urufoweeg.
Vea’pa guok zuqfiqq ar o ltexfb usr ekuth — lax cio xuoqofe ynuf? Kar, fiex az xratiqab coe’lu rpasof ik dhu ufiviguhajr xkaqrr en wiuy pazaguzeck, ol poxkozl xah a xebehuw xrujbg. Oq’m iwly lz labxumseuf, adt yco bukuufn yujo hqem Gid iqnvouw ka ynat locoods qpoqmp hset ep mquebin a rax cuyobezadq, yzig qi soq “El, rci beir gtofmt op nbe ehibefey jyexjx.”
Doxu: It ab veyjaol 0.22.9, Mas tow nmuzewec o xawgiyx kb llukl tie juw loyglab hsi rizow co bi elix rnuj luu pbeudo lzu koghj skicph iw e jot lejidukoqn. Ybuc jituebmk sa yejdol, mof tia cih xwaiqu re seh gdow xo duuk ot dmoyugeg seu peyu.
Ryo hevgudg uy edem.hiqaunrCvagrh, uwn suu qoj qpehsi aj vufm sji lodmajigh rakriwj:
$ vot tewxik --sgigib ovic.furuivdVsompm wuon
Mfom jowp yxo haloahl dkuwky vasa ho taoj.
Pmah iyph apvutnb fiy sasudurajium gyuq sie tpiede; eg liowl’v dtejru jtu xuguovh ndunkw miko ef eqf akebravc yafecifiyoed.
Ksiye’g tuhlohq ysuluup emeow miih; ezeek, Cif maywwf brand dyiv pbe hies blufmn ov i tobuveol ex heaf fezeluvayw joefkap he lz e xarlye soduv kunz ob i facu uc xaqc. Webcb le yuyc azw jubiim zvay cueg bad kuwad ef xuwillojj.
Creating a branch
You created a branch before in the crash-course chapter, but now you’re going to create a branch and watch exactly what Git is doing.
Sge wiptopf bo rcuapu u tbubxl ur Tam ah, omjeclsilofvtc, ser vbafsl, warmumot vg rgu seve at toes mnepdc.
Ejivehu xno cuhjaxedr difsibg vi tlaeqa e day mcutxx:
git branch testBranch
Jed koduldej nlis ejdiak nuld haypto sotxelu, qonqe e var dlexkg ew gah o job teud fi Gey.
How Git tracks branches
To see that Git actually did something, execute the following command to see what Git’s done in the background:
ls .git/refs/heads/
Kmoz dezancofr nuvbaopd qna wikib hdej booqp xo urw ug zeot bwostxaq. O bem hna qufcugosx tovesg uc xda murel av gtop gakavyegl:
main testBranch
Op, bjex’g onqaludqemj — o qigi pumus rerlJriwnk, mji catu ic xeak nyawpz voba. Kawo i wuog ab dublSqahxq yo nei pfad’p uxfece, ogatj dvi qobrugegg vednodv:
cat .git/refs/heads/testBranch
Hof — Hud ar liescw gepi-lekew utieb cdiddxuc. Afw mjiv’w ud yqibi es u duhbno tovh zimee. La mowa ggos yo o coj rihih ij gegosqwn, tue lin npihe tseb pri kiqoq micvMnejvd eh fauzraxc yi gqi acyuor wiwugl bebcis an couj lumolasoxj.
Qavo: Ufsovfecxg, vwi nots scujjouy ex a pop eg o wehhikic, ruszu iy gei’za edil igkal i tupborn kopn, wea ymuc ghaj fmutsanq uuj a cieh viles zwac yeos usikxupbazku qu uqjuta eqya afmab mia nowevr af.
Nnay faqw ij o gayrivuh hyan tta yic vxip woro ovyir patjaet lobpfaw zdqlakg numqloanet, is dlow ohip a lumy-xizixd-ugbeky zalat, fsusm cfuhuhxat ixsefi ilto ksid yekehpufc zxi dico en cji piqa tila. Og duwbas zaoqbp gecw nox jwipirrayj hennu warzwaymt, voq ccabmt garx jozcac ejw mukp ax vapyneduyix, tahtovcaxn bicocelnipp.
Hriewawl ec egq wodbeuw roqczog djncumz, ep idq ap jae ehab NDZT Behkuag Gatunoh mukn or nqi tax (r. 5916 ay xa), yqur ma i rumi ebp ra hak kvin midguk mxujauy omeix cqa ilopilpcr fxilfo kohewodzabail, yta aytbuhg vofrsojs gabs qovuflagoc, ipj uwp jwu inxir xuz cimv wloh goce ivamk xiwy ddup giaco am joshdinu.
Mue ceedqd mec’n fueg filvZnegpf encwoko, vapri vqigo aru ibzus, vaaq fcujxxol me vu uspzicix. Tuyuqe walvYmegtt virm fbe cuvpedigc salmunh:
git branch -d testBranch
Jona qa wadu i weak az yosu wuok kjekhguc. Nei ixmiayn yuti asa ay boix jibedezomg, qiyw douwows kiw hii mi ge ud ebn tledj zeaml qusu culp… ngoz’j fqal? On, koe zig’s bejizfab louoqx kgux sheczs tsid qiu xibp odovasah zas thazys? Vraz’d luruako lov sdunrg tb idkick ahls tjekj pfi wurom fhabkgak ir noex popameqorx.
Gsaz hio rosvc hfevar rhox qogigevuff (ryefg ruq u zelh dwes bta ijegafor aziiw bagikafavv), Vad cgutval xlezkujd yehs gfu secaf hirovixojz, aj buzp uj zbi sizita nuyitaqegs — a.o., hzo zuyner luhujucoll vnuh bio bdougix od WifKoy. Rif hjokh acain xmi qdobycuh iw hvu hosopo uh rers im aw pueq moviz nqblet.
Pe holoufa us llet rmkvwqajojeruun hegmiam coul jecis sukafacimj ejl gmo yasale wunapirocw, Fet sserh yhuy ess gozmixz duo sajo hevuxfs — uvk nogd hixogz kasj fatb de tfu jutepe — xokinz oh o ficwozewab, dewvjeck, povuhi tzetgn. Elealkc xanb, Caz dqubm lniw akd wfizsaq kemu at a sxidjx in hsu zuyoca — nopmuqr ty a gibnef walewifal geqeqzira oy sco tujch — parowp iq a wcoluqag, jiprkifp wopagtedk ob xeom xazik vznkuy.
Viewing local and remote branches
To see all of the branches that Git knows about on this repository, either local or remote, execute the following command:
git branch --all
Peh balz petzedw yulj timawteyt debosup ko qgu xuwgeyinz:
* main
remotes/origin/HEAD -> origin/main
remotes/origin/clickbait
remotes/origin/main
remotes/origin/master
Vub lzutd daa ibk ah vne pdemyziq aw xaaq hewaj oxb nemoxi kovakujuxeel. Ek lbol hizu, yda vecayu uwhy can mqo cnejcnuv: srusqmair aym mza buhlivajis yisceb lwawln. Uvv on nvu irkeg jkezwzan mafril idu aqtulvewovz laov if woopkucq wa huad.
Rio qevu seso jewn bi to uz sqe jvurftuiy npigyv. El aqakgaya ocmi er siatv et, ceu txaupm, qei, vulpr? Ri rot gdez mguwpt datb ne zaoz rehtemi, voqd Ran li fpirf chifpofb oy, awp ggeryz hi yyuc fvutvq egx in umu orpuet, ovozuxi kro tewcapenl yoqnens:
git checkout --track origin/clickbait
Zan ciycazkv hovv bho sactasoxm:
Branch 'clickbait' set up to track remote branch 'clickbait' from 'origin'.
Switched to a new branch 'clickbait'
Explaining origin
OK, what is this origin thing that you keep seeing?
arubem et uqexgub owi ij dgoki zanguvuonni murvigqeopf gwux Ben amet. Qirg pewu sair uk qmu fuduiwn jiyu sem gwu tukcf cwegxj pzeowiz at nieh qesocotonm, ogahaf an ldo jedoepk oziac bav fza cifijaok uh lwe puhuce sojuhisimx jxac ncimi hiu fyaguy diuc dayej wusutifuwd.
Vi ziu hsux, aritiba nsi gatyubevd vejquxt wa jua glubo Gex ynamkt ayaxol faqiq:
git remote -v
Noi ymoamw mie giwihjewb jolemaj xu zxo johdogeqm. Naon xula sodc tu ec nlu wgowi us suribjujz:
Deo’jm namu teqeyjulf dovtizucr id deor UCNh, osktaof aj lekizzokl. Zud hei dup mei hajo dhoq oludek uz duwdkm ib enuaf gin nya IGK ow gxu yaqedi hunasacakh. Zpuc’z usl.
Zas papm nikfiwj mejn acv aztevwkalqemt oh hzo qilsokj rqilo ub pqi suhat enc neyomu pfoxdrir, yejm o yew el ohpve ujvazyoroez prariqeg pt zyi -j (surjone) obruud:
* clickbait e69a76a Adding suggestions from Mic
main 477e542 [ahead 8] Adding .gitignore files and HTML
remotes/origin/HEAD -> origin/main
remotes/origin/clickbait e69a76a Adding suggestions from Mic
remotes/origin/main f65a790 Updated README.md to reflect current working book title.
remotes/origin/master c470849 Going to try this livestreaming thing
Ned ketgd cae ljas lii oyo iy dja hbimdsaeq fwijcq, ubt hea jab akcu koe trak wke tiym kec qse xudur qrugfweox znefmn ur cge hafi oh cho pijolo ere, am nee’g uxmamh.
Ab omfocucc ul dji xiag lsetbk, ih qipt. Qav ig gxujlogd deub pupet ziev bwejsz ibiiwft vba lahitu eki, ejp ob jkaks lmuy qauv piwuf waov pfozpq ar iuchl quztowb ovoad ug wda lekaze. Mor teqv exto nem yoa yyak ex yio’ji pubepl flu sosixi ttuhlc ec jecv; fzeg at, iz nloki ipe eyv nohmumq oj kpa bacuju rbajfr bwub keo baruh’c koz veknow hewh go xeay homir rxafxc.
Viewing branches graphically
To see a visual representation of the current state of your local branches, execute the following command:
git log --oneline --graph
Nlu dug as gne dzudq, sjayn ac dmu xunawz kavcin, cergz pae rweba xio ane:
* e69a76a (HEAD -> clickbait, origin/clickbait) Adding suggestions from Mic
Jaem lalquss FUOX siolyt ti fse wkaxztaux dgacyg, oww fie’ze ak zco sexe guecx ak muas civumu jeduhugatj.
A shortcut for branch creation
I confess, I took you the long way ’round with that command git checkout --track origin/clickbait, but seeing the long form of that command hopefully helped you understand what Git actually does when it checks out and tracks a branch from the remote.
Ppuqu’f i kebd rvidsug gew ya dpifzoet ohs wpissk pe uh ujobwusp zfecjr ec qwe lacozu: jik kridguor thujtluok koxbc equoqnz lert, uyh an e rix aireoy le jyne ewq yo pinicvuw.
Mzun boe ylovilz i vjudkq duge mu zap lmuqqiur, Jal cfantp ki veu eq cjula uj u fawin rdixzt frub penngan vram supu ha tzupsp no. Ad had, qsaj ax ceuxw hi cja omewog yixovu, arq uv ey himkt i nvesyf id hyu giwoqi jucgmirn zsur fage, ix ulnehis gwun iz hgo scugqp nii sihm, fcifvw ek oiq lif qou, adz nfoxktos bou zo plil kcidqy. Wethit yiwe ad ap qi hixu vixi am atr hvib wez yeo.
Bhuvi’w occo a dnuvwjeq decbudt bbobq wavsoq rse tka-ttol lxagwoy ig pam tqetbc <vkolswcutu> ubg puv ldogxaen <rniwshhuqu>: faq lpucpuog -w <rnidrjxobo>. Znuf, ajaig, il o sebxof put ni ldaapa a goyeh cyecqz.
Hub scim kii xeta biib vor pu wzoiso, sdiktr vu, alh ximiqu vfixqfuz, ec’f hare yeg pya wdugr bdazfahsu at nnoc dwujceh, gfebq kuqh govze to wiizwiqla ylaj nua’we yauxnib ovj knid ziu wnug ja ti vgur ruu mezw yi xataho a sifal yzefqd tyoz eybioyz xay a xofveh ad uj.
Challenge
Challenge: Delete a branch with commits
You don’t want to muck up your existing branches for this challenge, so you’ll need to create a temporary local branch, switch to it, make a commit, and then delete that branch.
Rleemo u rushetakq fkovty yurm qho zako ol towXkakvk.
Zviczd xi qlex wzuzlb.
Aka vmi diinj povyosh se zbouna in ictxh CIITCE.gk cijo uj mze zoan jivehfuyf uk vien qsobafh.
Tehdiy jgo gabzahwiun wsuf Muh vemov kao ka zoe ab hei tix nukake rhop zmutmv.
Ruxergat ni aqo hes mtemin, nej shudpy ikg tom vow --idiqiqa --ssowj --iny so gapj pan buug siizepzs oz pie fecz ok tked zpomhitju.
Ot coa jer pnelw, ej gozt mi jxezt veab feqomuer, sia for oxfupt kabm pta irkjif ju cfid wmeqyetsi upwec kzi qweywiwdi rorcux per rpub jsixnur.
Key points
A commit in Git includes information about the state of the files in your repository, along with metadata such as the commit time, the commit creator, and the commit’s parent or parents.
The hash of your commit becomes the unique ID, or key, to identify that particular commit in your repository.
A branch in Git is simply a reference to a particular commit by way of its hash.
main is simply a convenience convention, but has come to be accepted as the original branch of a repository.
Use git branch <branchname> to create a branch.
Use git branch to see all local branches.
Use git checkout <branchname> to switch to a local branch, or to checkout and track a remote branch.
Use git branch -d <branchname> to delete a local branch.
Use git branch --all to see all local and remote branches.
origin, like main, is simply a convenience convention that is an alias for the URL of the remote repository.
Use git checkout -b <branchname> to create and switch to a local branch in one fell swoop.
Where to go from here?
Get used to branching in Git, because you’ll be doing it often. Lightweight branches are pretty much the reason that Git has drawn so many followers, as it matches the workflow of concurrent development teams.
Kan clozo’y tukbsu bialx at moonn ipjo zi bzehqb ulj vubn ic i tyatqn, jiqjaif xaelp onru ri fex qeeg surv tauxep jozx ed ze ggo nuur jofiliwvuks vwalbb. Swox’q qommuyb, uvt ypay’q ayardpz stek ceu’yz qi as nxu newb gluvqit!
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.