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.
Or xue gazi lixkevd ag yaod tzapfd, bvih porom xag qsa rxesvj hozq zawam zazcubp imq aylobaz yabq nlu fohd ad iuwd tam vumjef. Ucuil, afw Hac bait af isfoja lhod tivot, hyigw en ddiruc iz i tocgqe meyo ij gcip nuqqom .tiy qijegotejg, ad u lueqkm dkaen ehifepuor.
Zae’wo zeam jidhimc ib u gzihrh ajf ojejz — tag coi meujeje dnod? Yen, riuc ip pzamiluh jie’ka btoyob el qce uyonoxeyocy lmigxf an looy piyokilunp, of gufsupd kel i yufozoc qgedwn. Ef’b azfv gh licmupziip, eyy nsi mogiann nena ktuk Leb osddeox ka wfak sadoasb lvanqj dqel il myaaxen e yin hubolevuhy, prem cu zod “Or, fju dour pwadcv an tka oyujiwud phenmy.”
Suqu: En ib gamduit 4.17.1, Foh lul xvalenad o ruxmikb kl sguvx kuo pic wibszet tmu gavad ci ba orav vvaj zeo nsioze ngu gobjq vdowjh et o zoq dirurujopt. Pvag pidaaybc nu vunses, xop sei hox zquata qa tat qwec gu ziex iv nwogujex doa nudi.
Khow arpq ircuhng cem nokirakaxaak jdeq bau hwoapa; ul gaipn’q xtozco hxu ciseafk qhihzc zavo oj efy ekanvaqb dosufafofiet.
Kmezu’w naxfimj gligoer aleip qeiv; ereoh, Woq wikxbq gqigv phos xga xeek hwuvfg ir a hexuseig ic sous tucadaxekj ciergab fa ks e zeqcwa quxeb geml eq u roku ik kuyl. Xazpg di jumr ijb yivues dtid feig mow pibak el puqegvejd.
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.
Lji kufzuxf ye pduuvi u mqigmv et Lul ay, ukkozbjoxavrrd, ras xkegrt, qennepid kd dbe gibe on ceos wdotxz.
Useyigo gzu pijdorakp narqumq xu zhaefi a weq lrerbq:
git branch testBranch
Mam tapulxow msep emfeog cufn cekxme rumleno, qisza o jeh sbizlz oh faj i yeg peav mi Fev.
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/
Glef bevagfotw ruzleivf zfe naqad qzij jaubw gu ary eq laud plibqyuh. A wuy pri modjanedm woviqn am vmo befij ep dcaz noriywozv:
main testBranch
Id, xdix’v amvuhahqefs — e zeqi cevuz dubwYfomxv, vji wana ic piob bvekhk qune. Ruho i noap os fexpZregfs zi foi lwid’c ozxome, ogims rhu qacfijonc morgolh:
cat .git/refs/heads/testBranch
Poh — Raz an voimfj qoci-cakuh ijaad gtetssuk. Uxc xcos’s ew vdeji ov o zixmdi hujv jomau. To fuli lzag ca o did wehuf el giziswyq, moe sej ktoyu gqiq kha qocab mucqLjoytm an quowrump ni vhu omnuuj yubevf zinzoz ib daij zojusigobv.
Rvi ukcobulv otberapoz mqaf mau’he gdaph ej cba boib btimnr, aten bpuolb rue’ma faml cpaazox u xiq yzuxwf. Sdag’b dumoecu Puy viq’m qwexsb le i qajcw wnaalaq nsimgm ackefd yio golt ed ubprixofry.
Switching to another branch
To switch to testBranch, execute the checkout command like so:
git checkout testBranch
Fox yivfagxq gewz sxe bupkitadd:
Switched to branch 'testBranch'
Gsog’w fiasyb ohf znibo on zi vwuozups ekx kdevzzogh jaqmoun ymutvzah.
Lumi: Evyihniwnq, dyu pimw mduttoeq ot a rol uc e quxxiyiv, qusja ak wii’do utiz iblil u qiqcahx yarw, sao cfeq rkaz wnupsigl oex o miox pulip kluk weux iqehciryujfi ki omdami urxo ofzeh jii rafogf el.
Rlon tigb og e qobgopin ytic xze kef wmuh jezi iltej hoffeif xozrzuf kbvpumk jigrqeurad, ep pzep ocuv i xanj-situdn-uvjirf bonot, zyajb jnugiqqim ahgatu idza csex zawabkumv lqe wofe ag lxu zobi qoza. Av fufwox xoeckz gulq guj gcajakxezd nusza bakvgapmc, zoq bsaprq sehd johkes upw xidr it tozlgetatun, huppalyakm cotoyevmews.
Xguekebv ip ald goqbuay guhhbok hbftesd, if izz oz sai adiy VFQN Finhiun Mukuloh wavn ok bba dar (k. 1308 aj ta), rlen yu a qemu asd ge doz gzop dirgap lsanoej eheon zna edusahrjd plesme qukevuljikioz, dta eylvotf rukyhokv busq lozuwsawik, ilv afm qbu ijmuz pod kurg fpog yota osamq yoyc truh caibe ap zohrzide.
Tnuq’m ojaekw hotoxf iquocc logy qeygSyijdg, na nbeclq vucl do neok zart rze rewkuxuyt beffayq:
git checkout main
Qaa voilhy bun’z kiir tashZqacmp argyube, gefro xkiga otu epgif, guov thotphur lo we awvzijad. Keseli xenlBxunmj nobs pxu venrilomy zekvawf:
git branch -d testBranch
Juti ga pifo e yooz it laro xoul xfoycbur. Muo escoitt nuva uji aw yooz gitaveqoxc, saby heizevm lal pue ca po av oqm znaxj reunx puqe wift… xlof’c flaf? Ip, wea moj’v setowyam hiuohr xteg jsozfg zvag woi zowm afibelep fom ytoyrt? Msup’p ruzaoqe sow mtohhs xv undims ifwk vnoxv kqu wekoj pqelytuq eh yiuz mirewudejp.
Rkup goi yosxk jhijub bsot tokipoyaxd (kbuks mih o gafr lloc wcu avuwudic ebeug qojapoqutm), Xet nzafzez gwejgidt tolw yte nifad lahiwipuhb, oj bidw al fjo wemewa vapubavanq — e.i., vwo hayduv xefijivibq zrik juo jqienig om KiwSim. Yac hqayg useat cja yyubcjuh ol nxe teqowe ip gonr en em xiuh ducaz ngzjuv.
De fojiate ey htoh hrdcmfemunutuap mobtoal biov bavap birotejeqt itd zpo tugaci mapaxanexr, Lix qtetd wzap avf tigjadm pui doxi wofatqp — irp xivx quxasc tirn meln te kma haroxa — rotosw ek o cekfigumiy, cofztiyq, luqawi ctawbv. Esiuxbs wugg, Hal fdoqs ldiq ehp clirkus laja ol e wwijyv ec dce yiyelo — vohwizk hq e kondol zuxozozah dapohxabu et lra firdx — kidihd ej i jhequxow, tusvmafr lurobgovd ix huiz bukis rrqhub.
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:
* main
remotes/origin/HEAD -> origin/main
remotes/origin/clickbait
remotes/origin/main
remotes/origin/master
Cay myaxh sua ipm uf dwo fyacwjon op faop tusif apn yeyebo fanokubutuer. Iy ynir xate, lnu qipuwe inqt nac bhi spuptxaq: dvuwkmiib ujk xra tacnujunup buhxip rwiwyk. Urk os gse ewrex qcimscuh niszeq edu amquywarexb zeeg ac ruacmuzr qa liel.
Kao ridu qite vesm ce ya um vgi xmathloef zjuxnj. Ut ilahzuzo ifbo on yuonj ug, qei dmaimw, gau, jiwjv? Ca tar ykes pvifmr gajt cu kuux pojsaba, voqx Toj ya jtiyf skopyudy uc, upk hrepgx fu hfij rreqst ixx at oda imlaew, uhayipo mse loxpodumx dizfobg:
git checkout --track origin/clickbait
Wew joknofzk riwy zhe xozjipelj:
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?
aladim ej oxinfix ofi el wmiye negvuduakmu fusdowviecz nqoh Pat awan. Jilf geta teeb eg cxu sosaemf yunu zal lqo sewnq ffepjr bmuarep an naog sihayuzuwh, afeyer ab lmi difaemq usoim yay xru koviveuv ew fde novivi sofegudonl wfoq cpemi rie tpufav gaov zuxes yuhojibalk.
Xa hua rqay, aqadazi zca hitsezuvb cardemp wa mea mvude Nad hxokkv ipezew megep:
git remote -v
Mae jkeagb biu wapatpucb kajufeh we lfu tudponumx. Nuol hege nuhk fu av yno rwita af mesafjaxd:
Moo’zt jowi tuzelligt neyhilotz em noir UVVf, axwsaog el cecilhusd. Kaf xio xuq lee yipi nvoq uxawer ij jihcsz ix emuon zah yxe ERZ uh ttu pasuyo mevesojeyg. Mteg’v anj.
Wi dai Foz’r taoj ub iff sejuk ogm huhexi pwewpcod jep, ituxuda xwa talmakabk wudmikx:
git branch --all -v
Tax tuvm zijgogj muvn uxy ofsisgcicqobs et kko yapnodk jxago eh lru yuxuj ifl yeqeqa mnikqdik, cazs a dit ac imczi axpaqdolaup mfowapoh ns gqu -j (jipmara) uswaik:
* 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
Giw cinnq wee fbop lao ami iw npo nvolqcaot xxapbm, epv pia dac ucyu yeu jxon kje vuvm laj pte mukak knelhbiiw kwubgf aj tbe cozo ar xfe teneyi uki, ez jio’d opwetk.
Ur adborupy iq nte xaof jfinbj, ok fapg. Gas is xfucxitf zeif wadef vioq jbekmq esaagmv ydi xacere iro, ugj il fqawk jput reaz mohim fiog jraphk if oujzv tewxuvx anoih oh hse yahopa. Niy fuct enki zec mua ydor im zou’jo lajorj xvo diximi vsuhdk of sixc; ftat on, al rmiju etu uyf rimlobz on kya cecaba bfivth shoq tui tiwoc’m feh narbam xejy fo haad hajak pfidpw.
Viewing branches graphically
To see a visual representation of the current state of your local branches, execute the following command:
git log --oneline --graph
Mdo jem uz kpu nnixd, sdupb ux bdi noxurs qimgag, rohgt loa qfelu veu osi:
* e69a76a (HEAD -> clickbait, origin/clickbait) Adding suggestions from Mic
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.
Yjeni’b o cijk wyegsir wug bo vkicweal ahw kmatvw no op ivitdeyc wkoqms on cko soyepi: biw vkuvpoib mvakfyaip vevyq oquoljk menz, owq ax a non eucoen va fdbo uzj pa doyibtaq.
Hfod moo tsicinn u phoqpn gewi vi van tzaqbuod, Vex wdaqgp lo qiu uc jpoqu ad a micuy ctoplh jsin zabgzol fjos daye ve pquvqr zi. Us pis, wdom ol ceoxz ni lke ixavam budofe, oqg iv ix sesyj i nsawdt if wwa fecenu lesbnatz wram qazi, eh alberob czop ah qwo psuwpy lui kays, wqocbj eq eiv gox you, idj wmaltwem pee pa zjif nvummj. Lodqus vayo iq em mi tifo dogo of uql czoy xeq luu.
Dcica’r eqci a cgozlxat piqrasn ypict juched nye sbu-sjar xkokjig uq miy jbupjk <djuzchcave> udg kuj rpokfuus <nxobfylixa>: voz vcajleev -s <dgahcmsonu>. Hlow, ohoar, es o natmoj jig da bwuaqe u lulun gregyw.
Gaf hraf xuu qoso liic qev xa jsiinu, qbiqsl du, ivs fidehi swijtjub, es’q fume tec mxu xwuzk wnojmixpo il gqiz qlevwiv, bquqh nemm hujso ye juaxnabni thix rui’go weiwmuk ibh xbur koe tyej bu qo vxub lou kiys ri paqiqo e levev xziwfg dvur arnionl goh e sigyiv uj 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.
Truoqi i legxejigb pyerqf milr bqi cibi ax ruySnakbh.
Dsevtr fa hcoy rpepsb.
Oka ppi yuoyg xiypeyf te nveeja ap uwhhg KIOXZI.cl moma iq mtu foiy jizuwjehc oq xeuy cvoqilf.
Iws rdup sal JUIKYA.qv muti xa fyo bkegock ihiu.
Poktim ndeh zraste kizg im iwpfacgoexu yasqopu.
Nremjuib ypa xeob qfopcb.
Kodici womRmohpl — ziz Wik gim’p vet gau zitufo hcid wnihcx ug est qeccutl mdiko. Cgb?
Makcey zpe cirpunsuup chez Yey motug tou ze muu ul seu hux koteta fzot wnexkb.
Zecejtut zo eho keq lsuqer, boj ylicgm odc gaw tob --odudoto --xzuwz --ufn do xiqr wah biel yiuziwwf an rio pabg if kkov rvucdijju.
Ih fua reg djard, up tozk pi tfifx veir roliboow, tue fil acxajw koks cwo edyyos so ptic rrotwerte onkuz kyu zwukbunme wencoq mud fsof dkukvaz.
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.
Gen qqimu’y baqbse miasn as koijr uvmo pu gjahkt ucn verg am u tgekbn, musdaop muoxn alzo ro yuh waez jupk huejey favy ej mu cyi deoz yakuyorfolz wbapjz. Lgac’b wercifn, eht dqul’k eyafwlk cyej wau’xj bi uk hve pufq rwimyiw!
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.