Debian Codegraph @

identity/identity.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 provides ways to identify values in Hugo. Used for dependency tracking etc.
15 package identity
16
17 import (
18 "fmt"
19 "path"
20 "path/filepath"
21 "sort"
22 "strings"
23 "sync"
24 "sync/atomic"
25
26 "github.com/gohugoio/hugo/common/types"
27 "github.com/gohugoio/hugo/compare"
28 )
29
30 const (
31 // Anonymous is an Identity that can be used when identity doesn't matter.
32 Anonymous = StringIdentity("__anonymous")
33
34 // GenghisKhan is an Identity everyone relates to.
35 GenghisKhan = StringIdentity("__genghiskhan")
36
37 StructuralChangeAdd = StringIdentity("__structural_change_add")
38 StructuralChangeRemove = StringIdentity("__structural_change_remove")
39 )
40
41 var NopManager = new(nopManager)
42
43 // NewIdentityManager creates a new Manager.
44 func NewManager(opts ...ManagerOption) Manager {
45 idm := &identityManager{
46 Identity: Anonymous,
47 ids: Identities{},
48 }
49
50 for _, o := range opts {
51 o(idm)
52 }
53
54 return idm
55 }
56
57 // CleanString cleans s to be suitable as an identifier.
58 func CleanString(s string) string {
59 s = strings.ToLower(s)
60 s = strings.Trim(filepath.ToSlash(s), "/")
61 return "/" + path.Clean(s)
62 }
63
64 // CleanStringIdentity cleans s to be suitable as an identifier and wraps it in a StringIdentity.
65 func CleanStringIdentity(s string) StringIdentity {
66 return StringIdentity(CleanString(s))
67 }
68
69 // GetDependencyManager returns the DependencyManager from v or nil if none found.
70 func GetDependencyManager(v any) Manager {
71 switch vv := v.(type) {
72 case Manager:
73 return vv
74 case types.Unwrapper:
75 return GetDependencyManager(vv.Unwrapv())
76 case DependencyManagerProvider:
77 return vv.GetDependencyManager()
78 }
79 return nil
80 }
81
82 // FirstIdentity returns the first Identity in v, Anonymous if none found
83 func FirstIdentity(v any) Identity {
84 var result Identity = Anonymous
85 WalkIdentitiesShallow(v, func(level int, id Identity) bool {
86 result = id
87 return result != Anonymous
88 })
89 return result
90 }
91
92 // PrintIdentityInfo is used for debugging/tests only.
93 func PrintIdentityInfo(v any) {
94 WalkIdentitiesDeep(v, func(level int, id Identity) bool {
95 var s string
96 fmt.Printf("%s%s (%T)%s\n", strings.Repeat(" ", level), id.IdentifierBase(), id, s)
97 return false
98 })
99 }
100
101 func Unwrap(id Identity) Identity {
102 switch t := id.(type) {
103 case IdentityProvider:
104 return t.GetIdentity()
105 default:
106 return id
107 }
108 }
109
110 // WalkIdentitiesDeep walks identities in v and applies cb to every identity found.
111 // Return true from cb to terminate.
112 // If deep is true, it will also walk nested Identities in any Manager found.
113 func WalkIdentitiesDeep(v any, cb func(level int, id Identity) bool) {
114 seen := make(map[Identity]bool)
115 walkIdentities(v, 0, true, seen, cb)
116 }
117
118 // WalkIdentitiesShallow will not walk into a Manager's Identities.
119 // See WalkIdentitiesDeep.
120 // cb is called for every Identity found and returns whether to terminate the walk.
121 func WalkIdentitiesShallow(v any, cb func(level int, id Identity) bool) {
122 walkIdentitiesShallow(v, 0, cb)
123 }
124
125 // WithOnAddIdentity sets a callback that will be invoked when an identity is added to the manager.
126 func WithOnAddIdentity(f func(id Identity)) ManagerOption {
127 return func(m *identityManager) {
128 m.onAddIdentity = f
129 }
130 }
131
132 // DependencyManagerProvider provides a manager for dependencies.
133 type DependencyManagerProvider interface {
134 GetDependencyManager() Manager
135 }
136
137 // DependencyManagerProviderFunc is a function that implements the DependencyManagerProvider interface.
138 type DependencyManagerProviderFunc func() Manager
139
140 func (d DependencyManagerProviderFunc) GetDependencyManager() Manager {
141 return d()
142 }
143
144 // DependencyManagerScopedProvider provides a manager for dependencies with a given scope.
145 type DependencyManagerScopedProvider interface {
146 GetDependencyManagerForScope(scope int) Manager
147 GetDependencyManagerForScopesAll() []Manager
148 }
149
150 // ForEeachIdentityProvider provides a way iterate over identities.
151 type ForEeachIdentityProvider interface {
152 // ForEeachIdentityProvider calls cb for each Identity.
153 // If cb returns false, the iteration is terminated.
154 // It returns false if the iteration was terminated early.
155 ForEeachIdentity(cb func(id Identity) bool) bool
156 }
157
158 // ForEeachIdentityProviderFunc is a function that implements the ForEeachIdentityProvider interface.
159 type ForEeachIdentityProviderFunc func(func(id Identity) bool) bool
160
161 func (f ForEeachIdentityProviderFunc) ForEeachIdentity(cb func(id Identity) bool) bool {
162 return f(cb)
163 }
164
165 // ForEeachIdentityByNameProvider provides a way to look up identities by name.
166 type ForEeachIdentityByNameProvider interface {
167 // ForEeachIdentityByName calls cb for each Identity that relates to name.
168 // If cb returns true, the iteration is terminated.
169 ForEeachIdentityByName(name string, cb func(id Identity) bool)
170 }
171
172 type FindFirstManagerIdentityProvider interface {
173 Identity
174 FindFirstManagerIdentity() ManagerIdentity
175 }
176
177 func NewFindFirstManagerIdentityProvider(m Manager, id Identity) FindFirstManagerIdentityProvider {
178 return findFirstManagerIdentity{
179 Identity: Anonymous,
180 ManagerIdentity: ManagerIdentity{
181 Manager: m, Identity: id,
182 },
183 }
184 }
185
186 type findFirstManagerIdentity struct {
187 Identity
188 ManagerIdentity
189 }
190
191 func (f findFirstManagerIdentity) FindFirstManagerIdentity() ManagerIdentity {
192 return f.ManagerIdentity
193 }
194
195 // Identities stores identity providers.
196 type Identities map[Identity]bool
197
198 func (ids Identities) AsSlice() []Identity {
199 s := make([]Identity, len(ids))
200 i := 0
201 for v := range ids {
202 s[i] = v
203 i++
204 }
205 sort.Slice(s, func(i, j int) bool {
206 return s[i].IdentifierBase() < s[j].IdentifierBase()
207 })
208
209 return s
210 }
211
212 func (ids Identities) String() string {
213 var sb strings.Builder
214 i := 0
215 for id := range ids {
216 sb.WriteString(fmt.Sprintf("[%s]", id.IdentifierBase()))
217 if i < len(ids)-1 {
218 sb.WriteString(", ")
219 }
220 i++
221 }
222 return sb.String()
223 }
224
225 // Identity represents a thing in Hugo (a Page, a template etc.)
226 // Any implementation must be comparable/hashable.
227 type Identity interface {
228 IdentifierBase() string
229 }
230
231 // IdentityGroupProvider can be implemented by tightly connected types.
232 // Current use case is Resource transformation via Hugo Pipes.
233 type IdentityGroupProvider interface {
234 GetIdentityGroup() Identity
235 }
236
237 // IdentityProvider can be implemented by types that isn't itself and Identity,
238 // usually because they're not comparable/hashable.
239 type IdentityProvider interface {
240 GetIdentity() Identity
241 }
242
243 // SignalRebuilder is an optional interface for types that can signal a rebuild.
244 type SignalRebuilder interface {
245 SignalRebuild(ids ...Identity)
246 }
247
248 // IsRebuildProvider signals if we're in a rebuild or not.
249 type IsRebuildProvider interface {
250 IsRebuild() bool
251 }
252
253 // IncrementByOne implements Incrementer adding 1 every time Incr is called.
254 type IncrementByOne struct {
255 counter atomic.Uint64
256 }
257
258 func (c *IncrementByOne) Incr() int {
259 return int(c.counter.Add(uint64(1)))
260 }
261
262 // Incrementer increments and returns the value.
263 // Typically used for IDs.
264 type Incrementer interface {
265 Incr() int
266 }
267
268 // IsProbablyDependentProvider is an optional interface for Identity.
269 type IsProbablyDependentProvider interface {
270 IsProbablyDependent(other Identity) bool
271 }
272
273 // IsProbablyDependencyProvider is an optional interface for Identity.
274 type IsProbablyDependencyProvider interface {
275 IsProbablyDependency(other Identity) bool
276 }
277
278 // Manager is an Identity that also manages identities, typically dependencies.
279 type Manager interface {
280 Identity
281 AddIdentity(ids ...Identity)
282 AddIdentityForEach(ids ...ForEeachIdentityProvider)
283 GetIdentity() Identity
284 Reset()
285 forEeachIdentity(func(id Identity) bool) bool
286 }
287
288 type ManagerOption func(m *identityManager)
289
290 // StringIdentity is an Identity that wraps a string.
291 type StringIdentity string
292
293 func (s StringIdentity) IdentifierBase() string {
294 return string(s)
295 }
296
297 type identityManager struct {
298 Identity
299
300 // mu protects _changes_ to this manager,
301 // reads currently assumes no concurrent writes.
302 mu sync.RWMutex
303 ids Identities
304 forEachIds []ForEeachIdentityProvider
305
306 // Hooks used in debugging.
307 onAddIdentity func(id Identity)
308 }
309
310 func (im *identityManager) AddIdentity(ids ...Identity) {
311 im.mu.Lock()
312 defer im.mu.Unlock()
313
314 for _, id := range ids {
315 if id == nil || id == Anonymous {
316 continue
317 }
318
319 if _, found := im.ids[id]; !found {
320 if im.onAddIdentity != nil {
321 im.onAddIdentity(id)
322 }
323 im.ids[id] = true
324 }
325 }
326 }
327
328 func (im *identityManager) AddIdentityForEach(ids ...ForEeachIdentityProvider) {
329 im.mu.Lock()
330 im.forEachIds = append(im.forEachIds, ids...)
331 im.mu.Unlock()
332 }
333
334 func (im *identityManager) ContainsIdentity(id Identity) FinderResult {
335 if im.Identity != Anonymous && id == im.Identity {
336 return FinderFound
337 }
338
339 f := NewFinder(FinderConfig{Exact: true})
340 r := f.Contains(id, im, -1)
341
342 return r
343 }
344
345 // Managers are always anonymous.
346 func (im *identityManager) GetIdentity() Identity {
347 return im.Identity
348 }
349
350 func (im *identityManager) Reset() {
351 im.mu.Lock()
352 im.ids = Identities{}
353 im.mu.Unlock()
354 }
355
356 func (im *identityManager) GetDependencyManagerForScope(int) Manager {
357 return im
358 }
359
360 func (im *identityManager) GetDependencyManagerForScopesAll() []Manager {
361 return []Manager{im}
362 }
363
364 func (im *identityManager) forEeachIdentity(fn func(id Identity) bool) bool {
365 // The absence of a lock here is deliberate. This is currently only used on server reloads
366 // in a single-threaded context.
367 for id := range im.ids {
368 if fn(id) {
369 return true
370 }
371 }
372 for _, fe := range im.forEachIds {
373 if !fe.ForEeachIdentity(fn) {
374 return false
375 }
376 }
377 return true
378 }
379
380 type nopManager int
381
382 func (m *nopManager) AddIdentity(ids ...Identity) {
383 }
384
385 func (m *nopManager) AddIdentityForEach(ids ...ForEeachIdentityProvider) {
386 }
387
388 func (m *nopManager) IdentifierBase() string {
389 return ""
390 }
391
392 func (m *nopManager) GetIdentity() Identity {
393 return Anonymous
394 }
395
396 func (m *nopManager) Reset() {
397 }
398
399 func (m *nopManager) forEeachIdentity(func(id Identity) bool) bool {
400 return false
401 }
402
403 // returns whether further walking should be terminated.
404 func walkIdentities(v any, level int, deep bool, seen map[Identity]bool, cb func(level int, id Identity) bool) {
405 if level > 20 {
406 panic("too deep")
407 }
408 var cbRecursive func(level int, id Identity) bool
409 cbRecursive = func(level int, id Identity) bool {
410 if id == nil {
411 return false
412 }
413 if deep && seen[id] {
414 return false
415 }
416 seen[id] = true
417 if cb(level, id) {
418 return true
419 }
420
421 if deep {
422 if m := GetDependencyManager(id); m != nil {
423 m.forEeachIdentity(func(id2 Identity) bool {
424 return walkIdentitiesShallow(id2, level+1, cbRecursive)
425 })
426 }
427 }
428 return false
429 }
430 walkIdentitiesShallow(v, level, cbRecursive)
431 }
432
433 // returns whether further walking should be terminated.
434 // Anonymous identities are skipped.
435 func walkIdentitiesShallow(v any, level int, cb func(level int, id Identity) bool) bool {
436 cb2 := func(level int, id Identity) bool {
437 if id == Anonymous {
438 return false
439 }
440 if id == nil {
441 return false
442 }
443 return cb(level, id)
444 }
445
446 if id, ok := v.(Identity); ok {
447 if cb2(level, id) {
448 return true
449 }
450 }
451
452 if ipd, ok := v.(IdentityProvider); ok {
453 if cb2(level, ipd.GetIdentity()) {
454 return true
455 }
456 }
457
458 if ipdgp, ok := v.(IdentityGroupProvider); ok {
459 if cb2(level, ipdgp.GetIdentityGroup()) {
460 return true
461 }
462 }
463
464 return false
465 }
466
467 var (
468 _ Identity = (*orIdentity)(nil)
469 _ compare.ProbablyEqer = (*orIdentity)(nil)
470 )
471
472 func Or(a, b Identity) Identity {
473 return orIdentity{a: a, b: b}
474 }
475
476 type orIdentity struct {
477 a, b Identity
478 }
479
480 func (o orIdentity) IdentifierBase() string {
481 return o.a.IdentifierBase()
482 }
483
484 func (o orIdentity) ProbablyEq(other any) bool {
485 otherID, ok := other.(Identity)
486 if !ok {
487 return false
488 }
489
490 return probablyEq(o.a, otherID) || probablyEq(o.b, otherID)
491 }
492
493 func probablyEq(a, b Identity) bool {
494 if a == b {
495 return true
496 }
497
498 if a == Anonymous || b == Anonymous {
499 return false
500 }
501
502 if a.IdentifierBase() == b.IdentifierBase() {
503 return true
504 }
505
506 if a2, ok := a.(compare.ProbablyEqer); ok && a2.ProbablyEq(b) {
507 return true
508 }
509
510 if a2, ok := a.(IsProbablyDependentProvider); ok {
511 return a2.IsProbablyDependent(b)
512 }
513
514 return false
515 }