Skip to content

Commit 22d8652

Browse files
committed
Parse commit trailers using mail.ParseAddress()
1 parent 17205fa commit 22d8652

File tree

2 files changed

+10
-19
lines changed

2 files changed

+10
-19
lines changed

modules/util/commit_trailers.go

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ package util
66
import (
77
"errors"
88
"net/mail"
9-
"strings"
109
)
1110

1211
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
1716
//
1817
// Foo Bar <[email protected]>
1918
func ParseCommitTrailerValueWithAuthor(value string) (name, email string, err error) {
20-
value = strings.TrimSpace(value)
21-
if !strings.HasSuffix(value, ">") {
22-
return "", "", ErrInvalidCommitTrailerValueSyntax
19+
addr, err := mail.ParseAddress(value)
20+
if err != nil {
21+
return name, email, err
2322
}
2423

25-
closedBracketIdx := len(value) - 1
26-
openBracketIdx := strings.LastIndex(value, "<")
27-
if openBracketIdx == -1 {
28-
return "", "", ErrInvalidCommitTrailerValueSyntax
24+
if addr.Name == "" {
25+
return name, email, errors.New("commit trailer missing name")
2926
}
3027

31-
email = value[openBracketIdx+1 : closedBracketIdx]
32-
if _, err := mail.ParseAddress(email); err != nil {
33-
return "", "", ErrInvalidCommitTrailerValueSyntax
34-
}
35-
36-
name = strings.TrimSpace(value[:openBracketIdx])
37-
if len(name) == 0 {
38-
return "", "", ErrInvalidCommitTrailerValueSyntax
39-
}
28+
name = addr.Name
29+
email = addr.Address
4030

4131
return name, email, nil
4232
}

modules/util/commit_trailers_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,16 @@ func TestParseCommitTrailerValueWithAuthor(t *testing.T) {
2424
{" <[email protected]>", true, "", ""},
2525
{"Foo Bar <[email protected]>", false, "Foo Bar", "[email protected]"},
2626
{" Foo Bar <[email protected]>", false, "Foo Bar", "[email protected]"},
27-
// Account for edge case where name contains an open bracket.
28-
{" Foo < Bar <[email protected]>", false, "Foo < Bar", "[email protected]"},
2927
}
3028

3129
for n, c := range cases {
3230
name, email, err := ParseCommitTrailerValueWithAuthor(c.input)
3331
if c.shouldBeError {
3432
assert.Error(t, err, "case %d should be a syntax error", n)
3533
} else {
34+
if err != nil {
35+
assert.Fail(t, "did not expect an error: %v", err)
36+
}
3637
assert.Equal(t, c.expectedName, name, "case %d should have correct name", n)
3738
assert.Equal(t, c.expectedEmail, email, "case %d should have correct email", n)
3839
}

0 commit comments

Comments
 (0)