MCPcopy Index your code
hub / github.com/cheat/cheat / cmdSearch

Function cmdSearch

cmd/cheat/cmd_search.go:17–100  ·  view source on GitHub ↗

cmdSearch searches for strings in cheatsheets.

(cmd *cobra.Command, args []string, conf config.Config)

Source from the content-addressed store, hash-verified

15
16// cmdSearch searches for strings in cheatsheets.
17func cmdSearch(cmd *cobra.Command, args []string, conf config.Config) {
18
19 phrase, _ := cmd.Flags().GetString("search")
20 colorize, _ := cmd.Flags().GetBool("colorize")
21 useRegex, _ := cmd.Flags().GetBool("regex")
22
23 // load the cheatsheets
24 cheatsheets, err := sheets.Load(conf.Cheatpaths)
25 if err != nil {
26 fmt.Fprintf(os.Stderr, "failed to list cheatsheets: %v\n", err)
27 os.Exit(1)
28 }
29 if cmd.Flags().Changed("tag") {
30 tagVal, _ := cmd.Flags().GetString("tag")
31 cheatsheets = sheets.Filter(
32 cheatsheets,
33 strings.Split(tagVal, ","),
34 )
35 }
36
37 // prepare the search pattern
38 pattern := "(?i)" + phrase
39
40 // unless --regex is provided, in which case we pass the regex unaltered
41 if useRegex {
42 pattern = phrase
43 }
44
45 // compile the regex once, outside the loop
46 reg, err := regexp.Compile(pattern)
47 if err != nil {
48 fmt.Fprintf(os.Stderr, "failed to compile regexp: %s, %v\n", pattern, err)
49 os.Exit(1)
50 }
51
52 // iterate over each cheatpath
53 out := ""
54 for _, pathcheats := range cheatsheets {
55
56 // sort the cheatsheets alphabetically, and search for matches
57 for _, sheet := range sheets.Sort(pathcheats) {
58
59 // if <cheatsheet> was provided, constrain the search only to
60 // matching cheatsheets
61 if len(args) > 0 && sheet.Title != args[0] {
62 continue
63 }
64
65 // `Search` will return text entries that match the search terms.
66 // We're using it here to overwrite the prior cheatsheet Text,
67 // filtering it to only what is relevant.
68 sheet.Text = sheet.Search(reg)
69
70 // if the sheet did not match the search, ignore it and move on
71 if sheet.Text == "" {
72 continue
73 }
74

Callers 1

runFunction · 0.85

Calls 9

LoadFunction · 0.92
FilterFunction · 0.92
SortFunction · 0.92
FaintFunction · 0.92
IndentFunction · 0.92
WriteFunction · 0.92
SearchMethod · 0.80
ColorMethod · 0.80
ColorizeMethod · 0.80

Tested by

no test coverage detected