0
0
Fork 0
mirror of https://github.com/go-gitea/gitea synced 2024-11-21 23:21:08 +01:00

Parse commit trailers using mail.ParseAddress()

This commit is contained in:
Kemal Zebari 2024-10-25 22:48:32 -07:00
parent 17205fa1d3
commit 22d8652f64
2 changed files with 10 additions and 19 deletions

View file

@ -6,7 +6,6 @@ package util
import (
"errors"
"net/mail"
"strings"
)
var ErrInvalidCommitTrailerValueSyntax = errors.New("syntax error occurred while parsing a commit trailer value")
@ -17,26 +16,17 @@ var ErrInvalidCommitTrailerValueSyntax = errors.New("syntax error occurred while
//
// Foo Bar <foobar@example.com>
func ParseCommitTrailerValueWithAuthor(value string) (name, email string, err error) {
value = strings.TrimSpace(value)
if !strings.HasSuffix(value, ">") {
return "", "", ErrInvalidCommitTrailerValueSyntax
addr, err := mail.ParseAddress(value)
if err != nil {
return name, email, err
}
closedBracketIdx := len(value) - 1
openBracketIdx := strings.LastIndex(value, "<")
if openBracketIdx == -1 {
return "", "", ErrInvalidCommitTrailerValueSyntax
if addr.Name == "" {
return name, email, errors.New("commit trailer missing name")
}
email = value[openBracketIdx+1 : closedBracketIdx]
if _, err := mail.ParseAddress(email); err != nil {
return "", "", ErrInvalidCommitTrailerValueSyntax
}
name = strings.TrimSpace(value[:openBracketIdx])
if len(name) == 0 {
return "", "", ErrInvalidCommitTrailerValueSyntax
}
name = addr.Name
email = addr.Address
return name, email, nil
}

View file

@ -24,8 +24,6 @@ func TestParseCommitTrailerValueWithAuthor(t *testing.T) {
{" <foobar@example.com>", true, "", ""},
{"Foo Bar <foobar@example.com>", false, "Foo Bar", "foobar@example.com"},
{" Foo Bar <foobar@example.com>", false, "Foo Bar", "foobar@example.com"},
// Account for edge case where name contains an open bracket.
{" Foo < Bar <foobar@example.com>", false, "Foo < Bar", "foobar@example.com"},
}
for n, c := range cases {
@ -33,6 +31,9 @@ func TestParseCommitTrailerValueWithAuthor(t *testing.T) {
if c.shouldBeError {
assert.Error(t, err, "case %d should be a syntax error", n)
} else {
if err != nil {
assert.Fail(t, "did not expect an error: %v", err)
}
assert.Equal(t, c.expectedName, name, "case %d should have correct name", n)
assert.Equal(t, c.expectedEmail, email, "case %d should have correct email", n)
}