Debian Codegraph @

hugolib/doctree/support.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package doctree
15
16 import (
17 "fmt"
18 "iter"
19 "strings"
20 "sync"
21
22 radix "github.com/gohugoio/go-radix"
23 "github.com/gohugoio/hugo/common/collections"
24 "github.com/gohugoio/hugo/common/hmaps"
25 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
26 )
27
28 var _ MutableTrees = MutableTrees{}
29
30 const (
31 LockTypeNone LockType = iota
32 LockTypeRead
33 LockTypeWrite
34 )
35
36 // AddEventListener adds an event listener to the tree.
37 // Note that the handler func may not add listeners.
38 func (ctx *WalkContext[T]) AddEventListener(event, path string, handler func(*Event[T])) {
39 ctx.eventHandlersMu.Lock()
40 defer ctx.eventHandlersMu.Unlock()
41
42 if ctx.eventHandlers == nil {
43 ctx.eventHandlers = make(eventHandlers[T])
44 }
45 if ctx.eventHandlers[event] == nil {
46 ctx.eventHandlers[event] = make([]func(*Event[T]), 0)
47 }
48
49 // We want to match all above the path, so we need to exclude any similar named siblings.
50 if !strings.HasSuffix(path, "/") {
51 path += "/"
52 }
53
54 ctx.eventHandlers[event] = append(
55 ctx.eventHandlers[event], func(e *Event[T]) {
56 // Propagate events up the tree only.
57 if e.Path != path && strings.HasPrefix(e.Path, path) {
58 handler(e)
59 }
60 },
61 )
62 }
63
64 func (ctx *WalkContext[T]) Data() *SimpleThreadSafeTree[any] {
65 ctx.dataInit.Do(func() {
66 ctx.data = NewSimpleThreadSafeTree[any]()
67 })
68 return ctx.data
69 }
70
71 func (ctx *WalkContext[T]) initDataRaw() {
72 ctx.dataRawInit.Do(func() {
73 ctx.dataRaw = hmaps.NewCache[sitesmatrix.Vector, *SimpleThreadSafeTree[any]]()
74 })
75 }
76
77 func (ctx *WalkContext[T]) DataRaw(vec sitesmatrix.Vector) *SimpleThreadSafeTree[any] {
78 ctx.initDataRaw()
79 v, _ := ctx.dataRaw.GetOrCreate(vec, func() (*SimpleThreadSafeTree[any], error) {
80 return NewSimpleThreadSafeTree[any](), nil
81 })
82 return v
83 }
84
85 func (ctx *WalkContext[T]) DataRawForEeach() iter.Seq2[sitesmatrix.Vector, *SimpleThreadSafeTree[any]] {
86 ctx.initDataRaw()
87 return func(yield func(vec sitesmatrix.Vector, data *SimpleThreadSafeTree[any]) bool) {
88 ctx.dataRaw.ForEeach(func(vec sitesmatrix.Vector, data *SimpleThreadSafeTree[any]) bool {
89 return yield(vec, data)
90 })
91 }
92 }
93
94 // SendEvent sends an event up the tree.
95 func (ctx *WalkContext[T]) SendEvent(event *Event[T]) {
96 ctx.eventMu.Lock()
97 defer ctx.eventMu.Unlock()
98 ctx.events = append(ctx.events, event)
99 }
100
101 // StopPropagation stops the propagation of the event.
102 func (e *Event[T]) StopPropagation() {
103 e.stopPropagation = true
104 }
105
106 // ValidateKey returns an error if the key is not valid.
107 func ValidateKey(key string) error {
108 if key == "" {
109 // Root node.
110 return nil
111 }
112
113 if len(key) < 2 {
114 return fmt.Errorf("too short key: %q", key)
115 }
116
117 if key[0] != '/' {
118 return fmt.Errorf("key must start with '/': %q", key)
119 }
120
121 if key[len(key)-1] == '/' {
122 return fmt.Errorf("key must not end with '/': %q", key)
123 }
124
125 return nil
126 }
127
128 // Event is used to communicate events in the tree.
129 type Event[T any] struct {
130 Name string
131 Path string
132 Source T
133 stopPropagation bool
134 }
135
136 type LockType int
137
138 // MutableTree is a tree that can be modified.
139 type MutableTree interface {
140 DeleteRaw(key string)
141 DeletePrefix(prefix string) int
142 DeletePrefixRaw(prefix string) int
143 Lock(writable bool)
144 Unlock(writable bool)
145 CanLock() bool // Used for troubleshooting only.
146 }
147
148 // WalkableTree is a tree that can be walked.
149 type WalkableTree[T any] interface {
150 WalkPrefixRaw(prefix string, walker radix.WalkFn[T]) error
151 }
152
153 var _ WalkableTree[any] = (*WalkableTrees[any])(nil)
154
155 type WalkableTrees[T any] []WalkableTree[T]
156
157 func (t WalkableTrees[T]) WalkPrefixRaw(prefix string, walker radix.WalkFn[T]) error {
158 for _, tree := range t {
159 if err := tree.WalkPrefixRaw(prefix, walker); err != nil {
160 return err
161 }
162 }
163 return nil
164 }
165
166 var _ MutableTree = MutableTrees(nil)
167
168 type MutableTrees []MutableTree
169
170 func (t MutableTrees) DeleteRaw(key string) {
171 for _, tree := range t {
172 tree.DeleteRaw(key)
173 }
174 }
175
176 func (t MutableTrees) DeletePrefix(prefix string) int {
177 var count int
178 for _, tree := range t {
179 count += tree.DeletePrefix(prefix)
180 }
181 return count
182 }
183
184 func (t MutableTrees) DeletePrefixRaw(prefix string) int {
185 var count int
186 for _, tree := range t {
187 count += tree.DeletePrefixRaw(prefix)
188 }
189 return count
190 }
191
192 func (t MutableTrees) Lock(writable bool) {
193 for _, tree := range t {
194 tree.Lock(writable)
195 }
196 }
197
198 func (t MutableTrees) Unlock(writable bool) {
199 for _, tree := range t {
200 tree.Unlock(writable)
201 }
202 }
203
204 func (t MutableTrees) CanLock() bool {
205 for _, tree := range t {
206 if !tree.CanLock() {
207 return false
208 }
209 }
210 return true
211 }
212
213 // WalkContext is passed to the Walk callback.
214 type WalkContext[T any] struct {
215 data *SimpleThreadSafeTree[any]
216 dataInit sync.Once
217
218 dataRaw *hmaps.Cache[sitesmatrix.Vector, *SimpleThreadSafeTree[any]]
219 dataRawInit sync.Once
220
221 eventHandlersMu sync.Mutex
222 eventHandlers eventHandlers[T]
223 eventMu sync.Mutex
224 events []*Event[T]
225
226 hooksPostInit sync.Once
227 hooksPost *collections.StackThreadSafe[func() error]
228 }
229
230 type eventHandlers[T any] map[string][]func(*Event[T])
231
232 func cleanKey(key string) string {
233 if key == "/" {
234 // The path to the home page is logically "/",
235 // but for technical reasons, it's stored as "".
236 // This allows us to treat the home page as a section,
237 // and a prefix search for "/" will return the home page's descendants.
238 return ""
239 }
240 return key
241 }
242
243 func (ctx *WalkContext[T]) HandleEvents() error {
244 ctx.eventHandlersMu.Lock()
245 defer ctx.eventHandlersMu.Unlock()
246
247 for len(ctx.events) > 0 {
248 event := ctx.events[0]
249 ctx.events = ctx.events[1:]
250
251 // Loop the event handlers in reverse order so
252 // that events created by the handlers themselves will
253 // be picked up further up the tree.
254 for i := len(ctx.eventHandlers[event.Name]) - 1; i >= 0; i-- {
255 ctx.eventHandlers[event.Name][i](event)
256 if event.stopPropagation {
257 break
258 }
259 }
260 }
261 return nil
262 }
263
264 func (ctx *WalkContext[T]) HooksPost() *collections.StackThreadSafe[func() error] {
265 ctx.hooksPostInit.Do(func() {
266 ctx.hooksPost = collections.NewStackThreadSafe[func() error]()
267 })
268 return ctx.hooksPost
269 }
270
271 func (ctx *WalkContext[T]) HandleEventsAndHooks() error {
272 if err := ctx.HandleEvents(); err != nil {
273 return err
274 }
275
276 for _, hook := range ctx.HooksPost().All() {
277 if err := hook(); err != nil {
278 return err
279 }
280 }
281 return nil
282 }
283
284 func mustValidateKey(key string) string {
285 if err := ValidateKey(key); err != nil {
286 panic(err)
287 }
288 return key
289 }