support.go - hugo - [fork] hugo port for 9front
(HTM) git clone https://git.drkhsh.at/hugo.git
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) Submodules
(DIR) README
(DIR) LICENSE
---
support.go (5752B)
---
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 "strings"
19 "sync"
20 )
21
22 var _ MutableTrees = MutableTrees{}
23
24 const (
25 LockTypeNone LockType = iota
26 LockTypeRead
27 LockTypeWrite
28 )
29
30 // AddEventListener adds an event listener to the tree.
31 // Note that the handler func may not add listeners.
32 func (ctx *WalkContext[T]) AddEventListener(event, path string, handler func(*Event[T])) {
33 if ctx.eventHandlers == nil {
34 ctx.eventHandlers = make(eventHandlers[T])
35 }
36 if ctx.eventHandlers[event] == nil {
37 ctx.eventHandlers[event] = make([]func(*Event[T]), 0)
38 }
39
40 // We want to match all above the path, so we need to exclude any similar named siblings.
41 if !strings.HasSuffix(path, "/") {
42 path += "/"
43 }
44
45 ctx.eventHandlers[event] = append(
46 ctx.eventHandlers[event], func(e *Event[T]) {
47 // Propagate events up the tree only.
48 if strings.HasPrefix(e.Path, path) {
49 handler(e)
50 }
51 },
52 )
53 }
54
55 // AddPostHook adds a post hook to the tree.
56 // This will be run after the tree has been walked.
57 func (ctx *WalkContext[T]) AddPostHook(handler func() error) {
58 ctx.HooksPost = append(ctx.HooksPost, handler)
59 }
60
61 func (ctx *WalkContext[T]) Data() *SimpleThreadSafeTree[any] {
62 ctx.dataInit.Do(func() {
63 ctx.data = NewSimpleThreadSafeTree[any]()
64 })
65 return ctx.data
66 }
67
68 // SendEvent sends an event up the tree.
69 func (ctx *WalkContext[T]) SendEvent(event *Event[T]) {
70 ctx.events = append(ctx.events, event)
71 }
72
73 // StopPropagation stops the propagation of the event.
74 func (e *Event[T]) StopPropagation() {
75 e.stopPropagation = true
76 }
77
78 // ValidateKey returns an error if the key is not valid.
79 func ValidateKey(key string) error {
80 if key == "" {
81 // Root node.
82 return nil
83 }
84
85 if len(key) < 2 {
86 return fmt.Errorf("too short key: %q", key)
87 }
88
89 if key[0] != '/' {
90 return fmt.Errorf("key must start with '/': %q", key)
91 }
92
93 if key[len(key)-1] == '/' {
94 return fmt.Errorf("key must not end with '/': %q", key)
95 }
96
97 return nil
98 }
99
100 // Event is used to communicate events in the tree.
101 type Event[T any] struct {
102 Name string
103 Path string
104 Source T
105 stopPropagation bool
106 }
107
108 type LockType int
109
110 // MutableTree is a tree that can be modified.
111 type MutableTree interface {
112 DeleteRaw(key string)
113 DeleteAll(key string)
114 DeletePrefix(prefix string) int
115 DeletePrefixAll(prefix string) int
116 Lock(writable bool) (commit func())
117 CanLock() bool // Used for troubleshooting only.
118 }
119
120 // WalkableTree is a tree that can be walked.
121 type WalkableTree[T any] interface {
122 WalkPrefixRaw(prefix string, walker func(key string, value T) bool)
123 }
124
125 var _ WalkableTree[any] = (*WalkableTrees[any])(nil)
126
127 type WalkableTrees[T any] []WalkableTree[T]
128
129 func (t WalkableTrees[T]) WalkPrefixRaw(prefix string, walker func(key string, value T) bool) {
130 for _, tree := range t {
131 tree.WalkPrefixRaw(prefix, walker)
132 }
133 }
134
135 var _ MutableTree = MutableTrees(nil)
136
137 type MutableTrees []MutableTree
138
139 func (t MutableTrees) DeleteRaw(key string) {
140 for _, tree := range t {
141 tree.DeleteRaw(key)
142 }
143 }
144
145 func (t MutableTrees) DeleteAll(key string) {
146 for _, tree := range t {
147 tree.DeleteAll(key)
148 }
149 }
150
151 func (t MutableTrees) DeletePrefix(prefix string) int {
152 var count int
153 for _, tree := range t {
154 count += tree.DeletePrefix(prefix)
155 }
156 return count
157 }
158
159 func (t MutableTrees) DeletePrefixAll(prefix string) int {
160 var count int
161 for _, tree := range t {
162 count += tree.DeletePrefixAll(prefix)
163 }
164 return count
165 }
166
167 func (t MutableTrees) Lock(writable bool) (commit func()) {
168 commits := make([]func(), len(t))
169 for i, tree := range t {
170 commits[i] = tree.Lock(writable)
171 }
172 return func() {
173 for _, commit := range commits {
174 commit()
175 }
176 }
177 }
178
179 func (t MutableTrees) CanLock() bool {
180 for _, tree := range t {
181 if !tree.CanLock() {
182 return false
183 }
184 }
185 return true
186 }
187
188 // WalkContext is passed to the Walk callback.
189 type WalkContext[T any] struct {
190 data *SimpleThreadSafeTree[any]
191 dataInit sync.Once
192 eventHandlers eventHandlers[T]
193 events []*Event[T]
194
195 HooksPost []func() error
196 }
197
198 type eventHandlers[T any] map[string][]func(*Event[T])
199
200 func cleanKey(key string) string {
201 if key == "/" {
202 // The path to the home page is logically "/",
203 // but for technical reasons, it's stored as "".
204 // This allows us to treat the home page as a section,
205 // and a prefix search for "/" will return the home page's descendants.
206 return ""
207 }
208 return key
209 }
210
211 func (ctx *WalkContext[T]) HandleEvents() error {
212 for len(ctx.events) > 0 {
213 event := ctx.events[0]
214 ctx.events = ctx.events[1:]
215
216 // Loop the event handlers in reverse order so
217 // that events created by the handlers themselves will
218 // be picked up further up the tree.
219 for i := len(ctx.eventHandlers[event.Name]) - 1; i >= 0; i-- {
220 ctx.eventHandlers[event.Name][i](event)
221 if event.stopPropagation {
222 break
223 }
224 }
225 }
226 return nil
227 }
228
229 func (ctx *WalkContext[T]) HandleEventsAndHooks() error {
230 if err := ctx.HandleEvents(); err != nil {
231 return err
232 }
233
234 for _, hook := range ctx.HooksPost {
235 if err := hook(); err != nil {
236 return err
237 }
238 }
239 return nil
240 }
241
242 func mustValidateKey(key string) string {
243 if err := ValidateKey(key); err != nil {
244 panic(err)
245 }
246 return key
247 }