Skip to content

Commit

Permalink
Add regexp support to gopass grep (#1544)
Browse files Browse the repository at this point in the history
Fixes #1543

RELEASE_NOTES=[ENHANCEMENT] Add regexp support to gopass grep

Signed-off-by: Dominik Schulz <[email protected]>
  • Loading branch information
dominikschulz authored Aug 22, 2020
1 parent 66c83e6 commit 66848af
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 11 deletions.
7 changes: 7 additions & 0 deletions internal/action/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,13 @@ func (s *Action) GetCommands() []*cli.Command {
Before: s.Initialized,
Action: s.Grep,
Hidden: true,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "regexp",
Aliases: []string{"r"},
Usage: "Interpret pattern as RE2 regular expression",
},
},
},
{
Name: "history",
Expand Down
15 changes: 14 additions & 1 deletion internal/action/grep.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package action

import (
"regexp"
"strings"

"github.com/gopasspw/gopass/internal/out"
Expand All @@ -25,6 +26,18 @@ func (s *Action) Grep(c *cli.Context) error {
return ExitError(ExitList, err, "failed to list store: %s", err)
}

matchFn := func(haystack string) bool {
return strings.Contains(haystack, needle)
}

if c.Bool("regexp") {
re, err := regexp.Compile(needle)
if err != nil {
return ExitError(ExitUsage, err, "failed to compile regexp '%s': %s", needle, err)
}
matchFn = re.MatchString
}

var matches int
var errors int
for _, v := range haystack {
Expand All @@ -34,7 +47,7 @@ func (s *Action) Grep(c *cli.Context) error {
continue
}

if strings.Contains(string(sec.Bytes()), needle) {
if matchFn(string(sec.Bytes())) {
out.Print(ctx, "%s matches", color.BlueString(v))
}
}
Expand Down
33 changes: 23 additions & 10 deletions internal/action/grep_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,27 @@ func TestGrep(t *testing.T) {
}()

c := gptest.CliCtx(ctx, t, "foo")
assert.NoError(t, act.Grep(c))
buf.Reset()

// add some secret
sec := secret.New()
sec.Set("password", "foobar")
sec.WriteString("foobar")
assert.NoError(t, act.Store.Set(ctx, "foo", sec))
assert.NoError(t, act.Grep(c))
buf.Reset()
t.Run("empty store", func(t *testing.T) {
defer buf.Reset()
assert.NoError(t, act.Grep(c))
})

t.Run("add some secret", func(t *testing.T) {
defer buf.Reset()
sec := secret.New()
sec.Set("password", "foobar")
sec.WriteString("foobar")
assert.NoError(t, act.Store.Set(ctx, "foo", sec))
})

t.Run("should find existing", func(t *testing.T) {
defer buf.Reset()
assert.NoError(t, act.Grep(c))
})

t.Run("RE2", func(t *testing.T) {
defer buf.Reset()
c := gptest.CliCtxWithFlags(ctx, t, map[string]string{"regexp": "true"}, "f..bar")
assert.NoError(t, act.Grep(c))
})
}

0 comments on commit 66848af

Please sign in to comment.