作为Tim Biegeleisen noted in a comment,您没有有在 Git 中执行此操作。对于像这样的单个文件,完全绕过 Git 将更新后的文件完全绕过可能同样容易,甚至更容易:
cp .gitignore /tmp/save # the .gitignore update was good, but
git checkout master
git branch -D feature # the feature idea turned out to be bad
mv /tmp/save .gitignore
git add .gitignore
git commit
(然后写一个好的提交信息)。
作为Jasen noted in another comment,如果您自己提交了此.gitignore 更新,您可以轻松地从功能分支中挑选提交。您可以在删除功能分支之前或之后执行此操作,但如果您在删除功能分支之前找到提交会容易得多功能分支。例如:
git checkout master
git cherry-pick feature~3 # the good idea was 3 commits back
git branch -D feature
如果提交消息可以进行一些调整,请将--edit 添加到您的git cherry-pick 命令中。
最后——如果有多个文件要更新,这会更有用,因为 /tmp/save 方法不够用——您可以使用 git restore(仅在 Git 2.23 或更高版本中找到)复制特定文件,在它们提交形式,来自其他一些提交。因此,如果功能分支中的最终提交对 .gitignore 文件有很好的改进,但您不想要它的任何其他内容:
git checkout master
git restore --source=feature --staged --worktree -- .gitignore
git branch -D feature
git commit
这里的--staged --worktree 导致新的和改进的文件已经暂存以提交,因此不需要单独的git add。
如果你没有git restore,git checkout 有一个与上面完全相同的模式:
git checkout master
git checkout feature -- .gitignore
git branch -D feature
git commit
这个git checkout <em>specifier</em> -- <em>paths</em> 命令与git restore --source=<em>specifier</em> --staged --worktree -- <em>paths</em> 的效果完全相同。请注意,git checkout 这种形式的 -- <em>paths</em> 部分表示不经询问就销毁任何未保存的工作(通常git restore 也是如此)。
如果你已经删除了功能分支怎么办?
回答标题问题,上面的所有 Git 方法仍然有效,只要你能找到正确的提交哈希 ID。此哈希 ID 将在 HEAD 的引用日志中找到。在 reflog 中找到分支名称(在这种情况下为feature)会更容易,但不幸的是,当分支名称被删除时,该 reflog 会被删除。
所以,运行git reflog——它的默认设置是显示HEAD reflog——并找到一个合适的提交哈希ID。然后使用鼠标将哈希 ID 剪切并粘贴为 --source 的 git restore,例如。