Created
October 28, 2018 02:45
-
-
Save suyanhanx/48d65e3e5785370f327a984bac3b9809 to your computer and use it in GitHub Desktop.
a commit message check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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