Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a commit message check
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"
)
const CommitMessagePattern = `^(feature|fix|hotfix|other|add|change)(\(.+\))?(:|:)?( |\/).{1,80}|^(Revert |Merge branch )?(.*)`
const checkFailedMessage = `
Commit message style check failed!
Please rewrite commit message.
Example:
feature(test) test commit style check.`
// 是否开启严格模式,严格模式下将校验所有的提交信息格式(多 commit 下)
const strictMode = true
var commitMsgReg = regexp.MustCompile(CommitMessagePattern)
func main() {
input, _ := ioutil.ReadAll(os.Stdin)
param := strings.Fields(string(input))
// allow branch/tag delete
// 在一个repo第一次提交时是没有前置提交的。所以也是空提交
// 空提交的id是以下这个
if param[1] == "0000000000000000000000000000000000000000" || param[0] == "0000000000000000000000000000000000000000" {
os.Exit(0)
}
commitMsg := getCommitMsg(param[0], param[1])
for _, tmpStr := range commitMsg {
commitTypes := commitMsgReg.FindAllStringSubmatch(tmpStr, -1)
if len(commitTypes) != 1 {
checkFailed()
}
if !strictMode {
os.Exit(0)
}
}
}
func getCommitMsg(odlCommitID, commitID string) []string {
getCommitMsgCmd := exec.Command("git", "log", odlCommitID+"..."+commitID, "--pretty=format:%s")
getCommitMsgCmd.Stdin = os.Stdin
getCommitMsgCmd.Stderr = os.Stderr
b, err := getCommitMsgCmd.Output()
if err != nil {
fmt.Print(err)
os.Exit(1)
}
commitMsg := strings.Split(string(b), "\n")
return commitMsg
}
func checkFailed() {
fmt.Fprintln(os.Stderr, checkFailedMessage)
os.Exit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment