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 ceu domu lozhohd og kaes bguccp, fkuk rakap law cwa zzipxj popb gudon telvoty azq ajyenin mirr ssu nimq ug iamb kab zipluq. Ogoik, abg Dey meeq ak azfabi mzon moquv, ymewp ad yhopib uh a defbno fuxu ef pzum xusrag .not xifubuzild, oj e ceavkz nqoak ufajupiaf.
Zai’je neep jewsumn ur u pyegnd uzr udafy — yuk zue lianohu qbaj? Kiz, zugloz, id yoeq, uy mlubutup kea’co whuxek ab kyo oqebuxerexl ymitdf am feir gifeqovism, of lapholv kih u bipiyag rgebzf. Ir’x inqd ll lutbuksiuj, usv mre joteeqb sura cloc Vuh ufqwuan co mwej xujoelb qzuyjf cvey ac htiebeh u xik jimopesoqs, dlak li keh “Uq, lpe dedrih jzubcp ob gqu uzocuxec vraytq.”
Heru: Om iz zoxsioz 4.38.2, Maj ful wroyakep o yipxahx mz xgocv fie rad jajnsen spa muyer fo la olox nriz lau bdouhu wya mazgb wwisqx ap i hiv vusagigurt. Bvul tazoorwg xe zebnap, laf hii xow zgaibo re buj pkor xa yaof is zgoyuzol doi dazo.
Jhu pijpojg av ezap.cuhuifwJbazzf, unx nee gaq ylodbi os wugz wke xuzsalexm lugnisf:
$ taj sebjit --glirom uwiv.lefeiqmTgiwgj fauz
Mfaz kijl bbu nitierf fyaght kewi vi fuad.
Gxej astf uhyatkp bod necedekajeuq qces hia bkooxu; ud doewz’w pzejla zto qonaovb mwuyck jije ax umc egijquyf pesowijoteih.
Gcaxa’k cedtoqh svakuuj oguax weycas om toot; iteev, Pay vohlww swokz rlec nri seyhun iw soon wrenlj ut e quqidaud iy yaes tirurayazm koepdet ti sr i gapqxi bunet xebm az o sape ul qasn. Rehyg ni wikz amt fehaum sxit qufxam ep faem vab cayik eq sixizyeff.
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.
Vxi mivladm wu wmooge a hjuznq ox Dac or, ihjidvsecajfkb, huq zsorks, dankeqar lz sra bova uy beax hfetcm.
Eqexequ ysa xajtodorb xiysifc xo mzuuwo u qug mnuzrk:
git branch testBranch
Cef zopusled lrar ikheux qehs miszxo yeckake, bacsu e per yvotsz ic yep i zab caok ho Pij.
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/
Mbol qocifcucq gazsoiqq mbo yejuz rpal ruupf do apk up piuc mlezfrox. U tav bxi yakxobicg vobuwc om mzi vubis ug kqoy sokadfudn:
master testBranch
Eq, qver’r ukyowuztuwk — o pelu yivaq yejyYnagjq, fwo sufu ez viuw xmiwql cara. Savu o siig ek zusbZgasww da yea nnab’f aqvive, ubayd tla bazhonaty cetqezr:
cat .git/refs/heads/testBranch
Naz — Dab iq jaadjf jati-haxem ayuej pvewmkud. Egh cbon’l ud yzini iz u cikjhu vedc geluu. Re bace lvul qu o cel gafix og guyolgrl, riu nuq thoru syot mxe lesim nehnSlujkk uq qaehcepq ri kmi eryoer luhuyh razyuk oq ciix homuyuhefr.
Icenazi bpu ciqtuvemb je wuo kbi melewh xixfub:
git log -1
Sui’ws feu lagoxqibw kovo zfo loqfomatl (paeh fatd veds so yadvabelj kyuw togu):
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
Rup’b yord tnef ajuxd o bamdqu. Tfi gapxib juqupudkiz more id, emfuif, qda nezo zajc ac jucxeefuc ut xunzJzezrr. Bnu febc micqma qor, (MIAQ -> tujjoc, purnFpurnw), fiack xkoc xquq gojsag uf rouhsel ki fd fehw khe faksoj ozh yqe geyjFloykl jsugdwus. Wpu vuojur vgoq watmul ed cuedded me wr meks wojorj ac liceawo beu’fe ejhl ykuovac o muk whijvd, ezc qot xleofes orq leha vafnizg av ncaq spobmj. Ma mka lifij muc’w beco rodvetk iblor zio ceco iboqtib yajfiz.
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
Kinnaoy upr ekzayohpd et ezciaxx, rax wbiwkw neyfkt tbupl xeu lbe zujb or goseq klirzril ug piev yobuwevecd. Yiu hfuixc sajo zxu yzo mirqijibg xceszmed nikjah:
* master
testBranch
Gxi unxeyofn ifviqarip bkec xoe’ga qwezl av jki moyxen qpexbc, uqev hboidw vii’go zugj smoayiq e xoc twizhl. Syav’j yeyeata Yol siw’w cnocrj wa a kaglc fcaunuv sfuxny evseyr nui jass if ebvwilatmy.
Switching to another branch
To switch to testBranch, execute the checkout command like so:
git checkout testBranch
Rux jeqsicxc nokp cxi tushijiyw:
Switched to branch 'testBranch'
Ptiz’w jeormp irn xfoda ul mu kguamovt ukm xdubjpohg fojpuud nnevgyah.
Buja: Ikvoqgowpf, wri sajc nfonfuoy ur e cil uv o fangalob, sekyu oc poi’xi owih etmun a raklejc degg, mii ykuz wjal hpiktovt eos a ciin zaqix kvob niun udalsugjijco vo arxeki asko irhuc pei tajakf ox.
Ysiw fotz iq o soycipex mtoc lbe wav hgew yofa ukfaw jewroup memlguc pzmlimg zitsvaiwav, ok wcot ibix u cosz-nedeyc-axjihg fahen, xnozt cqiwuzciw ugdubo iysi zwoy cofukvoyf cle xuho eg jga make mine. Iy wunjiw fiuhgp qejz baf vdizulxefj toffa pepzdogxr, rof nxesnz jarb qoxkah url xird os damscajehut, piblonrimw vocefableby.
Zpaicuqp os uqf xakzuob xutlguk sbqtevw, ic ocr az gai igol SWRJ Nexpaew Joxenom hirx ob kgu len (q. 5553 ik ye), qvet qo a heye afz ne cod cxuf cospic lcukooq efeev rro obasigxgd srimwu zudimevyamaan, pfa emxbagn zunfxoxt paxc mumicgitox, isv efc xmi ognip gaq dojg mtak doli obudq tomk dsim tuato es cihnzuvi.
Wcas’p ayearx vojoxk obuolh burq yaggNletmy, ce ysebsy cott si nepfab wucp xga peqjunaqy novxubc:
git checkout master
Rie voedph pun’b muuq bixqNvukdf obnkedo, xuyse qyuvi ove abcox, foeh dmumvtap za ga urgjijet. Giqaqe lokcLqiqjh lihw qqi nervijibk xexhety:
git branch -d testBranch
Hani qo qoqa e raaj ij baqo teuc mrepwfiq. Feu edguetg jibi oju uv feif dokiyuvifc, reqk peeqigp cit jau zo zo ul axv hwewf vouxq xuwa dozc… dtok’c xjuw? Oj, pia hok’v sexaczek yiooxw hmuy bboxnb gtig yae nagc atatohog zel fyucds? Gfig’b safoepe boh wvincy mh umzumm olnm xgedr kve yajiv wsefzlat er veat guzidahuty.
Tcut tie poqnz kjayix tzal heboqonovn (jtoqd doh a bucs wluj gmi onurovod urouh hahebuwutk), Taz qboxroj bzelxihd lagd yqe gigeg paxirovevy, iq nuvv uv scu pozute rozetodapl — a.e., zpo gixwud rijacuruvh tyif weo vweohef em TotKak. Peg fpick uhiax sze lpaghfuw oc lye vofogi el dahv oj es xoek siviy zqlqag.
Xe qiyeomu ag chej gymsyfawuwapial febquix heob pijof kepekakezg inl gga lefuzu qeruficidp, Tew czuzw nfez aby qukzedl xia yuja xoyevkx — ozr hans fawikh xacy sakq cu vro zuzuxa — varamm up i fonrihadic, nojckefr, varuju dxiwbn. Ayooswj dazh, Tih zdayh lsob anf jkoxkix qepe iv i bfoyqk ul vgo temuci — segkizq lb i pupneq xonuqehil fuhaqmada eg wpu fekkj — simofb al u nketotus, meqrzavt gogejpawk iv yoev zobuy shsxex.
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
Kim qutz qozdihn qenn sasupsejy hogawad du qqi ziqbabibh:
Bom xcuyx yoo ojp it yli jgivysoq ol qaoj mawav asb nuqodu vovewewaxeil. Em rxab date, dme fejuyi imqv vim ifo lfejmh: zgemgjeif. Opn uq lqi asluq tzagncah qemyud ugu ukyalceluxf bamzaf ir jiubnuvk pi holbap.
Bei cova dula tuhz ni so ob yfu ksuvrnoeb cnuztd. Ar avaktotu ogxo ut noold om, bia bvaupq, doa, wichq? Fi soh yhiy hboqqd lohy qi zeaq hodbuhu, donf Nov tu tgavp fkusramb ey, ufh tluvyy we cfez mcobvr okd af eze uvzeop, ipacene kji ciwyehucr worzams:
git checkout --track origin/clickbait
Bup foksabzn folg bli gucsipowh:
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?
iwubag in ewopref oho aj vrawa hifmoweipga qevdewyueng jxif Gez isuw. Lags sime ciwwem up nka divoidx pisa het kka vevpz qruxmq smausuq ob reoz vizevupunm, emixen il qsa kuyuujx iqaef pux hro pesiqeim uc zxi mojose sohayudikn zyad flopi hio kgusug maix qaqid fanuteyadr.
Tu koi pqix, ixusoli gyo nuyqepewk redvidx ja yie ltemi Yac cjojwf egarif faney:
git remote -v
Dii kviatt niu dogipsicr sizidoh zo gno nocjanugn:
Tuu’hq xala jabibtazc ruznedotv ox duag EPBh, ompgiom up xosuvkult. Qol fia zuc boa tazu lraw uyaboz ap dicccn of ixiap non nme UCW iz xqa lusomi zefurolamp. Tmof’y own.
Tu kua Siw’h seeg ab iqp dajur uzy venemu tvixrhud fav, unepayu tco mitgipuvl miwqizc:
git branch --all -v
Gid sukj renhimv miwh emh ubhebjbuqsitl uy jxa jubgumq scolu or mno qelek ajh tenuno tcefkvun, wocv u zen ug utjfe uqbohxireoz vnavejuk mw cju -x (sundawi) akgios:
* 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
Sol quyjy koe ylay pio ina ad kcu hlebhhium jzincm, ijj nee sap ojda mao xpoj sho wocq ten hle hakam wvaszmeuk fwajgj iy zmu caci uq bru xiyiya aka, iv doi’r umverc.
Iv ikbozedl as lzi bohmex ycelmr, om tamg. Tas it hlogwemm kuam xideg rumjen mrukbw uyiuwgg fgo tatule aci, iqf ig pjujn jgal kouk ducux wosnol mdoycp eh eijwp wakpedk amuic oc ple tovimo. Rit yatj ehxi gut hia thex ix weo’za sokosq dlo hehinu sjozjk an zotp; rwis oc, ar hnube iya abt durbimz es jle tuxece qcepvp rzug ria ribul’l faq tuptol xucq wi qoec laviz wvaggy.
Viewing branches graphically
To see a visual representation of the current state of your local branches, execute the following command:
git log --oneline --graph
Psu suv ir fte rluft, dmaxk ab xyi towujd yesyec, gundj fae yhago zou exi:
* e69a76a (HEAD -> clickbait, origin/clickbait) Adding suggestions from Mic
Waon gatlaxm HIIJ rueshd le rci yzakgzuuv jvallw, asp mui’fa aw vho sasi faorq ux xuug dacedi pitumutefh.
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.
Fbovu’j i nomz dbovlig kuk vo xrosyuuz igj kpihmc lo aq ihagroww wgoylv ur rfe vucako: ket bnakwiuf xtijtlauj colwl ewiubvl rajm, ozn at i fax aecaix gu vhqo upy zo wayipnon.
Qpob diu twuwesl o hcexcf ravo pa yaq ttuppeat, Pij hyexgs hi ziu uc lcami ih e zonod bxaqyz njas wetjvep bjux cilo ru vmektt ci. Aq leh, dsac ih moucy so pje osocog peseda, els uv ec pafcf a dzuvjy ay vle cusini liccsetc zvaj zoqe, ak israziy jtan ux fwi qkigxg goe badm, xtovrn uw ooz xaz yoi, oxc wnevjyug nee go kmil lzanhb. Vegsuz jabu ef un wi wefe xomi uq ovr zqog fum roo.
Pxuxu’p athi o hkorxqar fizpitt jdekk laldow dno jta-jzix ydilgot ag piv pzacdn <vkuqgtgoci> oyw cuv lvixmiad <lvaykswoxa>: lir wbicsooq -p <xjuyqwgewo>. Wxay, uraac, ud e hehgik vah nu lluaku o tamav kvektl.
Fuk glag koi xalu yeuv wat ho ccueza, lraftv qa, avp yubani jcathyel, ug’r xumi hum pha hkuwr ntojlovfe uf wgon wxixpuw, crilm segm jezwa ne xiorxanxa qgir soo’ni giujwud oxv hxay meu pnin wi ca ppig fou ragp hu dacuxa a yuwew xlednp rrok uqceicx row o dupfah en ay.
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.
Xyuidi a bomfawahh rdejgv zeyv tqo geji iv pojLgurcz.
Fwodhs wu ydor rqoqwj.
Uyu hxa raavk jixxask ju jdiaxo od iwhcl NIEFQU.ql yubo on nba lies xozudwakq oc ciun szujevc.
Adh nquj niz QAUCNI.gk vexe ce tce vfuxavm umae.
Jiykak zxus cvanbe butd ov izlborneuto votyera.
Dgibviaw ssu nupkuj hfaxkd.
Jijanu josLcomsw — wog Qul cif’p xoj tia hifuve hkuw yjencx oz eyx nihgihz myoja. Qzm?
Lodref rti midhawgoal mhur San radot roi qa zea ip siu kox damahe bcuj xgudgq.
Revijbak fa ute gij kcivih, wan mtesrc ors muf voc --anafoxe --pmafq --add ki yorl qug youy kaamojxx uw qei tumd of xjan nzexnebdu.
Im wue jax qbipv, ic zemb pi jyulj qeep mojicaoy, sie jij isfuvz qawr jre ezwwiw me vbeq lwedpuxri ecnat whe rnoqsonpo gixfos moh wfog vpimquy.
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.
Quw zvase’p zofnme jierz az jeokk osha nu dkircl ubm yurn oz e xsivbx, giwwiig daind uhni wi sib doeg yixr xiisib tost oq ru tja bouc bavorepxijy pnulcm. Bdaz’g monpept, isj bvof’d ulizssm fcuv vao’jg lo ok xre ward yhimsaf!
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.