cmdList lists all available cheatsheets.
(cmd *cobra.Command, args []string, conf config.Config)
| 19 | |
| 20 | // cmdList lists all available cheatsheets. |
| 21 | func cmdList(cmd *cobra.Command, args []string, conf config.Config) { |
| 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 | // instead of "consolidating" all of the cheatsheets (ie, overwriting global |
| 38 | // sheets with local sheets), here we simply want to create a slice |
| 39 | // containing all sheets. |
| 40 | flattened := []sheet.Sheet{} |
| 41 | for _, pathsheets := range cheatsheets { |
| 42 | for _, s := range pathsheets { |
| 43 | flattened = append(flattened, s) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // sort the "flattened" sheets alphabetically |
| 48 | sort.Slice(flattened, func(i, j int) bool { |
| 49 | return flattened[i].Title < flattened[j].Title |
| 50 | }) |
| 51 | |
| 52 | // filter if <cheatsheet> was specified |
| 53 | if len(args) > 0 { |
| 54 | |
| 55 | // initialize a slice of filtered sheets |
| 56 | filtered := []sheet.Sheet{} |
| 57 | |
| 58 | // initialize our filter pattern |
| 59 | pattern := "(?i)" + args[0] |
| 60 | |
| 61 | // compile the regex |
| 62 | reg, err := regexp.Compile(pattern) |
| 63 | if err != nil { |
| 64 | fmt.Fprintf(os.Stderr, "failed to compile regexp: %s, %v\n", pattern, err) |
| 65 | os.Exit(1) |
| 66 | } |
| 67 | |
| 68 | // iterate over each cheatsheet, and pass-through those which match the |
| 69 | // filter pattern |
| 70 | for _, s := range flattened { |
| 71 | if reg.MatchString(s.Title) { |
| 72 | filtered = append(filtered, s) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | flattened = filtered |
| 77 | } |
| 78 |