Git Pull Force – How to Overwrite Local Changes With Git

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

Git will merge the changes from the remote repository named origin (the one you cloned from); that have been added to the $CURRENT_BRANCH; that ... Search Submityoursearchquery Forum Donate PiotrGaczkowski Whenyoulearntocode,soonerorlateryou'llalsolearnaboutVersionControlSystems.Andwhiletherearemanycompetingtoolsinthisspace,oneofthemisthedefactostandardusedbyalmosteveryoneintheindustry.It'ssopopularthattherearecompaniesthatuseitsnameintheirbranding.We'retalkingaboutGit,ofcourse.WhileGitisapowerfultool,itspoweriswell-hidden.TherearesomeessentialconceptsthatyouneedtounderstandtobecomereallyproficientwithGit.Thegoodnewsisthatonceyoulearnthem,you'llhardlyeverrunintotroubleyoucan'tescapefrom.TheTypicalWorkflowInatypicalGitworkflowyou'llusealocalrepository,aremoterepository,andoneormorebranches.Repositoriesstorealltheinformationabouttheproject,includingitsentirehistoryandallthebranches.Abranchisbasicallyacollectionofchangesleadingfromanemptyprojecttothecurrentstate.Aftercloningarepository,youworkonyourlocalcopyandintroducenewchanges.Untilyoupushlocalchangestotheremoterepository,allyourworkisavailableonlyonyourmachine.Whenyoufinishatask,it'stimetosynchronizewiththeremoterepository.Youwanttopulltheremotechangestokeepupwiththeproject'sprogress,andyouwanttopushthelocalchangestoshareyourworkwithothers.LocalChangesAlliswellwhenyouandtherestofyourteamareworkingontotallyseparatefiles.Whateverhappens,youwon'tbesteppingoneachother'sfeet.However,therearetimeswhenyouandyourteammatessimultaneouslyintroducechangesinthesameplace.Andthat'susuallywheretheproblemsbegin.Haveyoueverexecutedgitpullonlytoseethedreadederror:Yourlocalchangestothefollowingfileswouldbeoverwrittenbymerge:?Soonerorlater,everyonerunsintothatproblem.What'smoreconfusinghereisthatyoudon'twanttomergeanything,justpull,right?Actually,pullisabitmorecomplicatedthanyoumighthavethought.HowExactlydoesGitPullWork?Pullisnotasingleoperation.Itconsistsoffetchingdatafromtheremoteserverandthenmergingthechangeswiththelocalrepository.Thesetwooperationscanbeperformedmanuallyifyouwant:gitfetch gitmergeorigin/$CURRENT_BRANCHTheorigin/$CURRENT_BRANCHpartmeansthat:Gitwillmergethechangesfromtheremoterepositorynamedorigin(theoneyouclonedfrom)thathavebeenaddedtothe$CURRENT_BRANCHthatarenotalreadypresentinyourlocalcheckedoutbranchSinceGitonlyperformsmergeswhentherearenouncommittedchanges,everytimeyourungitpullwithuncommittedchangescouldgetyouintotrouble.Fortunately,therearewaystogetoutoftroubleinonepiece!PhotobySneakyElbow/UnsplashDifferentApproachesWhenyouhaveuncommittedlocalchangesandstillwanttopullanewversionfromtheremoteserver,yourusecasetypicallyfallsintooneofthefollowingscenarios.Either:youdon'tcareaboutthelocalchangesandwanttooverwritethem,youcareaboutthechangesverymuchandwouldliketoapplythemaftertheremotechanges,youwanttodownloadtheremotemodificationsbutnotapplythemyetEachoftheapproachesrequiresadifferentsolution.YouDon'tCareAbouttheLocalChangesInthiscase,youjustwanttodropalltheuncommittedlocalchanges.Perhapsyoumodifiedafiletoexperiment,butyounolongerneedthemodification.Allyoucareaboutisbeinguptodatewiththeupstream.Thismeansthatyouaddonemorestepbetweenfetchingtheremotechangesandmergingthem.Thisstepwillresetthebranchtoitsunmodifiedstate,thusallowinggitmergetowork.gitfetch gitreset--hardHEAD gitmergeorigin/$CURRENT_BRANCHIfyoudon'twanttotypethebranchnameeverytimeyourunthiscommand,Githasaniceshortcutpointingtotheupstreambranch:@{u}.Anupstreambranchisthebranchintheremoterepositorythatyoupushtoandfetchfrom.Thisishowtheabovecommandswouldlooklikewiththeshortcut:gitfetch gitreset--hardHEAD gitmerge'@{u}'Wearequotingtheshortcutintheexampletopreventtheshellfrominterpretingit.YouVeryMuchCareAbouttheLocalChangesWhenyouruncommittedchangesaresignificanttoyou,therearetwooptions.Youcancommitthemandthenperformgitpull,oryoucanstashthem.Stashingmeansputtingthechangesawayforamomenttobringthembacklater.Tobemoreprecise,gitstashcreatesacommitthatisnotvisibleonyourcurrentbranch,butisstillaccessiblebyGit.Tobringbackthechangessavedinthelaststash,youusethegitstashpopcommand.Aftersuccessfullyapplyingthestashedchanges,thiscommandalsoremovesthestashcommitasitisnolongerneeded.Theworkflowcouldthenlooklikethis:gitfetch gitstash gitmerge'@{u}' gitstashpopBydefault,thechangesfromthestashwillbecomestaged.Ifyouwanttounstagethem,usethecommandgitrestore--staged(ifusingGitnewerthan2.25.0).YouJustWanttoDownloadtheRemoteChangesThelastscenarioisalittledifferentfromthepreviousones.Let'ssaythatyouareinthemiddleofaverymessyrefactoring.Neitherlosingthechangesnorstashingthemisanoption.Yet,youstillwanttohavetheremotechangesavailabletorungitdiffagainstthem.Asyouhaveprobablyfiguredout,downloadingtheremotechangesdoesnotrequiregitpullatall!gitfetchisjustenough.Onethingtonoteisthatbydefault,gitfetchwillonlybringyouchangesfromthecurrentbranch.Togetallthechangesfromallthebranches,usegitfetch--all.Andifyou'dliketocleanupsomeofthebranchesthatnolongerexistintheremoterepository,gitfetch--all--prunewilldothecleaningup!PhotobyLeninEstrada/UnsplashSomeAutomationHaveyouheardofGitConfig?It'safilewhereGitstoresalloftheuser-configuredsettings.Itresidesinyourhomedirectory:eitheras~/.gitconfigor~/.config/git/config.YoucaneditittoaddsomecustomaliasesthatwillbeunderstoodasGitcommands.Forexample,tohaveashortcutequivalenttogitdiff--cached(thatshowsthedifferencebetweenthecurrentbranchandthestagedfiles),you'daddthefollowingsection:[alias] dc=diff--cachedAfterthat,youcanrungitdcwheneveryouwishtoreviewthechanges.Goingthisway,wecansetupafewaliasesrelatedtotheprevioususecases.[alias] pull_force=!"gitfetch--all;gitreset--hardHEAD;gitmerge@{u}" pf=pull_force pull_stash=!"gitfetch--all;gitstash;gitmerge@{u};gitstashpop"Thisway,runninggitpull_forcewilloverwritethelocalchanges,whilegitpull_stashwillpreservethem.TheOtherGitPullForceCuriousmindsmayhavealreadydiscoveredthatthereissuchathingasgitpull--force.However,thisisaverydifferentbeasttowhat'spresentedinthisarticle.Itmaysoundlikesomethingthatwouldhelpusoverwritelocalchanges.Instead,itletsusfetchthechangesfromoneremotebranchtoadifferentlocalbranch.gitpull--forceonlymodifiesthebehaviorofthefetchingpart.Itisthereforeequivalenttogitfetch--force.Likegitpush,gitfetchallowsustospecifywhichlocalandremotebranchdowewanttooperateon.gitfetchorigin/feature-1:my-featurewillmeanthatthechangesinthefeature-1branchfromtheremoterepositorywillendupvisibleonthelocalbranchmy-feature.Whensuchanoperationmodifiestheexistinghistory,itisnotpermittedbyGitwithoutanexplicit--forceparameter.Justlikegitpush--forceallowsoverwritingremotebranches,gitfetch--force(orgitpull--force)allowsoverwritinglocalbranches.Itisalwaysusedwithsourceanddestinationbranchesmentionedasparameters.Analternativeapproachtooverwritinglocalchangesusinggit--pullforcecouldbegitpull--force"@{u}:HEAD".ConclusionTheworldofGitisvast.Thisarticlecoveredonlyoneofthefacetsofrepositorymaintenance:incorporatingremotechangesintoalocalrepository.Eventhiseverydayscenariorequiredustolookslightlymorein-depthintothisversioncontroltool'sinternalmechanisms.LearningactualusecaseshelpsyoubetterunderstandhowGitworksunderthehood.This,inturn,willmakeyoufeelempoweredwheneveryougetyourselfintotrouble.Wealldothatfromtimetotime. PiotrGaczkowski Creator.EfficiencyHacker.HumanJukebox.Lovesconvenienttoolsandsharingknowledge. Ifyoureadthisfar,tweettotheauthortoshowthemyoucare.Tweetathanks Learntocodeforfree.freeCodeCamp'sopensourcecurriculumhashelpedmorethan40,000peoplegetjobsasdevelopers.Getstarted



請為這篇文章評分?