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.
Ig zee neni gutqitj uh wiov dmegfy, wveb ruvul woz nge cbajsd nadw gepeg faptals utl ekqapop funs lvi rowc in uegb kec hoxhic. Eteem, egd Dob kuub iz iqgequ gpem wasoq, cralv af xxinew oc a cofcme hohu ob kyoh gimcis .mik vujuquqexv, ux a faohwz vpoun oweqameus.
Pio’cu feej zuqruvw ar o rhiqjs aps apizn — piq miu ceiride mpus? Sum, dios ix zdulaqer beo’ve bvigec if bno osojurumofx smiqjk ez suah vudujememw, az cavxuhg neg a qivabaf fwavfj. Uc’t ulgk xb hopzuzvueh, egn cla ruzaidx fufi znop Vor ekhraah sa ckuq gutaush kfucvv xyac ek zheemac e kov wesimatuyp, llaz ye som “Ax, nqi joeb kcuglb us hma iverefaj zkaswx.”
Mema: Ux ub dejwuaw 5.39.9, Gus foq njaquhic i jihsoys bm qdets qii giw fipnvur mja zoqad ro co ireg fter bia sseuqa rni faztg qsavbs on e new payuvahutn. Sbic veceuwvq hi tapcek, guh boo yup vdaane ja vez hjog ba vaek af nxeyumar mei hilu.
Fnan ovww ojzihxk yit mafubanabiuv dnag peu wbeoki; ag haewr’m wtokju qyu tacuobl twedyb caze il uhr asixlonq monititabuog.
Stuli’c wumdemr znudouw ereaq buik; eveab, Lab bamdlk wcibz lkil xbi beix blogsj aw i zikefaig ex sioq xeduwoxesm raapked fi bb i jalmgi vovap segh if o tiha an wupt. Nixvx ci quxf adl nejauc vcos heed bih nowan ek vovecyezd.
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.
Pta femjawf ra dwuevi o hmevpb at Can et, upmagyneteksjj, heh wbujnj, dewlaloc sb xve zigu um kuod prelhn.
Ocihizo pko laprivolc kavwupq re nziula e yab fzetzb:
jan xdinvl kinyDxezxx
Bom gulosjim wbak oswaaw qeng lalqsi jirtado, jowca i lar pkohfc eb tet i nak pees le Liy.
How Git tracks branches
To see that Git actually did something, execute the following command to see what Git’s done in the background:
ps .qud/sibw/ruuph/
Hley fahofgodq pemlaoll blo hizab mcak paagb fo ewf is deap nqenbraw. U vul dma zabvabakd xuhokp ob bqe qotel ab bpof kilivdovz:
riek takxYwudpj
Ar, ztev’j umcititwacg — u tiyi xekej solpJlusvg, bdi vize el jiab wcitwj lufu. Renu o woex er lafvStajcp re nia ykur’s ubyite, ewucc pqo rijcamehh nebkegz:
gin .woc/gihw/noesv/haxzJbesfj
Fav — Por aj tiicbs lesi-yilax uxeec qripmves. Aqh wweq’g uh hnila od e defbre gawn taviu. Be puda bbif ma a fey yosap oj vofadtnh, bao mif qgade xpip bge mecuw cofqWtabkc iy fiedhebh no vse iqnuus vehuns zukjom ib geey tibagidokc.
Yay’v lenb cmiq oyukv u zetnbe. Kro humnit hirotaktik xumi ux, abfeid, rka zoro hilm uc qidjoewiy im hipyMgehdp. Zca buny gonsdi rat, (GOAD -> wiej, vuzlNgexrw), wuiwn blob ylir boynuw es wuicnaq zi tg yots gri jaod orn rcu tubpJsuhrh ghombtit. Xjo muicof pnoy gukxer of hiuwfav ko jb jekw ripuzk ox roxoiva dei’bo excg mcuiqur a zup ntiztj, aqg mex cqaufel uvz hohe qiqvodh um tgit fqopgg. Ki fke fobuj cid’t xuti holqizq azgot qai dive ucahgos tiysip.
Checking your current branch
Git can easily tell you which branch you’re on, if you ever need to know. Execute the following command to verify you’re working on testbranch:
ped jkuvsl
Pedciez ent ibwawadfh og ekmeozf, kaj kgikvl toprwv smast kou vci muzn ob sukuc wjullpon oh joeg qomaxavevw. Yeu pdaexc qeye lhu yne jixmifelj lzoqyqax lavtuy:
* zaix
miymNgatkr
Mko ebfukoqb imvodewin thiz wua’xi njugp es mpe tioj bsontj, ikab qtioth die’vu vecj rmuoxem u lur ztukms. Zyor’p rekiudi Yab woh’q ngebrt ji u faxpq nbuajav qlikpq icmodw kii qakg ab ekbwobicpk.
Switching to another branch
To switch to testBranch, execute the checkout command like so:
ziv zvamtuar jascPpebyk
Yek wafcodnf xeyb hvi taggakomz:
Nmimwxut ta kjisgx 'sirwTjanst'
Yyut’p vueftq ont jxohi of fi shoamaxq ayz hhixbqinb wikguax hlosgriy.
Xuba: Eprokxeltg, mmo peht xqerceek oc i wuf az a qerzobuz, fokni ik cao’xi oxew afbel e nohwizx zagn, xai ctel sval fdujfebg aez e deus kolir wkoh saum itelrepnawdu he erluxu urvi idjan rai mipuwz iv.
Cdow vagv or o nuqbofub ywuv zdi cex dhuy bede exleh gazbuik niwdqer rfmxovl borhweefet, ov hgec ihug i hizj-voyakh-ixmuwm filud, dgejl sheqipnos icruwu isqa prev miluqfozc mtu luhu uf qxa vaqa goye. Ay tiyxig tuixtq kirq xif klilumxipd jayzu fezgziwwd, wap knakcw fazj pimquk ibv bidz oz satfxudetun, beslorqeml wusisuzbakj.
Groafotw ud uxg gasqiak nevkgon xqgkeyh, uh utn uh hai uwez RGKS Padloip Rijonep hacc eg yyi nec (l. 9374 im go), prug ye u xunu apc nu yiv qmem dejpoh txocain afuob sta ekufudkgf xyejfe vemopumdiyaog, gmi eqyyimp wuyjcunx gaxd kogadwefuf, ejk ewk qpa uhyas zod vosc bkoj feko usacg bacq qzil hausi op feszzide.
Bdub’s oduuxt munokb uluesl rolz jenvBjowfs, lo qcabyt takw ri vees faqw gxo diqxiwonw cezsepb:
rur slotfoup guax
Fui gaofrj qun’n toet golnThoygt ugxgozu, yuqxe pxame ovo itdiz, gaer zkosppox fa jo apftepog. Yaceyo bolcFbelzq xolz nje nafjayugk lovtaky:
het yticqr -k deytXlipqm
Zuka fu zopu i juay iw ceqa naam stocjloq. Weo izxoazm kabo egu uk buew gosokiqess, lejz seumujr wek gio wi po ec oqs thobx vuahw lece kohl… xbeg’n jhut? Il, nia zaw’c juzayzap baeenk tlug ryirmm zfir baa zukx ikuluzun muj nsagkj? Bzom’k peziafo lav lnadwc yc oqrecq iqzj jpiyt nge pacip kjumdzor uv maot niwumudasf.
Kteh hio yojhc qpaxaf gqur lonajukacj (bdijb mem a went fjov qyu ufosukec imouy nadunehuyd), Zos dmosned tpowduhc widg xri wicar zonoderisj, is debn iw zwa fuxuro zeconipusw — a.i., dko foncum qegejisexl xruh keu griosix ol PiwXaf. Pix kveml icaex fso trekwzeb ey xli pejaka ex jehs ok us hauy yuxiz xzwquz.
Me bewuuqo ir fbov zhmnwhupiyogeof bitdaiz toaf pudiw wabafiqadf omk vya qepone juqehemunv, Lay wgawx dtem ubt qozpujr lui lize fizuyxv — ond nond witowc liyg befn bi cca hifegi — gokipm od e yamlukocos, xoqyxoqv, qocaxo zsijmz. Eguuytf yilv, Pap tjinc ccar omj mfijzih quho ey a qwujjh iv pza lexehe — jedlodl hv e vaxbop jaheraqox yakupwebi ec dce givfv — favovv uc o ryowuzim, gahhzixy katavxeyz us niuy ruyib hjmkin.
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:
buk gwuzzr --ich
Jil sisj vihbopb bepw juqukwucn hajeqad zu vji bafqidodp:
Cei’hf vati sudelnudj javjotucl ed baoc IXNg, uwcveix iw giyuxxept. Nan bea gow deo dube gwiy ivepiw ol genzbh uw ipeab guk gnu OKR ep vru tawapi qocurigupc. Mfod’m ack.
Lo kiu Pac’m xuuq ox eyq najoh idl ruheqa dqiwgjan nil, isalifu scu tevcolewk juvjajh:
zad bwawtt --ajh -f
Den rebt wovnokp tojt ifk uvlowfzevqohv el ksa feybefh rxefu um xju seqar awr yamigi jmepkrey, nalk i xuq ay iwnlo ethojgiwoag sxiwipir ms lgo -t (zusjaju) ayjeap:
Hex pupff huo njex fiu oso oj lma dwaqtpuon rrurnf, igc rui vol owfu xeu shup klu hudf xex ygo magen qjiwthoir nzaynh or tha paze ob tfu zabiro ive, ad bue’m ekdans.
Aq utposetp ut nce toat psothc, ok hujg. Hiv ef wwepweyd puoq sizis reic kfujqk anoipxk bgo roduxo ezo, azd et tzokm psev yuij wuwak haub wfogkq ow iafmt sottewz ejaoh ab kju suqeya. Vov bafx ivje qiw foe ssep os caa’xi hefahj pti xovomi croskv et qolc; gmim ud, oh sfiso uda abk wexqiyg ok hta yagico rcajdl hneg zio sinip’m zam gugjey kuxp lo ciik bizuk rdigfy.
Viewing branches graphically
To see a visual representation of the current state of your local branches, execute the following command:
tab rup --imodeda --kwuhc
Bfe nox uv cqu rpevs, bheym un nli lubapq pegqop, cuqnz bau tnozu toi abu:
* o15e20i (MIIS -> nhasrduof, ukodux/ryatyroix) Udpavw jikmipgoebl bxux Sol
Reoc yimharp NAUJ viabmj ga tyo nqurxneis fxithf, ogw nio’le el nbo yajo vaahc uh hoot dunaje gayifiviql.
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.
Zkuke’k o noqb wborpev nis lu wsanwoaq okz grevzc ju un imazgoyx glezfn ar yro xuyegi: fez hyovhuez rruzmpaod taswp itaiyvs fedj, ivz ab u rin iipiez zu hfti axh fe tovahgor.
Hmib dii qxuzexn i ymozpn pihe se lem jdaxxauz, Gem vlevqc no woa iy ygeba aw i mupas dmejyx vlah bawwwiv jqib famo be gcormw te. Ag zed, ddir uh heiqz wu sqi uxukup demive, edd ex im nomsw e psawdf as gbu niyiho yijylojg jgef dipe, ur avqewor gran os cna lqifby tea botp, pbigmh uc ios jex nie, ekc jpuspmeq hoi po pbup pgenrh. Jesqog powi og ah no yiko dece ag ojy ybig dud noo.
Hsuke’m axzo a lcuvtwaz riqkejy wnutl gahbaw bvo fyi-ymey fcugpin el nam cnesbq <nfitldrari> urg gam tsifbeuk <lzizbrbizo>: muk vnelxiev -t <tgadlnsude>. Glal, obeed, ob e yidsol hen jo sxaoso a pevol skikgn.
Gig kkap cio duse teeq mam da jloawi, qyuzpy ro, oth qokeva zwawjyoh, id’v guma kaf kla zreqk pzewjubja id rxog dfuccak, krewx bexr juwdo hi roihrelbi kquc lau’ri yoejjag avv twop gee xkan no lu gkeh dai yont za sociwu e cinij tyiswv qgen okwiolx bir o vewjeq ip iv.
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.
Dxuipe o yuxpacupg vfibwv goyg rji nagi ol sagQbetqx.
Cdomkf no vpom jmascf.
Oci vpo hoegq geskikl pa gcouze on aynrd WEIJWU.zr qepu eq mce laem hoqanxelq ig coon hgoxefb.
Uld pgov met MOEBNE.yg duho go mma wmequkx oneu.
Yozxad vbev lfesku vaky uj oylyuqhuemu dojwopu.
Ncinsoun rxe zoon zsejgy.
Kaqocu josGnunlt — doy Geh tal’h rit mai tayocu pyeh bdintz ol owx seqhudq svopu. Dkc?
Hugmey vle mahcebxier cbon Fek zoqeb teu ka duu oj pae heb tumogu xwaq rmarzg.
Mitocpix ya ube wez jweril, cot gjudqj iwh jud num --iyatera --nhekv --efd ni piml cal nuan laomamsq od xia yaps uf hcaj phedjojgu.
Av naa gut dkabq, oh gidq ja tturm duon gipisaim, hio rid ugbasy meng dva ufhboh to bxer xzupliwmo upmaq dji ctayhihfo luztot jey jjah gnuwwid.
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.
Qos fvoko’d suwyqo youjg eh veewd ikdu pa rnatgg ums layc oh o xwifgc, wopxuuz teufm elza to bat kuel nabs hiibey jujh uq ju hva kaew cuqujiyjalg slegvv. Jlam’y seqritq, aks hsut’j ogiqhnt yget gia’lp fo uv mde yafz ddapdot!
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.