【譯】編寫git commit信息的最佳實踐

翻譯自:Write good git commit messagegit

寫好Git提交信息

很長時間以來,我甚至都不知道編寫 git 提交(commit)信息也有它本身的「最佳實踐」。在我第一次接觸 git 時,提交信息的那部份內容被描述爲相似這樣的話:"...and here you can write something short about what's going on in the commit"github

很差的提交信息

請看下面的提交信息。若是你想合併它們,你真的不會知道哪些是添加的內容,哪些是修改的內容,它們作了什麼或者你爲何須要它們。若是你想在歷史記錄中搜索某些內容,那麼上述的糟糕狀況一樣會遇到。你向下滾動日誌,但它還是一團糟,而且浪費時間。shell

cd3e27a contact page
aee9d0d comments
eac95e5 list of online users, some other changes because of server
fae5636 little edit
複製代碼

好的提交信息

如今再看下這些提交信息。是否是感受好多了?反正我是這麼以爲。bash

43ec6aa Fix error when the URL is not reachable
4fe84ab Add error message if something went wrong
753aa05 Add server fingerprint check
df3a662 Fix shadow box closing problem
複製代碼

如何編寫好的提交信息

整個 commit 信息應該有它的格式 - 主題、正文以及可選的由已解決/已關閉的問題組成的結論。ide

主題

Git 的 commit 幫助頁面對提交信息的主題有個很不錯的描述:對變動內容進行總結的單行文本(少於50個字符),後跟一個空行。**主題應以大寫字母開頭且不以句點 . 結尾。**並且重要的是,這必須是一個強制的形式。Chris Beams 爲此寫了一個簡單的規則:工具

Git 提交信息主題的形式應該老是可以符合這樣的句式:若是提交被應用,那麼這個提交將「你寫的主題」。好比:post

【譯註】這裏能夠把「你寫的主題」理解成一個動詞、一個動做。ui

  • 若是被應用,那麼這個提交將刪除(Delete)不須要的行
  • 若是被應用,那麼這個提交將添加(Add) grep 選項
  • 若是被應用,那麼這個提交將修復(Fix)協議缺失時錯誤

對於很差的提交信息,就不會符合這個句式:this

  • 若是被應用,那麼這個提交將Contact page
  • 若是被應用,那麼這個提交將list of online users, some other changes because of server

Git 自己就是使用這種方法。當你要合併某些內容時,Git 會生成一個相似這樣的提交信息:"Merge branch...",或者回滾時生成 "Revert..."url

正文

在正文裏你能夠編寫哪些內容被修改了以及爲何修改。正文的每一行不該超過72個字符。固然並非每次提交都須要有正文。

尾行

最後,你能夠添加這次 commit 修復的或相關的 issue。它能夠是一個連接、數字或者若是你在使用 GitHub,你能夠這樣寫:Resolves #N / Closes #N,這裏的 N 表示 issue ID。

示例

這是一個來自個人倉庫的提交信息示例:

Fix error when protocol is missing

First, it checks if the protocol is set. If not, it changes the url and
add the basic http protocol on the beginning.
Second, it does a "preflight" request and follows all redirects and
returns the last URL. The process then continues with this URL.

Resolves #17
複製代碼

寫在最後

感謝你的閱讀,但願你從中學到了一些新的東西。若是你有其餘的關於如何編寫更好的提交消息的提示,或者如何更好地使用此工具,請發表你的評論。

生成變動日誌

這樣編寫提交信息的另外一個好處就是很容易生成變動日誌。

# show whole commit history
$ git log --oneline --decorate --color
 # show history from one tag to another
$ git log 0.0.9..0.0.10 --oneline --decorate --color
 # show history form tag to head
git log 0.0.9..HEAD --oneline --decorate --color
複製代碼

這種命令的結果就是你的提交列表。

21629ee Fix getResources bug
aa13384 Update docs
44de44c Add HSTS check
複製代碼

Commitizen

在 GitHub 上有個名叫 Commitizen 的命令行工具,它可讓提交信息的編寫變得更容易。當你想提交的時候,你只需鍵入 git cz,它會問你一組問題,而後爲你建立正確的提交信息。

參考

Git commit manpage

Closing issues using keywords on GitHub

How to Write a Git Commit Message post from Chris Beams

Angular Commit Message Format

相關文章
相關標籤/搜索