假设您想在 ref master 处添加 octocat git repo 的 images/ 前缀。
假设我们要使用托管在https://github.com/octocat/octocat.github.io.git 的远程(注意:GitHub 在以下fetch 命令中返回error: Server does not allow request for unadvertised object 是你指定了一个不与命名引用关联的sha1)
从您希望添加子树的分支开始,让我们首先获取所需的提交历史记录并检查我们的新分支
git fetch https://github.com/octocat/octocat.github.io.git master:tmp_octocat_master
git checkout tmp_octocat_master
接下来,让我们创建一个新的历史记录,其中仅存在我们所需前缀 (images/) 下的文件。
git subtree split --prefix=images -b subtree_split_branch
最后,让我们将这个子树添加到我们想要的分支(大概是你所在的最后一个分支,git checkout -)
git checkout -
git subtree add --prefix=public/images subtree_split_branch
现在您应该在当前分支上拥有所有需要的文件以及完整的 git 历史记录。
Alt Squashed 历史
有时您希望将子树中的提交压缩成一个提交。这在一定程度上违背了添加子树的目的,但它有它的位置。以下是上述内容的变体,以限制拉入您的回购的历史记录
从您希望将子树添加到的分支开始:
git fetch --depth=1 https://github.com/octocat/octocat.github.io.git master:tmp_octocat_master
git checkout tmp_octocat_master
注意:我们在上面指定了--depth=1,因为我们使用--squash是下面的git subtree split命令。
git subtree split --squash --prefix=images -b subtree_split_branch
git checkout -
git subtree add --prefix=public/images subtree_split_branch