如何通过将父文件添加到回购并保留历史记录来将回购移动到父文件夹

How to move a repo to a parent folder with adding parent's files to the repo & preserve history

我在 foo/src 中有一个多分支回购,但是我想向上移动回购(。git 成为 src 的邻居)同时保留历史并将所有这些文件添加到整个历史。

--- foo/  
      |-bar/  
      |-src/
           |-.git
      |-hello.txt

我该怎么做?

注意:我试过 this answer,但无法将文件添加到整个存储库历史记录。 然后我尝试了 rebase -i --root (here) 但这只适用于一个分支,破坏和过时了其余部分。

开始之前: 备份您的 git 存储库,因为 filter-branch 命令具有破坏性!


您可以使用 git filter-branch--tree-filter 选项。 --tree-filter 选项的手册指出:

This is the filter for rewriting the tree and its contents. The argument is evaluated in shell with the working directory set to the root of the checked out tree. The new tree is then used as-is (new files are auto-added, disappeared files are auto-removed - neither .gitignore files nor any other ignore rules HAVE ANY EFFECT!).

因此,对于每次提交,我们要创建一个新目录 src 并将树中的所有文件移动到该目录(当然不包括 src/ 本身)。

git filter-branch --tree-filter '
mkdir -p src
for i in *; do
    if [ "$i" != "src" ]; then
        mv "$i" src/
    fi
done
' --all

之后您可以添加未跟踪的 bar/ 目录和 hello.txt 作为顶部的新提交。

如果您希望 bar/hello.txt 从历史开始就出现在 repo 中,您必须稍微调整树过滤器命令。

git filter-branch --tree-filter '
mkdir -p src
for i in *; do
    if [ "$i" != "src" ]; then
        mv "$i" src/
    fi
done
cp -R "/path/to/bar" .
cp "/path/to/hello.txt" .
' --all