git - 将旧分支中的一些特定文件 merge 到我当前的分支

标签 git

我在分支 B 上工作。我创建了我的分支并从最新的主提交中 check out 。我的同事在分支 A 工作。他很久以前就从 master 那里 checkout 了,所以他在后面:

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

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

最佳答案

您可以使用 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.

希望这对您有所帮助。

关于git - 将旧分支中的一些特定文件 merge 到我当前的分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62508728/

相关文章:

git - 在多个子目录上切换分支

ios - 我需要将一些文件从现有的git repo移到新文件。我可以保留他们的历史吗?

git - 如何更改或修改 git 分支的起点(提交)?

Git 服务器的主机 key 未缓存在注册表中 - GitHub.com

git - Git 是否存储文件创建时间?

git - 无法推送到 heroku

git - 如何配置 gogs 以快速加载大型 git 存储库?

git - 使用git,如何忽略一个分支中的文件但将其提交到另一个分支中?

linux - 如何将 Meld 的 flatpak 版本设置为 git mergetool?

git - 我应该排除 .gitignore 中的 Aurelia 脚本文件夹吗?