/
search.go
98 lines (78 loc) · 2.15 KB
/
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
87
88
89
90
91
92
93
94
95
96
97
98
package commands
import (
"encoding/json"
"io"
"log"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/cjnosal/manifer/v2/lib"
"github.com/cjnosal/manifer/v2/pkg/scenario"
"github.com/cjnosal/manifer/v2/pkg/yaml"
)
type searchCmd struct {
printJson bool
logger *log.Logger
writer io.Writer
manifer lib.Manifer
}
var search searchCmd
func NewSearchCommand(l io.Writer, w io.Writer, m lib.Manifer) *cobra.Command {
search.logger = log.New(l, "", 0)
search.writer = w
search.manifer = m
cobraSearch := &cobra.Command{
Use: "search",
Short: "search scenarios in selected libraries by name and description.",
Long: `search (--library <library path>...) (query...):
search scenarios in selected libraries by name and description.
`,
Args: cobra.MinimumNArgs(1),
Run: search.execute,
TraverseChildren: true,
}
cobraSearch.Flags().StringSliceVarP(&libraryPaths, "library", "l", []string{}, "Path to library file")
cobraSearch.Flags().BoolVarP(&search.printJson, "json", "j", false, "Print output in json format")
return cobraSearch
}
func (p *searchCmd) execute(cmd *cobra.Command, args []string) {
if len(libraryPaths) == 0 {
p.logger.Printf("Library not specified")
p.logger.Printf(cmd.Long)
os.Exit(1)
}
entries, err := p.manifer.ListScenarios(libraryPaths, true)
if err != nil {
p.logger.Printf("%v\n while looking up scenarios", err)
os.Exit(1)
}
matches := []scenario.ScenarioEntry{}
for _, e := range entries {
for _, query := range args {
if strings.Contains(e.Name, query) || strings.Contains(e.Description, query) {
matches = append(matches, e)
break
}
}
}
var outBytes []byte
if p.printJson {
outBytes = p.formatJson(matches)
} else {
outBytes = p.formatYaml(matches)
}
_, err = p.writer.Write(outBytes)
if err != nil {
p.logger.Printf("%v\n while writing search output", err)
os.Exit(1)
}
}
func (p *searchCmd) formatJson(entries []scenario.ScenarioEntry) []byte {
bytes, _ := json.Marshal(entries)
return bytes
}
func (p *searchCmd) formatYaml(entries []scenario.ScenarioEntry) []byte {
yaml := yaml.Yaml{}
bytes, _ := yaml.Marshal(entries)
return bytes
}