转换一个git文件夹到一个子模块回顾?

通常情况下,您正在编写某种项目,过了一段时间,项目的某些组件实际上可以作为一个独立的组件(也许是一个库)变得非常有用。 如果你从早期就有了这个想法,那么很可能大部分代码都在自己的文件夹中。

有没有办法将一个git项目的子目录转换成子模块? 理想情况下,会发生这样的情况,即从该父项目中删除该目录中的所有代码,并且将该子模块项目添加到其所有相应的历史logging中,并且使得所有父项目提交指向正确的子模块提交。

要将子目录分离到其自己的存储库中,请在原始存储库的克隆上使用filter-branch

 git clone <your_project> <your_submodule> cd <your_submodule> git filter-branch --subdirectory-filter 'path/to/your/submodule' --prune-empty -- --all 

然后就是删除原来的目录,并将子模块添加到父项目中。

首先将目录更改为将成为子模块的文件夹。 然后:

 git init git remote add origin repourl git add . git commit -am'first commit in submodule' git push -u origin master cd .. rm -rf folder wich will be a submodule git commit -am'deleting folder' git submodule add repourl folder wich will be a submodule git commit -am'adding submodule' 

这可以做,但并不简单。 如果你searchgit filter-branchsubdirectorysubmodule ,那么在这个过程中有一些体面的写法。 它基本上需要创build两个项目的克隆,使用git filter-branch删除除了一个子目录之外的所有东西,并且只删除另一个子目录。 然后,您可以将第二个存储库build立为第一个存储库的子模块。

我知道这是一个古老的线程,但是这里的答案压缩了其他分支中的任何相关的提交。

克隆和保留所有额外分支和提交的简单方法:

1 – 确保你有这个混帐别名

 git config --global alias.clone-branches '! git branch -a | sed -n "/\/HEAD /d; /\/master$/d; /remotes/p;" | xargs -L1 git checkout -t' 

2 – 克隆远程,拉动所有分支,更换遥控器,过滤目录,按下

 git clone git@github.com:user/existing-repo.git new-repo cd new-repo git clone-branches git remote rm origin git remote add origin git@github.com:user/new-repo.git git remote -v git filter-branch --subdirectory-filter my_directory/ -- --all git push --all git push --tags