Skip to content

Commit

Permalink
Added support for regexp flags
Browse files Browse the repository at this point in the history
  • Loading branch information
zealws committed Nov 24, 2015
1 parent 6e0b900 commit 7978600
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
11 changes: 11 additions & 0 deletions flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,14 @@ func TestRequiredWithEnvar(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, 123, *flag)
}

func TestRegexp(t *testing.T) {
app := New("test", "")
flag := app.Flag("reg", "").Regexp()
_, err := app.Parse([]string{"--reg", "^abc$"})
assert.NoError(t, err)
assert.NotNil(t, *flag)
assert.Equal(t, "^abc$", (*flag).String())
assert.Regexp(t, *flag, "abc")
assert.NotRegexp(t, *flag, "abcd")
}
13 changes: 13 additions & 0 deletions parsers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"net"
"net/url"
"os"
"regexp"
"time"

"github.com/alecthomas/units"
Expand Down Expand Up @@ -210,3 +211,15 @@ func (p *parserMixin) Counter() (target *int) {
func (p *parserMixin) CounterVar(target *int) {
p.SetValue(newCounterValue(target))
}

// Regexp
func (p *parserMixin) Regexp() (target **regexp.Regexp) {
target = new(*regexp.Regexp)
p.RegexpVar(target)
return
}

// Regexp
func (p *parserMixin) RegexpVar(target **regexp.Regexp) {
p.SetValue(newRegexpValue(target))
}
29 changes: 29 additions & 0 deletions values.go
Original file line number Diff line number Diff line change
Expand Up @@ -445,3 +445,32 @@ func (c *counterValue) Set(s string) error {
func (c *counterValue) Get() interface{} { return (int)(*c) }
func (c *counterValue) IsBoolFlag() bool { return true }
func (c *counterValue) String() string { return fmt.Sprintf("%d", *c) }

// -- regexp.Regexp value
type regexpValue struct {
r **regexp.Regexp
}

func newRegexpValue(r **regexp.Regexp) *regexpValue {
return &regexpValue{r}
}

func (r *regexpValue) Set(value string) error {
if re, err := regexp.Compile(value); err != nil {
return err
} else {
*r.r = re
return nil
}
}

func (r *regexpValue) Get() interface{} {
return (*regexp.Regexp)(*r.r)
}

func (r *regexpValue) String() string {
if *r.r == nil {
return "<nil>"
}
return (*r.r).String()
}

0 comments on commit 7978600

Please sign in to comment.