如何在git的历史记录中更改文件路径?

4

以下是我拥有的内容 - 我的代码的git存储库:

projects
       |-proj1 (no git repo here yet)
             |-subproj1 <- current git repo here

这是我想要的 - 一个 Git 仓库,现在正在跟踪使用我的代码的新项目:

projects
       |-proj1 <-git repo moved to here, but still tracking files in subproj1
             |-subproj1 (no git repo here)

我希望保留历史记录,因此新的存储库将引用比原始文件深一级的文件。有什么最简单的方法可以做到这一点?
3个回答

13
重写Git历史记录可以使用“git filter-branch”命令。实际上,将目录树移动到子目录中是在“git filter-branch”手册中提供的一个剪切和粘贴的示例之一。请参考git filter-branch手册。
git filter-branch --index-filter '
  git ls-files -s |
  sed "s-\t\"*-&subproj1/-" |
  GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info &&
  mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE
' HEAD

2
我正在尝试做类似的事情,并注意到我的临时索引文件没有被写入(https://gist.github.com/60d14f45a0b2fb98e641)。是否有任何有效的原因导致临时索引未被写入? - Mark Derricutt
1
sed 命令似乎不太稳定,我没有得到预期的结果。 - mxcl
1
我也遇到了sed命令的问题。使用“-”作为分隔符对于名称中带有连字符的目录来说是不寻常且无法使用的。我使用了:sed "s#\t\"*#&sub-proj1/#" - Daniel Alder

0

Git在跟踪文件移动方面并不是很好,因此如果您想保留文件历史记录,就必须使旧存储库始终将其文件放在您现在需要的子目录中。

git-filter-branch工作得还不错,但已经不再推荐使用。现在的man页面指向了git-filter-repo,它可以让您以更简单的方式(除了git-filter-branch之外的其他事情)回溯地移动文件。

我的答案复制:

export SUBTREE_PREFIX="subproj1"

git remote add -f "${SUBTREE_PREFIX:?}-remote" https://my-git-repo.invalid/subproj1.git

git checkout "${SUBTREE_PREFIX:?}-remote"/master -b "${SUBTREE_PREFIX:?}-master"

# --force is to skip the "freshly cloned repo" check.
# All the refs we'll be operating on are fresh, even if the repo isn't

# Remove --dry-run once you've checked .git/filter-repo/fast-export.filtered
# to be sure that everything is correct.
git filter-repo --refs "${SUBTREE_PREFIX:?}-master" --to-subdirectory-filter "${SUBTREE_PREFIX:?}" --force --dry-run

git checkout master
git merge "${SUBTREE_PREFIX:?}-master" --allow-unrelated-histories

# Repeat for however many repos you need to add

另请参阅如何合并两个Git存储库?


-2

只需在存储库中创建所需的目录结构 - 即将所有文件和文件夹移动到“subproj1”文件夹。

然后暂存所有添加和删除的文件,Git 将计算它们实际上是重命名:

git add .
git add -u .
git commit -m "Moved to a subfolder"

2
这意味着如果我检出以前的提交,文件将被检出到proj1内部。我不想要那样。我希望能够检出以前的提交,并影响subproj1中的文件。 - Carl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接