From 22d8652f6464942b492f69baa35b637e4d8ceb3b Mon Sep 17 00:00:00 2001 From: Kemal Zebari Date: Fri, 25 Oct 2024 22:48:32 -0700 Subject: [PATCH] Parse commit trailers using `mail.ParseAddress()` --- modules/util/commit_trailers.go | 24 +++++++----------------- modules/util/commit_trailers_test.go | 5 +++-- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/modules/util/commit_trailers.go b/modules/util/commit_trailers.go index 9c6547d0cd..62b3c8305e 100644 --- a/modules/util/commit_trailers.go +++ b/modules/util/commit_trailers.go @@ -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 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 } diff --git a/modules/util/commit_trailers_test.go b/modules/util/commit_trailers_test.go index fe9b64d896..f5ab2e6449 100644 --- a/modules/util/commit_trailers_test.go +++ b/modules/util/commit_trailers_test.go @@ -24,8 +24,6 @@ func TestParseCommitTrailerValueWithAuthor(t *testing.T) { {" ", true, "", ""}, {"Foo Bar ", false, "Foo Bar", "foobar@example.com"}, {" Foo Bar ", false, "Foo Bar", "foobar@example.com"}, - // Account for edge case where name contains an open bracket. - {" Foo < Bar ", 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) }