|
| 1 | +package messageregexp |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "regexp" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/vbatts/git-validation/git" |
| 9 | + "github.com/vbatts/git-validation/validate" |
| 10 | +) |
| 11 | + |
| 12 | +func init() { |
| 13 | + validate.RegisterRule(RegexpRule) |
| 14 | +} |
| 15 | + |
| 16 | +var ( |
| 17 | + // RegexpRule for validating a user provided regex on the commit messages |
| 18 | + RegexpRule = validate.Rule{ |
| 19 | + Name: "message_regexp", |
| 20 | + Description: "checks the commit message for a user provided regular expression", |
| 21 | + Run: ValidateMessageRegexp, |
| 22 | + Default: false, // only for users specifically calling it through -run ... |
| 23 | + } |
| 24 | +) |
| 25 | + |
| 26 | +// ValidateMessageRegexp is the message regex func to run |
| 27 | +func ValidateMessageRegexp(r validate.Rule, c git.CommitEntry) (vr validate.Result) { |
| 28 | + if r.Value == "" { |
| 29 | + vr.Pass = true |
| 30 | + vr.Msg = "noop: message_regexp value is blank" |
| 31 | + return vr |
| 32 | + } |
| 33 | + |
| 34 | + re := regexp.MustCompile(r.Value) |
| 35 | + vr.CommitEntry = c |
| 36 | + if len(strings.Split(c["parent"], " ")) > 1 { |
| 37 | + vr.Pass = true |
| 38 | + vr.Msg = "merge commits are not checked for message_regexp" |
| 39 | + return vr |
| 40 | + } |
| 41 | + |
| 42 | + hasValid := false |
| 43 | + for _, line := range strings.Split(c["subject"], "\n") { |
| 44 | + if re.MatchString(line) { |
| 45 | + hasValid = true |
| 46 | + } |
| 47 | + } |
| 48 | + for _, line := range strings.Split(c["body"], "\n") { |
| 49 | + if re.MatchString(line) { |
| 50 | + hasValid = true |
| 51 | + } |
| 52 | + } |
| 53 | + if !hasValid { |
| 54 | + vr.Pass = false |
| 55 | + vr.Msg = fmt.Sprintf("commit message does not match %q", r.Value) |
| 56 | + } else { |
| 57 | + vr.Pass = true |
| 58 | + vr.Msg = fmt.Sprintf("commit message matches %q", r.Value) |
| 59 | + } |
| 60 | + return vr |
| 61 | +} |
0 commit comments