如果我想将仅对特定提交中更改的部分文件(包括对多个文件的更改)进行的更改合并到Git分支中,如何实现这一点?

假设名为stuff的Git提交对文件A、B、C和D进行了更改,但我只想将stuff的更改合并到文件A和B。这听起来像Git cherry-pick的工作,但cherry pick只知道如何合并整个提交,而不是文件的子集。


当前回答

我通常将-p标志与来自其他分支的git签出一起使用,我发现这比我遇到的大多数其他方法更容易和更精细。

原则上:

git checkout <other_branch_name> <files/to/grab in/list/separated/by/spaces> -p

例子:

git checkout mybranch config/important.yml app/models/important.rb -p

然后,您会看到一个对话框,询问您希望在“blobs”中进行哪些更改,这基本上适用于连续代码更改的每个块,然后您可以为每个代码块发出y(是)n(否)等信号。

-p或patch选项适用于git中的各种命令,包括git stash save-p,它允许您从当前工作中选择要隐藏的内容

当我做了很多工作,并希望将其分离出来,使用gitadd-p提交更多基于主题的提交,并选择每次提交所需的内容时,我有时会使用此技术:)

其他回答

将分支合并为新分支(挤压)并删除不需要的文件:

git checkout master
git checkout -b <branch>
git merge --squash <source-branch-with-many-commits>
git reset HEAD <not-needed-file-1>
git checkout -- <not-needed-file-1>
git reset HEAD <not-needed-file-2>
git checkout -- <not-needed-file-2>
git commit

我会使用cherry-pick-n(--no-commit)来完成,它允许您在提交之前检查(和修改)结果:

git cherry-pick -n <commit>

# unstage modifications you don't want to keep, and remove the
# modifications from the work tree as well.
# this does work recursively!
git checkout HEAD <path>

# commit; the message will have been stored for you by cherry-pick
git commit

如果绝大多数修改都是您不想要的,那么您可以重新设置所有内容,然后添加您想要的内容,而不是检查各个路径(中间步骤):

# unstage everything
git reset HEAD

# stage the modifications you do want
git add <path>

# make the work tree match the index
# (do this from the top level of the repo)
git checkout .

有时,使用签出从提交中获取特定文件可能更容易。在我看来,它给了你更多的控制权,而且在樱桃采摘后不必检查和拆封。

我会这样做:

git checkout <branch|hash> -- path/to/file1 path/to/filen

然后,在提交之前,取消编写必要的更改以适应代码并对其进行测试。如果一切按预期进行,那么提交。

我会选择一切,然后这样做:

git reset --soft HEAD^

然后我会还原我不想要的更改,然后进行新的提交。

情况:

你在你的分支上,比如说,你在任何其他分支上都有你的承诺。您只能从该特定提交中选择一个文件。

方法:

步骤1:在所需的分支上签出。

git checkout master

步骤2:确保已复制所需的提交哈希。

git checkout commit_hash path\to\file

步骤3:您现在在所需的分支上对所需文件进行了更改。你只需要添加并提交它们。

git add path\to\file
git commit -m "Your commit message"