我有2个git分支:
branch1 branch2
我想合并所有的历史(多次提交)的文件。py在branch2到文件。py在branch1,只有该文件。
实际上,我只是想在branch1中的file.py上工作,但想利用merge命令。
最好的方法是什么?
我有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完全合并后的文件。
其他回答
当来自branch2的file.py中的内容不再适用于branch1时,它需要选择一些更改并保留其他更改。为了完全控制,使用——patch switch进行交互式合并:
$ git checkout --patch branch2 file.py
git-add(1)手册页中的交互模式部分解释了要使用的键:
y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk nor any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk nor any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
split命令特别有用。
如果git checkout——patch branch2 file.py将被接受,那么我应该分享我们还可以使用:
git difftool <branch> [-- <file>]
([]表示可选。)
如果配置为diff.tool,像meld这样的合并工具将允许您使用图形界面手动合并两个文件。
它的一个缺点是,如果某个文件不存在于某个分支中,则无法复制或删除该文件。在这种情况下,我们需要git checkout branch2——file.py。
Git difftool也不保存历史。
Matthew Turner的解决方案是最简单的,但是如果branch1和file有相同的名字就会给出一个错误。在这种情况下,将第二行替换为
Git checkout branch2——file.py
我在同样的情况下,我想合并一个文件从一个分支上有许多提交它在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