-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmd_search.go
86 lines (73 loc) · 1.57 KB
/
cmd_search.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strings"
"github.com/olekukonko/tablewriter"
)
var cmdSearch = &Command{
Run: runSearch,
UsageLine: "search",
Short: "Search keywords",
Long: `Search keywords interactively (default filtering tool: peco)`,
}
func runSearch(ctx context, args []string) error {
cfg, err := GetConfig()
if err != nil {
return err
}
err = Initialize(cfg)
if err != nil {
return err
}
is, err := LoadItemsWithConfig(cfg)
if err != nil {
return err
}
if is.HasMaster() {
if err = confirmMasterPassword(is.Master()); err != nil {
return err
}
}
if len(is) == 0 {
_, err = fmt.Fprintln(ctx.out, "no password.")
return err
}
buf := &bytes.Buffer{}
err = runCommand(cfg.FilteringCommand, strings.NewReader(filteringText(is)), buf)
if err != nil {
return err
}
name := strings.TrimSpace(strings.Split(buf.String(), "|")[0])
err = findAndCopy(ctx, is, name)
if err != nil {
return err
}
PrintSuccess(ctx.out, "password of '%s' is copied to clipboard successfully", name)
return nil
}
func filteringText(is Items) string {
buf := &bytes.Buffer{}
tw := tablewriter.NewWriter(buf)
tw.SetColumnSeparator("|")
tw.SetBorder(false)
tw.AppendBulk(is.ToDataTable())
tw.Render()
return buf.String()
}
func runCommand(cmdText string, r io.Reader, w io.Writer) error {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd", "/c", cmdText)
} else {
cmd = exec.Command("sh", "-c", cmdText)
}
cmd.Stderr = os.Stderr
cmd.Stdout = w
cmd.Stdin = r
return cmd.Run()
}