forked from knqyf263/pet
/
util.go
84 lines (73 loc) · 1.88 KB
/
util.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
package cmd
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strings"
"github.com/fatih/color"
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/dialog"
"github.com/knqyf263/pet/snippet"
)
func editFile(command, file string) error {
command += " " + file
return run(command, os.Stdin, os.Stdout)
}
func run(command string, r io.Reader, w io.Writer) error {
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.Command("cmd", "/c", command)
} else {
cmd = exec.Command("sh", "-c", command)
}
cmd.Stderr = os.Stderr
cmd.Stdout = w
cmd.Stdin = r
return cmd.Run()
}
func filter(options []string) (commands []string, err error) {
var snippets snippet.Snippets
if err := snippets.Load(); err != nil {
return commands, fmt.Errorf("Load snippet failed: %v", err)
}
snippetTexts := map[string]snippet.SnippetInfo{}
var text string
for _, s := range snippets.Snippets {
t := fmt.Sprintf("[%s]: %s", s.Description, s.Command)
tags := ""
for _, tag := range s.Tag {
tags += fmt.Sprintf(" #%s", tag)
}
t += tags
snippetTexts[t] = s
if config.Flag.Color {
t = fmt.Sprintf("[%s]: %s",
color.RedString(s.Description), s.Command)
}
text += t + "\n"
}
var buf bytes.Buffer
selectCmd := fmt.Sprintf("%s %s",
config.Conf.General.SelectCmd, strings.Join(options, " "))
err = run(selectCmd, strings.NewReader(text), &buf)
if err != nil {
return nil, nil
}
lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
params := dialog.SearchForParams(lines)
if params != nil {
snippetInfo := snippetTexts[lines[0]]
dialog.CurrentCommand = snippetInfo.Command
dialog.GenerateParamsLayout(params, dialog.CurrentCommand)
res := []string{dialog.FinalCommand}
return res, nil
}
for _, line := range lines {
snippetInfo := snippetTexts[line]
commands = append(commands, fmt.Sprint(snippetInfo.Command))
}
return commands, nil
}