Git:仅从另一个分支添加文件的某些部分的最佳方法?
假设您有一个分支 master
和另一个分支 product
,两者都包含文件 prog.py
的一个版本,以及许多其他文件。想象一下,您修改了生产分支中的许多文件,包括 prog.py
。现在,将 生产
分支中的 prog.py
上的一些更改应用到 prog.py
中的版本的最佳方法是什么?代码>主分支?
我开始移动到 master
分支并从 product
分支导入文件:
git checkout master
git checkout production -- prog.py
因为我希望能够执行 git add -p
并手动选择更改。问题是 prog.py
既在工作树中又在索引中。如何在不接触工作树的情况下将其从索引中删除?
或者是否有更好的方法来选择 prog.py
中的哪些更改应从 生产
分支导入到 master
分支?
Let's say you have a branch master
and another branch production
, both containing a version of the file prog.py
, as well as many other files. Imagine that you modify many files in the production branch, including prog.py
. Now, what is the best way of having only some changes made on prog.py
in the production
branch be applied to its version in the master
branch?
I started moving to the master
branch and importing the file from the production
branch:
git checkout master
git checkout production -- prog.py
because I was hoping to be able to do git add -p
and select the changes by hand. The problem is that prog.py
is both in the working tree and in the index. How can I remove it from the index without touching the working tree?
Or is there a better way of choosing which changes in prog.py
should be imported from the production
branch into the master
branch?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定当这个问题被问到时这是否属实,但是使用当前版本的 git,您可以执行以下操作:
并且您将获得与大多数
-p命令。
I'm not sure if this was true when this question was asked, but with a current version of git you can do the following:
and you'll get the same interactive hunk-picker you do for most
-p
commands.进行只做一件事的小规模提交,然后使用 gitcherry-pick $commit_id 在另一个分支中挑选您也想要的更改似乎是一种合理的方法。
Making small and granular commits that only do one thing, and then later cherry-picking the changes you also want in the other branch using
git cherry-pick $commit_id
would seem like a reasonable approach.好吧,我刚刚尝试了 git reset,它确实删除了索引中存储的更改。 git add -p 然后按预期工作,允许选择应应用的单个更改(即存储在索引中)。然后可以使用 git commit 和 git reset --hard 来丢弃不需要的更改。
希望这个问题和这个答案会引起其他人的兴趣! :)
PS:我将此答案标记为已接受的答案,因为它确实按照原始问题中的要求检查了一个单个文件。
Alright, I just tried
git reset
, and it did remove the changes stored in the index.git add -p
then works as expected, allowing one to choose the individual changes that should be applied (i.e. stored in the index). The non-wanted changes can then be discarded withgit commit
, and thengit reset --hard
.Hopefully the question and this answer will be of interest to someone else! :)
PS: I marked this answer as the accepted one because it does check out a single file, as asked in the original question.