我有2个git分支:

branch1 branch2

我想合并所有的历史(多次提交)的文件。py在branch2到文件。py在branch1,只有该文件。

实际上,我只是想在branch1中的file.py上工作,但想利用merge命令。

最好的方法是什么?


当前回答

我发现的最不让我头疼的方法是:

git checkout <b1>
git checkout -b dummy
git merge <b2>
git checkout <b1>
git checkout dummy <path to file>
git branch -D dummy

这样做之后,b2中文件路径下的文件就是与b1完全合并后的文件。

其他回答

我所做的有点手动,但我:

正常合并分支;使用revert恢复合并; 检出我所有的文件到HEAD~1,即它们的状态在 合并提交; 重设我的提交隐藏这个黑客从 提交历史。

丑吗?是的。容易记住吗?也没错。

你可以隐藏和隐藏弹出文件:

git checkout branch1
git checkout branch2 file.py
git stash
git checkout branch1
git stash pop

最简单的解决方案是:

Git签出源分支的名称和我们想要添加到当前分支的特定文件的路径

git checkout sourceBranchName pathToFile

其他当前答案实际上都不会“合并”文件,就像您使用merge命令一样。(在最好的情况下,他们会要求你手动选择差异。)如果你真的想利用来自公共祖先的信息进行合并,你可以遵循一个基于git参考手册“高级合并”部分的过程。

对于这个协议,我假设你想要将文件“path/to/file.txt”从origin/master合并到HEAD - modify中。(你不必在你的存储库的顶部目录,但这是有帮助的。)

# Find the merge base SHA1 (the common ancestor) for the two commits:
git merge-base HEAD origin/master

# Get the contents of the files at each stage
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show HEAD:path/to/file.txt > ./file.ours.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt

# You can pre-edit any of the files (e.g. run a formatter on it), if you want.

# Merge the files
git merge-file -p ./file.ours.txt ./file.common.txt ./file.theirs.txt > ./file.merged.txt

# Resolve merge conflicts in ./file.merged.txt
# Copy the merged version to the destination
# Clean up the intermediate files

Git的合并文件应该使用所有默认的合并设置来格式化等等。

还要注意,如果你的“ours”是工作副本版本,你不想过于谨慎,你可以直接对文件进行操作:

git merge-base HEAD origin/master
git show <merge-base SHA1>:path/to/file.txt > ./file.common.txt
git show origin/master:path/to/file.txt > ./file.theirs.txt
git merge-file path/to/file.txt ./file.common.txt ./file.theirs.txt

如果您只关心解决冲突,而不关心保存提交历史记录,那么下面的方法应该是有效的。假设你想把a.py b.py从BRANCHA合并到BRANCHB。首先,确保BRANCHB中的任何更改都已提交或隐藏,并且没有未跟踪的文件。然后:

git checkout BRANCHB
git merge BRANCHA
# 'Accept' all changes
git add .
# Clear staging area
git reset HEAD -- .
# Stash only the files you want to keep
git stash push a.py b.py
# Remove all other changes
git add .
git reset --hard
# Now, pull the changes
git stash pop

Git不会识别a.py b.py中存在冲突,但如果确实存在冲突,则会出现合并冲突标记。使用第三方合并工具,如VSCode,可以更轻松地解决冲突。