-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
grep.go
63 lines (51 loc) · 1.44 KB
/
grep.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package action
import (
"regexp"
"strings"
"github.com/fatih/color"
"github.com/gopasspw/gopass/internal/action/exit"
"github.com/gopasspw/gopass/internal/out"
"github.com/gopasspw/gopass/internal/tree"
"github.com/gopasspw/gopass/pkg/ctxutil"
"github.com/urfave/cli/v2"
)
// Grep searches a string inside the content of all files.
func (s *Action) Grep(c *cli.Context) error {
ctx := ctxutil.WithGlobalFlags(c)
if !c.Args().Present() {
return exit.Error(exit.Usage, nil, "Usage: %s grep arg", s.Name)
}
// get the search term.
needle := c.Args().First()
haystack, err := s.Store.List(ctx, tree.INF)
if err != nil {
return exit.Error(exit.List, 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 exit.Error(exit.Usage, err, "failed to compile regexp %q: %s", needle, err)
}
matchFn = re.MatchString
}
var matches int
var errors int
for _, v := range haystack {
sec, err := s.Store.Get(ctx, v)
if err != nil {
out.Errorf(ctx, "failed to decrypt %s: %v", v, err)
continue
}
if matchFn(string(sec.Bytes())) {
out.Printf(ctx, "%s matches", color.BlueString(v))
}
}
if errors > 0 {
out.Warningf(ctx, "%d secrets failed to decrypt", errors)
}
out.Printf(ctx, "\nScanned %d secrets. %d matches, %d errors", len(haystack), matches, errors)
return nil
}