我一直在关注这个优秀的答案,将我的git存储库的子目录提取到自己的存储库中,同时保留完整的历史记录.
我的存储库看起来像:
src/
http/
math/
tests/
http/
math/
Run Code Online (Sandbox Code Playgroud)
我想创建一个只包含src/math和tests/math目录的新分支 .
如果我运行以下命令:
git subtree split -P src/math -b math
Run Code Online (Sandbox Code Playgroud)
它创建一个包含目录内容的分支src/math,但丢弃该src/math/前缀.
如果我尝试使用两个目录的相同命令:
git subtree split -P src/math -P tests/math -b math
Run Code Online (Sandbox Code Playgroud)
它只提取tests/math,忽略src/math和丢弃tests/math前缀的内容.
总而言之,我希望我的最终存储库看起来像:
src/
math/
tests/
math/
Run Code Online (Sandbox Code Playgroud)
也就是说,保留原始目录结构,但丢弃命令行中未明确提及的所有内容.
我怎样才能做到这一点?
git-subtree add分割# First create two *split-out* branches
cd /repos/repo-to-split
git subtree split --prefix=src/math --branch=math-src
git subtree split --prefix=test/math --branch=math-test
# Now create the new repo
mkdir /repos/math
cd /repos/math
git init
# This approach has a gotcha:
# You must commit something so "revision history begins",
# or `git subtree add` will complain about.
# In this example, an empty `.gitignore` is commited.
touch .gitignore
git add .gitignore
git commit -m "add empty .gitignore to allow using git-subtree"
# Finally, *split-in* the two branches
git subtree add --prefix=src/math ../repo-to-split math-src
git subtree add --prefix=test/math ../repo-to-split math-test
Run Code Online (Sandbox Code Playgroud)
它对我有用git --version2.23.0。另请注意,您可以在拆分时间设置不同的前缀,即添加src/math/tosrc/和test/math/to test/。
旁注:git log在提交到远程之前在新的存储库中使用,看看结果历史记录是否适合您。就我而言,我有一些带有重复消息的提交,因为我的回购历史记录太脏了,但这对我来说没关系。
使用git-filter-repo 从版本 2.25 开始,这不是 git 的一部分。这需要 Python3 (>=3.5) 和 git 2.22.0
git filter-repo --path src/math --path tests/math
Run Code Online (Sandbox Code Playgroud)
对于包含约 12000 次提交的存储库,git-filter-branch花费了超过 24 小时,而git-filter-repo花费了不到一分钟。
根据您的需要,您可能会逃脱git filter-branch。
我不完全确定您想要实现什么,但如果您只想拥有一个删除了两个目录的存储库(在历史记录中?),这可能是您最好的选择。
另请参阅重写 Git 历史记录。
$ git filter-branch --tree-filter 'rm -rf tests/http src/http' --prune-empty HEAD
Run Code Online (Sandbox Code Playgroud)
这将查看每个提交并从此提交中删除两个目录。请注意,这会重写历史记录(即:更改您的提交 sha),并且如果您与另一个存储库有共同的历史记录,则会引起头痛。