如何在保存历史的同时将文件从一个git存储库移动到另一个

我试图将一个文件(称为foo.txt)从一个存储库移动到另一个(不相关的)存储库,以保留其历史logging。 ebneter的问题显示了如何为子目录执行此操作。 taw的问题有一些提示和build议,但不是一步一步遵循的。 jkeating的问题看起来很有希望,但对我来说并不合适。 Googlesearch对于这个特定的用例来说是空的。 我正在寻找的是一个明确的命令序列来完成这一点。

我开始遵循的命令序列是这样的:

$ git clone source-repo/ source-repo-copy $ cd source-repo-copy $ git filter-branch --tree-filter 'test ! "$@" = "foo.txt" && \ git rm --cached --ignore-unmatch $@ || true' --prune-empty 

我的过滤命令的逻辑是git rm所有不是foo.txt的文件。 我加了|| true || true的命令强制它有一个零返回值来满足filter分支。

我的意图是将源repo-copy设置为我的目标存储库(target-repo)的远程,并假设git filter-branch过滤掉除foo.txt以外的所有内容,将source-repo-copy取回并合并到target-repo。 不幸的是, git filter-branch命令似乎没有效果。 它运行没有错误,似乎通过在源代码回购中的600多个提交,但是当它完成时, git log和源代码复制副本中的文件看起来是一样的。 不应该所有的文件,但foo.txt丢失,所有提交没有触摸它会从日志中消失?

在这一点上,我不知道如何进行。 有什么build议么?

这为我工作,但有一个完整的目录。

如图所示

 ~$ cd neu ~/neu$ git filter-branch --subdirectory-filter FooBar HEAD ~/neu$ git reset --hard ~/neu$ git remote rm origin ~/neu$ rm -r .git/refs/original/ ~/neu$ git reflog expire --expire=now --all ~/neu$ git gc --aggressive ~/neu$ git prune ~/neu$ git remote add origin git://github.com/FooBar/neu.git 

编辑:对于单个文件:

首先筛选目录:

  git filter-branch --prune-empty --subdirectory-filter myDirectory -- --all 

过滤单个文件:

  git filter-branch -f --prune-empty --index-filter "git rm --cached --ignore-unmatch $(git ls-files | grep -v 'keepthisfile.txt')" 

做一些清理:

  git reset --hard git gc --aggressive git prune 

这应该做到这一点。

请参阅我的答案有关移动文件夹的类似问题,我也回答如何移动一个文件。 https://stackoverflow.com/a/24693985/464618

我试图在这里复制它,但它似乎是不允许的,因为它被删除。