git — 如何撰寫優雅的 git message

shangrex
4 min readAug 3, 2021

--

以下主要是翻譯自 reference。

大原則

主要格式不要變動,統一一致性。格式包括 Style, Content, Metadata。

  • Style: 文法,段落邊緣,標點符號等
  • Content: 文章應該包含哪些,不應該包含哪些
  • Metadata: Pull Request數字,issue’s ID等

七大守則

  1. 把主題 (title) 和文章 (body) 用一行隔開

這樣如果使用 git shortlog 可以很清楚只看主題。主題 (title) 描述哪裡改變。有時候 commit 只需要有主題,不需要有文章,若需要解釋 commit,則寫在文章中。例子如下:


Derezz the master control program
MCP turned out to be evil and had become intent on world domination.
This commit throws Tron’s disc into MCP (causing its deresolution)
and turns it back into a chess game.

2. 只需要有主題也可以採用 git commit -m "commit message"
git commit -m "Fix typo in introduction to user guide"

3. 主題 (title) 最好少於 50 字元,最多 72 字元

  • 若是超過 72 字元,GitHub 會有警告,並且把多餘的換成 …

4. 主題 (title) 第一個字大寫

  • 錯誤例子:

accelerate to 88 miles per hour

  • 正確例子:

Accelerate to 88 miles per hour

5. 主題 (title) 不要有句號

  • 錯誤例子:

Open the pod bay doors.

  • 正確例子:

Open the pod bay doors

6. 主題句 (title) 使用祈使語氣
雖然使用祈使語句不太禮貌,但 git 本身就是祈使語句,且此種語句簡單易懂。
若是無法想出,可以簡單帶入以下句子完成祈使語句。

  • If applied, this commit will refactor subsystem X for readability
  • If applied, this commit will update getting started documentation
  • If applied, this commit will remove deprecated methods
  • If applied, this commit will release version 1.0.0
  • If applied, this commit will merge pull request #123 from user/branch

對比以下非祈使語句

  • If applied, this commit will fixed bug with Y
  • If applied, this commit will changing behavior of X
  • If applied, this commit will more fixes for broken stuff
  • If applied, this commit will sweet new API methods
    在文章 (body) 中可以不使用祈使語句。

7. 文章 (body) 一行最好不要超過 72 字元,至多 80 字元
留下右邊的空白,讓 git 可以有空間放入縮排。

文章 (body) 寫下 what, why and how
清楚的描述為什麽要更動,更動前運作邏輯為何和有什麽缺點,更動的方法是什麽以及這個選擇這個方法的原因。

小技巧

  1. 使用 CLI 而不是用 IDE,雖然 IDE 做簡單的 git 操作很簡單,但無法做比較複雜的操作如 git rebase。使用 CLI 才可發揮 git 的最大效用。

特別感謝 lincc 協助
若有錯誤或是侵權請告知作者

Reference: How to Write a Git Commit Message
Reference: 中英文格式

--

--

shangrex

CS student in UIUC from Taiwan, Love to read books , travel around the world and play LOL