Skip to content

Commit

Permalink
fix numeric extract on optional groups
Browse files Browse the repository at this point in the history
  • Loading branch information
choffmeister committed Dec 9, 2021
1 parent 5c7a152 commit e6c73f6
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
12 changes: 12 additions & 0 deletions internal/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,10 @@ func (str LexicographicExtractStrategy) IsCompatible(v1 string, v2 string) bool

func (str NumericExtractStrategy) IsValid(v string) bool {
vi, ve := strconv.Atoi(v)
if v == "" {
vi = 0
ve = nil
}
return ve == nil && vi >= 0
}

Expand All @@ -210,6 +214,14 @@ func (str NumericExtractStrategy) Compare(v1 string, v2 string) int {
}
v1i, v1e := strconv.Atoi(v1)
v2i, v2e := strconv.Atoi(v2)
if v1 == "" {
v1i = 0
v1e = nil
}
if v2 == "" {
v2i = 0
v2e = nil
}
if v1e != nil {
return -1
}
Expand Down
42 changes: 41 additions & 1 deletion internal/policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,28 @@ func TestPolicyParse(t *testing.T) {
if assert.NoError(t, err) {
assert.Equal(t, &[]string{"123"}, actual)
}

p5 := Policy{
Pattern: regexp.MustCompile(`^(?P<major>\d+)(\.(?P<minor>\d+))?$`),
Extracts: []Extract{
{
Value: "<major>",
Strategy: NumericExtractStrategy{},
},
{
Value: "<minor>",
Strategy: NumericExtractStrategy{},
},
},
}
actual, err = p5.Parse("1", "", "")
if assert.NoError(t, err) {
assert.Equal(t, &[]string{"1", ""}, actual)
}
actual, err = p5.Parse("1.2", "", "")
if assert.NoError(t, err) {
assert.Equal(t, &[]string{"1", "2"}, actual)
}
}

func TestPolicyFilterAndSort(t *testing.T) {
Expand Down Expand Up @@ -118,6 +140,24 @@ func TestPolicyFilterAndSort(t *testing.T) {
if assert.NoError(t, err) {
assert.Equal(t, strings.Split("2.10-a 2.10 2.1 1.10-c 1.10-b 1.10-a 1.10 1.2", " "), *actual)
}

p3 := Policy{
Pattern: regexp.MustCompile(`^(?P<major>\d+)(\.(?P<minor>\d+))?$`),
Extracts: []Extract{
{
Value: "<major>",
Strategy: NumericExtractStrategy{},
},
{
Value: "<minor>",
Strategy: NumericExtractStrategy{},
},
},
}
actual, err = p3.FilterAndSort("1.2", strings.Split("1.0 2 1 1.1 1.2 1.3 2.0", " "), "", "")
if assert.NoError(t, err) {
assert.Equal(t, strings.Split("2.0 2 1.3 1.2 1.1 1.0 1", " "), *actual)
}
}

func TestPolicyFindNext(t *testing.T) {
Expand Down Expand Up @@ -211,7 +251,7 @@ func TestNumericSortStrategyIsValid(t *testing.T) {
assert.Equal(t, true, str.IsValid("2"))
assert.Equal(t, false, str.IsValid("-1"))
assert.Equal(t, false, str.IsValid("a"))
assert.Equal(t, false, str.IsValid(""))
assert.Equal(t, true, str.IsValid(""))
}

func TestNumericSortStrategyCompare(t *testing.T) {
Expand Down

0 comments on commit e6c73f6

Please sign in to comment.