Skip to content

Commit

Permalink
Wrap parsing error to allow caller to discern why things failed
Browse files Browse the repository at this point in the history
It's hard to reason with errors when `strconv.ParseUint` fails as
the returned error is untyped. This change wraps the parsing error.

Signed-off-by: crozzy <[email protected]>
  • Loading branch information
crozzy committed Nov 19, 2024
1 parent 1558ca3 commit b40b53a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
6 changes: 3 additions & 3 deletions version.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,13 @@ func NewVersion(v string) (*Version, error) {
var err error
sv.major, err = strconv.ParseUint(m[1], 10, 64)
if err != nil {
return nil, fmt.Errorf("Error parsing version segment: %s", err)
return nil, fmt.Errorf("error parsing version segment: %w", err)
}

if m[2] != "" {
sv.minor, err = strconv.ParseUint(m[2], 10, 64)
if err != nil {
return nil, fmt.Errorf("Error parsing version segment: %s", err)
return nil, fmt.Errorf("error parsing version segment: %w", err)
}
} else {
sv.minor = 0
Expand All @@ -171,7 +171,7 @@ func NewVersion(v string) (*Version, error) {
if m[3] != "" {
sv.patch, err = strconv.ParseUint(m[3], 10, 64)
if err != nil {
return nil, fmt.Errorf("Error parsing version segment: %s", err)
return nil, fmt.Errorf("error parsing version segment: %w", err)
}
} else {
sv.patch = 0
Expand Down
30 changes: 30 additions & 0 deletions version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package semver
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"strconv"
"testing"
)

Expand Down Expand Up @@ -193,6 +195,34 @@ func TestOriginal(t *testing.T) {
}
}

func TestErrors(t *testing.T) {
tests := map[string]error{
"1.3.2023080721291691443750": strconv.ErrRange,
"1.2.3.4.5": ErrInvalidSemVer,
"": ErrInvalidSemVer,
"1.2.0+invalid_metadata": ErrInvalidSemVer,
}
for v, e := range tests {
_, err := NewVersion(v)
if !errors.Is(err, e) {
t.Errorf("Expecting error: %s but got: %s, version %s", e, err, v)
}
}

strictTests := map[string]error{
"1.3.2023080721291691443750": strconv.ErrRange,
"1.2.3.4.5": ErrInvalidCharacters,
"": ErrEmptyString,
"1.2.0+invalid$metadata": ErrInvalidMetadata,
}
for v, e := range strictTests {
_, err := StrictNewVersion(v)
if !errors.Is(err, e) {
t.Errorf("Expecting error: %s but got: %s, version: %s", e, err, v)
}
}
}

func TestParts(t *testing.T) {
v, err := NewVersion("1.2.3-beta.1+build.123")
if err != nil {
Expand Down

0 comments on commit b40b53a

Please sign in to comment.