我使用
git subtree
,例如:
git subtree add \
--prefix=directory_destination_path \
--squash [email protected]:kicaj/projectname.git \
master
但是在
directory_destination_path
中,它从 projectname.git
复制整个存储库。
如何仅将子目录或文件从
projectname.git
复制到 directory_destination_path
?
另外,如何更新(自动)两个存储库中的文件更改仍然相同?有可能吗?
如果我理解,您似乎只想合并到不同存储库的某个目录中,并且希望它成为存储库中的子树。我将调用项目中感兴趣的目录。git
path_of_interest_in_project
并调用您的存储库中的目的地 directory_desination_path
。
尝试将远程project.git添加为远程项目,然后在本地检查其分支之一。然后使用
git-subtree split
只拆分出您感兴趣的 project.git 目录。之后使用子树合并将其合并到您的存储库中。
git remote add project [email protected]:kicaj/projectname.git
git branch project_master project/master
分支project_master现在应该存储project.git存储库的整个历史记录。
然后您需要使用
git-subtrees-split
流程。
git checkout -f project_master
git subtree split --squash --prefix=path_of_interest_in_project -b temp_branch
现在应该有一个名为
temp_branch
的分支,其中仅包含您感兴趣的目录。现在您可以执行 git-subtree-merge
将其全部放入您的存储库中。
git checkout -f master
git subtree merge --allow-unrelated-histories --prefix=directory_destination_path temp_branch
这应该将 temp_branch 合并到您的 master 分支中。
假设您想在参考文献
images/
处添加 octocat git 存储库的 master
前缀。
假设我们要使用托管在 https://github.com/octocat/octocat.github.io.git 的远程(注意:GitHub 在以下
error: Server does not allow request for unadvertised object
命令中返回 fetch
如果您指定了 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 历史记录。
有时您希望将子树中的提交压缩为单个提交。这在一定程度上违背了添加子树的目的,但它有它的用处。以下是上述内容的变体,用于限制拉入您的存储库的历史记录
从您想要添加子树的分支开始:
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
这是来自 @eddiemoya 的很棒的答案,但是截至今天,有些命令不起作用。所以我就在这里重新发布它们:
# create a target branch in the new repo
git branch target
# check out the other repo into a new branch
git remote add temp [email protected]:aRepo/any-service.git
git fetch temp
git branch temp_master temp/master
# split desired folder into a temp branch
git checkout -f temp_master
git subtree split --prefix=path/to/desired/folder -b temp_branch
# check out target branch and add all commits in temp branch to the correct folder
git checkout -f target
git subtree add --prefix=path/to/destination/folder temp_branch
# ... voila
# clean up
git branch -d temp_branch
git branch -d temp_master
git remote remove temp