Git merge with force overwrite - Stack Overflow

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

Not really related to this answer, but I'd ditch git pull , which just runs git fetch followed by git merge . You are doing three merges, ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams Gitmergewithforceoverwrite AskQuestion Asked 5years,9monthsago Modified 10monthsago Viewed 402ktimes 183 65 IhaveabranchcalleddemowhichIneedtomergewithmasterbranch.Icangetthedesiredresultwithfollowingcommands: gitpullorigindemo gitcheckoutmaster gitpulloriginmaster gitmergedemo gitpushoriginmaster Myonlyconcernis,ifthereareanymergeissues,Iwanttotellgittooverwritechangesinmasterbranchwithoutgivingmemergeprompt.Sobasicallychangesindemobranchshouldautomaticallyoverwritechangesinmasterbranch. IlookedaroundtherearemultipleoptionsbutIdon'twanttotakechanceswithmerging. gitgithubmerge Share Follow editedNov9,2016at22:34 OpenStack askedNov9,2016at22:33 OpenStackOpenStack 4,16388goldbadges3131silverbadges5858bronzebadges 5 2 gitpush-foriginmaster – MDXF Nov9,2016at22:33 6 @MDXF:MaybeIamwrongbutshouldn'tIbeusing-foptionwithmergecommandandnotwithpushcommand – OpenStack Nov9,2016at22:35 Youcouldtrybothandseewhatworksforyou – MDXF Nov9,2016at22:38 1 Seebelowlinkforasolutionofforceoverwrite:stackoverflow.com/a/42454737/984471 – ManoharReddyPoreddy Feb25,2017at10:21 git-scm.com/docs/merge-strategies – chharvey Apr7,2018at17:56 Addacomment  |  6Answers 6 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 174 Notreallyrelatedtothisanswer,butI'dditchgitpull,whichjustrunsgitfetchfollowedbygitmerge.Youaredoingthreemerges,whichisgoingtomakeyourGitrunthreefetchoperations,whenonefetchisallyouwillneed.Hence: gitfetchorigin#updateallourorigin/*remote-trackingbranches gitcheckoutdemo#ifneeded--yourexampleassumesyou'reonit gitmergeorigin/demo#ifneeded--seebelow gitcheckoutmaster gitmergeorigin/master gitmerge-Xtheirsdemo#butseebelow gitpushoriginmaster#again,seebelow Controllingthetrickiestmerge Themostinterestingparthereisgitmerge-Xtheirs.Asroot545noted,the-Xoptionsarepassedontothemergestrategy,andboththedefaultrecursivestrategyandthealternativeresolvestrategytake-Xoursor-Xtheirs(oneortheother,butnotboth).Tounderstandwhattheydo,though,youneedtoknowhowGitfinds,andtreats,mergeconflicts. Amergeconflictcanoccurwithinsomefile1whenthebaseversiondiffersfromboththecurrent(alsocalledlocal,HEAD,or--ours)versionandtheother(alsocalledremoteor--theirs)versionofthatsamefile.Thatis,themergehasidentifiedthreerevisions(threecommits):base,ours,andtheirs.The"base"versionisfromthemergebasebetweenourcommitandtheircommit,asfoundinthecommitgraph(formuchmoreonthis,seeotherStackOverflowpostings).Githasthenfoundtwosetsofchanges:"whatwedid"and"whattheydid".Thesechangesare(ingeneral)foundonaline-by-line,purelytextualbasis.Githasnorealunderstandingoffilecontents;itismerelycomparingeachlineoftext. Thesechangesarewhatyouseeingitdiffoutput,andasalways,theyhavecontextaswell.It'spossiblethatthingswechangedareondifferentlinesfromthingstheychanged,sothatthechangesseemliketheywouldnotcollide,butthecontexthasalsochanged(e.g.,duetoourchangebeingclosetothetoporbottomofthefile,sothatthefilerunsoutinourversion,butintheirs,theyhavealsoaddedmoretextatthetoporbottom). Ifthechangeshappenondifferentlines—forinstance,wechangecolortocolouronline17andtheychangefredtobarneyonline71—thenthereisnoconflict:Gitsimplytakesbothchanges.Ifthechangeshappenonthesamelines,butareidenticalchanges,Gittakesonecopyofthechange.Onlyifthechangesareonthesamelines,butaredifferentchanges,orthatspecialcaseofinterferingcontext,doyougetamodify/modifyconflict. The-Xoursand-XtheirsoptionstellGithowtoresolvethisconflict,bypickingjustoneofthetwochanges:ours,ortheirs.Sinceyousaidyouaremergingdemo(theirs)intomaster(ours)andwantthechangesfromdemo,youwouldwant-Xtheirs. Blindlyapplying-X,however,isdangerous.Justbecauseourchangesdidnotconflictonaline-by-linebasisdoesnotmeanourchangesdonotactuallyconflict!Oneclassicexampleoccursinlanguageswithvariabledeclarations.Thebaseversionmightdeclareanunusedvariable: inti; Inourversion,wedeletetheunusedvariabletomakeacompilerwarninggoaway—andintheirversion,theyaddaloopsomelineslater,usingiastheloopcounter.Ifwecombinethetwochanges,theresultingcodenolongercompiles.The-Xoptionisnohelpheresincethechangesareondifferentlines. Ifyouhaveanautomatedtestsuite,themostimportantthingtodoistorunthetestsaftermerging.Youcandothisaftercommitting,andfixthingsuplaterifneeded;oryoucandoitbeforecommitting,byadding--no-committothegitmergecommand.We'llleavethedetailsforallofthistootherpostings. 1Youcanalsogetconflictswithrespectto"file-wide"operations,e.g.,perhapswefixthespellingofawordinafile(sothatwehaveachange),andtheydeletetheentirefile(sothattheyhaveadelete).Gitwillnotresolvetheseconflictsonitsown,regardlessof-Xarguments. Doingfewermergesand/orsmartermergesand/orusingrebase Therearethreemergesinbothofourcommandsequences.Thefirstistobringorigin/demointothelocaldemo(yoursusesgitpullwhich,ifyourGitisveryold,willfailtoupdateorigin/demobutwillproducethesameendresult).Thesecondistobringorigin/masterintomaster. It'snotcleartomewhoisupdatingdemoand/ormaster.Ifyouwriteyourowncodeonyourowndemobranch,andothersarewritingcodeandpushingittothedemobranchonorigin,thenthisfirst-stepmergecanhaveconflicts,orproducearealmerge.Moreoftenthannot,it'sbettertouserebase,ratherthanmerge,tocombinework(admittedly,thisisamatteroftasteandopinion).Ifso,youmightwanttousegitrebaseinstead.Ontheotherhand,ifyouneverdoanyofyourowncommitsondemo,youdon'tevenneedademobranch.Alternatively,ifyouwanttoautomatealotofthis,butbeabletocheckcarefullywhentherearecommitsthatbothyouandothers,made,youmightwanttousegitmerge--ff-onlyorigin/demo:thiswillfast-forwardyourdemotomatchtheupdatedorigin/demoifpossible,andsimplyoutrightfailifnot(atwhichpointyoucaninspectthetwosetsofchanges,andchoosearealmergeorarebaseasappropriate). Thissamelogicappliestomaster,althoughyouaredoingthemergeonmaster,soyoudefinitelydoneedamaster.Itis,however,evenlikelierthatyouwouldwantthemergetofailifitcannotbedoneasafast-forwardnon-merge,sothisprobablyalsoshouldbegitmerge--ff-onlyorigin/master. Let'ssaythatyouneverdoyourowncommitsondemo.Inthiscasewecanditchthenamedemoentirely: gitfetchorigin#updateorigin/* gitcheckoutmaster gitmerge--ff-onlyorigin/master||die"cannotfast-forwardourmaster" gitmerge-Xtheirsorigin/demo||die"complexmergeconflict" gitpushoriginmaster Ifyouaredoingyourowndemobranchcommits,thisisnothelpful;youmightaswellkeeptheexistingmerge(butmaybeadd--ff-onlydependingonwhatbehavioryouwant),orswitchittodoingarebase.Notethatallthreemethodsmayfail:mergemayfailwithaconflict,mergewith--ff-onlymaynotbeabletofast-forward,andrebasemayfailwithaconflict(rebaseworksby,inessence,cherry-pickingcommits,whichusesthemergemachineryandhencecangetamergeconflict). Share Follow editedMay23,2017at12:18 CommunityBot 111silverbadge answeredNov10,2016at3:13 torektorek 402k4949goldbadges549549silverbadges689689bronzebadges 0 Addacomment  |  70 Ihadasimilarissue,whereIneededtoeffectivelyreplaceanyfilethathadchanges/conflictswithadifferentbranch. ThesolutionIfoundwastousegitmerge-soursbranch. Notethattheoptionis-sandnot-X.-sdenotestheuseofoursasatoplevelmergestrategy,-Xwouldbeapplyingtheoursoptiontotherecursivemergestrategy,whichisnotwhatI(orwe)wantinthiscase. Steps,whereoldbranchisthebranchyouwanttooverwritewithnewbranch. gitcheckoutnewbranchchecksoutthebranchyouwanttokeep gitmerge-soursoldbranchmergesintheoldbranch,butkeepsallofourfiles. gitcheckoutoldbranchchecksoutthebranchthatyouwanttooverwrite getmergenewbranchmergesinthenewbranch,overwritingtheoldbranch Share Follow answeredJul9,2019at4:13 NiallMccormackNiallMccormack 1,1141212silverbadges1919bronzebadges 2 1 Itdidn'tworkforme.Itsolvedtheconflict(solvedtheconflictedfiles)butthefileisnotmerged.Andcan'tmergeneither. – c-an Sep17,2019at6:32 Ifanyonehappenstogetstuckwhereyouarepromptedto"Pleaseenteracommitmessagetoexplainwhythismergeisnecessary":Enteryourmessage,thenpresstheESCkeyonyourkeyboard,type:wqandpressENTERtoexittheprompt. – topherPedersen Apr6,2020at11:40 Addacomment  |  52 Thismergeapproachwilladdonecommitontopofmasterwhichpastesinwhateverisinfeature,withoutcomplainingaboutconflictsorothercrap. Beforeyoutouchanything gitstash gitstatus#ifanythingshowsuphere,moveittoyourdesktop Nowpreparemaster gitcheckoutmaster gitpull#ifthereisaprobleminthisstep,itisoutsidethescopeofthisanswer Getfeaturealldressedup gitcheckoutfeature gitmerge--strategy=oursmaster Goforthekill gitcheckoutmaster gitmerge--no-fffeature Share Follow editedOct16,2019at3:25 answeredOct16,2019at1:35 WilliamEntrikenWilliamEntriken 34.5k2222goldbadges138138silverbadges183183bronzebadges 3 11 gitpushtofinish – Kochchy Mar10,2020at9:27 git-scm.com/docs/git-merge#Documentation/git-merge.txt-ours.Itworkedwhenthecommitswerenotcleanlymerging.Butthisapproachwillnotworkalways,toquotethesourceChangesfromtheothertreethatdonotconflictwithoursidearereflectedinthemergeresult.Itdidnotworkforme,asIhadcleanlymergingcommitsinmybranchwhichwasbeingoverwritten.Isthereanyotherway? – NiharGht Aug12,2020at17:02 Thisdidthetrickforme!ExactlywhatIwaslookingfor.(Wehadtriedswitchingframeworksanditwasaflop.Weneededtocherrypicksomerecentworkfromontopofthebadframework,andthenoverwritewhateverwasonmasterwithourcherry-pickedbranch.) – ForOhFor Jan14,2021at3:43 Addacomment  |  24 Thesecommandswillhelpinoverwritingcodeofdemobranchintomaster gitfetch--all PullYourdemobranchonlocal gitpullorigindemo Nowcheckouttomasterbranch.Thisbranchwillbecompletelychangedwiththecodeondemobranch gitcheckoutmaster Stayinthemasterbranchandrunthiscommand. gitreset--hardorigin/demo resetmeansyouwillberesettingcurrentbranch --hardisaflagthatmeansitwillberesetwithoutraisinganymergeconflict origin/demowillbethebranchthatwillbeconsideredtobethecodethatwillforcefullyoverwritecurrentmasterbranch Theoutputoftheabovecommandwillshowyouyourlastcommitmessageonorigin/demoordemobranch Then,intheend,forcepushthecodeonthemasterbranchtoyourremoterepo. gitpush--force Share Follow answeredDec14,2020at11:02 RahulShyokandRahulShyokand 87577silverbadges1717bronzebadges 2 Whywasremote'origin/demo'branchwasusedandnotlocal'demo'branch. – NevetsKuro Aug10,2021at10:42 @NevetsKuroYoucanuselocaltoo.Both"gitreset--harddemo"and"gitreset--hardorigin/demo"wouldresultinthesameactionifthelatestcommitsaregitfetchedusing"gitfetch--all"andpulledbranch"demo". – RahulShyokand Aug11,2021at4:45 Addacomment  |  16 Youcantry"ours"optioningitmerge, gitmergebranch-Xours Thisoptionforcesconflictinghunkstobeauto-resolvedcleanlybyfavoringourversion.Changesfromtheothertreethatdonotconflict withoursidearereflectedtothemergeresult.Forabinaryfile,theentirecontentsaretakenfromourside. Share Follow answeredNov9,2016at23:02 rootroot 3,07711goldbadge1717silverbadges2525bronzebadges 2 3 Thiswouldbebackwards,astheOPsaidhewantsthedemoversiontobepreferredeventhoughheismergingintomaster.Thereis-Xtheirsaswell,butit'snotclearthatthisiswhattheOPreallywants. – torek Nov10,2016at2:30 Youhavenotreadthewholeway.Yournotedescribeswhatoursdoeswhenusingonthebackendwiththe-soption.Whenusingourswith-X:Itdiscardseverythingtheothertreedid,declaringourhistorycontainsallthathappenedinit.source – jimasun Jul13,2017at10:54 Addacomment  |  6 WhenItriedusing-XtheirsandotherrelatedcommandswitchesIkeptgettingamergecommit.Iprobablywasn'tunderstandingitcorrectly.Oneeasytounderstandalternativeisjusttodeletethebranchthentrackitagain. gitbranch-D gitbranch--trackorigin/ Thisisn'texactlya"merge",butthisiswhatIwaslookingforwhenIcameacrossthisquestion.InmycaseIwantedtopullchangesfromaremotebranchthatwereforcepushed. Share Follow answeredDec8,2019at18:09 MattMatt 33055silverbadges99bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedgitgithubmergeoraskyourownquestion. TheOverflowBlog Ahistoryofopen-sourcelicensingfromalawyerwhohelpedblazethetrail... Thelasttechnicalinterviewyou’llevertake FeaturedonMeta PlannedmaintenancescheduledforTuesday,August23,2022at00:00-03:00AM... PleasewelcomeValuedAssociate#1301-Emerson StagingGroundWorkflow:QuestionLifecycle AnnouncingDesignAccessibilityUpdatesonSO Shouldweburninatethe[maintenance]tag? Linked 1998 HowtoreplacemasterbranchinGit,entirely,fromanotherbranch? 338 HowdoI'overwrite',ratherthan'merge',abranchonanotherbranchinGit? 1 Replacebranchcompletelywithanotherbranch 1 HowcanIgitforcechangestooriginmasterwithoutmerging? Related 13312 Whatisthedifferencebetween'gitpull'and'gitfetch'? 10621 HowdoIundo'gitadd'beforecommit? 24643 HowdoIundothemostrecentlocalcommitsinGit? 8841 HowdoIforce"gitpull"tooverwritelocalfiles? 3570 HowdoIcreatearemoteGitbranch? 19440 HowdoIdeleteaGitbranchlocallyandremotely? 4634 UndoaGitmergethathasn'tbeenpushedyet 2528 HowdoIsafelymergeaGitbranchintomaster? 10648 HowdoIrenamealocalGitbranch? 1690 CanIdeleteagitcommitbutkeepthechanges? HotNetworkQuestions Preventingauxiliarycondenserjugoverflowinaportableairconditioner Whydoesn'tAuthorityoftheConsulspreventthegoblintokenfromDenoftheBugbearfromattacking? WhyarebeansIsoakmyselfalwayssmallerthancanned? Whatisthepurposeofnothavingjurytrialsforjuveniles? WhydoJupiter’smoonshavesomuchwater? SplittingcolumnsinTSVintoCSV Awordwithastrongermeaningthan"intéressant"? CannotinstallAndroidEmulatorviaAndroidStudioinMacbookM1Pro nodetoolwithJava8u331returns"URISyntaxException:'MalformedIPv6addressatindex7:rmi://[127.0.0.1]:7199'" constructionofYgatefromX,ZandHgates WhyarepapercopiesofPresidentialrecordssupposedtobeimportantgiventhatdigitalcopiesareextremelyeasytomake? CanauniversityforceaJ1exchangestudenttopurchasetheirhealthinsuranceplan? Isthedifferencebetweentwoordinalvariablesordinal? DartmouthBASICarraydimensionsquestion Inputtypographyusingquantifierssuchas`ForAll` WhyisManchintheonlyDemocraticSenatorleveragingthe50/50votesplitforthebenefitoftheirstate? StandbytravelonKoreanAirviaICN PythonprogramtoscrambleMP3audio DoUbuntureleases"pin"aspecificPythonminorversion("3.9.X")? Breathedinlead-freesolderfumes,shouldIbeworried? WhydidFeynmansaythedoubleslitexperiment"containstheonlymystery"ofquantummechanics? DoesaUSPresidenthavetofileanypaperworktodeclassifyinformation? WhyarealltheDS9runaboutsnamedafterEarthrivers? RadicalIQchallenge morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?