cmdSearch searches for strings in cheatsheets.
(cmd *cobra.Command, args []string, conf config.Config)
| 15 | |
| 16 | // cmdSearch searches for strings in cheatsheets. |
| 17 | func 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 |