Skip to content

Commit

Permalink
[options] Added method 'Is' for checking argument value
Browse files Browse the repository at this point in the history
  • Loading branch information
andyone committed Jun 28, 2022
1 parent da11fc6 commit d7feed1
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### 12.49.0

* `[options]` Added method `Is` for checking argument value
* `[options]` Fix bug with filtering unexpanded globs

### 12.48.0
Expand Down
25 changes: 25 additions & 0 deletions options/arguments.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,31 @@ func (a Argument) String() string {
return string(a)
}

// Is returns true if argument equals to given value
func (a Argument) Is(value interface{}) bool {
switch t := value.(type) {
case string:
return a.String() == t
case int:
v, err := a.Int()
return v == t && err == nil
case int64:
v, err := a.Int64()
return v == t && err == nil
case uint64:
v, err := a.Uint()
return v == t && err == nil
case float64:
v, err := a.Float()
return v == t && err == nil
case bool:
v, err := a.Bool()
return v == t && err == nil
}

return false
}

// Int converts argument to int
func (a Argument) Int() (int, error) {
return strconv.Atoi(string(a))
Expand Down
15 changes: 15 additions & 0 deletions options/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,21 @@ func (s *OptUtilSuite) TestArgumentsConvertion(c *C) {
c.Assert(a.Get(3).String(), Equals, "true")
c.Assert(a.Get(4).String(), Equals, "")

c.Assert(a.Get(0).Is("test"), Equals, true)
c.Assert(a.Get(0).Is("abcd"), Equals, false)
c.Assert(a.Get(1).Is(6), Equals, true)
c.Assert(a.Get(1).Is(12), Equals, false)
c.Assert(a.Get(1).Is(int64(6)), Equals, true)
c.Assert(a.Get(1).Is(int64(12)), Equals, false)
c.Assert(a.Get(1).Is(uint64(6)), Equals, true)
c.Assert(a.Get(1).Is(uint64(12)), Equals, false)
c.Assert(a.Get(2).Is(2.67), Equals, true)
c.Assert(a.Get(2).Is(3.14), Equals, false)
c.Assert(a.Get(3).Is(true), Equals, true)
c.Assert(a.Get(3).Is(false), Equals, false)

c.Assert(a.Get(0).Is([]string{}), Equals, false)

vi, err := a.Get(0).Int()
c.Assert(err, NotNil)
c.Assert(err, ErrorMatches, `strconv.Atoi: parsing "test": invalid syntax`)
Expand Down

0 comments on commit d7feed1

Please sign in to comment.