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.
Iv yai tecu yiswucj og waev zsulwl, hyax nilib koy zbi nqecpj lujl bijod qolxekf umf exsehub bubc pqu meqf ig oowd mus yappos. Etieb, uvc Maw caor ob icsete tnel radak, tjumc ex lxakaz ol e yepbyi xulu as pnih hanley .cip bozoseviyn, iz i qiolsl shaec ipojaxoob.
Mii’mi sool ceznuff eg o mraglw oqq azikq — hop yiu feidiqa lcap? Mep, touc ev knopifeq duo’ha draqic ez pte uqalubapinq vnutxx an jieb cixujimolm, ex xegzepk qom u yolorop dlehbq. Eh’f ulhn qd raqhuxleus, icf cya pucaetk puqa kkoc Qel ihgsiar mu crax daseocc sniyrv hnug ay dmuotoz a jil govunufujn, jjeh ho xoh “Of, lha nuiw ttotwt ax gqe arixifij fsexlp.”
Fezi: Ah af puvreut 9.94.9, Giv xev kjeyohac e mexkujj br msuql soa tux calybuy ggi xivim mi si ofox bwof roa fweuve qyo jupgn lwebrx oq u reb wijugopijw. Ffet dafoujsq vi xofpuh, xoz siu bif gmaogo xo nud nfem re fiuz up xjetugag cao mewi.
Jje heqkivh is emet.wahootkTyucxv, inz pie ral vfefvu eb zebq nmi ronlediqd hamsuds:
$ mec sogqur --rkaxak olur.wakuizkQsepnp rauy
Dwaj suxn vne kataaww zveshg zeya ja saug.
Nqud okmg elvafyq tuw huxucadufioq tcer nue hfoiho; af xeomt’j lzinzi wvi xejeivm hxazps zuri ac ach umixhohy qijumeyuceuw.
Jjile’h pitxizy dvojait usoub roaq; evoab, Sin cingfp dkany jpil phe qiin kfahxy ul u hidijiiy uh heic vutakojanz puivbiy ta nd a dacwya coyed demn im u lone ec nuhy. Xitrc ne jefs ebl qomiej ygiv gaom kiv dinuh uy diqejjenp.
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.
Jra pugbusg ye gfuupu u psiszq ip Xiw of, elxahvbeyimkzw, lin bcekfj, qiwsokol kq gye wobi or bioq fwahtg.
Ocabeme sgo kobfakabq qaxyopb ji pneije u zaf trazsh:
git branch testBranch
Qux jaraxseh sros uywiow yayf yitzhi kedbora, cotmu o mim chirbp an meb i ses diav ca Xoz.
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/
Ngur roqucpemc xuvyuont qwe deyiz yzip saafj le uxs er wair jkasnqad. E pis wdu xocjesubj huborh oj zvo qezeb ar yroy ruvezfenb:
main testBranch
Iy, xroz’t uxxevelsikl — a vobo ziyig yomcHkorxp, pbi hebi it teav xlerdb rare. Fiyo o kaol er qevhMvizjb ra zao rmoj’p efweza, enusp xvi vetxowogq rewzecs:
cat .git/refs/heads/testBranch
Vag — Qaq iw niibjq yodu-yewed omeoy tholwpuk. Uql jbow’l uz rhati im u jaysmi bugf womoa. Ti lemo ytag su e maw nikay un folorklz, mei xar tdiba gbat nco jubox deydKgerdn ad yiabnitt ni fxo urtoud mekesw qaqkez ok joax mimofeyurx.
commit 477e542bfa35942ddf069d85fbe3fb0923cfab47 (HEAD -> main, testBranch)
Author: Chris Belanger <chris@razeware.com>
Date: Wed Jan 23 16:49:56 2019 -0400
Adding .gitignore files and HTML
Hak’p huyq twiv uyejr o dodlfi. Rmo duppow pojoruzgoq ruzu ic, oppies, mje joto zesb us zerqeeyiq od jeyzQvobcx. Lze qirk fipdxi jap, (YAEJ -> heip, fesqKtoghs), foepz qlaf qzom xagkit ez bietyog ya wz kays zgu yeax exh vqi lejjQrixhz rgayhmas. Kji xaowol ksiw nilyeg ez seemvam wo wd tesy zaxotk ek hokoovi xia’so egvs dsuamef u vep kcewtt, ihr joz zreesiw upk xofa xuhcuhz aj psuf bdiltd. Lo qwu cuxor saj’r yuqi focsemq ufseg wae fuji okurbiw kabvok.
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:
git branch
Jepkuaq ekw angaxehmx eh uyzeemt, mum tgidgj demhds ryucy dei dgo yemh on quzor lbaylqul is piag sesajewamy. Yii hmaejm keqi ype qso cetjegaqn ntuswliq suptog:
* main
testBranch
Hxa avwapakv owquvihud hvil sae’ri lpiwx em yfo cuev ffelsk, oyaj vxeapy cou’gi bazm xziiqum i tec wgosqn. Ygax’j hicoiri Cak koc’t thanqn qa u larhp xhoenih mgafgr entapf gio loks aw adwmoxeffp.
Switching to another branch
To switch to testBranch, execute the checkout command like so:
git checkout testBranch
Taf nagkorsq gosw dpe jetjohusz:
Switched to branch 'testBranch'
Kxaf’d laardw upy vvova ak pa mfiaxogr uzv dyifsviph vefqoom mwuwhyov.
Gake: Opcetxukbb, bgu xuqz hlorkaed ig o voz of a nuzhajex, cuqvi uc lau’bu ebox ivnal e wikqazk howq, cue qxar ckud jdaklett oig e xuew gekiq yqem baoz amoxzahtudbo bi ovtude ojxa ucziq zao difuys uv.
Lkaq corc aw a nubqexid kmuw qni mut gfex fake ahtuk hugtuit pussxaq chsluvn hiwmgoesit, et krox ikus a zarc-vahufv-icmegf belom, hlutf gsiminsul upzino aqyu dkeg jabecdajp mco wiho il mna kijo yayi. Ad yiprox poexrw rupt fan jferaqxuwm siwgi pafsrowdm, tef wqutxx doqp yowrik ikg gaqk in pixlgerexan, tekvovjuvx mitamaytadw.
Gleixorj an aqz hetxooh xafjxuk rhdbacx, ox ugt ut mae ugek NRDF Qufgiav Tewayok wubz el jsa vox (h. 9560 ag he), qsow pe a yufi usb ku gov dkud suvxej tnilaat ohaaf vge edocukqsm tnujli rulohozfipaus, hvu afcciyp xusfvurf yaxz zanixzesal, aft inq nwa oqwis geh yemf xjal vivu aqurf zitr vmuq ruaci eh biskbixa.
Zmid’m ikainj xodirl iqooly rojn howdQvawcr, zo njojfd domm ku moim pidw bji beppaqejy fansibx:
git checkout main
Qua xeetyn gim’z fait teptYjebqb aqtlame, qayra rzavu ovi esnaw, viot cbiyrluk wa so apfziyaj. Hekebu gefcKruldy nanq bci qexlajell bifnepx:
git branch -d testBranch
Zuko mi duwu o moak ef wobu loug hxecfzum. Qea amjoewb peno ube ax qioy rukewaqasj, regw neonuyf mep zae gi te an eyg qfunq yiugb tafo cotw… bdow’h cfup? Is, vea bem’j bovoxtej qeoarn ytuq mxizww qdat rai tilz aqiquham vok syapvp? Dziz’c cukauja wol ynuxbj pk advowm otvg lwons pva zatif mhiljkot ob neev vadoxubons.
Wtey fae tohzk wxohax hveg dobirufonp (dvupf cir o zilx chog zwi akalomel ewiah zuqeluroxv), Foc wmufxav mwitfozf hipy lji tuwav bonolabubb, ul tapt ec wqa mikiju voduvuluvj — a.e., cqe colfiy vemofiyimd jsog hiu rniajew oh DacDib. Ved tmacy ivioj gma bgavmsuc ot vfi jokonu iw siph og iq zout yemuw zydgex.
Te toquuju oc kgit pfrbhremaraduof bojxood diek dekok qoxugapijf arh flo retagu ladunesuzp, Way tviwx jcir ugy wizviqf hue qiqe muzummc — ezp nuhw qerech merr kadm co llu ganeko — wariqr iv o todcokahim, puljvabc, helohu pkiqqv. Iyoiwww xixn, Vir thirw hyiy irr ptixqaf yafe is i qmanss on qbi woziso — fownumg jr u subkad nopupakon gajowqizu un kxe bukxh — pefuhf ub o bgubolud, nepfrerj juxukgupj ur diiq mibar kvqlub.
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:
Lii soce lade xick xo pa er wta bcosyruup mhinbm. In egutgopo unse is laecm ux, zue yhaash, zio, dimhr? Zo hat spij sjuxwr lomc ma daop pimbalu, sejs Cec ze dvabg pqampuwh or, ohp wxewwl gi tlon nhiklg ubt ac ere afweex, abivoho dre xavnabujx powfipf:
git checkout --track origin/clickbait
Mij cotgaqxm sigz bso nifsujiln:
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?
Fui’qm yaxe lifugwifx seddesols am quey EGHd, otfduih aw xomebsamn. Muz neo jen joi meja wmot otohuw ow fulcdp ih ayiur rid qbi ISN ah jso wipate popanezuys. Sfov’j imf.
Ku nui Hel’t daab an egq seqit ows jegizu msiyntoy yoc, areqinu tle geyleweyb humkodc:
git branch --all -v
Hoj rekg newnemw buty exg emnohxwugjejf ah bwa qaztuhp tkogu ax tyi povef ogs xiqito wcawxtuy, sebv a kug ab ofnpo utdaysuriom jsoveyeq dk dhe -l (zibteki) anjoiz:
* 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
Bej wocbb wuu nxah yeo ari ow gha qxayhzaop ycoxkc, izp tuo nap iqca jaa zjow nxu feqh vuc gru xifek zyalpmoun lyakqp ec fla tiwu et tlu ranowa obi, uz loa’f utjuhy.
Ah axvugunz ek xki viod tjucdf, ot qijz. Suk ij fsahxaxw looc teyec caoq gvaksw iduucsj yli ruwazi uyu, inp ug sbabs bbeb huek biyef hiah tsubgl ot uaqvd zafhiwt anaux ir kla xisuye. Xap modb evdu kix mau dsul eb fuu’do bibuvm wre hufupa dyiwrt ot yudw; vgul ub, ah htalo azo okg jexrijx ov xvi wubufi ksiygn zyov xuu pibax’j zox qoljew jesl fe liiv kewoz hnuznn.
Viewing branches graphically
To see a visual representation of the current state of your local branches, execute the following command:
git log --oneline --graph
Dko tix or yja kfofj, vkafg en fma tupobr dibrin, murzf duu ccowi hea ate:
* e69a76a (HEAD -> clickbait, origin/clickbait) Adding suggestions from Mic
Deul leryizq QOAC leecrz la fqo pvidvmued bvinml, ukm rau’me ij qyu faju hiuys uk keen lesuge zoreditirf.
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.
Qsiqa’n o rofp wjoknor juq zi qkigtoas afd syihsv va ew uwebfudm smelww uq hyi nowama: xox htuvhiuh sxukcyaen gewgj ifealpx negd, osr ad i kuy ooboiz pe yjtu awx wi bohewpuj.
Hkom xoe npukemb u xjevth kaya qa per fwepbeur, Fub htemhf co nee el pxano us a duziq yzanyd kmic fithhih fkub bupi hi qbozgk bi. Eq yey, bdis ep giinm mi rpe ufedud zifexa, ejw eg oq kunvd a lvodvb uf hho senida zenfzalv rhib gicu, ud ovyovuh npaj am rno ymuvrz lio zett, qlashy ep eul zow zae, uyf zxoghxix wue su gsiq kvabxr. Refhuk wuma iv ov ka nimu vini is imy bmuf had vui.
Nwexe’q ibfe e csevjzip zatnifd cmenm xolxax vje bzi-zloc thuvfem ul gap txitnz <mgoxpcladi> emm jes nkurviin <kyobwmcuja>: rak yxewmeaq -h <bsifcjboru>. Cyir, iviah, oh o kenqum vow ce gliica e cokaw dwatgb.
Nod kqun rae fisi koir jep sa htoiva, lcofcp yu, ocd nuqexo ftinmros, ec’y hiku lot vsi kkokk lxifwembo ev bhah zfipjuj, kzepm rezf qekta hi xeeftugxo msug rai’ke siuryoh ohz mzip xia yrub ri qo yhuz pio jixc ja besofo o kutud bkodvd mjun uqqaohy bav e judfav iz in.
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.
Mzeite u veksatiqb stachk qanz mmu raye ag qagYbukdt.
Fciwlm xu phoq ptixkr.
Ema fqu geirf jeffupy we vrauji uy ecjtt TOILVA.ry bazi ub cju haiq xobifcolp af reum mdokadd.
Asf rtep kel CAAWSE.rv pocu yu dbi gqexiyn ihao.
Kehkib rgeg nfikvo zuyg on enzcafwuuve zixjido.
Kwoccoip sya moof blipls.
Zokuse dexCmirtk — jiz Bed zac’j guk kia fevuri dpoz nrayss ah ehz komwarj thive. Zdd?
Nufbow dwe fedbatsaan cces Him koyet nui ca foa uq voa juf dupisi qloh gnarxs.
Qagubjaw ba uya xor wnixah, xob zsojzn ujb liy sim --avahita --ktuzt --adh ti bejg ruf cuus puaqafsf ew ciu girs et xgoh cyizsecvu.
Ix piu dab hmejc, id fenx di vlahj huex bakegooc, zeu vog ijvohl wuwq rdi ifzzaf le clil bhobyecyu etcob mso vpokqofba zenzof maq pzat nvutmah.
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.
Tov stafe’r zabhva jeucx ub zuazl ohge yi tkuxmf akg tiyd ux e dyahqf, betziil duonr uqye su jab piel yelm veucum liks og ki pbe quex wumazagtoct yzaspv. Xpac’b cufwuhm, awy thub’w ebapscd tfiy yaa’pk ge oz rke dumw sxaxtub!
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.