首页 > 解决方案 > Git rebase 奇怪地添加了对 .gitignore 的更改

问题描述

我有以下简单的测试仓库(没有.gitignore

使用https://gist.github.com/gabyx/6ea9cf93e3aaecc9229234ea1f1960fd创建

testGitExamples.sh GitTest ex-wrong-committed-files && cd GitTest
Current history is:
 * ec8ddf1 - Added file W (Wrong changes in W.2)  (HEAD -> feature)
 * 8dbb0a8 - Added file D 
 * 54f196a - Added file C 
 * 32834a3 - Added file W (Wrong committed file W.2) 
 * 44a223a - Added file B 
 * 196b079 - Added file A 
 * 9365b59 - Test your solution 
 * f00c3f7 - Init  (master)

当我重新基于这个 repo 时

git checkout feature
git rebase -i -x 'git rm -r --cache . && git add . && git commit --amend --no-edit' HEAD~4

echo "W.2" > .gitignore在第 2 行添加git-rebase-todo

pick 7678be8 Added file W (Wrong committed file)
exec echo "W.2" > .gitignore
exec git rm -r --cache . && git add . && git commit --amend --no-edit
pick ded904f Added file C
exec git rm -r --cache . && git add . && git commit --amend --no-edit
pick dfb4b33 Added file D
exec git rm -r --cache . && git add . && git commit --amend --no-edit
pick 311736d Added file W (Wrong changes)
exec git rm -r --cache . && git add . && git commit --amend --no-edit

并且做git rebase --continue(成功运行)git奇怪地将最后一次提交(ec8ddf1)中的更改添加.gitignore.

到底是怎么回事?这是一个错误吗?

初始回购@ https://github.com/gabyx/GitTest

标签: gitrebase

解决方案


由于 for的内容与 lastW.2的内容相同,的重命名检测启发式认为这是对重命名文件的更改(由于它们的高度相似性),并将更改从 应用到。.gitignorepickgitW.2.gitignore

这最终是由 git 不存储重命名的事实引起的。当您在 中重命名文件时git,假设使用git mv,记录的是“ File Added, File Deleted”对。

一些 git 操作会看到这对,如果它们的内容相似(高于您可以选择配置的阈值--find-renames=),会将其视为同一个文件,但已重命名。

这不仅适用于向git status您展示的内容,还适用于您mergerebase问题所展示的操作。

您可以rebase通过传递来要求不执行重命名检测-X no-renames

你的rebase命令是:

git rebase -i -x 'git rm -r --cache . && git add . && git commit --amend --no-edit' -X no-renames HEAD~4

这种类型的错误在最小的工作示例中更常见,因为 git 没有足够的上下文来做出正确的猜测。


推荐阅读