0
0
mirror of https://github.com/thegeeklab/git-sv.git synced 2024-11-25 07:30:38 +00:00
git-sv/sv/message.go

444 lines
12 KiB
Go
Raw Normal View History

package sv
import (
"bufio"
"errors"
"fmt"
"regexp"
"strings"
)
const (
BreakingChangeFooterKey = "BREAKING CHANGE"
BreakingChangeMetadataKey = "breaking-change"
IssueMetadataKey = "issue"
MessageRegexGroupName = "header"
)
var (
errInvalidCommitMessage = errors.New("commit message not valid")
errIssueIDNotFound = errors.New("could not find issue id using configured regex")
errInvalidIssueRegex = errors.New("could not compile issue regex")
errInvalidHeaderRegex = errors.New("invalid regex on header-selector")
)
// CommitMessage is a message using conventional commits.
type CommitMessage struct {
Type string `json:"type,omitempty"`
Scope string `json:"scope,omitempty"`
Description string `json:"description,omitempty"`
Body string `json:"body,omitempty"`
IsBreakingChange bool `json:"isBreakingChange,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
type CommitMessageConfig struct {
Types []string `yaml:"types,flow"`
HeaderSelector string `yaml:"header-selector"`
Scope CommitMessageScopeConfig `yaml:"scope"`
Footer map[string]CommitMessageFooterConfig `yaml:"footer"`
Issue CommitMessageIssueConfig `yaml:"issue"`
}
// IssueFooterConfig config for issue.
func (c CommitMessageConfig) IssueFooterConfig() CommitMessageFooterConfig {
if v, exists := c.Footer[IssueMetadataKey]; exists {
return v
}
return CommitMessageFooterConfig{}
}
// CommitMessageScopeConfig config scope preferences.
type CommitMessageScopeConfig struct {
Values []string `yaml:"values"`
}
// CommitMessageFooterConfig config footer metadata.
type CommitMessageFooterConfig struct {
Key string `yaml:"key"`
KeySynonyms []string `yaml:"key-synonyms,flow"`
UseHash bool `yaml:"use-hash"`
AddValuePrefix string `yaml:"add-value-prefix"`
}
// CommitMessageIssueConfig issue preferences.
type CommitMessageIssueConfig struct {
Regex string `yaml:"regex"`
}
// BranchesConfig branches preferences.
type BranchesConfig struct {
Prefix string `yaml:"prefix"`
Suffix string `yaml:"suffix"`
DisableIssue bool `yaml:"disable-issue"`
Skip []string `yaml:"skip,flow"`
SkipDetached *bool `yaml:"skip-detached"`
}
2021-07-31 19:03:58 +00:00
// NewCommitMessage commit message constructor.
func NewCommitMessage(ctype, scope, description, body, issue, breakingChanges string) CommitMessage {
metadata := make(map[string]string)
if issue != "" {
metadata[IssueMetadataKey] = issue
}
2023-10-12 14:18:25 +00:00
if breakingChanges != "" {
metadata[BreakingChangeMetadataKey] = breakingChanges
}
2023-10-12 14:18:25 +00:00
return CommitMessage{
Type: ctype,
Scope: scope,
Description: description,
Body: body,
IsBreakingChange: breakingChanges != "",
Metadata: metadata,
}
}
// Issue return issue from metadata.
func (m CommitMessage) Issue() string {
return m.Metadata[IssueMetadataKey]
}
// BreakingMessage return breaking change message from metadata.
func (m CommitMessage) BreakingMessage() string {
return m.Metadata[BreakingChangeMetadataKey]
}
2020-12-02 02:15:51 +00:00
// MessageProcessor interface.
type MessageProcessor interface {
SkipBranch(branch string, detached bool) bool
Validate(message string) error
2021-07-31 03:47:58 +00:00
ValidateType(ctype string) error
ValidateScope(scope string) error
ValidateDescription(description string) error
2023-10-12 14:18:25 +00:00
Enhance(branch, message string) (string, error)
2020-12-02 02:15:51 +00:00
IssueID(branch string) (string, error)
Format(msg CommitMessage) (string, string, string)
Parse(subject, body string) (CommitMessage, error)
}
// NewMessageProcessor BaseMessageProcessor constructor.
func NewMessageProcessor(mcfg CommitMessageConfig, bcfg BranchesConfig) *BaseMessageProcessor {
return &BaseMessageProcessor{
messageCfg: mcfg,
branchesCfg: bcfg,
}
}
// BaseMessageProcessor process validate message hook.
type BaseMessageProcessor struct {
messageCfg CommitMessageConfig
branchesCfg BranchesConfig
}
// SkipBranch check if branch should be ignored.
func (p BaseMessageProcessor) SkipBranch(branch string, detached bool) bool {
2023-10-12 14:18:25 +00:00
return contains(branch, p.branchesCfg.Skip) ||
(p.branchesCfg.SkipDetached != nil && *p.branchesCfg.SkipDetached && detached)
}
// Validate commit message.
func (p BaseMessageProcessor) Validate(message string) error {
subject, body := splitCommitMessageContent(message)
msg, parseErr := p.Parse(subject, body)
if parseErr != nil {
return parseErr
}
2021-07-31 20:52:25 +00:00
if !regexp.MustCompile(`^[a-z+]+(\(.+\))?!?: .+$`).MatchString(subject) {
2023-10-12 14:18:25 +00:00
return fmt.Errorf("%w: subject [%s] not valid", errInvalidCommitMessage, subject)
}
2021-07-31 03:47:58 +00:00
if err := p.ValidateType(msg.Type); err != nil {
return err
}
if err := p.ValidateScope(msg.Scope); err != nil {
return err
}
2023-10-12 14:18:25 +00:00
return p.ValidateDescription(msg.Description)
2021-07-31 03:47:58 +00:00
}
// ValidateType check if commit type is valid.
func (p BaseMessageProcessor) ValidateType(ctype string) error {
2021-07-31 03:47:58 +00:00
if ctype == "" || !contains(ctype, p.messageCfg.Types) {
2023-10-12 14:18:25 +00:00
return fmt.Errorf(
"%w: type must be one of [%s]",
errInvalidCommitMessage,
strings.Join(p.messageCfg.Types, ", "),
)
}
2023-10-12 14:18:25 +00:00
2021-07-31 03:47:58 +00:00
return nil
}
// ValidateScope check if commit scope is valid.
func (p BaseMessageProcessor) ValidateScope(scope string) error {
2021-07-31 03:47:58 +00:00
if len(p.messageCfg.Scope.Values) > 0 && !contains(scope, p.messageCfg.Scope.Values) {
2023-10-12 14:18:25 +00:00
return fmt.Errorf(
"%w: scope must one of [%s]",
errInvalidCommitMessage,
strings.Join(p.messageCfg.Scope.Values, ", "),
)
}
2023-10-12 14:18:25 +00:00
2021-07-31 03:47:58 +00:00
return nil
}
// ValidateDescription check if commit description is valid.
func (p BaseMessageProcessor) ValidateDescription(description string) error {
2021-07-31 03:47:58 +00:00
if !regexp.MustCompile("^[a-z]+.*$").MatchString(description) {
2023-10-12 14:18:25 +00:00
return fmt.Errorf("%w: description [%s] must start with lowercase", errInvalidCommitMessage, description)
2021-07-31 03:47:58 +00:00
}
2023-10-12 14:18:25 +00:00
return nil
}
// Enhance add metadata on commit message.
func (p BaseMessageProcessor) Enhance(branch, message string) (string, error) {
2023-10-12 14:18:25 +00:00
if p.branchesCfg.DisableIssue || p.messageCfg.IssueFooterConfig().Key == "" ||
hasIssueID(message, p.messageCfg.IssueFooterConfig()) {
2021-07-31 19:03:58 +00:00
return "", nil // enhance disabled
}
2020-12-02 02:15:51 +00:00
issue, err := p.IssueID(branch)
if err != nil {
return "", err
}
2023-10-12 14:18:25 +00:00
2020-12-02 02:15:51 +00:00
if issue == "" {
2023-10-12 14:18:25 +00:00
return "", errIssueIDNotFound
2020-12-02 02:15:51 +00:00
}
footer := formatIssueFooter(p.messageCfg.IssueFooterConfig(), issue)
if !hasFooter(message) {
2020-12-02 02:15:51 +00:00
return "\n" + footer, nil
}
return footer, nil
}
func formatIssueFooter(cfg CommitMessageFooterConfig, issue string) string {
if !strings.HasPrefix(issue, cfg.AddValuePrefix) {
issue = cfg.AddValuePrefix + issue
}
2023-10-12 14:18:25 +00:00
if cfg.UseHash {
return fmt.Sprintf("%s #%s", cfg.Key, strings.TrimPrefix(issue, "#"))
}
2023-10-12 14:18:25 +00:00
return fmt.Sprintf("%s: %s", cfg.Key, issue)
}
2021-02-14 04:07:07 +00:00
// IssueID try to extract issue id from branch, return empty if not found.
func (p BaseMessageProcessor) IssueID(branch string) (string, error) {
if p.branchesCfg.DisableIssue || p.messageCfg.Issue.Regex == "" {
return "", nil
}
2021-07-31 19:39:38 +00:00
rstr := fmt.Sprintf("^%s(%s)%s$", p.branchesCfg.Prefix, p.messageCfg.Issue.Regex, p.branchesCfg.Suffix)
2023-10-12 14:18:25 +00:00
r, err := regexp.Compile(rstr)
if err != nil {
2023-10-12 14:18:25 +00:00
return "", fmt.Errorf("%w: %s: %v", errInvalidIssueRegex, rstr, err.Error())
}
groups := r.FindStringSubmatch(branch)
2023-10-12 14:18:25 +00:00
if len(groups) != 4 { //nolint:gomnd
2020-12-02 02:15:51 +00:00
return "", nil
}
2023-10-12 14:18:25 +00:00
2020-12-02 02:15:51 +00:00
return groups[2], nil
}
2021-02-14 04:07:07 +00:00
// Format a commit message returning header, body and footer.
func (p BaseMessageProcessor) Format(msg CommitMessage) (string, string, string) {
2020-12-02 02:15:51 +00:00
var header strings.Builder
2023-10-12 14:18:25 +00:00
header.WriteString(msg.Type)
2023-10-12 14:18:25 +00:00
if msg.Scope != "" {
header.WriteString("(" + msg.Scope + ")")
2020-12-02 02:15:51 +00:00
}
2023-10-12 14:18:25 +00:00
2020-12-02 02:15:51 +00:00
header.WriteString(": ")
header.WriteString(msg.Description)
2020-12-02 02:15:51 +00:00
var footer strings.Builder
if msg.BreakingMessage() != "" {
footer.WriteString(fmt.Sprintf("%s: %s", BreakingChangeFooterKey, msg.BreakingMessage()))
2020-12-02 02:15:51 +00:00
}
2023-10-12 14:18:25 +00:00
if issue, exists := msg.Metadata[IssueMetadataKey]; exists && p.messageCfg.IssueFooterConfig().Key != "" {
2020-12-02 02:15:51 +00:00
if footer.Len() > 0 {
footer.WriteString("\n")
}
2023-10-12 14:18:25 +00:00
footer.WriteString(formatIssueFooter(p.messageCfg.IssueFooterConfig(), issue))
}
return header.String(), msg.Body, footer.String()
}
func removeCarriage(commit string) string {
return regexp.MustCompile(`\r`).ReplaceAllString(commit, "")
}
2021-02-14 04:07:07 +00:00
// Parse a commit message.
func (p BaseMessageProcessor) Parse(subject, body string) (CommitMessage, error) {
preparedSubject, err := p.prepareHeader(subject)
m := CommitMessage{}
if err != nil {
return m, err
}
m.Metadata = make(map[string]string)
m.Body = removeCarriage(body)
m.Type, m.Scope, m.Description, m.IsBreakingChange = parseSubjectMessage(preparedSubject)
2023-10-12 14:18:25 +00:00
for key, mdCfg := range p.messageCfg.Footer {
if mdCfg.Key != "" {
prefixes := append([]string{mdCfg.Key}, mdCfg.KeySynonyms...)
for _, prefix := range prefixes {
if tagValue := extractFooterMetadata(prefix, m.Body, mdCfg.UseHash); tagValue != "" {
m.Metadata[key] = tagValue
2023-10-12 14:18:25 +00:00
break
}
}
}
}
2023-10-12 14:18:25 +00:00
if m.IsBreakingChange {
m.Metadata[BreakingChangeMetadataKey] = m.Description
}
if tagValue := extractFooterMetadata(BreakingChangeFooterKey, m.Body, false); tagValue != "" {
m.IsBreakingChange = true
m.Metadata[BreakingChangeMetadataKey] = tagValue
}
return m, nil
}
func (p BaseMessageProcessor) prepareHeader(header string) (string, error) {
if p.messageCfg.HeaderSelector == "" {
return header, nil
}
regex, err := regexp.Compile(p.messageCfg.HeaderSelector)
if err != nil {
2023-10-12 14:18:25 +00:00
return "", fmt.Errorf("%w: %s: %s", errInvalidHeaderRegex, p.messageCfg.HeaderSelector, err.Error())
}
index := regex.SubexpIndex(MessageRegexGroupName)
if index < 0 {
return "", fmt.Errorf("%w: could not find group %s", errInvalidHeaderRegex, MessageRegexGroupName)
}
match := regex.FindStringSubmatch(header)
if match == nil || len(match) < index {
2023-10-12 14:18:25 +00:00
return "", fmt.Errorf(
"%w: could not find group %s in match result for '%s'",
errInvalidHeaderRegex,
MessageRegexGroupName,
2023-10-12 14:18:25 +00:00
header,
)
}
return match[index], nil
}
func parseSubjectMessage(message string) (string, string, string, bool) {
2021-07-31 20:52:25 +00:00
regex := regexp.MustCompile(`([a-z]+)(\((.*)\))?(!)?: (.*)`)
2023-10-12 14:18:25 +00:00
result := regex.FindStringSubmatch(message)
2023-10-12 14:18:25 +00:00
if len(result) != 6 { //nolint:gomnd
return "", "", message, false
}
2023-10-12 14:18:25 +00:00
return result[1], result[3], strings.TrimSpace(result[5]), result[4] == "!"
}
func extractFooterMetadata(key, text string, useHash bool) string {
regex := regexp.MustCompile(key + ": (.*)")
if useHash {
regex = regexp.MustCompile(key + " (#.*)")
}
result := regex.FindStringSubmatch(text)
2023-10-12 14:18:25 +00:00
if len(result) < 2 { //nolint:gomnd
return ""
}
2023-10-12 14:18:25 +00:00
return result[1]
}
func hasFooter(message string) bool {
r := regexp.MustCompile("^[a-zA-Z-]+: .*|^[a-zA-Z-]+ #.*|^" + BreakingChangeFooterKey + ": .*")
scanner := bufio.NewScanner(strings.NewReader(message))
lines := 0
2023-10-12 14:18:25 +00:00
for scanner.Scan() {
if lines > 0 && r.MatchString(scanner.Text()) {
return true
}
lines++
}
return false
}
func hasIssueID(message string, issueConfig CommitMessageFooterConfig) bool {
var r *regexp.Regexp
if issueConfig.UseHash {
r = regexp.MustCompile(fmt.Sprintf("(?m)^%s #.+$", issueConfig.Key))
} else {
r = regexp.MustCompile(fmt.Sprintf("(?m)^%s: .+$", issueConfig.Key))
}
2023-10-12 14:18:25 +00:00
return r.MatchString(message)
}
func contains(value string, content []string) bool {
for _, v := range content {
if value == v {
return true
}
}
2023-10-12 14:18:25 +00:00
return false
}
func splitCommitMessageContent(content string) (string, string) {
scanner := bufio.NewScanner(strings.NewReader(content))
scanner.Scan()
subject := scanner.Text()
var body strings.Builder
2023-10-12 14:18:25 +00:00
first := true
for scanner.Scan() {
if !first {
body.WriteString("\n")
}
2023-10-12 14:18:25 +00:00
body.WriteString(scanner.Text())
2023-10-12 14:18:25 +00:00
first = false
}
return subject, body.String()
}