更新
我创建了一个别名 git squash-all。
使用示例:git squash-all "a brand new start"。
[alias]
squash-all = "!f(){ git reset $(git commit-tree HEAD^{tree} -m \"${1:-A new start}\");};f"
注意:可选消息用于提交消息,如果省略,则默认为“A new start”。
或者您可以使用以下命令创建别名:
git config --global alias.squash-all '!f(){ git reset $(git commit-tree HEAD^{tree} -m "${1:-A new start}");};f'
一个班轮
git reset $(git commit-tree HEAD^{tree} -m "A new start")
这里,提交消息“A new start”只是一个示例,请随意使用您自己的语言。
TL;DR
无需压缩,使用git commit-tree 创建一个孤儿提交并使用它。
解释
-
通过git commit-tree创建一个提交
git commit-tree HEAD^{tree} -m "A new start" 所做的是:
根据提供的树对象创建一个新的提交对象
并在标准输出上发出新的提交对象 ID。日志消息是
从标准输入读取,除非给出 -m 或 -F 选项。
表达式HEAD^{tree}表示HEAD对应的树对象,即你当前分支的尖端。见Tree-Objects 和Commit-Objects。
- 将当前分支重置为新的提交
然后git reset 只需将当前分支重置为新创建的
提交对象。
这样,工作区中没有任何东西被触及,也没有
需要变基/壁球,这使得它非常快。而且所需的时间与存储库大小或历史深度无关。
变体:来自项目模板的新回购
这对于使用另一个存储库作为模板/原型/种子/骨架在新项目中创建“初始提交”很有用。例如:
cd my-new-project
git init
git fetch --depth=1 -n https://github.com/toolbear/panda.git
git reset --hard $(git commit-tree FETCH_HEAD^{tree} -m "initial commit")
这避免了将模板 repo 添加为远程(origin 或其他方式)并将模板 repo 的历史记录折叠到您的初始提交中。