From d7feed13b23efc8d16629325631040630c119267 Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Tue, 28 Jun 2022 11:03:39 +0300 Subject: [PATCH] [options] Added method 'Is' for checking argument value --- CHANGELOG.md | 1 + options/arguments.go | 25 +++++++++++++++++++++++++ options/options_test.go | 15 +++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9fb3503..821495a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/options/arguments.go b/options/arguments.go index 69306ebe..461edefe 100644 --- a/options/arguments.go +++ b/options/arguments.go @@ -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)) diff --git a/options/options_test.go b/options/options_test.go index 9137e412..4e8afdef 100644 --- a/options/options_test.go +++ b/options/options_test.go @@ -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`)