将一些特定文件从旧分支合并到我的当前分支

时间:2020-06-22 06:40:00

标签: git

我正在分支B上工作。我创建了分支,并从最新的主提交中签出。我的同事在A分行工作。很久以前他从主人那里结帐,所以他在后面:

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

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

2 个答案:

答案 0 :(得分:4)

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

以您的情况为例(例如file1.txt):

  1. 使用 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-scm.com中的git checkout --patch的具体描述:

-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.

希望这会有所帮助。

答案 1 :(得分: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