从以前的所有提交中删除目录

时间:2012-12-21 10:39:00

标签: git version-control

Git Repo,有一个文件夹ABC,其中包含三个文件,所有文件的名称均为file - 1.extfile - 2.extfile - 3.ext。我想删除文件夹和文件。我只知道如何通过此命令删除文件

git filter-branch \
  --index-filter 'git rm --cached --ignore-unmatch FILE' \
  --prune-empty --tag-name-filter cat -- --all

然后你git push origin master --force

(1)但是如何从以前的所有提交中删除文件夹ABC及其文件?

此外,文件中的名称中包含空格,以下内容未在repo提交中检测到它们:

git filter-branch \
  --index-filter 'git rm --cached --ignore-unmatch file\ -\ 1.ext' \
  --prune-empty --tag-name-filter cat -- --all

(2)语法应删除名称中带空格的文件? 备注

  • OSX
  • github上

2 个答案:

答案 0 :(得分:22)

假设您从

的历史开始
$ git lola --name-status
* e709131 (HEAD, master) bar
| A     bar
* 61493ac ABC/file - 3.ext
| A     ABC/file - 3.ext
* 34cce9e ABC/file - 2.ext
| A     ABC/file - 2.ext
* 115e6d5 ABC/file - 1.ext
| A     ABC/file - 1.ext
* 5ea5b42 foo
  A     foo

注意:git lola是一个非标准但非常有用的别名。

git rm支持删除子树的选项。

  

<强> -r
  在给出前导目录名时允许递归删除。

运行后

$ git filter-branch --index-filter 'git rm --cached -r --ignore-unmatch ABC' \
  --prune-empty --tag-name-filter cat -- --all

你会看到类似于

的输出
Rewrite 115e6d5cd06565ca08f1e5c98c4b91246cf59fa1 (2/5)rm 'ABC/file - 1.ext'
Rewrite 34cce9e90f832460137e620ebacc8a73a99e64ce (3/5)rm 'ABC/file - 1.ext'
rm 'ABC/file - 2.ext'
Rewrite 61493ac3211808f34f616dbc33d51d193b3f45a3 (4/5)rm 'ABC/file - 1.ext'
rm 'ABC/file - 2.ext'
rm 'ABC/file - 3.ext'
Rewrite e709131f1fe6103adf37616c9fa500994aeb30d0 (5/5)rm 'ABC/file - 1.ext'
rm 'ABC/file - 2.ext'
rm 'ABC/file - 3.ext'

Ref 'refs/heads/master' was rewritten

如果您对结果感到满意,请使用

删除旧主控
$ git update-ref -d refs/original/refs/heads/master

现在你有了

的历史
$ git lola --name-status
* 19680d4 (HEAD, master) bar
| A     bar
* 5ea5b42 foo
  A     foo

要回答您的第二个问题,请说您只想删除ABC/file - 2.ext。请记住,您需要两层引用:一个层用于整个命令,另一个层用于转义该命令的参数中的空格,即要删除的文件的名称。

一种方法是

$ git filter-branch --index-filter \
  'git rm --cached --ignore-unmatch "ABC/file - 2.ext"' --prune-empty \
  --tag-name-filter cat -- --all

请注意单引号内的双引号。

如果您改为运行此命令,则您的历史记录将变为

$ git lola
* a8d1b0d (HEAD, master) bar
* cff0c4e ABC/file - 3.ext
* 115e6d5 ABC/file - 1.ext
* 5ea5b42 foo

答案 1 :(得分:12)

请尝试使用--index-filter

,而不是使用--tree-filter
--tree-filter <command>
    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!).

命令行:

git filter-branch --tree-filter 'rm -rf path/to/ABC' \
  --prune-empty --tag-name-filter cat -- --all