Git merge conflicts | Atlassian Git Tutorial

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

Git can handle most merges on its own with automatic merging features. A conflict arises when two separate branches have made edits to the same line in a file, ... LearnGit LearnGitwithBitbucketCloud CreateaGitrepository CopyyourGitrepositoryandaddfiles PullchangesfromyourGitrepositoryonBitbucketCloud UseaGitbranchtomergeafile LearnaboutcodereviewinBitbucketCloud Createarepository Cloneandmakeachangeonanewbranch Ifyou'reusingcommandline Ifyou'reusingSourcetree Createapullrequesttomergeyourchange LearnbranchinginBitbucketCloud Getsetup Reviewbranchingworkflow LearnundoingchangeswithBitbucketCloud gitstatus gitlog gitreset gitrevert Beginner Whatisversioncontrol Benefitsofversioncontrol SourceCodeManagement WhatisGit Performance Security Flexibility VersioncontrolwithGit WhyGitforyourOrganization Gitfordevelopers Gitformarketing Gitforproductmanagement Gitfordesigners Gitforcustomersupport Gitforhumanresources Gitforanyonemanagingabudget InstallGit InstallGitonMacOSX InstallGitonWindows InstallGitonLinux GitSSH Gitarchive GitOps GitCheatsheet GettingStarted Settinguparepository gitinit gitclone gitconfig gitalias Savingchanges gitadd gitcommit gitdiff gitstash .gitignore Inspectingarepository gitstatus gittag gitblame Undoingchanges gitcheckout gitclean gitrevert gitreset gitrm Rewritinghistory gitcommit--amend gitrebase gitrebase-i gitreflog Collaborating Syncing gitremote gitfetch gitpush gitpull MakingaPullRequest Howitworks Example Wheretogofromhere Usingbranches gitbranch gitcheckout gitmerge Mergeconflicts Mergestrategies Comparingworkflows CentralizedWorkflow FeatureBranchWorkflow GitflowWorkflow ForkingWorkflow MigratingtoGit SVNtoGit-preppingforthemigration Foradministrators BasicGitcommands GitMigrationTools Fordevelopers MigratetoGitfromSVN Prepare Convert Synchronize Share Migrate PerforcetoGit-whytomakethemove MigratingfromPerforcetoGit HowtomoveaGitrepositorywithhistory AdvancedTips AdvancedGitTutorials Mergingvs.Rebasing ConceptualOverview TheGoldenRuleofRebasing WorkflowWalkthrough Summary Resetting,CheckingOut,andReverting AdvancedGitlog FormattingLogOutput FilteringtheCommitHistory Summary GitHooks ConceptualOverview LocalHooks Server-sideHooks Summary RefsandtheReflog Hashes Refs PackedRefs SpecialRefs Refspecs RelativeRefs TheReflog Summary Gitsubmodules Gitsubtree LargerepositoriesinGit GitLFS Gitgc Gitprune GitBash Howtostoredotfiles GitCherryPick GitK Git-show Home Tutorials Tutorials Articles Glossary Tutorials Submit Signup Search Search Gitmergeconflicts Versioncontrolsystemsareallaboutmanagingcontributionsbetweenmultipledistributedauthors(usuallydevelopers).Sometimesmultipledevelopersmaytrytoeditthesamecontent.IfDeveloperAtriestoeditcodethatDeveloperBiseditingaconflictmayoccur.Toalleviatetheoccurrenceofconflictsdeveloperswillworkinseparateisolatedbranches.The gitmergecommand'sprimaryresponsibilityistocombineseparatebranchesandresolveanyconflictingedits. Understandingmergeconflicts MergingandconflictsareacommonpartoftheGitexperience.ConflictsinotherversioncontroltoolslikeSVNcanbecostlyandtime-consuming.Gitmakesmergingsupereasy.Mostofthetime,Gitwillfigureouthowtoautomaticallyintegratenewchanges. Conflictsgenerallyarisewhentwopeoplehavechangedthesamelinesinafile,orifonedeveloperdeletedafilewhileanotherdeveloperwasmodifyingit.Inthesecases,Gitcannotautomaticallydeterminewhatiscorrect.Conflictsonlyaffectthedeveloperconductingthemerge,therestoftheteamisunawareoftheconflict.Gitwillmarkthefileasbeingconflictedandhaltthemergingprocess.Itisthenthedevelopers'responsibilitytoresolvetheconflict. Typesofmergeconflicts Amergecanenteraconflictedstateattwoseparatepoints.Whenstartingandduringamergeprocess.Thefollowingisadiscussionofhowtoaddresseachoftheseconflictscenarios. Gitfailstostartthemerge AmergewillfailtostartwhenGitseestherearechangesineithertheworkingdirectoryorstagingareaofthecurrentproject.Gitfailstostartthemergebecausethesependingchangescouldbewrittenoverbythecommitsthatarebeingmergedin.Whenthishappens,itisnotbecauseofconflictswithotherdeveloper's,butconflictswithpendinglocalchanges.Thelocalstatewillneedtobestabilizedusinggitstash,gitcheckout,gitcommitorgitreset.Amergefailureonstartwilloutputthefollowingerrormessage: error: Entry '' not uptodate. Cannot merge. (Changes in working directory) Gitfailsduringthemerge AfailureDURINGamergeindicatesaconflictbetweenthecurrentlocalbranchandthebranchbeingmerged.Thisindicatesaconflictwithanotherdeveloperscode.Gitwilldoitsbesttomergethefilesbutwillleavethingsforyoutoresolvemanuallyintheconflictedfiles.Amid-mergefailurewilloutputthefollowingerrormessage: error: Entry '' would be overwritten by merge. Cannot merge. (Changes in staging area) Creatingamergeconflict Inordertogetrealfamiliarwithmergeconflicts,thenextsectionwillsimulateaconflicttolaterexamineandresolve.TheexamplewillbeusingaUnix-likecommand-lineGitinterfacetoexecutetheexamplesimulation. $ mkdir git-merge-test$ cd git-merge-test$ git init .$ echo "this is some content to mess with" > merge.txt$ git add merge.txt$ git commit -am"we are commiting the inital content"[main (root-commit) d48e74c] we are commiting the inital content1 file changed, 1 insertion(+)create mode 100644 merge.txt Thiscodeexampleexecutesasequenceofcommandsthataccomplishthefollowing. Createanewdirectorynamedgit-merge-test,changetothatdirectory,andinitializeitasanewGitrepo.Createanewtextfilemerge.txtwithsomecontentinit. Addmerge.txttotherepoandcommitit. Nowwehaveanewrepowithonebranchmain andafilemerge.txtwithcontentinit.Next,wewillcreateanewbranchtouseastheconflictingmerge. $ git checkout -b new_branch_to_merge_later$ echo "totally different content to merge later" > merge.txt$ git commit -am"edited the content of merge.txt to cause a conflict"[new_branch_to_merge_later 6282319] edited the content of merge.txt to cause a conflict1 file changed, 1 insertion(+), 1 deletion(-) Theproceedingcommandsequenceachievesthefollowing: createandcheckoutanewbranchnamednew_branch_to_merge_lateroverwritethecontentinmerge.txt committhenewcontent Withthisnewbranch:new_branch_to_merge_laterwehavecreatedacommitthatoverridesthecontentofmerge.txt git checkout mainSwitched to branch 'main'echo "content to append" >> merge.txtgit commit -am"appended content to merge.txt"[main 24fbe3c] appended content to merge.tx1 file changed, 1 insertion(+) Thischainofcommandschecksoutthemain branch,appendscontenttomerge.txt,andcommitsit.Thisnowputsourexamplerepoinastatewherewehave2newcommits.Oneinthemain branchandoneinthenew_branch_to_merge_laterbranch.Atthistimeletsgitmergenew_branch_to_merge_laterandseewhathappen! $ git merge new_branch_to_merge_laterAuto-merging merge.txtCONFLICT (content): Merge conflict in merge.txtAutomatic merge failed; fix conflicts and then commit the result. BOOM💥.Aconflictappears.Thanks,Gitforlettingusknowaboutthis! Howtoidentifymergeconflicts Aswehaveexperiencedfromtheproceedingexample,GitwillproducesomedescriptiveoutputlettingusknowthataCONFLICThasocccured.Wecangainfurtherinsightbyrunningthegitstatuscommand $ git statusOn branch mainYou have unmerged paths.(fix conflicts and run "git commit")(use "git merge --abort" to abort the merge)Unmerged paths:(use "git add ..." to mark resolution)both modified:   merge.txt Theoutputfromgitstatusindicatesthatthereareunmergedpathsduetoaconflict.Themerge.textfilenowappearsinamodifiedstate.Let'sexaminethefileandseewhatsmodified. $ cat merge.txt<<<<<<>>>>>> new_branch_to_merge_later Herewehaveusedthecatcommandtoputoutthecontentsofthemerge.txt file.Wecanseesomestrangenewadditions <<<<<<>>>>>>new_branch_to_merge_later Thinkofthesenewlinesas"conflictdividers".The=======lineisthe"center"oftheconflict.Allthecontentbetweenthecenterandthe<<<<<<>>>>>>new_branch_to_merge_lateriscontentthatispresentinourmergingbranch. Howtoresolvemergeconflictsusingthecommandline Themostdirectwaytoresolveamergeconflictistoedittheconflictedfile.Openthemerge.txtfileinyourfavoriteeditor.Forourexampleletssimplyremovealltheconflictdividers.Themodifiedmerge.txtcontentshouldthenlooklike: this is some content to mess withcontent to appendtotally different content to merge later Oncethefilehasbeeneditedusegitaddmerge.txttostagethenewmergedcontent.Tofinalizethemergecreateanewcommitbyexecuting: git commit -m "merged and resolved the conflict in merge.txt" Gitwillseethattheconflicthasbeenresolvedandcreatesanewmergecommittofinalizethemerge. Gitcommandsthatcanhelpresolvemergeconflicts Generaltools git status ThestatuscommandisinfrequentusewhenaworkingwithGitandduringamergeitwillhelpidentifyconflictedfiles. git log --merge Passingthe--mergeargumenttothegitlogcommandwillproducealogwithalistofcommitsthatconflictbetweenthemergingbranches. git diff diffhelpsfinddifferencesbetweenstatesofarepository/files.Thisisusefulinpredictingandpreventingmergeconflicts. Toolsforwhengitfailstostartamerge git checkout checkoutcanbeusedforundoingchangestofiles,orforchangingbranches git reset --mixed resetcanbeusedtoundochangestotheworkingdirectoryandstagingarea. Toolsforwhengitconflictsariseduringamerge git merge --abort Executinggitmergewiththe--abortoptionwillexitfromthemergeprocessandreturnthebranchtothestatebeforethemergebegan. git reset Gitresetcanbeusedduringamergeconflicttoresetconflictedfilestoaknowgoodstate Summary Mergeconflictscanbeanintimidatingexperience.Luckily,Gitofferspowerfultoolstohelpnavigateandresolveconflicts.Gitcanhandlemostmergesonitsownwithautomaticmergingfeatures.Aconflictariseswhentwoseparatebrancheshavemadeeditstothesamelineinafile,orwhenafilehasbeendeletedinonebranchbuteditedintheother.Conflictswillmostlikelyhappenwhenworkinginateamenvironment. Therearemanytoolstohelpresolvemergeconflicts.Githasplentyofcommandlinetoolswediscussedhere.Formoredetailedinformationonthesetoolsvisitstand-alonepagesforgitlog,gitreset,gitstatus,gitcheckout,andgitreset.InadditiontotheGit,manythird-partytoolsofferstreamlinedmergeconflictsupportfeatures. Readytotrybranching?Trythisinteractivetutorial. Getstartednow Nextup: GitMergeStrategies Startnexttutorial



請為這篇文章評分?