如何解决 Git 存储库中的合并冲突?

发布于 2024-07-06 17:38:53 字数 26 浏览 8 评论 0 原文

如何解决 Git 存储库中的合并冲突?

How do I resolve merge conflicts in my Git repository?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

信愁 2024-07-13 17:38:53

尝试:

git mergetool

它会打开一个 GUI,引导您解决每个冲突,然后您可以选择如何合并。 有时事后需要进行一些手动编辑,但通常本身就足够了。 这肯定比手工完成整个事情要好得多。


根据 Josh Glover 的评论

[此命令]
除非您安装了 GUI,否则不一定会打开 GUI。 为我运行 git mergetool 导致使用 vimdiff 。 您可以安装
使用以下工具之一来代替:meldopendiff
kdiff3tkdiffxxdifftortoisemergegvimdiffdiffuse< /代码>,
ecmergep4mergearaxisvimdiffemerge



下面是使用 vimdiff 解决合并冲突的示例过程,基于 此链接

  1. 在终端中运行以下命令

    git config merge.tool vimdiff 
      git config merge.conflictstyle diff3 
      git config mergetool.prompt false 
      

    这会将 vimdiff 设置为默认合并工具。

  2. 在终端中运行以下命令

    git mergetool 
      
  3. 您将看到以下格式的 vimdiff 显示:

    <代码> ╔═══════╦══════╦════════╗ 
        ║║║║ 
        ║ 本地 ║ 基地 ║ 远程 ║ 
        ║║║║ 
        ╠═══════╩══════╩════════╣ 
        ║║ 
        ║ 合并║ 
        ║║ 
        ╚═══════════════════════╝ 
      

    这 4 个视图是

    • 本地:这是当前分支中的文件
    • BASE:共同的祖先,该文件在两次更改之前的外观
    • 远程:您要合并到分支中的文件
    • MERGED:合并结果; 这是在合并提交中保存并在将来使用的内容

    您可以使用 ctrl+w 在这些视图之间导航。 您可以使用 ctrl+w 后跟 j 直接访问 MERGED 视图。

    有关 vimdiff 导航的更多信息位于此处以及此处。。 p>

  4. 您可以像这样编辑 MERGED 视图:

    • 如果您想从 REMOTE 获取更改

      <前><代码>:diffg RE

    • 如果您想从 BASE 获取更改

      <前><代码>:diffg BA

    • 如果您想从 LOCAL 获取更改

      <前><代码>:diffg LO

  5. 保存、退出、提交和清理

    :wqa保存并退出vi

    git commit -m“消息”

    git clean 删除多余的文件(例如*.orig)。 警告:如果您不传递任何参数,它将删除所有未跟踪的文件。

Try:

git mergetool

It opens a GUI that steps you through each conflict, and you get to choose how to merge. Sometimes it requires a bit of hand editing afterwards, but usually it's enough by itself. It is much better than doing the whole thing by hand certainly.


As per Josh Glover's comment:

[This command]
doesn't necessarily open a GUI unless you install one. Running git mergetool for me resulted in vimdiff being used. You can install
one of the following tools to use it instead: meld, opendiff,
kdiff3, tkdiff, xxdiff, tortoisemerge, gvimdiff, diffuse,
ecmerge, p4merge, araxis, vimdiff, emerge.


Below is a sample procedure using vimdiff to resolve merge conflicts, based on this link.

  1. Run the following commands in your terminal

    git config merge.tool vimdiff
    git config merge.conflictstyle diff3
    git config mergetool.prompt false
    

    This will set vimdiff as the default merge tool.

  2. Run the following command in your terminal

    git mergetool
    
  3. You will see a vimdiff display in the following format:

      ╔═══════╦══════╦════════╗
      ║       ║      ║        ║
      ║ LOCAL ║ BASE ║ REMOTE ║
      ║       ║      ║        ║
      ╠═══════╩══════╩════════╣
      ║                       ║
      ║        MERGED         ║
      ║                       ║
      ╚═══════════════════════╝
    

    These 4 views are

    • LOCAL: this is the file from the current branch
    • BASE: the common ancestor, how this file looked before both changes
    • REMOTE: the file you are merging into your branch
    • MERGED: the merge result; this is what gets saved in the merge commit and used in the future

    You can navigate among these views using ctrl+w. You can directly reach the MERGED view using ctrl+w followed by j.

    More information about vimdiff navigation is here and here.

  4. You can edit the MERGED view like this:

    • If you want to get changes from REMOTE

      :diffg RE
      
    • If you want to get changes from BASE

      :diffg BA
      
    • If you want to get changes from LOCAL

      :diffg LO
      
  5. Save, Exit, Commit, and Clean up

    :wqa save and exit from vi

    git commit -m "message"

    git clean Remove extra files (e.g. *.orig). Warning: It will remove all untracked files, if you won't pass any arguments.

末が日狂欢 2024-07-13 17:38:53

从上到下,这是一个可能的用例:

您将进行一些更改,但是哎呀,您不是最新的:

git fetch origin
git pull origin master

From ssh://[email protected]:22/projectname
 * branch            master     -> FETCH_HEAD
Updating a030c3a..ee25213
error: Entry 'filename.c' not uptodate. Cannot merge.

所以您获得最新的并重试,但有冲突:

git add filename.c
git commit -m "made some wild and crazy changes"
git pull origin master

From ssh://[email protected]:22/projectname
 * branch            master     -> FETCH_HEAD
Auto-merging filename.c
CONFLICT (content): Merge conflict in filename.c
Automatic merge failed; fix conflicts and then commit the result.

所以您决定看看这些变化:

git mergetool

哦天哪,哦天哪,上游改变了一些东西,但只是为了使用我的改变......不......他们的改变......

git checkout --ours filename.c
git checkout --theirs filename.c
git add filename.c
git commit -m "using theirs"

然后我们最后一次尝试

git pull origin master

From ssh://[email protected]:22/projectname
 * branch            master     -> FETCH_HEAD
Already up-to-date.

Ta-da!

Here's a probable use case, from the top:

You're going to pull some changes, but oops, you're not up to date:

git fetch origin
git pull origin master

From ssh://[email protected]:22/projectname
 * branch            master     -> FETCH_HEAD
Updating a030c3a..ee25213
error: Entry 'filename.c' not uptodate. Cannot merge.

So you get up-to-date and try again, but have a conflict:

git add filename.c
git commit -m "made some wild and crazy changes"
git pull origin master

From ssh://[email protected]:22/projectname
 * branch            master     -> FETCH_HEAD
Auto-merging filename.c
CONFLICT (content): Merge conflict in filename.c
Automatic merge failed; fix conflicts and then commit the result.

So you decide to take a look at the changes:

git mergetool

Oh my, oh my, upstream changed some things, but just to use my changes...no...their changes...

git checkout --ours filename.c
git checkout --theirs filename.c
git add filename.c
git commit -m "using theirs"

And then we try a final time

git pull origin master

From ssh://[email protected]:22/projectname
 * branch            master     -> FETCH_HEAD
Already up-to-date.

Ta-da!

蓝天白云 2024-07-13 17:38:53

我发现合并工具很少能帮助我理解冲突或解决方案。 我通常更成功地查看文本编辑器中的冲突标记并使用 git log 作为补充。

这里有一些提示:

提示一

我发现的最好的办法是使用“diff3”合并冲突样式:

git config merge.conflictstyle diff3

这会产生如下所示的冲突标记:

<<<<<<<
Changes made on the branch that is being merged into. In most cases,
this is the branch that I have currently checked out (i.e. HEAD).
|||||||
The common ancestor version.
=======
Changes made on the branch that is being merged in. This is often a 
feature/topic branch.
>>>>>>>

中间部分是什么共同的祖先看起来像。 这很有用,因为您可以将其与顶部和底部版本进行比较,以更好地了解每个分支上的更改内容,从而更好地了解每个更改的目的是什么。

如果冲突只有几行,通常会使冲突变得非常明显。 (知道如何解决冲突是非常不同的;您需要了解其他人正在做什么。如果您感到困惑,最好将那个人叫到您的房间,以便他们可以看到您正在寻找的内容 如果冲突较长

,那么我会将这三个部分分别剪切并粘贴到三个单独的文件中,例如“我的”、“共同的”和“他们的”。

然后我可以运行以下命令来查看导致冲突的两个 diff 块:

diff common mine
diff common theirs

这与使用合并工具不同,因为合并工具也将包含所有不冲突的 diff 块。 我发现这让人分心。

提示

二 有人已经提到过这一点,但是理解每个差异块背后的意图通常对于理解冲突从何而来以及如何处理它非常有帮助。

git log --merge -p <name of file>

这显示了在共同祖先和您要合并的两个头之间触及该文件的所有提交。 (因此它不包括合并之前两个分支中已经存在的提交。)这可以帮助您忽略明显不是当前冲突因素的差异块。

提示三

使用自动化工具验证您的更改。

如果您有自动化测试,请运行它们。 如果您有 lint,请运行它。 如果它是一个可构建的项目,那么在提交之前构建它,等等。在所有情况下,您都需要进行一些测试以确保您的更改不会破坏任何内容。 (哎呀,即使没有冲突的合并也可能会破坏工作代码。)

技巧四

提前计划; 与同事沟通。

提前计划并了解其他人正在做什么可以帮助防止合并冲突和/或帮助尽早解决它们——同时细节仍然记忆犹新。

例如,如果您知道您和另一个人都在进行不同的重构,而这些重构都会影响同一组文件,那么您应该提前相互交谈,并更好地了解你们每个人正在做什么类型的更改制作。 如果您连续而不是并行地进行计划的更改,您可能会节省大量时间和精力。

对于跨越大量代码的主要重构,您应该强烈考虑串行工作:每个人都停止处理该代码区域,而一个人执行完整的重构。

如果您无法连续工作(可能是由于时间压力),那么就预期的合并冲突进行沟通至少可以帮助您更快地解决问题,同时细节仍然记忆犹新。 例如,如果一位同事在一周内进行一系列破坏性提交,您可以选择在该周内每天对该同事分支进行一次或两次合并/变基。 这样,如果您确实发现合并/变基冲突,您可以比等待几周将所有内容合并在一起更快地解决它们。

提示五

如果您不确定是否要合并,请不要强迫它。

合并可能会让人感到不知所措,尤其是当存在大量冲突文件并且冲突标记覆盖数百行时。 很多时候,在评估软件项目时,我们没有足够的时间来处理诸如处理粗糙合并之类的开销项目,因此花费几个小时来剖析每个冲突感觉确实很麻烦。

从长远来看,提前计划并了解其他人正在做什么是预测合并冲突并准备在更短的时间内正确解决它们的最佳工具。

I find merge tools rarely help me understand the conflict or the resolution. I'm usually more successful looking at the conflict markers in a text editor and using git log as a supplement.

Here are a few tips:

Tip One

The best thing I have found is to use the "diff3" merge conflict style:

git config merge.conflictstyle diff3

This produces conflict markers like this:

<<<<<<<
Changes made on the branch that is being merged into. In most cases,
this is the branch that I have currently checked out (i.e. HEAD).
|||||||
The common ancestor version.
=======
Changes made on the branch that is being merged in. This is often a 
feature/topic branch.
>>>>>>>

The middle section is what the common ancestor looked like. This is useful because you can compare it to the top and bottom versions to get a better sense of what was changed on each branch, which gives you a better idea for what the purpose of each change was.

If the conflict is only a few lines, this generally makes the conflict very obvious. (Knowing how to fix a conflict is very different; you need to be aware of what other people are working on. If you're confused, it's probably best to just call that person into your room so they can see what you're looking at.)

If the conflict is longer, then I will cut and paste each of the three sections into three separate files, such as "mine", "common" and "theirs".

Then I can run the following commands to see the two diff hunks that caused the conflict:

diff common mine
diff common theirs

This is not the same as using a merge tool, since a merge tool will include all of the non-conflicting diff hunks too. I find that to be distracting.

Tip Two

Somebody already mentioned this, but understanding the intention behind each diff hunk is generally very helpful for understanding where a conflict came from and how to handle it.

git log --merge -p <name of file>

This shows all of the commits that touched that file in between the common ancestor and the two heads you are merging. (So it doesn't include commits that already exist in both branches before merging.) This helps you ignore diff hunks that clearly are not a factor in your current conflict.

Tip Three

Verify your changes with automated tools.

If you have automated tests, run those. If you have a lint, run that. If it's a buildable project, then build it before you commit, etc. In all cases, you need to do a bit of testing to make sure your changes didn't break anything. (Heck, even a merge without conflicts can break working code.)

Tip Four

Plan ahead; communicate with co-workers.

Planning ahead and being aware of what others are working on can help prevent merge conflicts and/or help resolve them earlier -- while the details are still fresh in mind.

For example, if you know that you and another person are both working on different refactoring that will both affect the same set of files, you should talk to each other ahead of time and get a better sense for what types of changes each of you is making. You might save considerable time and effort if you conduct your planned changes serially rather than in parallel.

For major refactorings that cut across a large swath of code, you should strongly consider working serially: everybody stops working on that area of the code while one person performs the complete refactoring.

If you can't work serially (due to time pressure, maybe), then communicating about expected merge conflicts at least helps you solve the problems sooner while the details are still fresh in mind. For example, if a co-worker is making a disruptive series of commits over the course of a one-week period, you may choose to merge/rebase on that co-workers branch once or twice each day during that week. That way, if you do find merge/rebase conflicts, you can solve them more quickly than if you wait a few weeks to merge everything together in one big lump.

Tip Five

If you're unsure of a merge, don't force it.

Merging can feel overwhelming, especially when there are a lot of conflicting files and the conflict markers cover hundreds of lines. Often times when estimating software projects we don't include enough time for overhead items like handling a gnarly merge, so it feels like a real drag to spend several hours dissecting each conflict.

In the long run, planning ahead and being aware of what others are working on are the best tools for anticipating merge conflicts and prepare yourself to resolve them correctly in less time.

情释 2024-07-13 17:38:53
  1. 确定哪些文件存在冲突(Git 应该告诉您这一点)。

  2. 打开每个文件并检查差异; Git 对它们进行了划分。 希望保留每个块的版本是显而易见的。 您可能需要与提交代码的其他开发人员讨论。

  3. 解决文件中的冲突后,git add the_file

  4. 解决所有冲突后,执行git rebase --continue或任何命令
    Git 表示在完成后执行。

  1. Identify which files are in conflict (Git should tell you this).

  2. Open each file and examine the diffs; Git demarcates them. Hopefully it will be obvious which version of each block to keep. You may need to discuss it with fellow developers who committed the code.

  3. Once you've resolved the conflict in a file git add the_file.

  4. Once you've resolved all conflicts, do git rebase --continue or whatever command
    Git said to do when you completed.

请爱~陌生人 2024-07-13 17:38:53

当同时对文件进行更改时,就会发生合并冲突。 以下是解决方法。

git CLI

以下是进入冲突状态时应执行的简单步骤:

  1. 记下冲突文件列表:git status(在 Unmerged paths 部分)。
  2. 通过以下方法之一分别解决每个文件的冲突:

    • 使用 GUI 解决冲突:git mergetool(最简单的方法)。

    • 要接受远程/其他版本,请使用:git checkout --theirs path/file。 这将拒绝您对该文件所做的任何本地更改。

    • 要接受本地/我们的版本,请使用:git checkout --ours 路径/文件

      但是您必须小心,因为由于某种原因发生冲突的远程更改。

      相关:git中“我们的”和“他们的”的确切含义是什么?

      < /里>

    • 手动编辑冲突文件并查找 <<<<<<</>>>>>< 之间的代码块/code> 然后从上方或下方选择版本=====。 请参阅:如何呈现冲突

    • 路径和文件名冲突可以通过git add/git rm解决。

  3. 最后,使用 git status 查看准备提交的文件。

    如果未合并路径下仍有任何文件,并且您确实手动解决了冲突,请让 Git 知道您已通过以下方式解决了该问题:git add path/file .

  4. 如果所有冲突均已成功解决,请通过以下方式提交更改:git commit -a 并照常推送到远程。

另请参阅:通过命令解决合并冲突行位于 GitHub

有关实用教程,请检查:场景 5 - Katacoda 修复合并冲突

DiffMerge

我已经成功使用了 DiffMerge,它可以在 Windows、macOS 和 Linux/Unix 上直观地比较和合并文件。

它可以以图形方式显示 3 个文件之间的更改,并允许自动合并(在安全的情况下)并完全控制编辑结果文件。

DiffMerge

图片来源:DiffMerge(Linux 屏幕截图)

只需下载并运行在存储库中为:

git mergetool -t diffmerge .

macOS

在 macOS 上,您可以通过以下方式安装:

brew install caskroom/cask/brew-cask
brew cask install diffmerge

并且可能(如果未提供)您需要将以下额外的简单包装器放置在您的 PATH 中(例如 /usr/bin):

#!/bin/sh
DIFFMERGE_PATH=/Applications/DiffMerge.app
DIFFMERGE_EXE=${DIFFMERGE_PATH}/Contents/MacOS/DiffMerge
exec ${DIFFMERGE_EXE} --nosplash "$@"

然后您可以使用以下键盘快捷键:

  • -Alt-向上/向下跳转到上一个/下一个更改。
  • -Alt-Left/Right 接受左侧或右侧的更改

或者您可以使用 opendiff(Xcode工具的一部分)让您将两个文件或目录合并在一起以创建第三个文件或目录。

Merge conflicts happens when changes are made to a file at the same time. Here is how to solve it.

git CLI

Here are simple steps what to do when you get into conflicted state:

  1. Note the list of conflicted files with: git status (under Unmerged paths section).
  2. Solve the conflicts separately for each file by one of the following approaches:

    • Use GUI to solve the conflicts: git mergetool (the easiest way).

    • To accept remote/other version, use: git checkout --theirs path/file. This will reject any local changes you did for that file.

    • To accept local/our version, use: git checkout --ours path/file

      However you've to be careful, as remote changes that conflicts were done for some reason.

      Related: What is the precise meaning of "ours" and "theirs" in git?

    • Edit the conflicted files manually and look for the code block between <<<<</>>>>> then choose the version either from above or below =====. See: How conflicts are presented.

    • Path and filename conflicts can be solved by git add/git rm.

  3. Finally, review the files ready for commit using: git status.

    If you still have any files under Unmerged paths, and you did solve the conflict manually, then let Git know that you solved it by: git add path/file.

  4. If all conflicts were solved successfully, commit the changes by: git commit -a and push to remote as usual.

See also: Resolving a merge conflict from the command line at GitHub

For practical tutorial, check: Scenario 5 - Fixing Merge Conflicts by Katacoda.

DiffMerge

I've successfully used DiffMerge which can visually compare and merge files on Windows, macOS and Linux/Unix.

It graphically can show the changes between 3 files and it allows automatic merging (when safe to do so) and full control over editing the resulting file.

DiffMerge

Image source: DiffMerge (Linux screenshot)

Simply download it and run in repo as:

git mergetool -t diffmerge .

macOS

On macOS you can install via:

brew install caskroom/cask/brew-cask
brew cask install diffmerge

And probably (if not provided) you need the following extra simple wrapper placed in your PATH (e.g. /usr/bin):

#!/bin/sh
DIFFMERGE_PATH=/Applications/DiffMerge.app
DIFFMERGE_EXE=${DIFFMERGE_PATH}/Contents/MacOS/DiffMerge
exec ${DIFFMERGE_EXE} --nosplash "$@"

Then you can use the following keyboard shortcuts:

  • -Alt-Up/Down to jump to previous/next changes.
  • -Alt-Left/Right to accept change from left or right

Alternatively you can use opendiff (part of Xcode Tools) which lets you merge two files or directories together to create a third file or directory.

落花随流水 2024-07-13 17:38:53

查看 Stack Overflow 问题中的答案中止 Git 中的合并,尤其是 Charles Bailey 的回答,它展示了如何查看不同版本的有问题的文件,例如

# Common base version of the file.
git show :1:some_file.cpp

# 'Ours' version of the file.
git show :2:some_file.cpp

# 'Theirs' version of the file.
git show :3:some_file.cpp

Check out the answers in Stack Overflow question Aborting a merge in Git, especially Charles Bailey's answer which shows how to view the different versions of the file with problems, for example,

# Common base version of the file.
git show :1:some_file.cpp

# 'Ours' version of the file.
git show :2:some_file.cpp

# 'Theirs' version of the file.
git show :3:some_file.cpp
瑶笙 2024-07-13 17:38:53

如果您经常进行小型提交,请首先使用 git log --merge 来查看提交注释。 然后 git diff 会显示冲突。

对于涉及多于几行的冲突,可以更轻松地查看外部 GUI 工具中发生的情况。 我喜欢 opendiff —— Git 还支持 vimdiff、gvimdiff、kdiff3、tkdiff、meld、xxdiff、emerge 开箱即用,你可以安装其他的:git config merge.tool "your.tool" 将设置您选择的工具以及合并失败后的 git mergetool 会向您显示上下文中的差异。

每次您编辑文件以解决冲突时,git add filename 都会更新索引,并且您的 diff 将不再显示它。 当所有冲突都得到处理并且它们的文件已被 git add 编辑后,git commit 将完成合并。

If you're making frequent small commits, then start by looking at the commit comments with git log --merge. Then git diff will show you the conflicts.

For conflicts that involve more than a few lines, it's easier to see what's going on in an external GUI tool. I like opendiff -- Git also supports vimdiff, gvimdiff, kdiff3, tkdiff, meld, xxdiff, emerge out of the box and you can install others: git config merge.tool "your.tool" will set your chosen tool and then git mergetool after a failed merge will show you the diffs in context.

Each time you edit a file to resolve a conflict, git add filename will update the index and your diff will no longer show it. When all the conflicts are handled and their files have been git add-ed, git commit will complete your merge.

余生再见 2024-07-13 17:38:53

我要么想要我的或他们的完整版本,要么想要查看各个更改并为每个更改做出决定。

完全接受我或他们的版本

接受我的版本(本地、我们的):

git checkout --ours -- <filename>
git add <filename>              # Marks conflict as resolved
git commit -m "merged bla bla"  # An "empty" commit

接受他们的版本(远程、他们的):

git checkout --theirs -- <filename>
git add <filename>
git commit -m "merged bla bla"

如果您想对所有冲突文件执行以下操作:

git merge --strategy-option ours

git merge --strategy-option theirs

查看所有更改并单独接受它们

  1. git mergetool
  2. 查看更改并接受每个更改的任一版本。
  3. git add
  4. git commit -m "merged bla bla"

默认 mergetool命令行中工作。 如何使用命令行合并工具应该是一个单独的问题。

您还可以为此安装可视化工具,例如meld并运行

git mergetool -t meld

它将打开本地版本(我们的)、“基础”或“合并”版本(当前结果)合并)和远程版本(他们的)。 完成后保存合并的版本,再次运行 git mergetool -t meld 直到出现“没有文件需要合并”,然后转到步骤 3 和 4。

I either want my or their version in full, or want to review individual changes and decide for each of them.

Fully accept my or theirs version:

Accept my version (local, ours):

git checkout --ours -- <filename>
git add <filename>              # Marks conflict as resolved
git commit -m "merged bla bla"  # An "empty" commit

Accept their version (remote, theirs):

git checkout --theirs -- <filename>
git add <filename>
git commit -m "merged bla bla"

If you want to do for all conflict files run:

git merge --strategy-option ours

or

git merge --strategy-option theirs

Review all changes and accept them individually

  1. git mergetool
  2. Review changes and accept either version for each of them.
  3. git add <filename>
  4. git commit -m "merged bla bla"

Default mergetool works in command line. How to use a command line mergetool should be a separate question.

You can also install visual tool for this, e.g. meld and run

git mergetool -t meld

It will open local version (ours), "base" or "merged" version (the current result of the merge) and remote version (theirs). Save the merged version when you are finished, run git mergetool -t meld again until you get "No files need merging", then go to Steps 3. and 4.

吲‖鸣 2024-07-13 17:38:53

请参阅如何呈现冲突或者,在 Git 中,可以使用 git merge 文档来了解什么是合并冲突标记。

另外,如何解决冲突部分解释了如何解决冲突:

看到冲突后,您可以做两件事:

  • 决定不合并。 您需要的唯一清理是将索引文件重置为 HEAD 提交以反转 2. 并清理 2. 和 3. 所做的工作树更改; 可以使用 git merge --abort 来实现此目的。

  • 解决冲突。 Git 会在工作树中标记冲突。 将文件编辑为 shape 并将它们 git add 到索引中。 使用 git commit 来达成交易。

您可以使用多种工具解决冲突:

  • 使用合并工具。 git mergetool 启动图形合并工具,它将帮助您完成合并。

  • 查看差异。 git diff 将显示三向差异,突出显示 HEADMERGE_HEAD 版本的更改。

  • 查看每个分支的差异。 git log --merge -p 将首先显示 HEAD 版本的差异,然后显示 MERGE_HEAD 版本的差异。

  • 看原著。 git show :1:filename 显示共同祖先,git show :2:filename 显示 HEAD 版本,git show : 3:filename 显示MERGE_HEAD 版本。

您还可以在 Pro Git 书籍部分 基本合并冲突

See How Conflicts Are Presented or, in Git, the git merge documentation to understand what merge conflict markers are.

Also, the How to Resolve Conflicts section explains how to resolve the conflicts:

After seeing a conflict, you can do two things:

  • Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git merge --abort can be used for this.

  • Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.

You can work through the conflict with a number of tools:

  • Use a mergetool. git mergetool to launch a graphical mergetool which will work you through the merge.

  • Look at the diffs. git diff will show a three-way diff, highlighting changes from both the HEAD and MERGE_HEAD versions.

  • Look at the diffs from each branch. git log --merge -p <path> will show diffs first for the HEAD version and then the MERGE_HEAD version.

  • Look at the originals. git show :1:filename shows the common ancestor, git show :2:filename shows the HEAD version, and git show :3:filename shows the MERGE_HEAD version.

You can also read about merge conflict markers and how to resolve them in the Pro Git book section Basic Merge Conflicts.

夢归不見 2024-07-13 17:38:53

对于想要半手动解决合并冲突的 Emacs 用户:

git diff --name-status --diff-filter=U

显示所有需要解决冲突的文件。

通过以下方式逐一打开每个文件,或一次全部打开:

emacs $(git diff --name-only --diff-filter=U)

当访问需要在 Emacs 中编辑的缓冲区时,键入

ALT+x vc-resolve-conflicts

这将打开三个缓冲区(我的、他们的和输出缓冲区)。 按“n”(下一个区域)、“p”(预览区域)进行导航。 按“a”和“b”分别将我的或他们的区域复制到输出缓冲区。 和/或直接编辑输出缓冲区。

完成后:按“q”。 Emacs 询问您是否要保存此缓冲区:是。
完成缓冲区后,通过从终端运行将其标记为已解决:

git add FILENAME

完成所有缓冲区后,键入

git commit

以完成合并。

For Emacs users which want to resolve merge conflicts semi-manually:

git diff --name-status --diff-filter=U

shows all files which require conflict resolution.

Open each of those files one by one, or all at once by:

emacs $(git diff --name-only --diff-filter=U)

When visiting a buffer requiring edits in Emacs, type

ALT+x vc-resolve-conflicts

This will open three buffers (mine, theirs, and the output buffer). Navigate by pressing 'n' (next region), 'p' (prevision region). Press 'a' and 'b' to copy mine or theirs region to the output buffer, respectively. And/or edit the output buffer directly.

When finished: Press 'q'. Emacs asks you if you want to save this buffer: yes.
After finishing a buffer mark it as resolved by running from the teriminal:

git add FILENAME

When finished with all buffers type

git commit

to finish the merge.

甜中书 2024-07-13 17:38:53

奖励:

在前面的答案中谈到拉/取/合并时,我想分享一个有趣且富有成效的技巧,

git pull --rebase

上面的命令是我的 Git 生活中最有用的命令,节省了大量时间。

在将新提交的更改推送到远程服务器之前,请尝试使用 git pull --rebase 而不是 git pull 和手动 merge,它将自动同步最新版本远程服务器更改(使用 fetch + merge)并将本地最新提交放在 Git 日志的顶部。 无需担心手动拉取/合并。

如果发生冲突,只需使用

git mergetool
git add conflict_file
git rebase --continue

查找详细信息:“git pull –rebase”是什么做什么?

Bonus:

In speaking of pull/fetch/merge in the previous answers, I would like to share an interesting and productive trick,

git pull --rebase

This above command is the most useful command in my Git life which saved a lot of time.

Before pushing your newly committed change to remote server, try git pull --rebase rather git pull and manual merge and it will automatically sync the latest remote server changes (with a fetch + merge) and will put your local latest commit at the top in the Git log. No need to worry about manual pull/merge.

In case of a conflict, just use

git mergetool
git add conflict_file
git rebase --continue

Find details at: What does “git pull –rebase” do?

任性一次 2024-07-13 17:38:53

简而言之,如果您很清楚其中一个存储库中的更改并不重要,并且希望解决有利于另一个存储库的所有更改,请使用:

git checkout . --ours

解决有利于您的存储库的更改,或者

git checkout . --theirs

解决有利于其他或主存储库的更改。

否则,您将不得不使用 GUI 合并工具逐个浏览文件,假设合并工具是 p4merge,或者写下您已经安装的任何人的名字

git mergetool -t p4merge

,完成文件后,您必须保存并关闭,以便下一个将打开。

Simply, if you know well that changes in one of the repositories is not important, and want to resolve all changes in favor of the other one, use:

git checkout . --ours

to resolve changes in the favor of your repository, or

git checkout . --theirs

to resolve changes in favor of the other or the main repository.

Or else you will have to use a GUI merge tool to step through files one by one, say the merge tool is p4merge, or write any one's name you've already installed

git mergetool -t p4merge

and after finishing a file, you will have to save and close, so the next one will open.

ゝ偶尔ゞ 2024-07-13 17:38:53

共有三个步骤:

  1. 通过命令查找哪些文件引起冲突

     git 状态 
      
  2. 检查文件,在其中您会发现冲突标记为

    <前><代码> <<<<<<<

  3. 将其更改为您想要的方式,然后使用命令提交

     git addsolved_conflicts_files 
       git commit -m '合并消息' 
      

There are three steps:

  1. Find which files cause conflicts by the command

     git status
    
  2. Check the files, in which you would find the conflicts marked like

     <<<<<<<<head
     blablabla
    
  3. Change it to the way you want it, and then commit with the commands

     git add solved_conflicts_files
     git commit -m 'merge msg'
    
绅刃 2024-07-13 17:38:53

请按照以下步骤修复 Git 中的合并冲突:

  1. 检查 Git 状态:
    git status

  2. 获取补丁集:
    git fetch(从 Git 提交中签出正确的补丁)

  3. 签出本地分支(在我的示例中为 temp1):
    git checkout -b temp1

  4. 从 master 中提取最近的内容:
    git pull --rebase origin master

  5. 启动 mergetool 并检查冲突并修复它们...并检查远程分支与当前分支的更改:
    git mergetool

  6. 再次检查状态:
    git status

  7. 删除mergetool本地创建的不需要的文件,通常mergetool会创建带有*.orig扩展名的额外文件。 请删除该文件,因为这只是重复的文件,并在本地修复更改并添加文件的正确版本。
    git add #your_changed_ Correct_files

  8. 再次检查状态:
    git status

  9. 将更改提交到同一提交 ID(这避免了新的单独补丁集):
    git commit --amend

  10. 推送到主分支:
    git push(到您的 Git 存储库)

Please follow the following steps to fix merge conflicts in Git:

  1. Check the Git status:
    git status

  2. Get the patchset:
    git fetch (checkout the right patch from your Git commit)

  3. Checkout a local branch (temp1 in my example here):
    git checkout -b temp1

  4. Pull the recent contents from master:
    git pull --rebase origin master

  5. Start the mergetool and check the conflicts and fix them...and check the changes in the remote branch with your current branch:
    git mergetool

  6. Check the status again:
    git status

  7. Delete the unwanted files locally created by mergetool, usually mergetool creates extra file with *.orig extension. Please delete that file as that is just the duplicate and fix changes locally and add the correct version of your files.
    git add #your_changed_correct_files

  8. Check the status again:
    git status

  9. Commit the changes to the same commit id (this avoids a new separate patch set):
    git commit --amend

  10. Push to the master branch:
    git push (to your Git repository)

梦初启 2024-07-13 17:38:53

CoolAJ86 的回答几乎概括了一切。 如果您在同一段代码的两个分支中进行了更改,则必须进行手动合并。 在任何文本编辑器中打开冲突文件,您应该看到以下结构。

(Code not in Conflict)
>>>>>>>>>>>
(first alternative for conflict starts here)
Multiple code lines here
===========
(second alternative for conflict starts here)
Multiple code lines here too    
<<<<<<<<<<<
(Code not in conflict here)

按照您希望新代码的方式选择其中一种替代方案或两者的组合,同时删除等号和尖括号。

git commit -a -m "commit message"
git push origin master

CoolAJ86's answer sums up pretty much everything. In case you have changes in both branches in the same piece of code you will have to do a manual merge. Open the file in conflict in any text editor and you should see following structure.

(Code not in Conflict)
>>>>>>>>>>>
(first alternative for conflict starts here)
Multiple code lines here
===========
(second alternative for conflict starts here)
Multiple code lines here too    
<<<<<<<<<<<
(Code not in conflict here)

Choose one of the alternatives or a combination of both in a way that you want new code to be, while removing equal signs and angle brackets.

git commit -a -m "commit message"
git push origin master
软糖 2024-07-13 17:38:53

您可以通过多种方式解决合并冲突,正如其他人详细介绍的那样。

我认为真正的关键是了解更改如何在本地和远程存储库中流动。 关键是理解跟踪分支。 我发现我认为跟踪分支是我的本地实际文件目录和定义为源的远程目录之间的“中间缺失的一块”。

我个人养成了两件事的习惯来帮助避免这种情况。

而不是:

git add .
git commit -m"some msg"

它有两个缺点 -

a) 所有新的/更改的文件都会被添加,并且可能包括一些不需要的更改。
b) 您不必先查看文件列表。

所以我这样做:

git add file,file2,file3...
git commit # Then type the files in the editor and save-quit.

这样您就可以更加仔细地考虑添加哪些文件,并且您还可以在使用消息编辑器时查看列表并进行更多思考。 我发现当我使用全屏编辑器而不是 -m 选项时,它还改进了我的提交消息。

[更新 - 随着时间的推移,我已经切换到更多:

git status # Make sure I know whats going on
git add .
git commit # Then use the editor

]

另外(并且与您的情况更相关),我尝试避免:

git pull

或者

git pull origin master.

因为拉意味着合并,如果您在本地进行了更改,则您不想合并您很容易导致合并代码和/或不应该合并的代码的合并冲突。

相反,我尝试这样做,

git checkout master
git fetch   
git rebase --hard origin/master # or whatever branch I want.

您可能还会发现这很有帮助:

git分支、fork、fetch、merge、rebase和clone,有什么区别?

You could fix merge conflicts in a number of ways as other have detailed.

I think the real key is knowing how changes flow with local and remote repositories. The key to this is understanding tracking branches. I have found that I think of the tracking branch as the 'missing piece in the middle' between me my local, actual files directory and the remote defined as origin.

I've personally got into the habit of 2 things to help avoid this.

Instead of:

git add .
git commit -m"some msg"

Which has two drawbacks -

a) All new/changed files get added and that might include some unwanted changes.
b) You don't get to review the file list first.

So instead I do:

git add file,file2,file3...
git commit # Then type the files in the editor and save-quit.

This way you are more deliberate about which files get added and you also get to review the list and think a bit more while using the editor for the message. I find it also improves my commit messages when I use a full screen editor rather than the -m option.

[Update - as time has passed I've switched more to:

git status # Make sure I know whats going on
git add .
git commit # Then use the editor

]

Also (and more relevant to your situation), I try to avoid:

git pull

or

git pull origin master.

because pull implies a merge and if you have changes locally that you didn't want merged you can easily end up with merged code and/or merge conflicts for code that shouldn't have been merged.

Instead I try to do

git checkout master
git fetch   
git rebase --hard origin/master # or whatever branch I want.

You may also find this helpful:

git branch, fork, fetch, merge, rebase and clone, what are the differences?

一张白纸 2024-07-13 17:38:53

如果您想从分支test合并到master,可以按照以下步骤操作:

第1步:转到分支

git checkout test

第2步

git pull --rebase origin master

第3步:如果有冲突,请到这些文件中进行修改。

步骤 4:添加这些更改

git add #your_changes_files

步骤 5

git rebase --continue

步骤 6:如果仍然存在冲突,请再次返回步骤 3。 如果没有冲突,则执行以下操作:

git push origin +test

第7步:这样test和master之间就没有冲突了。 可以直接使用合并。

If you want to merge from branch test to master, you can follow these steps:

Step 1: Go to the branch

git checkout test

Step 2:

git pull --rebase origin master

Step 3: If there are some conflicts, go to these files to modify it.

Step 4: Add these changes

git add #your_changes_files

Step 5:

git rebase --continue

Step 6: If there is still conflict, go back to step 3 again. If there is no conflict, do following:

git push origin +test

Step 7: And then there is no conflict between test and master. You can use merge directly.

看轻我的陪伴 2024-07-13 17:38:53

使用 patience

对于大的合并冲突,使用 patience 为我提供了良好的结果。 它将尝试匹配块而不是单独的行。

例如,如果您更改程序的缩进,默认的 Git 合并策略有时会匹配属于不同函数的单大括号 { 。 通过耐心可以避免这种情况:

git merge -s recursive -X patience other-branch

来自文档:

With this option, merge-recursive spends a little extra time to avoid 
mismerges that sometimes occur due to unimportant matching lines 
(e.g., braces from distinct functions). Use this when the branches to 
be merged have diverged wildly.

与共同祖先的比较

如果您遇到合并冲突并且想了解其他人在修改其分支时的想法,有时直接比较他们的分支会更容易与共同的祖先(而不是我们的分支)。 为此,您可以使用 merge-base

git diff $(git merge-base <our-branch> <their-branch>) <their-branch>

通常,您只想查看特定文件的更改:

git diff $(git merge-base <our-branch> <their-branch>) <their-branch> <file>

Using patience

For a big merge conflict, using patience provided good results for me. It will try to match blocks rather than individual lines.

If you change the indentation of your program for instance, the default Git merge strategy sometimes matches single braces { which belongs to different functions. This is avoided with patience:

git merge -s recursive -X patience other-branch

From the documentation:

With this option, merge-recursive spends a little extra time to avoid 
mismerges that sometimes occur due to unimportant matching lines 
(e.g., braces from distinct functions). Use this when the branches to 
be merged have diverged wildly.

Comparison with the common ancestor

If you have a merge conflict and want to see what others had in mind when modifying their branch, it's sometimes easier to compare their branch directly with the common ancestor (instead of our branch). For that you can use merge-base:

git diff $(git merge-base <our-branch> <their-branch>) <their-branch>

Usually, you only want to see the changes for a particular file:

git diff $(git merge-base <our-branch> <their-branch>) <their-branch> <file>
花开浅夏 2024-07-13 17:38:53
git log --merge -p [[--] path]

似乎并不总是对我有用,通常最终会显示两个分支之间不同的每个提交,即使使用 -- 将路径与命令分开时也会发生这种情况。

我解决这个问题的方法是打开两个命令行,在一次运行中

git log ..$MERGED_IN_BRANCH --pretty=full -p [path]

,在另一次

git log $MERGED_IN_BRANCH.. --pretty=full -p [path]

运行中将 $MERGED_IN_BRANCH 替换为我合并的分支,将 [path] 替换为存在冲突的文件。 此命令将以补丁形式记录 (..) 两次提交之间的所有提交。 如果您像上面的命令一样将一侧留空,git 将自动使用 HEAD (在本例中您要合并到的分支)。

这将允许您查看两个分支分叉后哪些提交进入了文件。 它通常使解决冲突变得更加容易。

git log --merge -p [[--] path]

Does not seem to always work for me and usually ends up displaying every commit that was different between the two branches, this happens even when using -- to separate the path from the command.

What I do to work around this issue is open up two command lines and in one run

git log ..$MERGED_IN_BRANCH --pretty=full -p [path]

and in the other

git log $MERGED_IN_BRANCH.. --pretty=full -p [path]

Replacing $MERGED_IN_BRANCH with the branch I merged in and [path] with the file that is conflicting. This command will log all the commits, in patch form, between (..) two commits. If you leave one side empty like in the commands above git will automatically use HEAD (the branch you are merging into in this case).

This will allow you to see what commits went into the file in the two branches after they diverged. It usually makes it much easier to solve conflicts.

我不咬妳我踢妳 2024-07-13 17:38:53

自 2016 年 12 月 12 日起,您可以合并分支并解决 github.com 上的冲突

因此,如果您不想使用此处提供的命令行或任何第三方工具从旧的答案,使用 GitHub 的本机工具。

这篇博文详细解释了,但基础知识是通过用户界面“合并”两个分支后,您现在将看到一个“解决冲突”选项,该选项将带您进入编辑器,允许您处理这些合并冲突。

输入图像描述这里

As of December 12th 2016, you can merge branches and resolve conflicts on github.com

Thus, if you don't want to use the command-line or any 3rd party tools that are offered here from older answers, go with GitHub's native tool.

This blog post explains in detail, but the basics are that upon 'merging' two branches via the UI, you will now see a 'resolve conflicts' option that will take you to an editor allowing you to deal with these merge conflicts.

enter image description here

黑凤梨 2024-07-13 17:38:53

合并冲突可能在不同情况下发生:

  • 当运行 git fetch 然后运行 ​​git merge
  • 当运行 git fetch 然后运行 ​​git rebase
  • 当运行 git pull 时(实际上等于上述条件之一)
  • 当运行 git stash pop
  • 当你应用 git 补丁时(提交是导出到要传输的文件,例如通过电子邮件)

您需要安装与Git兼容的合并工具来解决冲突。 我个人使用 KDiff3,我发现它很好而且很方便。 您可以在此处下载其 Windows 版本:

https://sourceforge.net/projects/kdiff3/files/< /a>

顺便说一句,如果您安装了 Git Extensions,其安装向导中会有一个选项来安装 Kdiff3。

然后设置 Git 配置以使用 KDiff3 作为其合并工具:(

$ git config --global --add merge.tool kdiff3
$ git config --global --add mergetool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add mergetool.kdiff3.trustExitCode false

$ git config --global --add diff.guitool kdiff3
$ git config --global --add difftool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add difftool.kdiff3.trustExitCode false

记住将路径替换为 KDiff3 EXE 文件的实际路径。)

然后每次遇到合并冲突时,只需运行此命令:

$ git mergetool

然后它会打开Kdiff3,首先尝试自动解决合并冲突。 大多数冲突会自发解决,其余冲突需要您手动解决。

Kdiff3 如下所示:

在此处输入图像描述

完成后,保存文件,它将转到下一个有冲突的文件,然后再次执行相同的操作,直到解决所有冲突。

要检查所有内容是否合并成功,只需再次运行 mergetool 命令即可。 你应该得到这个结果:

$ git mergetool
No files need merging

Merge conflicts could occur in different situations:

  • When running git fetch and then git merge
  • When running git fetch and then git rebase
  • When running git pull (which is actually equal to one of the above-mentioned conditions)
  • When running git stash pop
  • When you're applying git patches (commits that are exported to files to be transferred, for example, by email)

You need to install a merge tool which is compatible with Git to resolve the conflicts. I personally use KDiff3, and I've found it nice and handy. You can download its Windows version here:

https://sourceforge.net/projects/kdiff3/files/

BTW, if you install Git Extensions there is an option in its setup wizard to install Kdiff3.

Then setup the Git configuration to use KDiff3 as its mergetool:

$ git config --global --add merge.tool kdiff3
$ git config --global --add mergetool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add mergetool.kdiff3.trustExitCode false

$ git config --global --add diff.guitool kdiff3
$ git config --global --add difftool.kdiff3.path "C:/Program Files/KDiff3/kdiff3.exe"
$ git config --global --add difftool.kdiff3.trustExitCode false

(Remember to replace the path with the actual path of the KDiff3 EXE file.)

Then every time you come across a merge conflict, you just need to run this command:

$ git mergetool

Then it opens Kdiff3, and first tries to resolve the merge conflicts automatically. Most of the conflicts would be resolved spontaneously and you need to fix the rest manually.

Here's what Kdiff3 looks like:

Enter image description here

Then once you're done, save the file and it goes to the next file with a conflict and you do the same thing again until all the conflicts are resolved.

To check if everything is merged successfully, just run the mergetool command again. You should get this result:

$ git mergetool
No files need merging
温柔女人霸气范 2024-07-13 17:38:53

我始终遵循以下步骤以避免冲突。

  • git checkout master (来到master分支)
  • git pull (更新你的master以获取最新代码)
  • git checkout -b mybranch (检查建立一个新的分支并开始在该分支上工作,以便您的 master 始终保持在主干的顶部。)
  • git add . git commit < em>和 git Push(更改后在本地分支上)
  • git checkout master(回到你的 master 那里)

现在你可以做同样的事情并维护只要有必要,只需对您的分支执行 git checkout 即可同时工作任意数量的本地分支。

I always follow the below steps to avoid conflicts.

  • git checkout master (Come to the master branch)
  • git pull (Update your master to get the latest code)
  • git checkout -b mybranch (Check out a new a branch and start working on that branch so that your master always remains top of trunk.)
  • git add . and git commit and git push (on your local branch after your changes)
  • git checkout master (Come back to your master)

Now you can do the same and maintain as many local branches you want and work simultaneous by just doing a git checkout to your branch whenever necessary.

只有影子陪我不离不弃 2024-07-13 17:38:53

我明白什么是合并冲突,但是当我看到 git diff 的输出时,一开始对我来说这看起来像是无稽之谈:

git diff
++<<<<<<< HEAD
 + display full last name boolean in star table
++=======
+ users viewer.id/star.id, and conversation uses user.id
+
++>>>>>>> feat/rspec-tests-for-cancancan

但是 这里对我有帮助:

  • <<<<<<<<<<之间的所有内容;======= 是一个文件中的内容,并且

  • =======>>>>>>> 之间的所有内容都是在另一个文件中

  • 因此,实际上您所要做的就是打开存在合并冲突的文件,并从任一分支中删除这些行(或者只是使它们相同),并且合并将立即成功。 问题解决了!

I understood what a merge conflict was, but when I saw the output of git diff, it looked like nonsense to me at first:

git diff
++<<<<<<< HEAD
 + display full last name boolean in star table
++=======
+ users viewer.id/star.id, and conversation uses user.id
+
++>>>>>>> feat/rspec-tests-for-cancancan

But here is what helped me:

  • Everything between <<<<<<< and ======= is what was in one file, and

  • Everything between ======= and >>>>>>> is what was in the other file

  • So literally all you have to do is open the file with the merge conflicts and remove those lines from either branch (or just make them the same), and the merge will immediately succeed. Problem solved!

天邊彩虹 2024-07-13 17:38:53

适用于 Visual Studio Code 的 GitLens

您可以尝试适用于 Visual Studio Code 的 GitLens。 主要功能是:

1. 轻松解决冲突

我已经喜欢这个功能了:

在此处输入图像描述

2. 当前行责怪。

输入图片此处描述

3. 装订线责备

在此处输入图像描述

4. 状态栏责怪

在此处输入图像描述

还有很多功能。 您可以在此处查看它们。

GitLens for Visual Studio Code

You can try GitLens for Visual Studio Code. The key features are:

1. Easily resolve conflicts

I already like this feature:

Enter image description here

2. Current Line Blame.

Enter image description here

3. Gutter Blame

Enter image description here

4. Status Bar Blame

Enter image description here

And there are many features. You can check them here.

痴情 2024-07-13 17:38:53

这个答案是为像我这样喜欢在编辑器中完成所有操作的 Vim 用户添加一个替代方案。


TL;DR

在此处输入图像描述


Tpope 为 Vim 想出了这个很棒的插件,名为 逃犯。 安装后,您可以运行 :Gstatus 来检查有冲突的文件,并运行 :Gdiff 以三向合并方式打开 Git。

一旦进入三向合并,fugitive将让您以以下方式获取正在合并的任何分支的更改:

  • :diffget //2,获取更改从原始 (HEAD) 分支:
  • :diffget //3,从合并分支获取更改:

完成合并文件后,输入 :Gwrite 在合并缓冲区中。

Vimcasts 发布了一个很棒的视频,解释了这些步骤细节。

This answer is to add an alternative for those Vim users like me that prefers to do everything within the editor.


TL;DR

Enter image description here


Tpope came up with this great plugin for Vim called fugitive. Once installed, you can run :Gstatus to check the files that have conflict and :Gdiff to open Git in a three-way merge.

Once in the three-way merge, fugitive will let you get the changes of any of the branches you are merging in the following fashion:

  • :diffget //2, get changes from original (HEAD) branch:
  • :diffget //3, get changes from merging branch:

Once you are finished merging the file, type :Gwrite in the merged buffer.

Vimcasts released a great video explaining these steps in detail.

北音执念 2024-07-13 17:38:53

我正在使用 Microsoft 的 Visual Studio Code 来解决冲突。 使用起来非常简单。 我让我的项目在工作区中保持打开状态。 它检测并突出显示冲突。 此外,它提供了 GUI 选项来选择我想要从 HEAD 或传入中保留的任何更改。

输入图片此处描述

I am using Microsoft's Visual Studio Code for resolving conflicts. It's very simple to use. I keep my project open in the workspace. It detects and highlights conflicts. Moreover, it gives GUI options to select whatever change I want to keep from HEAD or incoming.

Enter image description here

谁与争疯 2024-07-13 17:38:53
git fetch <br>
git checkout **your branch**<br>
git rebase master<br>

在此步骤中,您将尝试使用您首选的 IDE 修复冲突。

您可以点击此链接检查如何修复文件中的冲突。

git add<br>
git rebase --continue<br>
git commit --amend<br>
git push origin HEAD:refs/drafts/master  (push like a drafts)<br>

现在一切都很好,您将在 Gerrit 中找到您的提交。

git fetch <br>
git checkout **your branch**<br>
git rebase master<br>

In this step you will try to fix the conflict using your preferred IDE.

You can follow this link to check how to fix the conflict in the file.

git add<br>
git rebase --continue<br>
git commit --amend<br>
git push origin HEAD:refs/drafts/master  (push like a drafts)<br>

Now everything is fine and you will find your commit in Gerrit.

梦途 2024-07-13 17:38:53

如果您使用 IntelliJ IDEA 作为 IDE,请尝试通过以下方式将父级合并到您的分支:

git checkout <localbranch>
git merge origin/<remotebranch>

它将显示所有冲突,如下所示:

A_MBPro:测试 anu$ git merge origin/自动合并
src/test/java/com/.../TestClass.java 冲突
(内容):合并冲突
src/test/java/com/.../TestClass.java

现在请注意,文件 TestClass.java 在 IntelliJ IDEA 中显示为红色。

此外,git status 将显示:

Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified:   src/test/java/com/.../TestClass.java

在 IntelliJ IDEA 中打开文件。 它将包含一些部分,

  <<<<<<< HEAD
    public void testMethod() {
    }
    =======
    public void testMethod() { ...
    }
    >>>>>>> origin/<remotebranch>

其中 HEAD 在本地分支和 origin/ 上发生更改。 是来自远程分支的更改。 这里保留你需要的东西,删除你不需要的东西。 之后,应该执行正常步骤。 那是

   git add TestClass.java
   git commit -m "commit message"
   git push

If you are using IntelliJ IDEA as the IDE, try to merge the parent to your branch by:

git checkout <localbranch>
git merge origin/<remotebranch>

It will show all conflicts like this:

A_MBPro:test anu$ git merge origin/ Auto-merging
src/test/java/com/.../TestClass.java CONFLICT
(content): Merge conflict in
src/test/java/com/.../TestClass.java

Now note that the file TestClass.java is shown in red in IntelliJ IDEA.

Also git status will show:

Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified:   src/test/java/com/.../TestClass.java

Open the file in IntelliJ IDEA. It will have sections with

  <<<<<<< HEAD
    public void testMethod() {
    }
    =======
    public void testMethod() { ...
    }
    >>>>>>> origin/<remotebranch>

where HEAD is changes on your local branch and origin/<remotebranch> is changes from the remote branch. Here keep the stuff that you need and remove the stuff you don't need. After that, the normal steps should do. That is

   git add TestClass.java
   git commit -m "commit message"
   git push
放血 2024-07-13 17:38:53

如果您还没有尝试过使用 Visual Studio Code 进行编辑。

尝试合并(并陷入合并冲突)后,Visual Studio Code 会自动检测合并冲突。

它可以通过显示对原始更改所做的更改以及您是否应该接受传入

当前更改(指合并之前的原始更改)来为您提供帮助。

它对我有帮助,也对你有用!

PS:仅当您使用代码和 Visual Studio Code 配置了 Git 时,它才有效。

Try Visual Studio Code for editing if you aren't already.

After you try merging (and land up in merge conflicts), Visual Studio Code automatically detects the merge conflicts.

It can help you very well by showing the changes made to the original one and if you should accept incoming or

current change (meaning original one before merging)'.

It helped me and it can work for you too!

PS: It will work only if you've configured Git with with your code and Visual Studio Code.

夜深人未静 2024-07-13 17:38:53

解决冲突的更安全方法是使用 git-mediate (这里建议的常见解决方案相当恕我直言,容易出错)。

请参阅这篇文章 快速介绍如何使用它。

A safer way to resolve conflicts is to use git-mediate (the common solutions suggested here are quite error prone imho).

See this post for a quick intro on how to use it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文