Debian Codegraph @

hugolib/doctree/nodeshifttree.go

raw
1 // Copyright 2025 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 "context"
18 "fmt"
19 "path"
20 "sync"
21
22 radix "github.com/gohugoio/go-radix"
23 "github.com/gohugoio/hugo/common/hstrings"
24 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
25 "github.com/gohugoio/hugo/resources/resource"
26 )
27
28 type (
29 Config[T any] struct {
30 // Shifter handles tree transformations.
31 Shifter Shifter[T]
32 TransformerRaw Transformer[T]
33 }
34
35 // Shifter handles tree transformations.
36 Shifter[T any] interface {
37 // ForEeachInDimension will call the given function for each value in the given dimension d.
38 // This is typicall used to e.g. walk all language translations of a given node.
39 // If the function returns false, the walk will stop.
40 ForEeachInDimension(n T, vec sitesmatrix.Vector, d int, f func(T) bool)
41
42 // ForEeachInAllDimensions will call the given function for each value in all dimensions.
43 // If the function returns false, the walk will stop.
44 ForEeachInAllDimensions(n T, f func(T) bool)
45
46 // Insert inserts new into the tree into the dimension it provides.
47 // It may replace old.
48 // It returns the updated and existing T
49 // and a bool indicating if an existing record is updated.
50 Insert(old, new T) (T, T, bool)
51
52 // Delete deletes T from the given dimension.
53 // It returns the updated T, the deleted T, whether anything was deleted
54 // and whether T is empty after the delete.
55 Delete(v T, dimension sitesmatrix.Vector) (T, T, bool, bool)
56
57 // DeleteFunc deletes nodes in v where the given function returns true.
58 // It returns the updated T and whether it's empty after the delete.
59 DeleteFunc(v T, f func(n T) bool) (T, bool)
60
61 // Shift shifts v into the given dimension,
62 // if fallback is true, it will fall back a fallback match if found.
63 // It returns the shifted T and a bool indicating if the shift was successful.
64 Shift(v T, dimension sitesmatrix.Vector, fallback bool) (T, bool)
65 }
66
67 Transformer[T any] interface {
68 // Append appends vs to t and returns the updated or replaced T and a bool indicating if T was replaced.
69 // Note that t may be the zero value and should be ignored.
70 Append(t T, ts ...T) (T, bool)
71 }
72 )
73
74 // NodeShiftTree is the root of a tree that can be shaped using the Shape method.
75 // Note that multiplied shapes of the same tree is meant to be used concurrently,
76 // so use the applicable locking when needed.
77 type NodeShiftTree[T any] struct {
78 tree *radix.Tree[T]
79
80 // [language, version, role].
81 siteVector sitesmatrix.Vector
82 shifter Shifter[T]
83 transformerRaw Transformer[T]
84
85 mu *sync.RWMutex
86 }
87
88 func New[T any](cfg Config[T]) *NodeShiftTree[T] {
89 if cfg.Shifter == nil {
90 panic("Shifter is required")
91 }
92
93 return &NodeShiftTree[T]{
94 mu: &sync.RWMutex{},
95
96 shifter: cfg.Shifter,
97 transformerRaw: cfg.TransformerRaw,
98 tree: radix.New[T](),
99 }
100 }
101
102 // SiteVector returns the site vector of the current dimension.
103 func (r *NodeShiftTree[T]) SiteVector() sitesmatrix.Vector {
104 return r.siteVector
105 }
106
107 // Delete deletes the node at the given key in the current dimension.
108 func (r *NodeShiftTree[T]) Delete(key string) (T, bool) {
109 return r.delete(key)
110 }
111
112 // DeleteFuncRaw deletes nodes in the tree at the given key where the given function returns true.
113 // It will delete nodes in all dimensions.
114 func (r *NodeShiftTree[T]) DeleteFuncRaw(key string, f func(T) bool) (T, int) {
115 var count int
116 var lastDeleted T
117
118 v, ok := r.tree.Get(key)
119 if !ok {
120 return lastDeleted, count
121 }
122
123 updated, isEmpty := r.shifter.DeleteFunc(v, func(n T) bool {
124 if f(n) {
125 count++
126 lastDeleted = n
127 return true
128 }
129 return false
130 })
131
132 if isEmpty {
133 r.tree.Delete(key)
134 } else if count > 0 {
135 r.tree.Insert(key, updated)
136 }
137
138 return lastDeleted, count
139 }
140
141 // DeleteRaw deletes the node at the given key without any shifting or transformation.
142 func (r *NodeShiftTree[T]) DeleteRaw(key string) {
143 r.tree.Delete(key)
144 }
145
146 // DeletePrefix deletes all nodes with the given prefix in the current dimension.
147 func (r *NodeShiftTree[T]) DeletePrefix(prefix string) int {
148 count := 0
149 var keys []string
150 var zero T
151 var walkFn radix.WalkFn[T] = func(key string, value T) (radix.WalkFlag, T, error) {
152 keys = append(keys, key)
153 return radix.WalkContinue, zero, nil
154 }
155 r.tree.WalkPrefix(prefix, walkFn)
156 for _, key := range keys {
157 if _, ok := r.delete(key); ok {
158 count++
159 }
160 }
161 return count
162 }
163
164 func (r *NodeShiftTree[T]) delete(key string) (T, bool) {
165 var wasDeleted bool
166 var deleted T
167 if v, ok := r.tree.Get(key); ok {
168 var (
169 updated T
170 isEmpty bool
171 )
172 updated, deleted, wasDeleted, isEmpty = r.shifter.Delete(v, r.siteVector)
173 if isEmpty {
174 r.tree.Delete(key)
175 } else if wasDeleted {
176 r.tree.Insert(key, updated)
177 }
178 }
179 return deleted, wasDeleted
180 }
181
182 func (t *NodeShiftTree[T]) DeletePrefixRaw(prefix string) int {
183 count := 0
184 var zero T
185 var walkFn radix.WalkFn[T] = func(key string, value T) (radix.WalkFlag, T, error) {
186 if v, ok := t.tree.Delete(key); ok {
187 resource.MarkStale(v)
188 count++
189 }
190 return radix.WalkContinue, zero, nil
191 }
192 t.tree.WalkPrefix(prefix, walkFn)
193
194 return count
195 }
196
197 // Insert inserts v into the tree at the given key and the
198 // dimension defined by the value.
199 // It returns the updated and existing T and a bool indicating if an existing record is updated.
200 func (r *NodeShiftTree[T]) Insert(s string, v T) (T, T, bool) {
201 s = mustValidateKey(cleanKey(s))
202 var (
203 updated bool
204 existing T
205 )
206 if vv, ok := r.tree.Get(s); ok {
207 v, existing, updated = r.shifter.Insert(vv, v)
208 }
209 r.insert(s, v)
210 return v, existing, updated
211 }
212
213 func (r *NodeShiftTree[T]) insert(s string, v T) (T, bool) {
214 n, updated := r.tree.Insert(s, v)
215 return n, updated
216 }
217
218 // InsertRaw inserts v into the tree at the given key without any shifting or transformation.
219 func (r *NodeShiftTree[T]) InsertRaw(s string, v T) (T, bool) {
220 return r.insert(s, v)
221 }
222
223 func (r *NodeShiftTree[T]) InsertRawWithLock(s string, v T) (T, bool) {
224 r.mu.Lock()
225 defer r.mu.Unlock()
226 return r.insert(s, v)
227 }
228
229 // It returns the updated and existing T and a bool indicating if an existing record is updated.
230 func (r *NodeShiftTree[T]) InsertWithLock(s string, v T) (T, T, bool) {
231 r.mu.Lock()
232 defer r.mu.Unlock()
233 return r.Insert(s, v)
234 }
235
236 func (t *NodeShiftTree[T]) Len() int {
237 return t.tree.Len()
238 }
239
240 func (t *NodeShiftTree[T]) CanLock() bool {
241 ok := t.mu.TryLock()
242 if ok {
243 t.mu.Unlock()
244 }
245 return ok
246 }
247
248 // Lock locks the data store for read or read/write access.
249 // Note that NodeShiftTree is not thread-safe outside of this transaction construct.
250 func (t *NodeShiftTree[T]) Lock(writable bool) {
251 if writable {
252 t.mu.Lock()
253 } else {
254 t.mu.RLock()
255 }
256 }
257
258 // Unlock unlocks the data store.
259 func (t *NodeShiftTree[T]) Unlock(writable bool) {
260 if writable {
261 t.mu.Unlock()
262 } else {
263 t.mu.RUnlock()
264 }
265 }
266
267 // LongestPrefix finds the longest prefix of s that exists in the tree that also matches the predicate (if set).
268 // Set exact to true to only match exact in the current dimension (e.g. language).
269 func (r *NodeShiftTree[T]) LongestPrefix(s string, fallback bool, predicate func(v T) bool) (string, T) {
270 for {
271 longestPrefix, v, found := r.tree.LongestPrefix(s)
272
273 if found {
274 if v, ok := r.shift(v, fallback); ok && (predicate == nil || predicate(v)) {
275 return longestPrefix, v
276 }
277 }
278
279 if s == "" || s == "/" {
280 var t T
281 return "", t
282 }
283
284 // Walk up to find a node in the correct dimension.
285 s = path.Dir(s)
286
287 }
288 }
289
290 // LongestPrefiValueRaw returns the longest prefix and value considering all dimensions
291 func (r *NodeShiftTree[T]) LongestPrefiValueRaw(s string) (string, T) {
292 s, v, found := r.tree.LongestPrefix(s)
293 if !found {
294 var t T
295 return s, t
296 }
297 return s, v
298 }
299
300 // LongestPrefixRaw returns the longest prefix considering all dimensions.
301 func (r *NodeShiftTree[T]) LongestPrefixRaw(s string) (string, bool) {
302 s, _, found := r.tree.LongestPrefix(s)
303 return s, found
304 }
305
306 // GetRaw returns the raw value at the given key without any shifting or transformation.
307 func (r *NodeShiftTree[T]) GetRaw(s string) (T, bool) {
308 v, ok := r.tree.Get(s)
309 if !ok {
310 var t T
311 return t, false
312 }
313 return v, true
314 }
315
316 // AppendRaw appends ts to the node at the given key without any shifting or transformation.
317 func (r *NodeShiftTree[T]) AppendRaw(s string, ts ...T) (T, bool) {
318 if r.transformerRaw == nil {
319 panic("transformerRaw is required")
320 }
321 n, found := r.GetRaw(s)
322 n2, replaced := r.transformerRaw.Append(n, ts...)
323 if replaced || !found {
324 r.insert(s, n2)
325 }
326 return n2, replaced || !found
327 }
328
329 // WalkPrefixRaw walks all nodes with the given prefix in the tree without any shifting or transformation.
330 func (r *NodeShiftTree[T]) WalkPrefixRaw(prefix string, fn radix.WalkFn[T]) error {
331 return r.tree.WalkPrefix(prefix, fn)
332 }
333
334 // Shape returns a new NodeShiftTree shaped to the given dimension.
335 func (t *NodeShiftTree[T]) Shape(v sitesmatrix.Vector) *NodeShiftTree[T] {
336 x := t.clone()
337 x.siteVector = v
338 return x
339 }
340
341 func (t *NodeShiftTree[T]) String() string {
342 return fmt.Sprintf("Root{%v}", t.siteVector)
343 }
344
345 func (r *NodeShiftTree[T]) Get(s string) T {
346 t, _ := r.get(s)
347 return t
348 }
349
350 // GetWithFallback is like Get but uses the fallback/complement mechanism
351 // when finding a node for the current site vector.
352 func (r *NodeShiftTree[T]) GetWithFallback(s string) T {
353 s = cleanKey(s)
354 v, ok := r.tree.Get(s)
355 if !ok {
356 var t T
357 return t
358 }
359 if v, ok := r.shift(v, true); ok {
360 return v
361 }
362 var t T
363 return t
364 }
365
366 func (r *NodeShiftTree[T]) ForEeachInDimension(s string, dims sitesmatrix.Vector, d int, f func(T) bool) {
367 s = cleanKey(s)
368 v, ok := r.tree.Get(s)
369 if !ok {
370 return
371 }
372 r.shifter.ForEeachInDimension(v, dims, d, f)
373 }
374
375 func (r *NodeShiftTree[T]) ForEeachInAllDimensions(s string, f func(T) bool) {
376 s = cleanKey(s)
377 v, ok := r.tree.Get(s)
378 if !ok {
379 return
380 }
381 r.shifter.ForEeachInAllDimensions(v, f)
382 }
383
384 type WalkFunc[T any] func(string, T) (bool, error)
385
386 //go:generate stringer -type=NodeTransformState
387 type NodeTransformState int
388
389 const (
390 NodeTransformStateNone NodeTransformState = iota
391 NodeTransformStateUpdated // Node is updated in place.
392 NodeTransformStateReplaced // Node is replaced and needs to be re-inserted into the tree.
393 NodeTransformStateDeleted // Node is deleted and should be removed from the tree.
394 NodeTransformStateSkip // Skip this node, but continue the walk.
395 NodeTransformStateTerminate // Terminate the walk.
396 )
397
398 type NodeShiftTreeWalker[T any] struct {
399 // The tree to walk.
400 Tree *NodeShiftTree[T]
401
402 // Transform will be called for each node in the main tree.
403 // v2 will replace v1 in the tree if state returned is NodeTransformStateReplaced.
404 Transform func(s string, v1 T) (v2 T, state NodeTransformState, err error)
405
406 // Handle will be called for each node in the main tree.
407 Handle func(s string, v T) (f radix.WalkFlag, err error)
408
409 // Optional prefix filter.
410 Prefix string
411
412 // IncludeFilter is an optional filter that can be used to filter nodes.
413 // If it returns false, the node will be skipped.
414 // Note that v is the shifted value from the tree.
415 IncludeFilter func(s string, v T) bool
416
417 // IncludeRawFilter is an optional filter that can be used to filter nodes.
418 // If it returns false, the node will be skipped.
419 // Note that v is the raw value from the tree.
420 IncludeRawFilter func(s string, v T) bool
421
422 // Enable read or write locking if needed.
423 LockType LockType
424
425 // When set, no dimension shifting will be performed.
426 NoShift bool
427
428 // When set, will try to fall back to alternative match,
429 // typically a shared resource common for all languages.
430 Fallback bool
431
432 // Used in development only.
433 Debug bool
434
435 // Optional context.
436 // Note that this is copied to the nested walkers using Extend.
437 // This means that walkers can pass data (down) and events (up) to
438 // the related walkers.
439 WalkContext *WalkContext[T]
440
441 // Local state.
442 // This is scoped to the current walker and not copied to the nested walkers.
443 skipPrefixes []string
444 }
445
446 // Extend returns a new NodeShiftTreeWalker with the same configuration
447 // and the same WalkContext as the original.
448 // Any local state is reset.
449 func (r *NodeShiftTreeWalker[T]) Extend() *NodeShiftTreeWalker[T] {
450 return &NodeShiftTreeWalker[T]{
451 Tree: r.Tree,
452 Transform: r.Transform,
453 Handle: r.Handle,
454 Prefix: r.Prefix,
455 IncludeFilter: r.IncludeFilter,
456 IncludeRawFilter: r.IncludeRawFilter,
457 LockType: r.LockType,
458 NoShift: r.NoShift,
459 Fallback: r.Fallback,
460 Debug: r.Debug,
461 WalkContext: r.WalkContext,
462 }
463 }
464
465 // WithPrefix returns a new NodeShiftTreeWalker with the given prefix.
466 func (r *NodeShiftTreeWalker[T]) WithPrefix(prefix string) *NodeShiftTreeWalker[T] {
467 r2 := r.Extend()
468 r2.Prefix = prefix
469 return r2
470 }
471
472 // SkipPrefix adds a prefix to be skipped in the walk.
473 func (r *NodeShiftTreeWalker[T]) SkipPrefix(prefix ...string) {
474 r.skipPrefixes = append(r.skipPrefixes, prefix...)
475 }
476
477 func (r *NodeShiftTreeWalker[T]) ShouldSkipKey(s string) bool {
478 return hstrings.HasAnyPrefix(s, r.skipPrefixes...)
479 }
480
481 // ShouldSkip returns whether the given value should be skipped in the walk.
482 func (r *NodeShiftTreeWalker[T]) ShouldSkipValue(s string, v T) bool {
483 if r.IncludeRawFilter != nil {
484 if !r.IncludeRawFilter(s, v) {
485 return true
486 }
487 }
488 return false
489 }
490
491 type walkHandler[T any] struct {
492 r *NodeShiftTreeWalker[T]
493 handle func(s string, v T) (radix.WalkFlag, T, error)
494 }
495
496 func (h *walkHandler[T]) Check(s string) (radix.WalkFlag, error) {
497 if h.r == nil {
498 return radix.WalkContinue, nil
499 }
500 if h.r.ShouldSkipKey(s) {
501 return radix.WalkSkip, nil
502 }
503 return radix.WalkContinue, nil
504 }
505
506 func (h *walkHandler[T]) Handle(s string, v T) (radix.WalkFlag, T, error) {
507 if h.handle == nil {
508 return radix.WalkContinue, v, nil
509 }
510 return h.handle(s, v)
511 }
512
513 func (r *NodeShiftTreeWalker[T]) lock() {
514 switch r.LockType {
515 case LockTypeRead:
516 r.Tree.mu.RLock()
517 case LockTypeWrite:
518 r.Tree.mu.Lock()
519 default:
520 // No lock
521 }
522 }
523
524 func (r *NodeShiftTreeWalker[T]) unlock() {
525 switch r.LockType {
526 case LockTypeRead:
527 r.Tree.mu.RUnlock()
528 case LockTypeWrite:
529 r.Tree.mu.Unlock()
530 default:
531 // No lock
532 }
533 }
534
535 func (r *NodeShiftTreeWalker[T]) Walk(ctx context.Context) error {
536 var deletes []string
537
538 return func() error {
539 r.lock()
540 defer r.unlock()
541
542 r.resetLocalState()
543
544 main := r.Tree
545
546 var handleV radix.WalkFn[T] = func(s string, v T) (radix.WalkFlag, T, error) {
547 var zero T
548 // Context cancellation check.
549 if ctx != nil && ctx.Err() != nil {
550 return radix.WalkStop, zero, ctx.Err()
551 }
552 if r.ShouldSkipValue(s, v) {
553 return radix.WalkContinue, zero, nil
554 }
555 var t T
556 if r.NoShift {
557 t = v
558 } else {
559 var ok bool
560 t, ok = r.toT(r.Tree, v)
561 if !ok {
562 return radix.WalkContinue, zero, nil
563 }
564 }
565 var (
566 ns NodeTransformState
567 t2 T
568 )
569 if r.IncludeFilter != nil && !r.IncludeFilter(s, t) {
570 return radix.WalkContinue, zero, nil
571 }
572 if r.Transform != nil {
573 if !r.NoShift {
574 panic("Transform must be performed with NoShift=true")
575 }
576 var err error
577 ns, err = func() (ns NodeTransformState, err error) {
578 t2, ns, err = r.Transform(s, t)
579 if ns >= NodeTransformStateSkip || err != nil {
580 return
581 }
582 switch ns {
583 case NodeTransformStateReplaced:
584 case NodeTransformStateDeleted:
585 // Delay delete until after the walk.
586 deletes = append(deletes, s)
587 ns = NodeTransformStateSkip
588 }
589 return
590 }()
591
592 if ns == NodeTransformStateTerminate || err != nil {
593 return radix.WalkStop, zero, err
594 }
595
596 if ns == NodeTransformStateSkip {
597 return radix.WalkContinue, zero, nil
598 }
599
600 }
601
602 if r.Handle != nil {
603 f, err := r.Handle(s, t)
604 if f.ShouldSet() {
605 panic("Handle cannot replace nodes in the tree, use Transform for that")
606 }
607 if f.ShouldStop() || err != nil {
608 return f, zero, err
609 }
610 }
611 if ns == NodeTransformStateTerminate {
612 return radix.WalkStop, zero, nil
613 }
614 if ns == NodeTransformStateReplaced {
615 return radix.WalkSet | radix.WalkContinue, t2, nil
616 }
617 return radix.WalkContinue, zero, nil
618 }
619
620 handle := &walkHandler[T]{
621 r: r,
622 handle: handleV,
623 }
624
625 if r.Prefix != "" {
626 if err := main.tree.WalkPrefix(r.Prefix, handle); err != nil {
627 return err
628 }
629 } else {
630 if err := main.tree.Walk(handle); err != nil {
631 return err
632 }
633 }
634
635 // This is currently only performed with no shift.
636 for _, s := range deletes {
637 main.tree.Delete(s)
638 }
639
640 return nil
641 }()
642 }
643
644 func (r *NodeShiftTreeWalker[T]) resetLocalState() {
645 r.skipPrefixes = nil
646 }
647
648 func (r *NodeShiftTreeWalker[T]) toT(tree *NodeShiftTree[T], v T) (T, bool) {
649 return tree.shift(v, r.Fallback)
650 }
651
652 func (r *NodeShiftTree[T]) Has(s string) bool {
653 _, ok := r.GetRaw(s)
654 return ok
655 }
656
657 func (t NodeShiftTree[T]) clone() *NodeShiftTree[T] {
658 return &t
659 }
660
661 func (r *NodeShiftTree[T]) shift(t T, fallback bool) (T, bool) {
662 return r.shifter.Shift(t, r.siteVector, fallback)
663 }
664
665 func (r *NodeShiftTree[T]) get(s string) (T, bool) {
666 s = cleanKey(s)
667 v, ok := r.tree.Get(s)
668
669 if !ok {
670 var t T
671 return t, false
672 }
673 if v, ok := r.shift(v, false); ok {
674 return v, true
675 }
676
677 var t T
678 return t, false
679 }