Git整理提交记录
前言
开发人员有时会说“我想要把这个提交放到这里, 那个提交放到刚才那个提交的后面”, 而接下来就讲的就是它的实现方式。
git rebase -i
当你知道你所需要的提交记录(并且还知道这些提交记录的哈希值)时, 用 cherry-pick 再好不过了 —— 没有比这更简单的方式了。
但是如果你不清楚你想要的提交记录的哈希值呢? 幸好 Git 帮你想到了这一点, 我们可以利用交互式的 rebase —— 如果你想从一系列的提交记录中找到想要的记录, 这就是最好的方法了
交互式 rebase 指的是使用带参数 --interactive
的 rebase 命令, 简写为 -i
如果你在命令后增加了这个选项, Git 会打开一个 UI 界面并列出将要被复制到目标分支的备选提交记录,它还会显示每个提交记录的哈希值和提交说明,提交说明有助于你理解这个提交进行了哪些更改。
实操:
测试项目有四次提交记录,目标:只保留第一的提交和最后一次的提交,丢弃其他的提交
此时会打开一个文件,内容如下:
// 后面的中文是我后续添加上的
pick 3eba7b8 modify README again pick e805ce4 .. # Rebase 0175914..82141c5 onto 0175914 (2 commands) # # Commands: # p, pick <commit> = use commit//使用提交 # r, reword <commit> = use commit, but edit the commit message//使用提交,但编辑提交消息 # e, edit <commit> = use commit, but stop for amending//使用提交,但停止修改 # s, squash <commit> = use commit, but meld into previous commit//将几个提交合并成一个提交。 # f, fixup [-C | -c] <commit> = like "squash" but keep only the previous # commit's log message, unless -C is used, in which case # keep only this commit's message; -c is same as -C but # opens the editor # x, exec <command> = run command (the rest of the line) using shell # b, break = stop here (continue rebase later with 'git rebase --continue') # d, drop <commit> = remove commit # l, label <label> = label current HEAD with a name # t, reset <label> = reset HEAD to a label # m, merge [-C <commit> | -c <commit>] <label> [# <oneline>] # create a merge commit using the original merge commit's # message (or the oneline, if no original merge commit was # specified); use -c <commit> to reword the commit message # u, update-ref <ref> = track a placeholder for the <ref> to be updated # to this position in the new commits. The <ref> is # updated at the end of the rebase # # These lines can be re-ordered; they are executed from top to bottom.//这些线可以重新排序;他们从上到下执行。 # # If you remove a line here THAT COMMIT WILL BE LOST.//如果你在这里删除一行,那COMMIT将会丢失。 # # However, if you remove everything, the rebase will be aborted.//但是,如果您删除了所有内容,则rebase操作将被中止。 #
删除第二行的内容【pick e805ce4 ..】,将文件保存关闭。其实查看上述的文件注释可以知道结果:If you remove a line here THAT COMMIT WILL BE LOST.
GIT BASH
控制台显示结果如下:
在控制台使用git push -f
命令强制提交到远程仓库,可以观察到本地和远程提交记录只剩两个了:
git cherry-pick
中文含义为:挑拣、精选、挑选、做出最佳选择
命令形式为:
git cherry-pick <提交号>...
如果你想将一些提交复制到当前所在的位置(HEAD
)下面的话, Cherry-pick 是最直接的方式了。我个人非常喜欢 cherry-pick
,因为它特别简单。
咱们还是通过例子来看一下!
执行 git cherry-pick C2 C4
命令后:
这就是了!我们只需要提交记录 C2
和 C4
,所以 Git 就将被它们抓过来放到当前分支下了。 就是这么简单!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?