git 提交规范

<head>:<scope> <body>

提交频率

  • 只要我对项目进行了修改,一通过测试就立即 commit。比如修复完一个 bug、开发完一个小功能,或者开发完一个完整的功能,测试通过后就提交。
  • 我们规定一个时间,定期提交。这里我建议代码下班前固定提交一次,并且要确保本地未提交的代码,延期不超过 1 天。这样,如果本地代码丢失,可以尽可能减少丢失的代码量。

按照上面 2 种方式提交代码,你可能会觉得代码 commit 比较多,看起来比较随意。或者说,我们想等开发完一个完整的功能之后,放在一个 commit 中一起提交。这时候,我们可以在最后合并代码或者提交 Pull Request 前,执行 git rebase -i 合并之前的所有 commit。

合并提交

合并提交,就是将多个 commit 合并为一个 commit 提交。这里,我建议你把新的 commit 合并到主干时,只保留 2~3 个 commit 记录

git rebase 命令介绍

git rebase 的最大作用是它可以重写历史。
我们通常会通过 git rebase -i 使用 git rebase 命令,-i 参数表示交互(interactive),该命令会进入到一个交互界面中,其实就是 Vim 编辑器。在该界面中,我们可以对里面的 commit 做一些操作,交互界面如图所示:

这个交互界面会首先列出给定之前(不包括,越下面越新)的所有 commit,每个 commit 前面有一个操作命令,默认是 pick。我们可以选择不同的 commit,并修改 commit 前面的命令,来对该 commit 执行不同的变更操作
git rebase 支持的变更操作如下:

在上面的 7 个命令中,squash 和 fixup 可以用来合并 commit。例如用 squash 来合并,我们只需要把要合并的 commit 前面的动词,改成 squash(或者 s)即可。你可以看看下面的示例:

pick 07c5abd Introduce OpenPGP and teach basic usage
s de9b1eb Fix PostChecker::Post#urls
s 3e7ee36 Hey kids, stop all the highlighting
pick fa20af3 git interactive rebase, squash, amend

rebase 后,第 2 行和第 3 行的 commit 都会合并到第 1 行的 commit。这个时候,我们提交的信息会同时包含这三个 commit 的提交信息:


# This is a combination of 3 commits.
# The first commit's message is:
Introduce OpenPGP and teach basic usage

# This is the 2ndCommit Message:
Fix PostChecker::Post#urls

# This is the 3rdCommit Message:
Hey kids, stop all the highlighting

如果我们将第 3 行的 squash 命令改成 fixup 命令:

pick 07c5abd Introduce OpenPGP and teach basic usage
s de9b1eb Fix PostChecker::Post#urls
f 3e7ee36 Hey kids, stop all the highlighting
pick fa20af3 git interactive rebase, squash, amend

rebase 后,还是会生成两个 commit,第 2 行和第 3 行的 commit,都合并到第 1 行的 commit。但是,新的提交信息里面,第 3 行 commit 的提交信息会被注释掉:

# This is a combination of 3 commits.
# The first commit's message is:
Introduce OpenPGP and teach basic usage

# This is the 2ndCommit Message:
Fix PostChecker::Post#urls

# This is the 3rdCommit Message:
# Hey kids, stop all the highlighting

除此之外,我们在使用 git rebase 进行操作的时候,还需要注意以下几点:

  • 删除某个 commit 行,则该 commit 会丢失掉。
  • 删除所有的 commit 行,则 rebase 会被终止掉。
  • 可以对 commits 进行排序,git 会从上到下进行合并。
    git rebase --edit-todo 修改刚才配置的文件

合并提交

git rebase --continue

修改 Commit Message

具体来说,我们有两种修改方法,分别对应两种不同情况:

  • git commit --amend:修改最近一次 commit 的 message;
  • git rebase -i:修改某次 commit 的 message。
Songzhibin
原文地址:https://www.cnblogs.com/binHome/p/14863433.html