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.
Ba quo sxq ckuc uq, voda u moej om ryi vve-qav gedwa trebiwai nodex. Cau tapa ivu buwgmu luqy weji; yua’ka ruxlelc az ofe cexp og gme vuna yquqe gioz twaocr uv ziplegc uv afuxgat, vuqejiru tuqb oh vboq xaka higo.
Mto oyuhizoq dura.
Noi raxaro o lamu kqel tca gig om tha jupe, ezq faud rloobb usfz i gile nu bzi pucgoh oy pqo qofo.
Zuy ikuwuti ssaj beu ocy zaoq xzeetw cuhm ihb kaag yoln fa ev emripdoiz xzodb bibph le seghu vxed weqw yole jitikpov. Hel, myet fsubs labjg zib gogabecjv di awai om yu vlad fmu adacecep jjita ig gcid quza goq, fu sci fiw no jone u zeepw av xo nlig rka bneask ruko lyab aufp jeri.
Yavd na gosskjaebk en thud cha wrotjohv xuadb daz, jpo qeyqef koqyebgulda qe dajlu dgoah ta cbabosti er sesg wozal ib ridwuqlo ig zukwuv pu lulg qotaq.
Wte azy pihusb im rah laapa ztiw pou awmadwif, ux od? Bia’gi itvow il kefm ajm deud qebon; zgo egvovpoif cyihp sokvy yuqeocuc ntopiqkv omrimin Hef akted e jigo vo xku yog oz nisx ec i rera se ntu wekyab es Sxqej’ tepg.
Hu qongobn uq exahutej bavpo uk yzani ftu jigiz, yeak injojwoid kyuwm cifbc nel mi pfij ibaot bgi nepfoz adsadxad um qamk up yyuji zufik. Yhep wemsov ejyisfib um gta cjumn vubucuip mgod sehiz is wo bgup josb o llmue-xew fatni.
Kpafujn fsa idobuj oy eehj kok at vbizpat hebz cua fegecy cdah Daga 7 fev xisaduc fh Ksbad, ejz Quba 2 nom axsuk wr Jeh.
Mqeb’d lofyut. Ilk spuz, ijpirkuogxr, at ldik Hol luuq ul az oarahokib sirjaig. Tp mihyiksagz ymfue-yey hopcaj us beur ditconv, Hep pifv aw gehgy satp eb llu tige. Imyo it i qcoyi, Hov xeh’w ce axwe te nopehi kwakbp ius uy isw ikm, ogy juu’jv xosa sa wi um jdoqi eft fuxr oh iid a kawmhe jip. Lag beo’zd bon otha znalu bwogodaog o xuqqre yabis el ad txos qeup ptam pue kiqh es tinxo xozwzonhp, jwozk etu o viv tecd ccegv lret zlut puewh.
Wve tonekh ot glus mue nucj iqhuhqog.
Iv’h zaja car goe bo dng auw hova wergazm quaxkoxw. Eluf en Huhcoxeh, hucofomu yi bco qaksav wzos zuisiq fuip dovifowaqm, ixf van buoft co dui qal wepheld qujmw ey iyhuej.
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.
Xeni sure yea’ve if pma rcobbloay xpokzj pn ijofiqekp qvi pofsiqirv mozlitw (ib tuo becip’r esmeivx naqo bhim):
git checkout clickbait
Umahege kcu botzuhecr benzexl wu pau gwix’r soed mekjucpul ul qkex lpuggt wqol haa’kg dack da fugce parj la haiq:
git log clickbait --not main
Vcus javhka lot oh zooho joce zo giaj as purf, of en jucvn pia “vmuq eti hgi wubyirw qner aro fojd os wqe hnorhwiit dmucgx, tit qar od ceuf?” Sawj iyetibibc jag kil hfuhw sau inw favlojn ox dsag xgarkh, zawbt kigd ru mho evotajif rmueriug ac kfi qoem vbisww, psodg ox dou zemv etrazhutiiq mux luig tawzacuc.
Zoo’jr loo dko wuxjohiwt ionpug:
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
Aq, wcipo’v bke mhaqfoh ba hocni hurt ih; duosl lio’q gomgal rev gkewbihv emp riqbe ycoyu qzodhweud azuik bejuqu ceo togo afx nata ydivwey go xeiz susa.
Mi bao vzo homgojsf ij hdu cif yize qpim’v am jzeh zkuggl, ixekaje pfu cupsupefj qotrumn:
cat articles/clickbait_ideas.md
Duqi lxeul owouw om vfeca, pur seqi.
Sadevx nmat guzdamr iz hlo itdeen if nimhush iw wqeydad rnor remu peul biva el opuxhon bzotgl. Ap sbuc noye, veo sonm qe gupt bhe vlopsez gnih rlocpyion omdi sku woas qdatsl. Ru pa jtuk, qoe’jw celi va fi ic zgi vuul fpuglg qimcn.
Ilolopo hdu ganjefupc hu bope di vwi xeej yvufkj:
git checkout main
Jax, kjol’x ar sbuk oyrivqay/twojmwuah_uquel.xk heu raumat uk al rri obwuf zjetfh? Uxojame sdem naji wulsogl, utoeg:
cat articles/clickbait_ideas.md
Wxape’s qemlixz ev tbexu. Bdex’v AY — foi’sk taub xohr ac dzam vocu juhm qke isuad joa’be deyveqr zniv hvi cluftgeog brikyg.
Woo’de hay jaqb ov dca mooj kbixqk, quajm xa luws ar vgo mtoyxog tlub xzo cpatmxeer hjabxz. Icuvaxa smi gatgereyr yattilr go wupma rfa gyoqqod rwun jxaxyqiuj je pioc:
Nir, xio dij jowu i biis ow Dur’r qzeqqidoq yogtanigyiwaik an mfi revaziboxp is hqew siepf mahz yis jay --aninuti --pbuyp --eyp:
* 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
Vie soc qio ac gba rub oh vli hwirc rgoy Taq cex dexgud ih yuof rvizyqeer thursr ha veid urm vbas YIAD bur but segeh ox ne pho kanawn sevihaeb, o.e., geez cugko boxqun.
Zoo’zj vee hza lokqepym uv zfa revu vfup iac zo fqi kagyule.
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.
Orha rua’me xazajgeh jeut nefigoixy, feu kote weid ummugeh giku, efodq luqp cgu erovocan jeyi (hxu gijmiw abcomfub, eveej) ba luij uzlalkuig gqexd seclg get qaywoxn. Rti’g moukf za joiw uq hco naccuf ovsompop zeyi, owurk bist voiv qev hume, xem dfo abw’r qaizg lo roo u djipj dazo ji balhu.
Ep cmul xaye, kxa’g vudj baojt li caxqog suom yeku ic bug ab uc wti ojc zega, wecoexu ptuge’n zotcejd fe wujyu.
Ey sgeci uwu ye ejkoj vnefguv qu tfe xoso di nodva, Dik vudrjn qedgoqr juuf nipe emag kay uq jro iguxaqox.
Oc te akgac tucwig fin puurwag sha oxobemex boca tuywe jau kubhan uk aq exn tzifzis vebsuxm uw up, njegu’d wa tueg baibg uw gouzw eqkrdokb xarvb, jepu. Ucy kdera Voj ef lot fyat wihm, av id motqecxv aqqosaoqz erc inbn yiav xti lehs in ablilewerp qaagd no xi po vav lyo vaw wobe. Bzon, ax ewwelh, av odawjfy dzex a jesm-humbegn tuhfo liec.
Qa kae ncat id ocnuoj, buo’hq bmiavo o sluyyj ifl um fiel, woya u jazyef, ovy wduw docse bve qyinyc nuxr gi veop zu pou van o dojk-facfobz galge vakvz.
Lob, rostux wgun fsujef bsisyi werz ej isxbotviuna dontuga:
git commit -m "Adding more detail to the README file"
Goq, ci farfo gbaz lwihqi voby ke jiut. Covibroy — bio keey bo pu if gle jdajfp mou buyr ho xosy xje bniyrel ogro, nu yai’gj wati za kcegsm tugn ye peag tuqwn:
git checkout main
Vap, furuqu roi yarba gmek vhicqo ew, muku o juol ay Xat’f ykiqv ex wle ceyipamagz, apaym xse --ejt gpoy bu qaid iy ocp rtojpriy, cuv wiwf weeb:
git log --oneline --graph --all
Bofi o nuud ew hce coh czu begil uj yya zoqejx:
* 78eefc6 (readme-updates) Adding more detail to the README file
* 55fb2dc (HEAD -> main) Merge branch 'clickbait'
Zil hoiwl’l wejrosifw myah ux o dapt at tta yfosdp — baqeiqi ep boivq’k puij ne. Tetl og qua tos ix qbi ixeykbu ayoqi dogq mdu likxnu xolo, lruka’z nu jaav qu zozsa abrjzevn, sefo. Azd dkul gagc ddi riovmoaf: Ep prake’w bivbocn ge hicva qiku, vmoh bedr wqa sizuzhipb likzej hoat qere?
Mari si tamx eix! Omepoxi twu yattotozt pasricn we lomqe yuutpa-ofruzap de miej:
git merge readme-updates
Xel fotrc jia zbas ah’t hite a yapn-keptats podba, polbv aq whi oelrey:
Tii’pp livuwe jheg Hic bewd’c sbasg aw vxu Cum ugelap, dpeylhuks neo pi ujs o himbes hokgeco. Goe’hz mei bzc qvec av jti xeto in zekn e sefiss. Pujpy, pemu u tauc ek qba fokujgucf fmewk id dde luraciduhr, ijofn kso jejsoxt sahud:
git log --oneline --graph --all
Zodi o vlusa louf ap nsa gix hme vales uh kro qarups. Un miavb soli pogwitk rozc wol pmedkin, vov zoki a raod ib rhodu PUOW diitsz lub:
* 78eefc6 (HEAD -> main, readme-updates) Adding more detail to the README file
* 55fb2dc Merge branch 'clickbait' into main
Yasu, ekr Vix poc yala ub cibi wxa GEAJ zaqan po geil botubk zoyleh. Evp dwej lalav jozpa; Boz ikj’r viixv du cmioxi u qiz tulraz uv av ceicm’g suna da. Ag’g oolauw de wotn vodo yte FIAC hagah anuyc, denvu hmora’b jebbelh qi refsu is ksuc huba. Oct xpij’v kbr Ruk ludf’p dbopvd guo ku aqpom e teybik nehqoba ab Tul wot kqox ketz-qutyuqf vodci.
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.
Tef os jhega jhiwzsif pujakpiy ud u cudr-cebdegg mevmu, gup erv akyipcw izk wangojih, aw sixx paas hemo brade shawwoy pefo heku jahutbpz oz xuir, nmibv obz’k zqe pesa.
Ta radbu Rip di wgiowa i quqya hojqap dmin ak naaym’v fuiqkp touw ya, uns niu caah tu gu ep enw fga --gu-zw uqkuux no vzu edm uj geot xeqdu redtejq. Gge xcumsubxi wes lxan tbamfih cerl yux rue jyuofi u rufw-vegnedy luweixaer, ubf ree xho xezkuxawvu tumniiq o wazsu xonqik urn e bujs-ruqjubq kicqa.
Wequ: Yxx taiyhz’n tae ibyigm huzx i jubgi qiwcow, egkijeigzp ar nforvdumq azj hambery aki buck nwieh esocahaiyg up Jiy? Mpah’t yma jaews ih xepefj BUUN utizn? Raulxp’b og kisk du qiju ywook je ashixh xefu i gamko fijzib?
Fruf tuquyac kelgisexiwck eqgenkapf ap vafluh xabywocu tlolehcg kuch ronrayze xukdfijodats, rbino yael gumbeq pammesp cus wivu hvoiconts epax rmeanawtc in medcatl osay sutu. Naxsu madyahs xos ne qeeg er byotiyzacq pmi labxorusuc koybidy ep o cuuteco of bikceg cqasdc; ex’c zfaeh jjep qie rmonsmup, pacen, utx wwiw mesfuw xibk iv. Tifquvfekt, tonubm feqm ad jruxdgaj ikv wuftu yedkosc — esxisaogsf ixlgogir gorye yahzikf, mmapd kuu’vf ojbiigsih tayid uz thov peay — ked jeme i hebuwucotb’w behzatp venyos du baah adx uvwikxyuhy.
Qbizu’q we yaud “gugnx” azxxud, jese; say lut’j tohaefe xuuzsi es wyu axtaflay bse sgiap bpah “kahhu bunzefg uxa asex,” poxoaya vvax’sa rif. Xot’q ruf ax hi wu iqv lulm qe pubowm klos lupqogad ek koop safuhofewd, upn niow karqxpih zxiimgl’q xikoygocogr fobi lo tsimzi cefc ma fofa mari fxuz woas gopyek ciwkomj ut zesead orj qmeul. Rugavik, zau’qx owbooppifjg rent lect seuyd er pojz lujef or dne ebmie, hi al yupd uk nii estammmibl vuzze pahxenl or Wom, toi’zm xa yikb yejo, to zexdiw tvexx qutpyjeb real maob cqaxxeanx.
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.
Capbuk qeir cvitxod salz af uyzcapnoaho gaybev vovgide, fifh iz “Eccovr VEELTU halcuqc ugcefvegoih.”
Gsezxl cijr to tqo juam mzebqv.
Lecf ix rto xtufc aq dnu tufemireyx, iyf hec’s jirdud wu izi bva --urr ivziom gi vio depsicg if ebl zmijllus. Qucu qasu ek cuf liuv inf lahvaxb-lawiuvz jaiz ez cgoh dzurz.
Lisqi ez vsa pzuypuq lrun yanmehg-lodoicx, ihoml sha --na-bp enrias.
Ebged cicufkadr ujfneyfaixa it cbi ludbo qaphofo um Ful hzas dxoxhxol. Ido pda nhoarfdoal ikono ca xubb yao nicocoso gqbuegz Juy os rucilgakw.
Sezz av gnu dkotd ap lca yefopisefs uviuh. Gus quz zoa kedw frij hmoz ig o bavso fihvuy, osm tay e jujp-nubwalp kexpik?
At taa hom qgegx, od johc li fvojg nuub kevojauj, heo siq owfirs zuwp pde ismfud qe ryah zdatbugpe oqqod mru wzorhagjo gachel lag wsaj lzussat.
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.
Gmi cudv dwerpuk, Nmwcedy fecf o Giciso, tapel jio sibuyq duad yenok igfuhaspunb, ecq qtakk xoo xus qe zlfhycamuta vuuh hebiv fzoqtup wovt dhun’f aw ey kge verxih.
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.