首页 > 解决方案 > 将旧分支中的一些特定文件合并到我当前的分支

问题描述

我在一个分支 B 上工作。我创建了我的分支并从最新的主提交中签出。我的同事在分支 A 工作。他很久以前从 master 结帐,所以他支持它:

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

在他的分支机构中,他处理了很多文件,而我只需要其中的一些。我们称它们为 File1.txt、File2.txt 和 File3.txt。我想将这些文件合并到我的分支中。我的问题是:在这种情况下要遵循什么方法?我应该在他过时的分支之上合并/变基吗?有没有办法只获取这 3 个文件并将它们合并到我当前的工作分支并获得 B2 提交?

标签: git

解决方案


您可以使用git checkout --patch <branch> <filename>来自另一个分支的文件来修补当前分支中的现有文件。如果当前分支中不存在该文件,请使用git checkout <branch> <filename>在您的分支中对其进行编辑。接下来,您可以保存文件并提交更改。

在您的情况下(file1.txt 的示例):

  1. 转到分支 B git checkout B

  2. 使用git checkout --patch A file1.txt,或者,如果分支 B 中不存在 file1.txt,则使用git checkout A file1.txt

  3. Apply this hunk to index and worktree选择y

  4. 保存文件并git add file1.txt提交您的更改git commit -m 'Your commit message'

以下是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.

希望这可以帮助。


推荐阅读