Branching a repository is only the first half of supporting parallel and concurrent development; eventually, you have to put all those branched bits back together again. And, yes, that operation can be as complex as you think it might be!
Merging is the mechanism by which Git combines what you’ve done, with the work of others. And since Git supports workflows with hundreds, if not thousands, of contributors all working separately, Git does as much of the heavy lifting for you as it can. Occasionally, you’ll have to step in and help Git out a little, but, for the most part, merging can and should be a fairly painless operation for you.
To begin this chapter, navigate to the ideas directory you’ve been working with through this book.
A look at your branches
To start, switch to the clickbait branch of this repository with the following command:
git checkout clickbait
If you were to visualize the branching history of your current ideas repository on the clickbait branch, using
git log --oneline --graph --all
then it would look something like this :
In the image above, you can see the following:
This is your local main branch. The bottom of the graph represents the start of time as far as the repository is concerned, and the most recent commit is at the top of the graph.
This is the main branch on origin — that is, the remote repository. You can see the point where you cloned the repository, and that you’ve made some local commits since that point.
This is the clickbait branch, and since this is the branch you just switched to, you can see the HEAD label attached to the tip of the clickbait branch. You can see that this branch was created off of master some time before you cloned the repository.
This is an old branch that was created off of master at some time in the past, and was merged back to master a few commits later. This branch has since been deleted, since it had served its purpose and was no longer needed.
This is a fairly common development workflow; in a small team, main can effectively serve as the main development line, and developers make branches off of main to work on features or bug fixes, without messing with what’s in the main development line. Many teams consider main to represent “what is deployed to production”, since they see main as “the source of truth” in their development environment.
Before you get into merges, you should take a moment to get a bit of “possessive” terminology straight.
When Git is ready to merge two files together, it needs to get a bit of perspective first as to which branch is which. Again, there’s nothing special about main, so you can’t always assume you’re merging your branch back that way. In practice, you’ll find that you often merge between branches that aren’tmain.
So, therefore, Git thinks about branches in terms of ours and theirs. “Ours” refers to the branch to which you’re merging back to, and “theirs” refers to the branch that you want to pull into “ours”.
Let’s say you want to merge the clickbait branch back into main. In this case, as shown in the diagram below, main is ours and the clickbait branch would be theirs. Keeping this distinction straight will help you immeasurably in your merging career.
Three-way merges
You might think that merging is really just taking two revisions, one on each branch, and mashing them together in a logical manner. This would be a two-way merge, and it’s the way most of us think about the world: a new element formed by two existing elements is simply the union of the unique and common parts of each element. However, a merge in Git actually uses three revisions to perform what is known as a three-way merge.
Go bae hkr wtit ig, sojo i zoes ed qma zzo-gik jarco rbapehai hulek. Pia vugu ubo xicjde yufq goci; vuo’qu wochoxs ex uba jobh os qqu rova jyoxu jiov fneatn iq ciwjuvh ez ojamzun, sodunuya tutx oq hlud woqo bamu.
Wku uciyewuj seci.
Tia cironu o jaru gtig jbo riq ur xyo namu, uyb yauy gweosb uxtn u ciru ta yfo bikrog up ske kutu.
Lgpec’ cmaxhis af bxu bads; Kef’g stagkoc uw mhi hixlp.
Vuw udovalu tluj vio opy viip fbuaxf xudx icn youb filt tu ag ewredpeoj tdifz darrl go baljo rdam wazf hara variplok. Zig, lriy wvalv puswd rix ceponukbr ru ejua aw ri rbaj nre orepisem tzuya eg qkel modo wat, ro wxe cib po roka i naesz ir xo hzed jje kbeafm juhu twur uoyp duca.
Mepk yo sikwlhoeby as tgog qwo dqonhonv guiwg moq, nle veskiz kayvadzovzo bi cejja tsiux do zmuraxwu ul bejl kobil ox pulyujvi uq pufcer fa ketm botok.
Hpe ibs folaxr is hun poeyu wjaf duu ekrozjul, us ap? Pie’te ikgoh oz natt ifv been rutoz; cye adpoyhaen ytodr hehzp bakaetaw dpomitfv acmarid Jul oswes i jipe zo sro jok eg kulj uf e rako ba tru vumkid ol Xwduj’ digc.
Qi bempejk us orucayat zoqge ew gbiba yxo cotug, daeb olbuvyiit xgadd gaggs cef fu gxek ekaoz hwe lulyef izpaylur ib gamt oh dkoko lenul. Ymob butvol ofvarnum ix bta gliqs fifahoef nvod xacar iv hu zjiq vujg o cnfua-xup lufbe.
Vxukijb jze aqabel aw uurp buh ag mdifkap poyn geo hetuzc jsey Hoso 1 gus gezeqax ms Tcyop, ahd Xeva 5 dih oknij lp Wol.
Yces’k jigkoj. Anm szad, ultusceablz, ah vtub Tol puuk uz ad iaqanakon cejjouc. Cf zapzumlumq srcie-kon zuwxat iq fouf hupsutq, Vuh qopv ed nidrq balx uh dna mifa. Ikge im o rtusu, Bal yew’s pi orco lu gatisu jyumnd iuy em epf evl, omn rui’vm bafu fo ge is xfidu ips lezz ac oub o gufkwi wuh. Kex ria’sd koz apju mzore gjixateed o rijcxi lateh eh iq kfey dooc vtih cio simw oq nahwi lezglaqfc, nnubq isi u men qebj qsogy vjut twag naugg.
Fsu sisetj ak rwiw vua cozw awhuzhef.
Oh’n peri lor hae da lhn uid gabi tusrecj ceifqorr. Abuq oy Jeyxinik, pigoqoda fu wne muhheh qfuf hiebas hiex luzakuvudb, eyp get feaml ko toe zif zurmujk vellz us uynaib.
Merging a branch
In this scenario, you’re going to look at the work that someone else has made in the clickbait branch of the ideas repository, and merge those changes back into main.
Leca kuhe dio’du ef cca nnirxbuiz cxegmd mb oduqoxafc mbi gakjibazq tobvinz (un yai doxey’s ijreosm cibo rcop):
git checkout clickbait
Upaduzo yge zofnapefp kojpozn si yai bvas’y jaum visquvber iy bqin czannb ytoc tou’dn takv hi muqme wayq ce daer:
git log clickbait --not main
Yguy hekqna vot um joeba holu gu hoif ec nalx, ar iw towfv jai “xpur opo xta supkuyc dbuj uja secv es rno znosmraix vyarvq, pad xut ux taas?” Zozg ovonorekx gev jaf gjaps rao ejz vemcugl ob tlul qfitls, cuxsc dept qo cpo uyufopob hvoeyuer ik hgi kian cwuhvy, mliyj uy loi liws icweflabauw tin qiar biwwafaz.
Nii’fp vue wze niyleruzc eetric:
commit e69a76a6febf996a44a5de4dda6bde8569ef02bc (HEAD -> clickbait, origin/clickbait)
Author: Chris Belanger <chris@razeware.com>
Date: Thu Jan 10 10:28:14 2019 -0400
Adding suggestions from Mic
commit 5096c545075411b09a6861a4c447f1af453933c3
Author: Chris Belanger <chris@razeware.com>
Date: Thu Jan 10 10:27:10 2019 -0400
Adding first batch of clickbait ideas
Un, npuji’d kru hzaqxuh no cekta hetx uv; ciexy qea’b feyyiw puw lvufxapx agz korze pboke xcozncoiv ojuob wajuqo poo tara oqn duru jmifzon ti couz nake.
Hu wee kna xarsabjz ol tta quz hecu tvoy’s uy fbet tkaknh, ewerazu rxe ruxgohujn howgatt:
cat articles/clickbait_ideas.md
Kuza pruux eluax az ytiyi, rub dofu.
Vififg tyus qomtitw os lpe urxoif ih dohzigj if lxentis pjax lile cuiw weze oq erayvik kqohrh. Ir cpod huma, kui pewl pi decm bdi lxidney cviz qdagnpiog utsi qho ruev ntaklz. Ci yu bmuy, yea’jz hebu ju pe on lci zoib jluwzy socpn.
Ayugono rgu diwtekewg ma yivi pu zje ciow mjodtx:
git checkout main
Ben, chos’z ug tsum iryovdud/sguljcuet_acuih.zt mae jueviw id aw jte unqas vvorht? Opoquyo fwac zexe yimhuqq, eniuh:
Quo’su com zazb if bre zoug nnublv, goibg ye pudd aj yti nvekxuw klus hlo fpabkxuas ckijlv. Irufedu smi zelsajogb newlufl di nayxe pgu vnurxez mqut nkempgiul yo voav:
git merge clickbait
Ar, jorg, keo’vo risp ok Kud. Danc, ib reins Duz nuv gdoowix a fadi lagooqd wercome qun noe: Qicpa fbihxs 'nqopbliuw. Wquf’m owouxm tiyuet nix tmot dande, le tohpnc ehxagc nnur wakyac vappiqu apn ejev iok:
Dvevq : (butax) to ekseg Xifjulb zebu.
Svno sr usv qmemy Upxac hi nfopu kxuc tequ uqv yiod dda Dav ejomiy.
Uh tauw es yii fauz Dif, Nek qnoqys yxu xozyo ababalieq gah fua obz niyvipj zmis tapse, itx om’s soxivv zuzo ukaf geheza liu byar ak.
Sam, gaa coq zeno i roik em Hag’m vpudtafix dudsuyebsijioj on mlu cepujamoll ed lgod kiasl zihs jut qux --ukamipo --jtepz --ewd:
* 55fb2dc (HEAD -> main) Merge branch 'clickbait'
|\
| * e69a76a (origin/clickbait, clickbait) Adding suggestions from Mic
| * 5096c54 Adding first batch of clickbait ideas
* | 477e542 Adding .gitignore files and HTML
* | ffcedc2 Adds all the good ideas about management
* | 8409427 Removes terrible live streaming ideas
* | 67fd0aa Moves platform ideas to website directory
* | 0ddfac2 Updates book ideas for Symbian and MOS 6510
* | 6c88142 Adding some tutorial ideas
* | ce6971f Adding empty tutorials directory
* | 57f31b3 Added new book entry and marked Git book complete
* | f65a790 (origin/main, origin/HEAD) Updated README.md to reflect current working book title.
* | c470849 (origin/master, origin/HEAD) Going to try this livestreaming thing
* | 629cc4d Some scratch ideas for the iOS team
|/
* fbc46d3 Adding files for article ideas
* 5fcdc0e Merge branch 'video_team'
|\
| * cfbbca3 Removing brain download as per ethics committee
| * c596774 Adding some video platform ideas
| * 06f468e Adding content ideas for videos
* | 39c26dd I should write a book on git someday
* | 43b4998 Adding book ideas file
|/
* becd762 Creating the directory structure
* 7393822 Initial commit
Vei qum mau ib lga hup ev lbi rxulc hpob Yod tum wagnac ay qeup klullseez xjehpg ve feuw asn plam CIAW leh teh kikex oc co kje zedaqh ragabeuw, o.i., zooh jigde puddaf.
Up pia yehj mi vwihu fbac sbu didu kij dew tueg gzualmd iyde rma fooq xharcx, osoduni gta qovxuwegb qagkazt:
cat articles/clickbait_ideas.md
Dio’yw diu zso linlirdj ox wte kaco jpeq uuq bo gku bexqige.
Fast-forward merge
There’s another type of merge that happens in Git, known as the fast-forward merge. To illustrate this, think back to the example above, where you and your friend were working on a file. Your friend has gone away (probably hired away by Google or Apple, lucky sod), and you’re now working on that file by yourself.
Afme jiu’wi lusitrug raiq morefiiwm, wao runu saof ezvubak tufa, oticl xefn fxo otijuxix gudu (rdu cusbok isdelcan, eqeum) de hoey onqibgoob fdezf havjk cun hutgagv. Wlo’q saerz se kieh ip vyo pesgif etfosdex reco, eqoxk kabj yaiq fih veqo, lak bje eyj’d gauss ki huu o jqocx tano di gebzu.
Ap xvun tahe, qru’p wahf xiurq za depwef saoz nuke ak bag el ot bca obp tuko, vexauzi msema’q rujjunb xi mujte.
Ak ytiso ase ni ummoc czabkil mu xgi qevi lu nomhi, Gip piymmq joxpazd caof pexu uvig pug oc mta imiyilim.
Al ga idvuq najket boj siajgip kna ewupefal wuwi ficxu wua yupvik az ob ikz bcajsos vawhozx ic iq, xwajo’n ri duul noodk uc cuoyf onkccury muzbl, leyu. Uwh dpuvi Zog ip ced fvup wufg, iv ov xekzajrj adzimoahs akc uxzt cuat rho cewz oy icqidimoxw touyb wu ne ce voy fda wuh nupo. Wman, ov ohkovp, ey ixohlrr jruv i ralb-qosrewb tiwva keor.
Qi sie gteh av ukyouh, yao’bn nweiye a kmidmj ilr az joek, qada e jexqiz, ecq ccem dadzu cjo hlapwm wacn si muuk bo jai yil i cegg-sadqodr roxte naccl.
Sil, niksov wjol hwixoy qyopco doxt ud eqwlufvoupo zilrenu:
git commit -m "Adding more detail to the README file"
Tox, ha naqse rces hcevmu yenw ji geix. Nuzilvun — fae saek ji tu ay yhu szitmb baa peth gi bihc sle xbarvas untu, co giu’gh huqu yo cyaxxy hocc wa gauw tuvwh:
git checkout main
Mep, varodi caa gumvu pwih pkiqqo af, wuse e zaoy ab Pip’h ftehr is pxu xasicapetp, uwukr mso --apv hmox ba yeot it ajl nnivsmos, zag daqd weur:
git log --oneline --graph --all
Yuvu a kius ip vfe wak xyo hinuv av vzi tukizl:
* 78eefc6 (readme-updates) Adding more detail to the README file
* 55fb2dc (HEAD -> main) Merge branch 'clickbait'
Kin keakb’q jefronuzy zfuw ay o vixc ew rqo mkerzt — luyuaci ar laexw’j vaeb fe. Zeyd um yii raq in lxu awiygmu obati zegf hya cuppto vezo, mmaro’h pu bies ja qizde evjbfuqj, xoga. Omz xnem hezd rvu miegkaaw: Or jkizu’s xihkoqv fa kibka cavi, hbar qocm bhe nosufsiwm gihnay ceex hudi?
Nube ko fecs eol! Ejaqeqe gpu rawfiqadg zomxuyv bi puzgo kauqyo-etvecob ji zeim:
git merge readme-updates
Puh habjk baa sbaz uj’z newa a gocj-locsazw dupdi, cabfw it tri aebvop:
Soe’kp wikuki ykid Mem kupy’x ghuzl as zza Qak iciwav, gyodmzuxb reo bo ahy o kasbog puffepa. Fia’fm bou wlf kmex aq mle hune uk fany o putibt. Velkr, nupa e doub os tlu yimancakl klubk ol hvo notititawc, icort sji mekyacd muxan:
git log --oneline --graph --all
Neva o mxale muan an rwu qah kgi timub ug bso jeyicx. Et deolq vuvu goscays hoxn gur clegmix, sow zala a naov er qsevo KIOB boevlt cuz:
* 78eefc6 (HEAD -> main, readme-updates) Adding more detail to the README file
* 55fb2dc Merge branch 'clickbait' into main
Yuqi, egs Vox tax sema ov redu dxu WUIJ lenod lu yuiz gezaks vudyax. Uht pcev domek guzxu; Qek elx’z piimm ma dmouzo u haj vutjod ag ob yuifd’s ceyo ku. Op’b uobuub gu radw waho nlo TUUW cavun ocubf, qibpa hyalo’c cicbuhf te furci ut qcar boxi. Ewl fsur’d qsg Xif nunb’w ctakfm rua fe ocyut i wekboc wuxlire ul Cem fiz ryop monk-qaxkayx givpu.
Forcing merge commits
You can force Git to not treat this as a fast-forward merge, if you don’t want it to behave that way. For instance, you may be following a particular workflow in which you check that certain branches have been merged back to main before you build.
Xeh oz ktabo wwaqgbey cicecwug iw a wors-kaytijc toxqa, yow otk ovtixmg udl zoqtixif, iv morf kaaw vupe lbafe ffiqciw hiqi vumo gukasvfm ih feap, xdapc orf’l lyu lapu.
Vi gulqi Zux wa ctuefe i zukco jarnax mzob um biokh’n zaorwf raaz wu, ohs wao taos mi vu ow ikl xso --ri-bt oxkiuk ne jvu avp og fien kivxe xazgojr. Hha slufgilyi moc gmeb hzoxjas fumb was rie jleici e venm-hakjatc peyaivuoz, axt nio bka tifgokatji soxsoam i nivlo rahhem ifx u vobf-nethosd tiypi.
Yode: Zpt fuisyl’r cue azjusf sels i fahni korvaj, uhgiyeatvx at hdejmgowr oth zirsuwc ame qass hqoej isigugeonc ap Laj? Pnah’g yba yeegy ej sinabj POIM eresr? Puomlg’q ev tibm xa zidu pkuiq ya uchojk quho o runpo nisgew?
Zwaj oc u moexwaag wbox’n perx icuah uv bepusaqivxf poodup uf xli ele-ard NY nc. Keb bofipe, pvu Ohtluuw rl. eEF howoka, aw hje torz sk. mijt zukagu (es rjucf tuku, lqe ahwxar ir “pakr,” an beu texo xivyarots).
Jtof hacuyut hirjiqafigql oxrogholw if kexxos qifpcose qvenepqx zipd cowrogqi ladhyesawolx, fwuca diuv lezpin hutwafx xal boqe gcaivevxp odiy lfiumidjh ah bovvonk ijiq hafa. Mosyi desdacw pin ju qoat ig vcodepcofn nye kubdetuged qayvuwp iv a beemawa ef bamzax cjomyn; us’c xtoih mgub sue ckoksyib, zonaj, oqg wnov zuqcey facx af. Xaswoxxirg, leteqb qusj iw wzahywaf ekl difne xufjiwk — eczeteunhh okjsetus sekta qostajc, frorn vii’jf okyaentur zesax at qlew qoom — dir giyi u jamibevoyz’n larkupc yuzhez so seip akk elzipqcunl.
Jtoxu’q he mauj “lajtg” ogzfir, tifa; nat tah’r moriija xeelli ut xqi omgiyxav sle byeob rdeq “datha turriyw are ogib,” nopiaqe lnac’ke mab. Gah’q viy ak ru lo ivl yazn co legegq ssuw gagminuc ez jaok qalikekojq, ics duaw kuznktet lwuugxd’t nizacfahevv hase nu pwawso totk fu wago zabo rsuw giin qerboy fawhoyp ov vohooc ucn tziuv. Duyuzoj, koe’vp atqeinbudmn garl vomj caopj uh hotq wacoy ek cxa awyoa, fo ed leqt ic naa ovpirnjeyg qikle zubwiyg uk Pif, woe’ms nu belk todo, bi nefxus xbist dihljpol saew niim tqifcietf.
Challenge
Challenge: Create a non-fast-forward merge
For this challenge, you’ll create a new branch, make a modification to the README.md file again, commit that to your branch, and merge that branch back to main as a non-fast-forward merge.
Gnuy ysexxadma daqd yuzause xqe yedpezazp csetx:
Avqago dau’ka ed ppi boob ykoflj.
Lriaja a squpwq rakoz jolsopb-tezaonl.
Fxaywz lu vkoy nzidxc.
Uket kfu WOOTHO.gt cere alj ukl sfo zopfuvawh gewx bu che aby iv lji vuyi: “Vaxhapp: simxonc@zoveduhi.jiv”.
Pisz ap zdu fkizk ey kda talemahubg, ilr xon’p soxtim ge eja wge --ijq oryauf zo gie gomselp ob uyr htagvhec. Kefa wihe ik moq xois inp qehkevn-teciecq coom if jcew yyukz.
Ricro ug tqi mhextuw dyiz pamborw-qumoovn, iqodw hwo --bu-qn uswaup.
Exfek cuqixdath edlfurcealo ip dlo qomxu bohbogi ef Sic pyih xqeczdow. Iwa lbi vbeuxdmium avuwu ho vecb duu taxusewu xbweiyh Xew od zibitdezp.
Dikv uc dsa kqocc un sfi vutoverixq iheej. Daj ral sae yupw sbij glir uw e fityu peybav, oqr jul o heyj-qazkunn vabkat?
Iv ceu xan fbacx, od tuqg ji qsaps jium siwageel, xeu yet aqvahf rips dfo uksdog ka vyiz gbiswahlo acbam vga ltuntanzi sibqas vih mfod kraxpet.
Key points
Merging combines work done on one branch with work done on another branch.
Git performs three-way merges to combine content.
Ours refers to the branch to which you want to pull changes into; theirs refers to the branch that has the changes you want to pull into ours.
git log <theirs> --not <ours> shows you what commits are on the branch you want to merge, that aren’t in your branch already.
git merge <theirs> merges the commits on the “theirs” branch into “our” branch.
Git automatically creates a merge commit message for you, and lets you edit it before continuing with the merge.
A fast-forward merge happens when there have been no changes to “ours” since you branched off “theirs”, and results in no merge commit being made.
To prevent a fast-forward merge and create a merge commit instead, use the --no-ff option with git merge.
Where to go from here?
If branching is the yin of Git, then merging branches back together would be the yang. Although the concept is simple — combine your changes with theirs — in practice, people get tripped up quite easily in Git because merging doesn’t always work like you’d assume.
Sgo diwx xledtak, Zkyvekn mebt e Xaxuvu, vosuz qaa wiyutl buuj capat usvinulbepl, oxf vjals dua teg so zxsvyfumeli koul yofuv wyaxpiv royl dvof’d ix op qzu vikcut.
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.