我有2个git分支:

branch1 branch2

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

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

最好的方法是什么?


当前回答

为了只合并来自branch2的file.py的更改,让其他更改消失。

git checkout -B wip branch2
git read-tree branch1
git checkout branch2 file.py
git commit -m'merging only file.py history from branch2 into branch1'
git checkout branch1
git merge wip

Merge甚至不会查看任何其他文件。如果树的差异足够大,您可能需要'-f'签出。

注意,这将使branch1看起来好像branch2历史中的所有内容都已合并,这可能不是您想要的。上面第一次签出的一个更好的版本可能是

git checkout -B wip `git merge-base branch1 branch2`

在这种情况下,提交消息也应该是

git commit -m"merging only $(git rev-parse branch2):file.py into branch1"

其他回答

我发现一些答案是有用的,但令人困惑,所以避免任何困惑的未来。我只是想帮助那些有同样困惑的人。

我不会使用branch1和branch2的名称,而是master(活动代码)和hotfix/abc(从master提取)和一个测试分支。

现在,我想将一些特定的文件从测试合并到hotfix/abc,因为不建议从测试或登台分支直接在master上合并。要做到这一点,我将做以下工作:

git checkout hotfix/abc git checkout --merge testing path/to/file1.php path/to/file2.js git add . git commit -m "Fixed specific issue" git push Now go to repo and make a pull request for hotfix/abc to master branch. If you don't know how to do that here I've a small tutorial on that. And if you generally want to learn how these branches and git work, I'd recommend you to watch this <= twenty minutes playlist. Now review your pull request with master and merge it. In case you see any conflicts, it's time to merge master into hotfix/abc. And resolve conflicts over there. And then again repeat step 3-5 followed by 7.

我还从参考教程中得到了帮助。

如果有用的话,竖起大拇指。快乐编码:)

我在同样的情况下,我想合并一个文件从一个分支上有许多提交它在2个分支。我尝试了上面提到的很多方法和我在网上找到的其他方法,都失败了(因为提交历史很复杂),所以我决定用我的方式(疯狂的方式)。

git merge <other-branch>
cp file-to-merge file-to-merge.example
git reset --hard HEAD (or HEAD^1 if no conflicts happen)
cp file-to-merge.example file-to-merge

对branch2中的file.py的所有修改是否都在各自的提交中,与对其他文件的修改分开?如果是这样,你可以简单地选择更改:

git checkout branch1
git cherry-pick <commit-with-changes-to-file.py>

否则,merge不会在单独的路径上操作…你也可以从branch2中创建一个file.py更改的git diff补丁,然后git将它们应用到branch1:

git checkout branch2
git diff <base-commit-before-changes-to-file.py> -- file.py > my.patch
git checkout branch1
git apply my.patch

如果您只关心解决冲突,而不关心保存提交历史记录,那么下面的方法应该是有效的。假设你想把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,可以更轻松地解决冲突。

Matthew Turner的解决方案是最简单的,但是如果branch1和file有相同的名字就会给出一个错误。在这种情况下,将第二行替换为

Git checkout branch2——file.py