-
Notifications
You must be signed in to change notification settings - Fork 0
/
menu.go
61 lines (55 loc) · 1.18 KB
/
menu.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
package main
import (
"fmt"
"io/fs"
"path/filepath"
"strings"
)
type MenuItem struct {
Title string
Path string
IsDir bool
Items []MenuItem
}
func NewMenuFromFs(filesystem fs.FS) ([]MenuItem, error) {
return menuEntries(filesystem, ".")
}
// todo: rewrite this so it only parses sections and pages.
func menuEntries(filesystem fs.FS, dir string) ([]MenuItem, error) {
entries, err := fs.ReadDir(filesystem, dir)
if err != nil {
return nil, fmt.Errorf("could not read files in directory %s: %w", dir, err)
}
var items []MenuItem
for _, e := range entries {
var item MenuItem
if e.IsDir() {
p := filepath.Join(dir, e.Name())
sub, err := menuEntries(filesystem, p)
if err != nil {
return nil, err
}
if len(sub) == 0 {
continue
}
item = MenuItem{
Title: stripNumberDotPrefix(e.Name()),
Path: p,
IsDir: true,
Items: sub,
}
} else {
if filepath.Ext(e.Name()) != ".md" {
continue
}
item = MenuItem{
Title: stripNumberDotPrefix(strings.TrimSuffix(e.Name(), filepath.Ext(e.Name()))),
Path: filepath.Join(dir, e.Name()),
IsDir: false,
Items: nil,
}
}
items = append(items, item)
}
return items, nil
}