forked from emad-elsaid/xlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown_fs.go
131 lines (105 loc) · 2.4 KB
/
markdown_fs.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package xlog
import (
"context"
"errors"
"io/fs"
"log/slog"
"os"
"path"
"path/filepath"
"strings"
"sync"
"github.com/emad-elsaid/memoize"
"github.com/emad-elsaid/memoize/cache/adapters/hashicorp"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/rjeczalik/notify"
)
func newMarkdownFS(p string) *markdownFS {
cache, err := lru.New[string, Page](1000)
if err != nil {
slog.Error("Can't create cache for pages", "error", err)
panic("Can't continue without cache instance")
}
m := markdownFS{
cache: cache,
path: p,
}
m._page = memoize.NewWithCache(
hashicorp.LRU(cache),
func(name string) Page {
if name == "" {
name = INDEX
}
return &page{
name: name,
}
},
)
m.watch = sync.OnceFunc(func() {
go func() {
events := make(chan notify.EventInfo, 1)
absPath, err := filepath.Abs(m.path)
if err != nil {
slog.Error("failed to get absolute path", "error", err)
os.Exit(1)
}
if err := notify.Watch(m.path+"/...", events, notify.All); err != nil {
slog.Error("Can't watch files for change", "error", err)
}
defer notify.Stop(events)
for {
switch ei := <-events; ei.Event() {
case notify.Write, notify.Remove, notify.Rename:
relPath, err := filepath.Rel(absPath, ei.Path())
if err != nil {
slog.Error("Can't resolve relative path", "error", err)
continue
}
if !strings.HasSuffix(relPath, ".md") {
continue
}
name := strings.TrimSuffix(relPath, ".md")
cp := m._page(name)
Trigger(Changed, cp)
m.cache.Remove(name)
}
}
}()
})
return &m
}
// MarkdownFS a current directory markdown pages
type markdownFS struct {
path string
cache *lru.Cache[string, Page]
_page func(string) Page
watch func()
}
// Page Creates an instance of Page with name. if no name is passed it's assumed INDEX
func (m *markdownFS) Page(name string) Page {
m.watch()
return m._page(name)
}
func (m *markdownFS) Each(ctx context.Context, f func(Page)) {
filepath.WalkDir(m.path, func(name string, d fs.DirEntry, err error) error {
if d.IsDir() {
for _, v := range ignoredDirs {
if v.MatchString(name) {
return fs.SkipDir
}
}
return nil
}
select {
case <-ctx.Done():
return errors.New("context stopped")
default:
ext := path.Ext(name)
basename := name[:len(name)-len(ext)]
if ext == ".md" {
f(m.Page(basename))
}
}
return nil
})
}