我有2个git分支:
branch1 branch2
我想合并所有的历史(多次提交)的文件。py在branch2到文件。py在branch1,只有该文件。
实际上,我只是想在branch1中的file.py上工作,但想利用merge命令。
最好的方法是什么?
我有2个git分支:
branch1 branch2
我想合并所有的历史(多次提交)的文件。py在branch2到文件。py在branch1,只有该文件。
实际上,我只是想在branch1中的file.py上工作,但想利用merge命令。
最好的方法是什么?
当前回答
我所做的有点手动,但我:
正常合并分支;使用revert恢复合并; 检出我所有的文件到HEAD~1,即它们的状态在 合并提交; 重设我的提交隐藏这个黑客从 提交历史。
丑吗?是的。容易记住吗?也没错。
其他回答
当来自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命令特别有用。
为了只合并来自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"
最简单的解决方案是:
Git签出源分支的名称和我们想要添加到当前分支的特定文件的路径
git checkout sourceBranchName pathToFile
我发现的最不让我头疼的方法是:
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完全合并后的文件。
虽然不是合并本身,但有时需要另一个分支上另一个文件的全部内容。Jason Rudolph的博客文章提供了一种将文件从一个分支复制到另一个分支的简单方法。应用如下技巧:
$ git checkout branch1 # ensure in branch1 is checked out and active
$ git checkout branch2 file.py
现在file.py在branch1中。