天天看點

Git生态探索之Commit message 和 Change log 編寫最佳實踐

背景

最近在學習規範如何使用git來更高效的開發,發現一個比較好用的來規範comment的工具,是以想來記錄一下。一般來說,commit message 應該清晰明了,說明本次送出的目的。是以需要一些規範來使這些comment變得可讀,commitizen則是最近發現的一款比較易用的工具。

git的送出一般的初學者都會使用git commit -m "hello world"來送出comment,但是一些像hello world這樣沒有意義的comment讓人無法了解這次的送出到底是為了什麼,是以我們就要規範一下comment的規範了。

PS:下面是一些基礎介紹如果大佬請直接檢視第二部分

  1. commit message format(資訊域)
  2. message一般分為三個部分Header,Body 和 Footer

():

// 空一行

其中,Header 是必需的,Body 和 Footer 可以省略

Example:

PS D:gitpythonPractice> git log

commit 58a7a966acb9aa2fffc0e02c9ce3be64b8949991 (HEAD -> master)

Author: Zhiwei Tian

[email protected]

Date: Fri Aug 17 17:38:36 2018 +0800

feat(serve): add grpc server
           

1.1 HEAD

type用于說明 commit 的類别,隻允許使用下面7個辨別

feat:新功能(feature)

fix:修補bug

docs:文檔(documentation)

style: 格式(不影響代碼運作的變動)

refactor:重構(即不是新增功能,也不是修改bug的代碼變動)

test:增加測試

chore:建構過程或輔助工具的變動

scope 用來說明本次Commit影響的範圍,即簡要說明修改會涉及的部分,比如資料層、控制層、視圖層等,

subjectcomment所在的位置,這次送出的簡短描述

1.2 Body 是對本次 commit 的較長的描述,可以分成多行

1.3 Footer 部分隻用于兩種情況

不相容變動

如果目前代碼與上一個版本不相容,則 Footer 部分以BREAKING CHANGE開頭,後面是對變動的描述、以及變動理由和遷移方法

關閉 Issue

如果目前 commit 針對某個issue,那麼可以在 Footer 部分關閉這個 issue (可依次關閉過個issueCloses #123, #245, #992)

1.4 Revert

還有一種特殊情況,如果目前 commit 用于撤銷以前的 commit,則必須以revert:開頭,後面跟着被撤銷 Commit 的 Header

revert: type(scope): some comment

This reverts commit bfe307ce57d87677c6c473c228e6c2ed8b81dcec.

Body部分的格式是固定的,必須寫成This reverts commit <hash>.,其中的hash是被撤銷 commit 的 HSHA 辨別符。

如果目前 commit 與被撤銷的 commit,在同一個釋出(release)裡面,那麼它們都不會出現在 Change log 裡面。如果兩者在不同的釋出,那麼目前 commit,會出現在 Change log 的Reverts小标題下面

  1. 使用commitizen來執行規範

    因為commitizen是node的子產品,是以前提需要安裝node(官網下載下傳位址)

全局安裝commitizennode子產品

npm install -g commitizen

在項目目錄下運作指令

commitizen init cz-conventional-changelog --save --save-exact

此時可能會報找不到package.json的錯誤,使用下面指令來自動生成一個項目的package,然後在運作2中的指令.

npm init --yes

運作完以上一律使用git cz 代替git commit來送出代碼,同時會顯示一下選項來自動生成符合格式的commit message.

PS D:gitpythonPractice> git cz

[email protected], [email protected]

Line 1 will be cropped at 100 characters. All other lines will be wrapped after 100 characters.

? Select the type of change that you're committing: (Use arrow keys)

feat: A new feature

fix: A bug fix

docs: Documentation only changes

style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)

refactor: A code change that neither fixes a bug nor adds a feature

perf: A code change that improves performance

test: Adding missing tests or correcting existing tests

(Move up and down to reveal more choices)

按照提示,你可以寫出規範的message了

idea有插件可以使用git commit template

commitizen同時可以檢查commit message是否符合格式.

生成change log,還又一些進階用法比如ghooks

這裡就不細說了.詳細請檢視參考連結和validate-commit-msg

現在項目中可能多出來dir:node_nodules, file:package.json, package-lock.json這些目錄和檔案,這是node安裝子產品産生的,如果不是node項目都可以忽略掉,熟悉node的同學肯定都知道哪些是有用的了.