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