Git merge with force overwrite - Stack Overflow
文章推薦指數: 80 %
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
延伸文章資訊
- 1git-merge Documentation - Git
This command is used by git pull to incorporate changes from another repository and can be used b...
- 2git merge force overwrite local Code Example
Merge branch_b into branch you're in. 5. git merge <branch_name>. 6. . 7. # Force merge if the b...
- 3Introduction to Git rebase and force-push - GitLab Docs
Introduction to Git rebase and force-push, methods to resolve merge conflicts through the command...
- 4Git Pull Force – How to Overwrite Local Changes With Git
Git will merge the changes from the remote repository named origin (the one you cloned from); tha...
- 5在Git 中合併與強制覆蓋| D棧- Delft Stack
大多數時候,當我們應用 git push 或 git merge 時,最終會發生一些衝突。在某些情況下,合併衝突的解決方案就像丟棄本地更改或遠端或其他分支更改一樣 ...