简体   繁体   English

Git合并仅更改来自特定提交的文件(而不是整个diff)

[英]Git Merge only changed files from a specific commit (not the entire diff)

So imagine an existing code base with files {A, B, C, D, E}. 因此,想象一下现有的代码库包含文件{A,B,C,D,E}。 I clone the repo, create a branch, and issue a series of changes 我克隆了仓库,创建了一个分支,并发布了一系列更改

Commit 1 changes files {A, B}
Commit 2 changes files {C, D}
Commit 3 changes files {D, E}

In this example, I need to merge to the parent the files that changed in commit 2, but without any of the changes in Commit 1. 在此示例中,我需要将提交2中更改的文件合并到父级,但提交1中没有任何更改。

It is my understanding that each commit contains snapshots of the entire code base, as illustrated here: 据我了解,每个提交都包含整个代码库的快照,如下所示: 在此处输入图片说明 source 资源

So commit 2 has the changes to files C and D, but it also has the changes to file A and B from commit 1, which should not be merged. 因此,提交2对文件C和D进行了更改,但也对提交1对文件A和B进行了更改,因此不应合并。

So, how would I merge up the versions of C and D from Commit 2, without changing the parent's version of A and B? 因此,如何合并提交2中的C和D版本,而不更改父级的A和B版本?

One way would be to create a new branch out of your branch which has all 3 commits. 一种方法是从分支中创建一个具有所有3个提交的新分支。 Use git rebase to drop unwanted commits. 使用git rebase删除不需要的提交。 Then checkout to parent branch and the use git merge new branch name 然后签出到父分支,并使用git merge新的分支名称

This is what git cherry-pick is for. 这就是git cherry-pick目的。

As I understand it, you want a new branch with only commit 2 on top of master , starting from this state: 据我了解,您想要一个新分支,仅在master之上提交commit 2,从这种状态开始:

o 8021  commit 3 that changes D and E  [feature-branch (HEAD)]
|
o bb6e  commit 2 that changes C and D
|
o f8a2  commit 1 that changes A and B
|
o 218a  commit 0 the initial state of the repository  [master]

First you should create a new branch just-commit-2 on top of master and check it out: 首先,您应该在master之上创建一个新分支just-commit-2 ,并进行检查:

git checkout master
git checkout -b just-commit-2

Then cherry-pick commit 2: 然后执行pick:

git cherry-pick bb6e

You will end up with this state: 您将最终得到以下状态:

o 12c9  commit 2 that changes C and D  [just-commit-2 (HEAD)]
|
| o 8021  commit 3 that changes D and E  [feature-branch]
| |
| o bb6e  commit 2 that changes C and D
| |
| o f8a2  commit 1 that changes A and B
|/
o 218a  commit 0 the initial state of the repository  [master]

If you look at the state of your working tree at just-commit-2 , files C and D will be the only files different from the files in master . 如果在just-commit-2上查看工作树的状态,则文件C和D将是与master唯一不同的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM