Git: Guide to Solving Merge Conflicts - Stack Abuse

文章推薦指數: 80 %
投票人數:10人

Solve Merge Conflict with git merge --continue SALogotypeArticlesLearnWritewithUsSigninSignupPythonJavaScriptJavaHomeArticlesGit:GuidetoSolvingMergeConflictsDavidLandupMergeConflictsarisewhenmultipleagentsmodifythesamepartofafileandpushtheirchangestoaremotebranch.Whenyouattempttomerge,pullfromorpushtothesebranches-there'saconflict,andGitisn'tsurewhichsetofchangestoacceptandwhichtoreject,sincethere'snoobjectivemeasureofwhichchangeisright. MergeConflictsonlyarisewhenit'simpossibletodiscernupfrontwhichchangestokeep,andinthiscase,youhavetostepinandmakeadecision. TherearethreewaysyoucandealwithaMergeConflict-youcancontinuewiththemerge,byupdatingyourlocalfiletomatchwhatalreadyexistsinaremoterepository,youcanabortamerge,whichistypicallydoneifthere'samajorconflictthatisn'teasilyremediedoryoucankeepthelocalchangesfromtheworkingdirectoryandforcethemupontheremoterepository. Inthisguide,we'lltakealookatthethreewaysyoucanresolveaMergeConflictwithGit. HowdoMergeConflictsHappen? Let'squicklycreatearepositoryandamergeconflictsowecanobservewhichchangescauseditandhowthefileslooklikewhenweresolveit.We'llemulatearemote-workenvironmentbycreatingtwofoldersandtwoGitrepositorieswithinthem: $cdJane $gitinit $gitremoteaddoriginhttps://github.com/DavidLandup0/solving-merge-conflicts.git $cd.. $cdJohn $gitinit $gitremoteaddoriginhttps://github.com/DavidLandup0/solving-merge-conflicts.git JaneandJohnareworkingonaprojecttogether,andsharethesamefile-README.md.Johnwrotethefile,accidentallyleavinginatypo,andpushedittotheremoteorigin.Janecaughtthis,fixedthetypoandpushedthefiletotheremoteoriginagain. OnceJohnwantedtoaddanewlinetothefile,andmergehisbranchtothemainbranch-hisREADME.md(whichhasthetypo)wasinconflictwiththemain'sREADME.md,whichhadthetypofixed. OnJohn'sfeaturebranch,headdedaREADME.mdfile: $gitbranchfeature_john $gitcheckoutfeature_john Switchedtobranch'feature_john' $echo'WelcometoourREADMW.md!'>>README.md $gitaddREADME.md $gitcommit-m"AddedREADME.md" [feature_johnc44d65f]AddedREADME.md 1filechanged,1insertion(+) createmode100644README.md $gitpushoriginfeature_john gitpushoriginfeature_john Enumeratingobjects:4,done. Countingobjects:100%(4/4),done. ... Tohttps://github.com/DavidLandup0/solving-merge-conflicts.git *[newbranch]feature_john->feature_john $gitcheckoutmain Switchedtobranch'main' $gitmergefeature_john Updating48f09c2..c44d65f Fast-forward README.md|1+ 1filechanged,1insertion(+) createmode100644README.md $gitpushoriginmain Total0(delta0),reused0(delta0),pack-reused0 Tohttps://github.com/DavidLandup0/solving-merge-conflicts.git 48f09c2..c44d65fmain->main Johnaddedanewfiletohisbranchandpushedittohisremotebranchandthenmergedintomain-noissues,thereweren'tanyfilestherebeforethat. Now,Janewantstogetuptodatewiththemainbranchbypullingthechangesmadethere,noticesthetypo-fixesit,andpushesbacktomaintopreventothersfrompullingtheerroneouspiece: $cdJane $gitpulloriginmain remote:Enumeratingobjects:4,done. remote:Countingobjects:100%(4/4),done. ... Updating48f09c2..c44d65f Fast-forward README.md|1+ 1filechanged,1insertion(+) createmode100644README.md $gitbranchfeature_jane $gitcheckoutfeature_jane $echo'WelcometoourREADME.md!'>README.md $gitaddREADME.md $gitcommit-m"FixedtypoinREADME.mdfile" [feature_jane60f64fc]FixedtypoinREADME.mdfile 1filechanged,1insertion(+),1deletion(-) $gitpushoriginfeature_jane Enumeratingobjects:5,done. Countingobjects:100%(5/5),done. Writingobjects:100%(3/3),292bytes|292.00KiB/s,done. ... Tohttps://github.com/DavidLandup0/solving-merge-conflicts.git *[newbranch]feature_jane->feature_jane $gitcheckoutmain Switchedtobranch'main' $gitmergefeature_jane Updatingc44d65f..60f64fc Fast-forward README.md|2+- 1filechanged,1insertion(+),1deletion(-) $gitpushoriginmain Total0(delta0),reused0(delta0),pack-reused0 Tohttps://github.com/DavidLandup0/solving-merge-conflicts.git c44d65f..60f64fcmain->main Nowmainisclean-notypointheREADME.md.Though,John'sfileisnowoutofsync. Ifhetriespullingtheorigin'smain-aMergeConflictwilloccur. Ifhetriestopushachangewithaconflictingchangeontheremotebranch-aMergeConflictwilloccur. Ifhetriestorun$gitmergeontwobranchesthathaveconflictingchanges-aMergeConflictwilloccur. SayJohnaddedanewlinetothefile,pulledfromthemainbranchandthentriedmerginghisnewadditionintomainbeforepushinghis: $echo'Newline!'>>README.md $gitaddREADME.md $gitcommit-m"AddednewlinetoREADME.md" [feature_johnba27684]AddednewlinetoREADME.md 1filechanged,1insertion(+) $gitcheckoutmain Switchedtobranch'main' $gitpulloriginmain Fromhttps://github.com/DavidLandup0/solving-merge-conflicts *branchmain->FETCH_HEAD Updatingc44d65f..60f64fc Fast-forward README.md|2+- 1filechanged,1insertion(+),1deletion(-) $gitmergefeature_john Auto-mergingREADME.md CONFLICT(content):MergeconflictinREADME.md Automaticmergefailed;fixconflictsandthencommittheresult. Thereitis-MergeconflictinREADME.md.TherearethreethingsJohncandotosolvethisconflict,asheisnowintheMERGINGphase.WhenGitencountersaconflict,itdoesn'tabandonthemerge-itallowsyoutoattemptfixingtheissueonthespotorabandonitifyou'dliketo. FindMergeConflictSource Thefirststepyouneedtotakeisfindoutwhythere'saMergeConflictinthefirstplace.WhenintheMERGINGphase,asweare,Gitwillannotatethefilethat'scausingtheconflict.IfweopentheREADME.mdfileonJohn'slocalmachine,we'llsee: <<<<<<

>>>>>>feature_john The<<<<<<>>>>>>denotesthatthat'stheendoftheconflict,withthebranchnamewe'retryingtomergeintothetopsideof=======. Note:Ifweweremergingbypullingmainchangesintofeature_john-theorderofchangeswouldbetheopposite,sincethecurrentreferencewouldbeonfeature_johnandthechangesonmainwouldbebeneaththe=======line.Though,keepinmindthatthisisn'tgoodpracticeasthefeaturebranchismeanttocontainseparatechangesfromthemainbranch. SolveMergeConflictwithgitmerge--abort Avalidwaytosolvetheconflictistoabortfromit-andstoptheMERGINGphase.Thisistypicallydonewhenthesolutionisn'ttofixasingleline-andwhenlargechangesneedtobemade.Thisusuallynecessitatesaplanwithateammemberaswell. Ifweabortthemerge,theaddedconflictlineswillberemovedandwe'llhaveJohn'sREADME.mdfileonceagain. Whilewe'restillinthemergingphase,let'sabortthemergealtogether: $gitmerge--abort Thissimplyabortsthemergeandyourfileisreturnedtoitsstatebeforeyou'veencounteredtheconflict: 'WelcometoourREADMW.md!' Newline! Ifyou'reusingGit'sCommand-LineEditor(orothershellsthatsupportthefeature),you'llalsobeabletoseewhichphaseyou'rein: (main) $gitmergefeature_john Auto-mergingREADME.md CONFLICT(content):MergeconflictinREADME.md Automaticmergefailed;fixconflictsandthencommittheresult. (main|MERGING) $gitmerge--abort (main) $ Now,withyourfileoutofharm'sway-phoneyourcolleagueanddiscussyournextsteps.Alternatively,ifyouaccepttheirchanges,youcancontinuewiththemerge. SolveMergeConflictwithgitmerge--continue Youcancontinuethemergewithaconflict,butGitwon'toverwritethefilesautomatically.Ifyoutrymerging,encounteraconflict,andtryto$gitmerge--continue,you'llfaceanothererror: $gitmergefeature_john Auto-mergingREADME.md CONFLICT(content):MergeconflictinREADME.md Automaticmergefailed;fixconflictsandthencommittheresult. $gitmerge--continue error:Committingisnotpossiblebecauseyouhaveunmergedfiles. hint:Fixthemupintheworktree,andthenuse'gitadd/rm' hint:asappropriatetomarkresolutionandmakeacommit. fatal:Exitingbecauseofanunresolvedconflict. UREADME.md Ifitwerepossibletocontinue,Gitwould'vecontinuedalready.You'restillintheMERGINGphase,soyoucanchangeyourREADME.mdtoconformtomain'sversionofit,marktheresolutionbyaddingorremovingthefileagain,andthenrunthe$gitmerge--continuecommand. Let'sfixthefilefirst.Inourcase,sincethe"Welcome..."linewascausinganissue,butthe"Newline!"wasn't-wecanleavethenewlinein-John'snewfeature-andfixthetypothat'sinconflict: WelcometoourREADME.md! Newline! Now,weaddthefileonceagainandrunthe$gitmerge--continuecommand: Fixthefile... $gitaddREADME.md $gitmerge--continue [mainfea8fbb]Mergebranch'feature_john' You'veacceptedthechangesfrommainandadaptedyourlocalfiletoreflectit,andaddingitback. Note:InnewerversionsofGit,whenyourunthe$gitmerge--continuecommand,it'llcommitthatmergeautomatically,soyoudon'thaveto,though,youdohavetoaddthechangedfileagain.Whenyourunthecommand,atexteditorwillopenupwiththedefaultcommitmessageofMergebranch'branch_name'.Youcanjustexitit,savingthemessage,tocommitthechangeandmergethebranches. SolveMergeConflictByForcingLocalChangestoRemote Insteadofaborting,oryieldingtochanges-ifyou'recertainthatthechangesmadeinyourworkingdirectoryarecertainlytheonestokeep,youcankeepthelocalchangesinsteadofadaptingtotheremoteones. WhenaMergeConflictoccurs,youcan$gitcheckoutthefilefromfeature_john,andthenaddittothemainbranch. Note:Rememberthat$gitcheckoutupdatesthefilesintheworkingtreetomatchtheversionintheindex. Whenupdating-youcankeepthechangesmadeonadifferentbranchandapplyittothisbranch.Onthemainbranch,intowhichwewishtomergefeature_john,let'supdatetheREADME.mdfiletocontainthechangesfromthefeature_johnbranch. Inthecontextofmain,thesechangesarereferredtoastheirs,whilethechangesonmainarereferredtoasours.Ifyouwishtokeepchangesfrommain,switchthe--theirsflagwith--ours: $gitcheckout--theirsREADME.md Updated1pathfromtheindex $gitaddREADME.md $gitcommit-m"Acceptingchangesfromfeature_john" [main5541f29]Acceptingchangesfromfeature_john Now,youcanmergetherestofthechangesthatarenotinconflictcleanly,sincewe'veonlycreatedaroundaboutmergefortheonefilethatcausedaconflictthisway. Conclusion Inthisguide,we'vetakenalookathowtoresolveMergeConflictsinGit.We'veexploredthethreewaysyoucanbumpintothiscommonerror,andhowtheyarise. Then,we'veexploredthreesolutionstotheissue,withthedummytwolocalrepositoriesandaremoterepositorywe'vecreatedintheexamples. #gitLastUpdated:January15th,2022Wasthisarticlehelpful?Youmightalsolike...Git:UndoLatestLocalCommitGit:AnIntroductionforBeginnersGit:AddingaCommitMessageGit:SquashMultipleCommitsintoOneCommitGit:StashingUncommittedChangesImproveyourdevskills!Gettutorials,guides,anddevjobsinyourinbox.EmailaddressSignUpNospamever.Unsubscribeatanytime.ReadourPrivacyPolicy.DavidLandupAuthorEntrepreneur,SoftwareandMachineLearningEngineer,withadeepfascinationtowardstheapplicationofComputationandDeepLearninginLifeSciences(Bioinformatics,DrugDiscovery,Genomics),Neuroscience(ComputationalNeuroscience),roboticsandBCIs. Greatpassionforaccessibleeducationandpromotionofreason,science,humanism,andprogress. InthisarticleHowdoMergeConflictsHappen?FindMergeConflictSourceSolveMergeConflictwithgitmerge--abortSolveMergeConflictwithgitmerge--continueSolveMergeConflictByForcingLocalChangestoRemoteConclusionFreeCourseGitEssentials:Developer'sGuidetoGit#gitGitEssentials:Developer'sGuidetoGitisacourseforalldevelopers,beginnertoadvanced,andwrittentogetyouuptospeedwiththe...DetailsWantaremotejob? MoreJobsJobsbyHireRemote.ioTwitterGitHubFacebook©2013-2022StackAbuse.Allrightsreserved.DisclosurePrivacyTerms


請為這篇文章評分?