2020-11-09 08:46:42 +00:00
|
|
|
package convention
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/haunt98/changeloguru/pkg/git"
|
|
|
|
)
|
|
|
|
|
|
|
|
// https://www.conventionalcommits.org/en/v1.0.0/
|
|
|
|
// <type>[optional scope]: <description>
|
|
|
|
// [optional body]
|
|
|
|
// [optional footer(s)]
|
|
|
|
|
|
|
|
var (
|
|
|
|
headerRegex = regexp.MustCompile(`(?P<type>[a-zA-Z]+)(?P<scope>\([a-zA-Z]+\))?(?P<attention>!)?:\s(?P<description>.+)`)
|
|
|
|
)
|
|
|
|
|
|
|
|
type Commit struct {
|
2020-11-10 10:07:34 +00:00
|
|
|
RawHeader string
|
|
|
|
Type string
|
2020-11-09 08:46:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewCommit(c git.Commit) (result Commit, err error) {
|
2020-11-09 09:29:27 +00:00
|
|
|
message := strings.TrimSpace(c.Message)
|
|
|
|
messages := strings.Split(message, "\n")
|
2020-11-09 08:46:42 +00:00
|
|
|
if len(messages) == 0 {
|
|
|
|
err = errors.New("empty commit")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
header := messages[0]
|
|
|
|
if err = parseHeader(header, &result); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseHeader(header string, commit *Commit) error {
|
|
|
|
if !headerRegex.MatchString(header) {
|
|
|
|
return errors.New("wrong header format")
|
|
|
|
}
|
|
|
|
|
2020-11-10 08:47:54 +00:00
|
|
|
commit.RawHeader = header
|
|
|
|
|
2020-11-09 08:46:42 +00:00
|
|
|
headerSubmatches := headerRegex.FindStringSubmatch(header)
|
|
|
|
|
|
|
|
commit.Type = headerSubmatches[1]
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|