Load produces a map of cheatsheet titles to filesystem paths
(cheatpaths []cp.Path)
| 13 | |
| 14 | // Load produces a map of cheatsheet titles to filesystem paths |
| 15 | func Load(cheatpaths []cp.Path) ([]map[string]sheet.Sheet, error) { |
| 16 | |
| 17 | // create a slice of maps of sheets. This structure will store all sheets |
| 18 | // that are associated with each cheatpath. |
| 19 | sheets := make([]map[string]sheet.Sheet, len(cheatpaths)) |
| 20 | |
| 21 | // iterate over each cheatpath |
| 22 | for i, cheatpath := range cheatpaths { |
| 23 | |
| 24 | // vivify the map of cheatsheets on this specific cheatpath |
| 25 | pathsheets := make(map[string]sheet.Sheet) |
| 26 | |
| 27 | // recursively iterate over the cheatpath, and load each cheatsheet |
| 28 | // encountered along the way |
| 29 | err := filepath.WalkDir( |
| 30 | cheatpath.Path, func( |
| 31 | path string, |
| 32 | d fs.DirEntry, |
| 33 | err error) error { |
| 34 | |
| 35 | // fail if an error occurred while walking the directory |
| 36 | if err != nil { |
| 37 | return fmt.Errorf("failed to walk path: %v", err) |
| 38 | } |
| 39 | |
| 40 | if d.IsDir() { |
| 41 | // skip .git directories to avoid hundreds/thousands of |
| 42 | // needless syscalls (see repo.GitDir for full history) |
| 43 | if filepath.Base(path) == ".git" { |
| 44 | return fs.SkipDir |
| 45 | } |
| 46 | return nil |
| 47 | } |
| 48 | |
| 49 | // get the base filename |
| 50 | filename := filepath.Base(path) |
| 51 | |
| 52 | // skip hidden files (files that start with a dot) |
| 53 | if strings.HasPrefix(filename, ".") { |
| 54 | return nil |
| 55 | } |
| 56 | |
| 57 | // skip files with extensions (cheatsheets have no extension) |
| 58 | if filepath.Ext(filename) != "" { |
| 59 | return nil |
| 60 | } |
| 61 | |
| 62 | // calculate the cheatsheet's "title" (the phrase with which it may be |
| 63 | // accessed. Eg: `cheat tar` - `tar` is the title) |
| 64 | title := strings.TrimPrefix( |
| 65 | strings.TrimPrefix(path, cheatpath.Path), |
| 66 | string(os.PathSeparator), |
| 67 | ) |
| 68 | |
| 69 | // parse the cheatsheet file into a `sheet` struct |
| 70 | s, err := sheet.New( |
| 71 | title, |
| 72 | cheatpath.Name, |