将旧分支中的特定文件合并到我的当前分支

3

我正在处理分支B。我创建了自己的分支,并从最新的主分支提交中检出。我的同事在分支A上工作。他很久以前从主分支检出,所以他落后于它:

                           --------- A1
                          /
                         /
                        /
--------- M1 --------- M2 --------- M3 --------- M4 --------- M5 --------- B1

在他的分支中,他处理了许多文件,而我只需要其中一些。我们称它们为File1.txt,File2.txt和File3.txt。我想将这些文件合并到我的分支中。我的问题是:在这种情况下应该采取什么方法?我应该将其合并/基于他过时的分支进行rebase吗?是否有一种方法只获取这3个文件并将它们与我的当前工作分支合并,并获得B2提交?

为什么不直接将A1合并到B1中呢? - Lasse V. Karlsen
@LasseV.Karlsen 那我只需要切换到我的分支,然后调用 git merge my_colleague_branch 并解决冲突就可以了吗?是这样的吗? - Pryda
应该这样,这就是git的工作方式。如果你的同事修改了你不想要的文件,那就是另一回事了,但如果你只想要那个分支上的所有更改,请将其合并到你的分支中,然后你就完成了。 - Lasse V. Karlsen
@LasseV.Karlsen 是的,他修改了很多文件,而我只需要其中的3个。 - Pryda
1
也许您想看看下面Marc留下的答案。 - Lasse V. Karlsen
2个回答

4
您可以使用 git checkout --patch <branch> <filename> 命令,从另一个分支中获取文件并将其应用于当前分支已存在的文件进行修改。如果该文件在您当前的分支中不存在,则可以使用 git checkout <branch> <filename> 命令在您的分支中进行编辑。接下来,您可以保存文件并提交更改。
对于您的情况(例如对于 file1.txt 文件):
  1. 使用 git checkout B 命令切换到分支 B。

  2. 如果 file1.txt 文件在分支 B 中不存在,则使用 git checkout A file1.txt 命令从分支 A 中获取。否则,使用 git checkout --patch A file1.txt 命令将分支 A 中的文件应用于分支 B 中的文件,并进行修改。

  3. 在提示信息 "Apply this hunk to index and worktree" 上选择 y

  4. 保存文件并使用 git add file1.txt 命令添加文件后,使用 git commit -m '您的提交消息' 命令提交更改。

下面是 git checkout --patch 命令的具体描述,摘自 git-scm.com
-p
--patch
Interactively select hunks in the difference between the <tree-ish> (or the index, if unspecified) and the working tree. The chosen hunks are then applied in reverse to the working tree (and if a <tree-ish> was specified, the index).

This means that you can use git checkout -p to selectively discard edits from your current working tree. See the “Interactive Mode” section of git-add[1] to learn how to operate the --patch mode.

Note that this option uses the no overlay mode by default (see also --overlay), and currently doesn’t support overlay mode.

希望这能帮到你。

0
如果您需要将文件File{1,2,3}.txt恢复为A1中的原始版本,丢弃在M2..M4期间对这些文件所做的所有更改,请使用以下命令:

git checkout A1 -- File1.txt File2.txt File3.txt

如果您确实需要合并(将A1中的更改与M2..M4中的更改结合起来),则可以创建一个仅包含这些文件的提交,并使用该提交:

# create a branch from A1 :
git branch wip A1
git checkout wip

# replay changes only for the files
git reset HEAD^
git add File1.txt File2.txt File3.txt
git commit
git checkout .  # drop other changes

# use merge or rebase to combine the changes
git rebase M4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接