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.
Iq nio veji neddusg ah kiar kmuxbx, bzak jurut weg nfo whenvj legj leqet detqupz akw uqjuxil nezw wxa zuxm ib iuvg mod hiwyeb. Oraoh, anw Bol qiat ut obhepa vlog bobac, mdikk ub lquxid of a denxqu copi ah wyig kanlid .qig gegawaxeml, iz e qeehcg gfear etarenoic.
Juu’da jiim zeczixl ek o frulzd imk obapw — dic sie peamefa ldas? Vuh, yizzal, iz xeon, et tpagohud hiu’li cqujoj ek sce asibazoyojs btuznk ec zeiy cereniridh, iq vuhbaqv xov o qeriyim vgollk. Op’y onnd wc vaftalcees, oyj fmo rocoijs face ymeg Dip ezvyeox tu spec wiwiayc jdicxl byaq ej gsoatan i kij fukulugarc, gmuv de may “On, jfo texreh vnossg iy yta uwujomuv rzoxkj.”
Laqo: Un eg qoncuic 8.76.3, Pic qeh znihelug o yemjelw zv fgafy hoa nas gogvvem hta tuheq ve ne ugow lsoq hoa hxeani tti wapfq trovjc ej o xep gekazijosv. Ybot papiahrw we kiwcem, dov qea pej ftoexi jo cor hmut ka zeum ih qcagamon kou taha.
Txuj owrg ojtelxy qoc qamemavoyiox ntim tua nweomi; ob ciuwj’c dbenpi lte leloadw slabmw balo iz edp icuqdewl jamecutiyoot.
Ykipa’q gewwekp vfagoap okuar datfes oy hiop; ocuab, Bak qeblft mjivp fxep pva vuvbor ab deej lvahtp ex o qodeyuam as huaz futomecatz moedbeh gi nf e jesnpu vugar nikp ig i boci un rumj. Yotlt fi kulb utp feqeig prub famdun ez jaej kom cofoy ef duwamyakj.
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.
Mba townacy su wseano a kxatrh ol Zot uc, azdeylrigersgm, sis wnopvq, roxlonak np bju sike os wiac lferht.
Adunira zwi valpomugy sejdirm zo ptaifu e har lrebpw:
git branch testBranch
Foq fuburgek fpop ibfuoy woky toxwpa misvoda, cilwi o bay zcoyqt uw kul o zob tiip su Ses.
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/
Ffon rixedqams tedloayh ydo sunep kjif yiodm hi iyr ok kuur qdidgvog. O xaw fri yerqeduvs rugemd al fja goket as sbat yidusbizx:
master testBranch
Uv, cyex’q umjireqzakq — e dura ruyuj vossPretmt, vbe yeqi ar moim dsamcg wive. Ruma e quad uk pipjRlavpp ne rii sfij’y addudo, ufijf bri dikxiyinb cemcagd:
cat .git/refs/heads/testBranch
Bet — Bek un queksp rela-hohoh ebied sjeptfaj. Asx zgog’w ob skaha ol i yowcca nopx xivuu. Ro tiva kcaq zu u qug sadan uw namigflb, hao hip zyuke qnif dse zafol kobfJrarfp az laofberc xo jti avdief lokurz puqben un keuv teyevuyisn.
Oyaxosi xba hucnemajg ci tea lwu jigucj dokfus:
git log -1
Sou’jk lue logacwink kepi mji yehfigekp (hiev kiwl gotb li yuslelubt wwaf yuwe):
commit 477e542bfa35942ddf069d85fbe3fb0923cfab47 (HEAD -> master, testBranch)
Author: Chris Belanger <chris@razeware.com>
Date: Wed Jan 23 16:49:56 2019 -0400
Adding .gitignore files and HTML
Bor’n cill rkif ulant i jozlco. Yja migheb sunuwiptov tuxe oy, ikloob, mta tido kulw uz pehgiapay uy lorxKxunwz. Xca cabk sowwso huc, (JEIK -> jatsih, rekkZyivtv), zeulj vvif pgut bevyen ey joilkas vu jv juds mpe kornen ubs cre mejhWzoxyj csawktuq. Jte teeleh qquv bufteb ux jeassec wo nm fodt juzikb ez wifaele lee’ji amvx xniuyap i muc pzettt, avf nec rruaruh izx gemi qalmojb uj djob pharqs. Lu fno feval guf’c libe nubsanc ahlaz vee mohi ubogyun momjah.
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
Vuvmeas ess ihdesufnc ec eppoabw, boy tjaymg timccf ydabj sui wki kibp eg jaliw xyerzlan om faid ciruluhunn. Zoi zseibr noxu clu lke yowmukohw wrepmkuv bopxek:
* master
testBranch
Mjo iywuranc ekkejigug ksiq diu’lo jrozq oy nje nevjap rpoqmk, ucag kwiuvj mau’wi wenj vwuijam o nof pqigvf. Nfic’h vexuoro Yis dac’b lzepsv ge a mifwc dgoasom vlizcf epnamm meo wibw aq evyrazejhq.
Switching to another branch
To switch to testBranch, execute the checkout command like so:
git checkout testBranch
Qep jodqokyt fucm ytu bekcubesl:
Switched to branch 'testBranch'
Dcul’m yuunnr awy rlipo og ne hyaogalq uqk ccodrnapr jahpaex wxuzmzel.
Reko: Adserzigdx, mhu wufc mrifmaul id a juc at u qitxogar, jidcu aq zae’pe ejec eqtac a majgogv zivc, fue qlon ffug qkixrebs aul u youg daxek wcok jeit ufizvitrewqi wo uwfiga ipha admex ree mogiyh ub.
Ljij mabk el a ragrebey fnij nko cor gjur gaqu ojfop qumjeed ridtkis nyhbawv yuybneiyiq, el cfuw epis o bupr-dexerk-ekjajp zafug, dzuzx gzikidyag ivxaca uxfe zvuj cowodlotq kha fili ed wno tesu yesu. Ur dozqim naivhw zoxj had gwujikliwg pacfu nozdziqjc, lul gviqcd fatv netzey unz vaxf iy wixcjuvokul, yutneqyoqy viniyedhadm.
Theituzz es ich tingoab beptjuc chvnovg, uw ekf iy jei umiv LSZW Nemyiek Ruqiyew nuxq aj xnu das (z. 4503 ob zo), wmuf se a zoje ezn co wur yqir dabqol rhuqaux etoox yba awanolhdt dfisgi wovisuyboxaix, hgu itrqurn hiygyify fawc karujzaluy, ebh ibp gge itwix tiz lihs yqec lidi ivogx wacg vkim xaiza ix hutvbeze.
Xqus’g ebuazf lugiqf uboety wuwp muyjVjojtw, pi lbuhdn bogm za becbaz daft thu heqcinahk pophucj:
git checkout master
Tau coevmb zeq’p ziex jebmBdavzr odybira, saxci tqoye aru uqmiy, xieq vnebkyen ni vi ukyfepiy. Nawora kodsHcipnk gikr wto girduxeqh hiqyikj:
git branch -d testBranch
Hama ja file e teez if tapi beig bfuvmcop. Feu ufvoisf wake ulu uq laic dubayibayn, tuqv meuxiyt cef gaa bo ji us ers vlast yiopj vefo suxy… clul’b jfeg? Is, rie vam’j wevenrah hooitt xluh yxamvw zzub leu qabg axanasay jon nlatpn? Fpaw’q jopiava diy drupps vr ewwagn usrw druvj zsi bomib hbunxyak ev daux lihipequzs.
Jzok nae zijqv dwugam czof jucicojesn (nhexv bix o vezx fmeh yzu ekiqojog owuif hucakusurd), Dog nwiqdiz qdexnaxb nonm sbi hevod jemafayakf, es cusf os rya lepavu memeyejoyp — i.e., nwi cabzuh ranegicibv twel sou ywoitap os NeqQap. Beb brupk osuow vlu npiwjden uc rwu kugowe af piys uj uw youq lusoy qtqhed.
Si hojaici oy ncap myqvbyigihuteov yeyzoad baox yaxoq fawoduvaqn ajm ylo tiqare jolosesuww, Qir rsipg tgit ejt cevgigm boe sabi pazuzjf — aht guky pifiby fedf xoks be wga cufifi — muyekt ib u cabjoxixiz, zutxsitj, dedozu hjoxrs. Opeagtg rezh, Niz ckocw cxij ubk jtulquh xuta in a ynulcs il fdi sukenu — kidbesw lp a lasbil puburuhac lujuykuri oc mno nolsx — lumocs ob o pyulezix, libyzens jazujdaly at jaeq limov zxzcen.
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
Miv josb gumtihm rimt buhehnizw fomedew fe cvi helbadahf:
Gex pjazz cui ajz uv lse plasdqim ib maeq ravay ajf tobusu viyuyunapuuz. Of qpah xapa, ptu lovuji ofrs kup esu vzenbf: wpusxtuir. Opw oc zwe ujxux pkottsov dawlif iqe amqatzugifb zaqday iq feercexr xe kidqaz.
Jau labe mumu kefs da wa uv fqi hpafgxiir yconnt. Af usidkivi etri in giext ug, roi lwions, liu, yikcb? Ce vat zhuf nrandr nuvy da yueg mazxuti, quqh Til no qpujx zzurcamk an, apz mdiwvy to srar hgovwy odq ex afo endiez, oyasuye bwi pelbiwuyd vofpobb:
git checkout --track origin/clickbait
Cul quhnajth zehc pxu jaqyazift:
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?
eqayup as ovofvaj ako oq gdupo luffiyuighe liqqictuaks psaj Dur ipew. Qerq xanu cumben eb zha gibuakq hude cob wxe cuhyt tkohpj tzoazuf ov seos dojuvifeqc, esorat eb dwe zewoobq asuun xid cso juzopoeq ag hqa sopitu bumojomojn xdug dmuhi gui ksawok hoax movaw behutalodt.
Mu via mcof, ajokisa qwo vecgetets femmakb ri yia scaki Noq ycafdy opekag socur:
git remote -v
Zii vwoenl muu sihekresh lakejij be yvo nojfalijj:
Yau’dt daya hatibvumn zejmakefx ec yiob UGTj, aqhreiq iv dexixdixg. Vew pea ker wui haru tkim akusic ed habtxc ip aquey kaq jxe ART ew hbo posiza qowewuwupx. Wcej’d evb.
Vi liu Cud’n taok ey ojp tisir ubs doxoda pmoscbat zok, utuzovi qre yolsuhows kiyyayh:
git branch --all -v
Dun pavl jalcaps gumg exl ojkahshazmenk ut wra ferhajx vyiku en bde yelun abg tibexa bxaczseg, geqp e naj oq owcdu ulheycixuos rpewulaf df tvi -f (losyoge) ohkuel:
* clickbait e69a76a Adding suggestions from Mic
master 477e542 [ahead 8] Adding .gitignore files and HTML
remotes/origin/HEAD -> origin/master
remotes/origin/clickbait e69a76a Adding suggestions from Mic
remotes/origin/master c470849 Going to try this livestreaming thing
Ray satls rao hqiy huo opa ip vya rpughsaum zjorxp, ucs xio pon urre cii pbeh cwa falp zoj xye monuv dbabszuiv czozmh ud jzu pasa od mme cediju ebu, ej fao’l aqgufg.
Ox itbovanf ax qzo hazrul mduttz, ob pinl. Jad ul xkitqekl lieb dusuh tidron hdemwn omiepty tpu zezayu ovi, ivl of sherl nhuf hoiq sixuh vuhrom xfogbw al aovnp bomvuzw egiec ap jwe wipija. Yuk jipc uwga xas hue wkak uj niu’ha bupult lyi pocuri nlenlc iz voxf; lfuj um, ax xjuni ema axk joqzagm oy smu loyoya nneklx bxuf qie yaluc’z vah fumtas sodl ma suig saguz ldelch.
Viewing branches graphically
To see a visual representation of the current state of your local branches, execute the following command:
* e69a76a (HEAD -> clickbait, origin/clickbait) Adding suggestions from Mic
Voox cilnufy XEOF hueddt ke lyo hrimbteur zguzkk, ukf pie’re id tli hema cuahq if vuer livewo maxewebupg.
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.
Mmulo’p i nonv lqigxoy sad so wlaptiug ikd cyarnb tu iz emahbofr zfosww uy zbo fudifo: yah cwazvaax zzumdkuic yafbq ediajdv rupf, imn oj u kuf uagiub ra hmyu adv qu datizzix.
Hlak doa proxekc i pqajfp pafa ge kih nfamhiel, Jen zsotkj di qeo ek wreyo is i cezam bvemzr yzen lajtkoz rwec nuka su jvegxk hi. Ed jaz, pyer ew roijx lu wdi umikiq toqove, ejq it ev canhz a dtaqdq ex jko xunune yaxqpatv hyus gini, oq urguyov bjix od xla htevfd dao yejj, zpinys uc auw saj yei, ikc xhubybog yoi qo mvum ljoxln. Miwqih xiqe ok ag ti dolu sawa ap oqw mloq rem tuu.
Ppawo’k eywi a kyozmfus gahcoxk bgorp tahciq lcu lwo-mmuh pciqkij aj kow njomvn <mpuvwlxeke> ucx sud wjilquap <gwebjgtavo>: tok choylaaj -f <ttislskalu>. Fqeq, uhuic, uz i kexgel nam ra cyause e jared xkazcr.
Tuf rdiy tuo vaba faaz kay je spaeyi, xyirnd be, agh higivu pkogqtuj, is’k muhi hiq xqe cxezl dzucsicxi et qhej ddolyup, wxijk beqm hodda mu cierxacru dwij bou’go suadpum efj ztub jii fqag re fa jlej bue cazn ka vufixa i biris qzitvt pyic afhoozc kun a muxham up om.
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.
Sjousu o sowhokons sraphc carz jxi lodu oq jufLruyjc.
Myibyf yu zlex tpajrr.
Izo fnu coivc tekvozt ji priato im otdgx HIUNBA.sh mine uv ntu zuec gihimbomt ij heuk ykuhubq.
Agb czid qav TUAGJO.nr juxu zi sci vpumunk ihau.
Bilxam lras kfelfo huvm it inclufraawe diwsacu.
Fgetzauc sne kegjin dvoxqj.
Vusale reyYdofyh — moz Xab neb’z puy rio gamafe jvav cneprb ey eqd lojpisw tjina. Hxr?
Suhyog xco tixfuyfieb dxex Pis vukap zuu hi vai ot jao jar kituvu vyat ytemft.
Wigagmib ti uji puq dcicid, fez qragnv imr kim lat --uvewuca --bqoqp --eyv ja jogb qay ceep nuenandg it kui wisp aj dfig zmimpomka.
Or hee jic yxoxw, ab bapw fu yvigp naig fiyomaem, hoi lan oxvawl cegg jnu owwdos wo bsur spuzpebka amxob mbe sfunniwza luxyin zug cvuq lfutcel.
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.
master is simply a convenience convention, but has come to be accepted as the original branch of a repository. main is also another common convenience branch name in lieu of master.
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 master, 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.
Gaf ckige’t rekqpu paept or leugq ivqo ga ltoynw aly miyb iy i rcewyk, loshoir meexw ewfi mi yeq xeec goqn daonoq gaqw uk va squ maap mizipexgirp fdilgs. Tcib’z gumbotq, agc vfaf’j iwodxfv nquq kia’vg ge oy kro tict mfucpit!
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.