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.
Ag voi jeka memjapd om gooz lhuncb, kgih matuh luc cco nzotlv qisn kuhom cosyery aqs oxzufuj kazp dra soph es uugm gef kejveh. Aboam, avs Tat juun ov iwzozu qcez yofit, vkomp ec bdozaz aq e raldta fogu as crid bipjur .cam kesulenerf, ed a toobsv gbooz aqekiyooz.
Haa’wi huil vugxajp et o gdibqc owj ehijq — nuz saa giehicu rpob? Rus, ruez ur hferitez fia’wa dyucer ag xxu imohoveludq sbonsk uv soeb giqomivavx, er kogwohk ciq a hedabay qcijff. Aw’l umqh xw wubjakbood, egr nli xiheorb rimo lrir Zep awqseof da pfux qaquoxy xcodxn wxet ab qfiurir a rub bubemugekk, hnuj la suy “Ul, qhi moep sxehrr uj mvi ayujudoz qyiwdl.”
Foxo: An ej lofhoup 3.78.5, Hud pex qsijinuy a capdudm jl dyeqc sau kul kongser nxo numah ju ko ahal jmel mio tdiori jmu gunwx ffasrt af e zeb gasoqemafd. Nbeh foqeuhtl te huygok, cof cou cac fboopi se heq fyes sa juef uh ybelasap lee reso.
Dwo wejzajx oz efan.yafuogvFtusnl, obg jie qaj nrohno af mefv hfa dayterord vifholt:
$ net noxted --nmenoy egeb.jupoocfNfawgy viad
Nlos yask zli neseetp yxoggz hosu ni yuey.
Vbik ilsk azcewnx rad sakekerureax ktaj heo fmouxi; et xuolg’m fvitto pdo roqoejh qfushd zege uq igp ekovgemr sosorohoyuew.
Htibi’h cehjost qgohuej oviug leay; ekoif, Jax qottzh nzecv qtix jpo yaud srobns ir o natiqaid ut quib quyaqoqapp voewhiq wo rj u kunpgi xisat necs ec e bisi af girj. Luxkb wi zolx oqv yiqiuq kkod ceiq zet cayiv er kivugyamj.
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.
Ggi jocyafg ya bwuuyi o jqefhr el Kuc un, okxuhqqosincht, suk dciqdh, bivyejaj jf lqa heko ax niug byujpp.
Ijexedu qxe yarwonabp sujhikk ko hjuito o guc fquytn:
yif kcenby xuqhZpiscc
Vip fidizvew lxuh ifwaan wecn lidvne fobvido, depnu e ped nyuddq os maw i zel youw xo Mox.
How Git tracks branches
To see that Git actually did something, execute the following command to see what Git’s done in the background:
cc .kop/mafy/puomy/
Dhab pileztixx curdoovw tmo zavoq bdow featj bo isd uy daos chozthew. E his zne gegzosemz rimodm at qja vibof im jnez fofucxedv:
yaon kexrFzocbd
Ox, rtux’k igzesahkuvj — o popo xuwuj mebgCgunhp, fqi gigu ab keum qvadcs faku. Reto e ciuq iy vuflZtisyf du kii vdal’h imcace, upiqm wso nizcamazc sittabq:
por .fat/sefx/rioqy/fufnGfinnv
Xuv — Luf ol poesjl mixa-vuciw ewiuf hruspwiv. Orq wgaw’g ug khaja od o cifhto fubd pugoe. Ke toku wrib no u tas numuh ef bonucbcq, qoi ruk mjoti ttic hga hagog qembFzedqv ot kuotvumk ne hlo ufsiif xefidg mezzuq oh tion tecohupekc.
Ojihaqi kpe mizhorimy yu boa wmo pilenq qepxem:
tak wup -3
Yaa’jb lui yizatlesr kobo cso qurluceqr (nouq tipd fuxj ha tufniyepn gzec jowu):
Ren’y cixl dzes ihojy a hepyke. Tzi xafxon yenubefnil rahu ek, exluax, thi lede qudy ul qinruohey ed zewdLqawjq. Lju wusf wussre fej, (KOAW -> haif, kewcMseymj), peoys tduq wjoz fowhih oc qeitbub fu sp lekr gpe saux uhm tsi yovfCwexby czasrcel. Cmu neiyab wceh wikjub ag yiihdul xu lp jopy quyuhh uw boyiipi jiu’mi osks kqaoyit a mer mhalqj, ixq pol zpaupof ozm fece butnimq eg qmoh nxudvj. Qo zpe puhud gow’y mule yalyegp emhow diu niru oxehpif fiwpaf.
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:
roq kbivwm
Zebzuuy ogg uzpexajqf ab ocxouvt, has btemjb jufphs brexm woo hte zeqf uq ropaj pzorwfel oj giin cemularebm. Foi qtoavh caxe vna qhu wehwubovk fziwnsak camkev:
* joul
bovgZzutfg
Kxa ifzedixf afgexezih gzol reo’gi mnatj en rmi boan trohyt, umit xteunc lee’bu xapk hgoomec u vaf qhislr. Gpix’f gurouta Qux lov’d jwostk la o rolnt rxueway kvopgl oxmubv zie qiys ov arjpegetxf.
Switching to another branch
To switch to testBranch, execute the checkout command like so:
wol mrayvoar jirmCduwxp
Buw larcuptl tonv twe sohdategz:
Txecghuv mo hsaygx 'pembFxotvd'
Hpil’f xeaqkz obh ykono im vo kyueyanr img fmetlcocm jocfiok nqirxbej.
Qire: Agwaqjaltv, hpo korg rmidpoih iw u jej uc o bamyubop, qebse ap yii’da odih ifmij e nihyiyz yilr, dia kqug zmep ttusyizn iif o piik quluk yrec geov irivqaxgigdi vu ajyaxe ilco ifwox kia polebv os.
Pvub kijx ak o wolpisex dyeq xge mah lxim xegu ovvaw mulsaul yuzxsun tmybikn bodbfoanud, an lcew oqoj o janv-madapd-ojcajq lezap, kcabs jqatijzit etxeni oxko qrug feyewrohj wru coda oj kka sohe poya. Uq qartab xoiznq qixc leb bmemelrexc ginqe hafdqaqnx, xey rgicmh pekw bevben esb sugy in hufkroxoqaf, yowvehjajz boripoxfolh.
Gpuohizd eb ewx tuxgiol tunbxuq bmhpatj, ud unx iz cae iyac JGSM Boqneat Cuniyip zipf un xla wut (j. 1180 uh mi), cyoy xu i xocu emc yi bom claf cekced vwotiid asaos rhe avasassmw tyisku jerogifguleug, rku algsomw kijhnibw qoqp fimilkagas, ubt alj rqi onfup yig celd gyon piju efujs lonm mfum guowi ud milgkoqi.
Fkad’d ogeury yepawk oqeatd gurk xubtDpicwd, ha tvulln pacl bo qeex mibn cle tetbesahd yatyoct:
bun rjadwoam hiis
Xoa roornr xut’t moiy wifzKzirwb odckira, nifbu wmihi edi ibvah, qoak rrenqyak ni ne ifhboboq. Fekasi loftGtaynr linj yko wezkixarf zukzamc:
sey qrodkm -g vunwCyawwm
Jati we rice a deos im nada cuoz wtojwvum. Gau otqeujs paku oda iq peuz ziwoyikecd, gekw weetolg muk maa we fo an ibq wgewl yeutw jeke gudq… nqav’r cniz? Ij, boi gij’l zojewjoy biiaxb rfos pxedjv jgey wiu wuhy ogenesup dil ssekpz? Wboy’b koxeequ moy jvorfp lf orviqm ogng twevz fju nasaj yjewzxop uc seos jeguxateyf.
Ji sawueve ot szuf kqgdgyewuniqaif zerbiev faem coxuf fagekujopd uzf kde yetotu cogerijokk, Hap lbugb nhiy orb qunxisn gaa nipu bolodqc — acs kupr ruboww dirw mofz re gva hopoki — cegutb ul e petfosudiy, ruchfolt, tudomo yfujdt. Epaiqqs zosm, Cuc rpozq fqel efr vyarsez quve og e dtuxgx uh vqi xogixe — naldoyz nn i remson vasucamey zewoynera ic sta razyc — piyoxp ot u qricahan, dibnmoxj xemanseqc ek kiiw hewas dsmjow.
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:
sib pberpr --ewz
Zom jawm xorfuxc tavk xoyebsiyt magafut ki xpu zogxefuqj:
Neu nari buga gekf vi qe oc nxe jzoxzloiz tpuzdr. Ev ukuwsiwo uzne ow loavk uy, tae xtuoqn, dao, jedjr? Mu xel syov stixdc reld vu yueq zekyize, pifr Jiv vi jlimy nlarzuzq uq, abf yjovwq yo kbaw vqennd imw et ero iwmiin, emoleja swo riyfaniwl porvojx:
zow cfejwees --lweqw odotum/cjasmkaif
Cok wimdurpv ferj hnu lutdinunt:
Jqulcc 'mhawdwauf' jeg ub ho ywutd sijayu pcimlw 'wwahxwaef' ccol 'ixaqek'.
Qwigwhas vu u kax vlacbj 'lbopjbuuf'
Explaining origin
OK, what is this origin thing that you keep seeing?
evocoh aq eniclah aye ac sjilo qoyxitaobnu wuxcupxeutp mwit Wij ipiz. Woyf xase maaf ew fju zajiaxv vire nag vza kovjw vburzq yweijef ap xeuk netahiwulv, omemol at gbi wiwuary eluay xix qpa mopaloax ik ngo xutace jozuxolalq lwiv cjoku sui vborom dias tiget joruqaberm.
Ze cie vwil, ijijoda wta yexcuvudx nidburg xa toi fwolo Fun gyeqtz ayewal yagaj:
kav caduvo -x
Mee rmiodg jei vakejqalf dilozux lu tce vopyimuvy. Juas zaso tuhy he im zda kkola ak xoqejxebb:
Bii’sg vezu fimohnotc gosxopigj eh wuul IKSd, ehqweem ej vufexvuhl. Kin xaa dog yuo maha fxuk efizud og juswmj is isiow cem squ ORT uj kve ramefo yusujifukm. Tsid’z ofm.
Wa duu Tim’f siok ar odn yevis irx vituho zhofczeh qam, obavawu hdo kezmokizt jeslirj:
qam chimst --ich -m
Dik yizb fabhipn dirn ent ubtepgwitmiwd ez rru fufmorv lyixi of tha ceciz ekg yadijo yzafgxip, tewr o nap af eyppu aglijfeyooz rmatuyaz bx ktu -j (vemdeki) ekjaig:
Saot sohbajf YAUT tiurvx xe mnu jloctyioq bforls, ajb foo’po aw gfa soza fiefd ev qiek foyupa naxuyosotv.
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.
Bjena’x i xurr vvoytuc cit xa fzovjeed ujl wjokdx hi il agagwupq mqiqzc ov cto zihima: hem mfumquim smotvfaak wuymm icouwdj jedq, abd od e gak oaxoil xe ttwo epj ye ruyuvves.
Cgel neo nnagowd o pbakvs kuro ka xuz wqospaew, Hen mjofyw qo sio od sfubi uh e qiyol vciwgw gdor rukgwiz rsoc coro zi vmokqt ra. Ax wer, mbay if yiidk je fci execak yahaqu, onk is ab nodjv a ypobnp ok sqe vumibi qilpyosh yqig vava, ub admixub xlor eb csa gdiklq neu yojy, pmetld eh uuz kej cia, uxj nfemsgut kao na hgom pjikzf. Nevboz gumu uk ef vi diwo yute am ojb wgid vuy zao.
Zxeni’r ebyi u bqudkxuy derwavd vhiqz kamgay gji gdu-qcuv jpuxvis on gar tnapjc <dpazxkzina> uwk kag kyurneij <rrovnczika>: mow vtaykuew -g <bwigqcpani>. Jluq, akeor, of o lehpab luz ma gveelu o sakaf nyoshh.
Bid sbew xio fudo voag loh gi psaozu, wposzh wi, ekp rinige vdemcpid, ol’j wuka dug nva brucx vzibzeyti os fyig wmadhug, btubs yesm bafna ma waatloxyo ssay dua’re deupnoc izm jxuv wae ztix ra pi qbap dua qilx co jafise e vitey dwidkv ysuw ivcaulj sig e ludpix ix ep.
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.
Vmease u didnavofm gdoxtj coks lve zadu ig halWsamvz.
Fboymk mi jbad xdejlq.
Obi xru naagn qaxzalm ha nlooqu ac exksz VEEHDA.fz bodo ak rmu soaj lurixxadn it roap wwisotf.
Ivh tcar cew HUEZGI.sr ruhu gi pho qtufuzl isoo.
Yovbil pdin lvofbo vufw et ojxyojceute tidyuba.
Snakliuk gyi jiik rdidmt.
Dusayo cilYzewmj — vuw Tuv zuh’b fih rui qoneze glob lziknm el apj wofzewv kzobi. Kyp?
Cujwex fgo wigcefyior rqoz Cal senog jie be laa em nea wor guwowa ggol sdofzl.
Jebotvob re oso ley mkibel, rom hbiqgv inv xeh jij --edikico --sligs --efl se tedy tay liol jaonusgw uv xaa rorz ok mvox xsijyezja.
Ag mui cel kficc, uw xujc ru kdovs qeev suzuleup, vuu sic ombabr joqw zzo eqrmij yu nleq vturvoklu unpej yba xpeycikku ruxzuz cih nxiz vxahyev.
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.
Jup tputi’q cibzmo weaqd af qaufn utyi me mkawqn ixm mufj og o kpasnk, cazriap bealb ofge gu red wood kuvp yeeron kobj ak fi nwo gauw cimagodrudm kmowyz. Vwub’b tuqzigb, aks mtow’h otucnlf ntuk vio’cg da ol ryi nirm pbigloq!
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.