Debian Codegraph @

hugolib/sitesmatrix/vectorstores.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 sitesmatrix
15
16 import (
17 "fmt"
18 "iter"
19 "maps"
20 "slices"
21 "sort"
22 "sync"
23
24 "github.com/gohugoio/hashstructure"
25 "github.com/gohugoio/hugo/common/hashing"
26 "github.com/gohugoio/hugo/common/hmaps"
27 "github.com/gohugoio/hugo/common/predicate"
28 "github.com/gohugoio/hugo/common/types"
29 "github.com/gohugoio/hugo/hugofs/hglob"
30 )
31
32 var (
33 _ VectorStore = &IntSets{}
34 _ VectorStore = &vectorStoreMap{}
35 _ hashstructure.Hashable = &IntSets{}
36 _ hashstructure.Hashable = &vectorStoreMap{}
37 )
38
39 func newVectorStoreMap(cap int) *vectorStoreMap {
40 return &vectorStoreMap{
41 sets: make(Vectors, cap),
42 h: &hashOnce{},
43 }
44 }
45
46 func newVectorStoreMapFromVectors(v Vectors) *vectorStoreMap {
47 return &vectorStoreMap{
48 sets: v,
49 h: &hashOnce{},
50 }
51 }
52
53 // A vector store backed by a map.
54 type vectorStoreMap struct {
55 sets Vectors
56 h *hashOnce
57 }
58
59 func (s *vectorStoreMap) initHash() {
60 s.h.once.Do(func() {
61 var err error
62 s.h.hash, err = hashing.Hash(s.sets)
63 if err != nil {
64 panic(fmt.Errorf("failed to calculate hash for MapVectorStore: %w", err))
65 }
66 })
67 }
68
69 func (s *vectorStoreMap) setVector(vec Vector) {
70 s.sets[vec] = struct{}{}
71 }
72
73 func (s *vectorStoreMap) KeysSorted() ([]int, []int, []int) {
74 var k0, k1, k2 []int
75 for v := range s.sets {
76 k0 = append(k0, v.Language())
77 k1 = append(k1, v.Version())
78 k2 = append(k2, v.Role())
79 }
80 sort.Ints(k0)
81 sort.Ints(k1)
82 sort.Ints(k2)
83 k0 = slices.Compact(k0)
84 k1 = slices.Compact(k1)
85 k2 = slices.Compact(k2)
86
87 return k0, k1, k2
88 }
89
90 func (s *vectorStoreMap) Hash() (uint64, error) {
91 s.initHash()
92 return s.h.hash, nil
93 }
94
95 func (s *vectorStoreMap) MustHash() uint64 {
96 i, _ := s.Hash()
97 return i
98 }
99
100 func (s *vectorStoreMap) HasVector(v Vector) bool {
101 if _, ok := s.sets[v]; ok {
102 return true
103 }
104 return false
105 }
106
107 func (s *vectorStoreMap) HasAnyVector(v VectorProvider) bool {
108 if v == nil || s.LenVectors() == 0 || v.LenVectors() == 0 {
109 return false
110 }
111
112 return !v.ForEachVector(func(vec Vector) bool {
113 if s.HasVector(vec) {
114 return false // stop iteration
115 }
116 return true // continue iteration
117 })
118 }
119
120 func (s *vectorStoreMap) LenVectors() int {
121 return len(s.sets)
122 }
123
124 // Complement returns a new VectorStore that contains all vectors in s that are not in any of ss.
125 func (s *vectorStoreMap) Complement(ss ...VectorProvider) VectorStore {
126 if len(ss) == 0 || (len(ss) == 1 && ss[0] == s) {
127 return nil
128 }
129
130 for _, v := range ss {
131 if v == s {
132 var s *vectorStoreMap
133 return s
134 }
135 }
136
137 result := newVectorStoreMap(36)
138
139 s.ForEachVector(func(vec Vector) bool {
140 var found bool
141 for _, v := range ss {
142 if v.HasVector(vec) {
143 found = true
144 break
145 }
146 }
147
148 if !found {
149 result.setVector(vec)
150 }
151
152 return true
153 })
154
155 return result
156 }
157
158 func (s *vectorStoreMap) EqualsVector(other VectorProvider) bool {
159 if other == nil {
160 return false
161 }
162 if s == other {
163 return true
164 }
165 if s.LenVectors() != other.LenVectors() {
166 return false
167 }
168 return other.ForEachVector(func(v Vector) bool {
169 _, ok := s.sets[v]
170 return ok
171 })
172 }
173
174 func (s *vectorStoreMap) VectorSample() Vector {
175 if len(s.sets) == 0 {
176 panic("no vectors available")
177 }
178 for v := range s.sets {
179 return v
180 }
181 panic("unreachable")
182 }
183
184 func (s *vectorStoreMap) ForEachVector(yield func(v Vector) bool) bool {
185 if len(s.sets) == 0 {
186 return true
187 }
188 for v := range s.sets {
189 if !yield(v) {
190 return false
191 }
192 }
193 return true
194 }
195
196 func (s *vectorStoreMap) Vectors() []Vector {
197 if s == nil || len(s.sets) == 0 {
198 return nil
199 }
200 var vectors []Vector
201 for v := range s.sets {
202 vectors = append(vectors, v)
203 }
204 sort.Slice(vectors, func(i, j int) bool {
205 v1, v2 := vectors[i], vectors[j]
206 return v1.Compare(v2) < 0
207 })
208 return vectors
209 }
210
211 func (s *vectorStoreMap) WithLanguageIndices(i ...int) VectorStore {
212 c := s.clone()
213
214 for v := range c.sets {
215 for _, i := range i {
216 nv := v
217 nv[Language] = i
218 c.sets[nv] = struct{}{}
219 }
220 }
221
222 return c
223 }
224
225 func (s *vectorStoreMap) WithVersionIndices(indices ...int) VectorStore {
226 old := s.clone()
227 c := newVectorStoreMap(len(old.sets) * len(indices))
228 for v := range old.sets {
229 for _, i := range indices {
230 nv := v
231 nv[Version] = i
232 c.sets[nv] = struct{}{}
233 }
234 }
235 return c
236 }
237
238 func (s *vectorStoreMap) WithRoleIndices(indices ...int) VectorStore {
239 old := s.clone()
240 c := newVectorStoreMap(len(old.sets) * len(indices))
241 for v := range old.sets {
242 for _, i := range indices {
243 nv := v
244 nv[Role] = i
245 c.sets[nv] = struct{}{}
246 }
247 }
248 return c
249 }
250
251 func (s *vectorStoreMap) HasLanguage(i int) bool {
252 for v := range s.sets {
253 if v.Language() == i {
254 return true
255 }
256 }
257 return false
258 }
259
260 func (s *vectorStoreMap) HasVersion(i int) bool {
261 for v := range s.sets {
262 if v.Version() == i {
263 return true
264 }
265 }
266 return false
267 }
268
269 func (s *vectorStoreMap) HasRole(i int) bool {
270 for v := range s.sets {
271 if v.Role() == i {
272 return true
273 }
274 }
275 return false
276 }
277
278 func (s *vectorStoreMap) clone() *vectorStoreMap {
279 c := *s
280 c.h = &hashOnce{}
281 c.sets = maps.Clone(s.sets)
282 return &c
283 }
284
285 func NewIntSetsBuilder(cfg *ConfiguredDimensions) *IntSetsBuilder {
286 if cfg == nil {
287 panic("cfg is required")
288 }
289 return &IntSetsBuilder{cfg: cfg, s: &IntSets{h: &hashOnce{}}}
290 }
291
292 type ConfiguredDimension interface {
293 predicate.IndexMatcher
294 IndexDefault() int
295 ResolveIndex(string) int
296 ResolveName(int) string
297 ForEachIndex() iter.Seq[int]
298 Len() int
299 }
300
301 // ConfiguredDimensions holds the configured dimensions for the site matrix.
302 type ConfiguredDimensions struct {
303 ConfiguredLanguages ConfiguredDimension
304 ConfiguredVersions ConfiguredDimension
305 ConfiguredRoles ConfiguredDimension
306 CommonSitesMatrix CommonSitestMatrix
307
308 singleVectorStoreCache *hmaps.Cache[Vector, *IntSets]
309 }
310
311 func (c *ConfiguredDimensions) IsSingleVector() bool {
312 return c.ConfiguredLanguages.Len() == 1 && c.ConfiguredRoles.Len() == 1 && c.ConfiguredVersions.Len() == 1
313 }
314
315 // GetOrCreateSingleVectorStore returns a VectorStore for the given vector.
316 func (c *ConfiguredDimensions) GetOrCreateSingleVectorStore(vec Vector) *IntSets {
317 store, _ := c.singleVectorStoreCache.GetOrCreate(vec, func() (*IntSets, error) {
318 is := &IntSets{}
319 is.setValuesInNilSets(vec, true, true, true)
320 return is, nil
321 })
322 return store
323 }
324
325 func (c *ConfiguredDimensions) Init() error {
326 c.singleVectorStoreCache = hmaps.NewCache[Vector, *IntSets]()
327 b := NewIntSetsBuilder(c).WithDefaultsIfNotSet().Build()
328 defaultVec := b.VectorSample()
329 c.singleVectorStoreCache.Set(defaultVec, b)
330 c.CommonSitesMatrix.DefaultSite = b
331
332 return nil
333 }
334
335 type CommonSitestMatrix struct {
336 DefaultSite VectorStore
337 }
338
339 func (c *ConfiguredDimensions) ResolveNames(v Vector) types.Strings3 {
340 return types.Strings3{
341 c.ConfiguredLanguages.ResolveName(v.Language()),
342 c.ConfiguredVersions.ResolveName(v.Version()),
343 c.ConfiguredRoles.ResolveName(v.Role()),
344 }
345 }
346
347 func (c *ConfiguredDimensions) ResolveVector(names types.Strings3) Vector {
348 var vec Vector
349 if s := names[0]; s != "" {
350 vec[0] = c.ConfiguredLanguages.ResolveIndex(s)
351 } else {
352 vec[0] = c.ConfiguredLanguages.IndexDefault()
353 }
354 if s := names[1]; s != "" {
355 vec[1] = c.ConfiguredVersions.ResolveIndex(s)
356 } else {
357 vec[1] = c.ConfiguredVersions.IndexDefault()
358 }
359 if s := names[2]; s != "" {
360 vec[2] = c.ConfiguredRoles.ResolveIndex(s)
361 } else {
362 vec[2] = c.ConfiguredRoles.IndexDefault()
363 }
364 return vec
365 }
366
367 // IntSets holds the ordered sets of integers for the dimensions,
368 // which is used for fast membership testing of files, resources and pages.
369 type IntSets struct {
370 languages *hmaps.OrderedIntSet `mapstructure:"-" json:"-"`
371 versions *hmaps.OrderedIntSet `mapstructure:"-" json:"-"`
372 roles *hmaps.OrderedIntSet `mapstructure:"-" json:"-"`
373
374 h *hashOnce
375 }
376
377 var NilStore *IntSets = nil
378
379 type hashOnce struct {
380 once sync.Once
381 hash uint64
382 }
383
384 func (s *IntSets) ToVectorStoreMap() *vectorStoreMap {
385 if s == nil {
386 return nil
387 }
388
389 result := newVectorStoreMap(36)
390
391 s.ForEachVector(func(vec Vector) bool {
392 result.setVector(vec)
393 return true
394 })
395
396 return result
397 }
398
399 func (s *IntSets) IsSuperSet(other *IntSets) bool {
400 return s.languages.IsSuperSet(other.languages) &&
401 s.versions.IsSuperSet(other.versions) &&
402 s.roles.IsSuperSet(other.roles)
403 }
404
405 func (s *IntSets) DifferenceCardinality(other *IntSets) Vector {
406 return Vector{
407 int(s.languages.Values().DifferenceCardinality(other.languages.Values())),
408 int(s.versions.Values().DifferenceCardinality(other.versions.Values())),
409 int(s.roles.Values().DifferenceCardinality(other.roles.Values())),
410 }
411 }
412
413 func (s *IntSets) Intersects(other *IntSets) bool {
414 if s == nil || other == nil {
415 return false
416 }
417 return s.languages.Values().IntersectionCardinality(other.languages.Values()) > 0 &&
418 s.versions.Values().IntersectionCardinality(other.versions.Values()) > 0 &&
419 s.roles.Values().IntersectionCardinality(other.roles.Values()) > 0
420 }
421
422 // Complement returns a new VectorStore that contains all vectors in s that are not in any of ss.
423 func (s *IntSets) Complement(ss ...VectorProvider) VectorStore {
424 if len(ss) == 0 || (len(ss) == 1 && ss[0] == s) {
425 return NilStore
426 }
427
428 for _, v := range ss {
429 vv, ok := v.(*IntSets)
430 if !ok {
431 continue
432 }
433 if vv.IsSuperSet(s) {
434 return NilStore
435 }
436 }
437
438 result := newVectorStoreMap(36)
439
440 s.ForEachVector(func(vec Vector) bool {
441 var found bool
442 for _, v := range ss {
443 if v.HasVector(vec) {
444 found = true
445 break
446 }
447 }
448
449 if !found {
450 result.setVector(vec)
451 }
452
453 return true
454 })
455
456 return result
457 }
458
459 func (s *IntSets) EqualsVector(other VectorProvider) bool {
460 if s == nil && other == nil {
461 return true
462 }
463 if s == nil || other == nil {
464 return false
465 }
466 if s == other {
467 return true
468 }
469 if s.LenVectors() != other.LenVectors() {
470 return false
471 }
472
473 return other.ForEachVector(func(v Vector) bool {
474 return s.HasVector(v)
475 })
476 }
477
478 func (s *IntSets) VectorSample() Vector {
479 if s.LenVectors() == 0 {
480 panic("no vectors available")
481 }
482
483 return Vector{
484 s.languages.Next(0),
485 s.versions.Next(0),
486 s.roles.Next(0),
487 }
488 }
489
490 // The reason we don't use iter.Seq is https://github.com/golang/go/issues/69015
491 // This is 60% faster and allocation free.
492 // The yield function should return false to stop iteration.
493 func (s *IntSets) ForEachVector(yield func(v Vector) bool) bool {
494 if s.LenVectors() == 0 {
495 return true
496 }
497
498 b := s.languages.ForEachKey(func(lang int) bool {
499 return s.versions.ForEachKey(func(ver int) bool {
500 return s.roles.ForEachKey(func(role int) bool {
501 return yield(Vector{lang, ver, role})
502 })
503 })
504 })
505
506 return b
507 }
508
509 func (s *IntSets) Vectors() []Vector {
510 if s.LenVectors() == 0 {
511 return nil
512 }
513
514 var vectors []Vector
515 s.ForEachVector(func(v Vector) bool {
516 vectors = append(vectors, v)
517 return true
518 })
519
520 sort.Slice(vectors, func(i, j int) bool {
521 v1, v2 := vectors[i], vectors[j]
522 return v1.Compare(v2) < 0
523 })
524
525 return vectors
526 }
527
528 func (s *IntSets) KeysSorted() ([]int, []int, []int) {
529 if s == nil {
530 return nil, nil, nil
531 }
532 languages := s.languages.KeysSorted()
533 versions := s.versions.KeysSorted()
534 roles := s.roles.KeysSorted()
535 return languages, versions, roles
536 }
537
538 func (s *IntSets) HasLanguage(lang int) bool {
539 if s == nil {
540 return false
541 }
542 return s.languages.Has(lang)
543 }
544
545 // LenVectors returns the total number of vectors represented by the IntSets.
546 // This is the Cartesian product of the lengths of the individual sets.
547 // This will be 0 if s is nil or any of the sets is empty.
548 func (s *IntSets) LenVectors() int {
549 if s == nil {
550 return 0
551 }
552 return s.languages.Len() * s.versions.Len() * s.roles.Len()
553 }
554
555 func (s *IntSets) HasRole(role int) bool {
556 if s == nil {
557 return false
558 }
559 return s.roles.Has(role)
560 }
561
562 func (s *IntSets) String() string {
563 return fmt.Sprintf("Languages: %v, Versions: %v, Roles: %v", s.languages, s.versions, s.roles)
564 }
565
566 // HasVector checks if the given vector is contained in the sets.
567 func (s *IntSets) HasVector(v Vector) bool {
568 if s == nil {
569 return false
570 }
571 if !s.languages.Has(v.Language()) {
572 return false
573 }
574 if !s.versions.Has(v.Version()) {
575 return false
576 }
577 if !s.roles.Has(v.Role()) {
578 return false
579 }
580 return true
581 }
582
583 func (s *IntSets) HasAnyVector(v VectorProvider) bool {
584 if s == nil || v == nil {
585 return false
586 }
587 if s.LenVectors() == 0 || v.LenVectors() == 0 {
588 return false
589 }
590 if v.LenVectors() == 1 {
591 // Fast path.
592 return s.HasVector(v.VectorSample())
593 }
594
595 if vs, ok := v.(*IntSets); ok {
596 // Fast path.
597 return s.Intersects(vs)
598 }
599
600 return !v.ForEachVector(func(vec Vector) bool {
601 if s.HasVector(vec) {
602 return false // stop iteration
603 }
604 return true // continue iteration
605 })
606 }
607
608 func (s *IntSets) HasVersion(ver int) bool {
609 if s == nil {
610 return false
611 }
612 return s.versions.Has(ver)
613 }
614
615 func (s IntSets) shallowClone() *IntSets {
616 s.h = &hashOnce{}
617 return &s
618 }
619
620 // WithLanguageIndices replaces the current language set with the given language indices.
621 func (s *IntSets) WithLanguageIndices(indices ...int) VectorStore {
622 c := s.shallowClone()
623 c.languages = hmaps.NewOrderedIntSet(indices...)
624 return c.init()
625 }
626
627 // WithVersionIndices replaces the current version set with the given version indices.
628 func (s *IntSets) WithVersionIndices(indices ...int) VectorStore {
629 c := s.shallowClone()
630 c.versions = hmaps.NewOrderedIntSet(indices...)
631 return c.init()
632 }
633
634 // WithRoleIndices replaces the current role set with the given role indices.
635 func (s *IntSets) WithRoleIndices(indices ...int) VectorStore {
636 c := s.shallowClone()
637 c.roles = hmaps.NewOrderedIntSet(indices...)
638 return c.init()
639 }
640
641 func (s *IntSets) Hash() (uint64, error) {
642 s.initHash()
643 return s.h.hash, nil
644 }
645
646 func (s *IntSets) MustHash() uint64 {
647 if s == nil {
648 return 0
649 }
650 hash, err := s.Hash()
651 if err != nil {
652 panic(fmt.Errorf("failed to calculate hash for IntSets: %w", err))
653 }
654 return hash
655 }
656
657 // setDefaultsIfNotSet applies default values to the IntSets if they are not already set.
658 func (s *IntSets) setDefaultsIfNotSet(cfg *ConfiguredDimensions) {
659 if s.languages == nil {
660 s.languages = hmaps.NewOrderedIntSet()
661 s.languages.Set(cfg.ConfiguredLanguages.IndexDefault())
662 }
663 if s.versions == nil {
664 s.versions = hmaps.NewOrderedIntSet()
665 s.versions.Set(cfg.ConfiguredVersions.IndexDefault())
666 }
667 if s.roles == nil {
668 s.roles = hmaps.NewOrderedIntSet()
669 s.roles.Set(cfg.ConfiguredRoles.IndexDefault())
670 }
671 }
672
673 func (s *IntSets) setDefaultsAndAllLAnguagesIfNotSet(cfg *ConfiguredDimensions) {
674 if s.languages == nil {
675 s.languages = hmaps.NewOrderedIntSet()
676 for i := range cfg.ConfiguredLanguages.ForEachIndex() {
677 s.languages.Set(i)
678 }
679 }
680 s.setDefaultsIfNotSet(cfg)
681 }
682
683 func (s *IntSets) setAllIfNotSet(cfg *ConfiguredDimensions) {
684 if s.languages == nil {
685 s.languages = hmaps.NewOrderedIntSet()
686 for i := range cfg.ConfiguredLanguages.ForEachIndex() {
687 s.languages.Set(i)
688 }
689 }
690 if s.versions == nil {
691 s.versions = hmaps.NewOrderedIntSet()
692 for i := range cfg.ConfiguredVersions.ForEachIndex() {
693 s.versions.Set(i)
694 }
695 }
696 if s.roles == nil {
697 s.roles = hmaps.NewOrderedIntSet()
698 for i := range cfg.ConfiguredRoles.ForEachIndex() {
699 s.roles.Set(i)
700 }
701 }
702 }
703
704 func (s *IntSets) initHash() {
705 s.h.once.Do(func() {
706 var err error
707 s.h.hash, err = hashing.Hash(s.languages.Words(), s.versions.Words(), s.roles.Words())
708 if err != nil {
709 panic(fmt.Errorf("failed to calculate hash for IntSets: %w", err))
710 }
711 })
712 }
713
714 func (s *IntSets) init() *IntSets {
715 return s
716 }
717
718 func (s *IntSets) setDimensionsFromOtherIfNotSet(other VectorIterator) {
719 if other == nil {
720 return
721 }
722 setLang := s.languages == nil
723 setVer := s.versions == nil
724 setRole := s.roles == nil
725
726 if !(setLang || setVer || setRole) {
727 return
728 }
729
730 other.ForEachVector(func(v Vector) bool {
731 if !s.HasVector(v) {
732 s.setValuesInNilSets(v, setLang, setVer, setRole)
733 }
734 return true
735 })
736 }
737
738 func (s *IntSets) setValuesInNilSets(vec Vector, setLang, setVer, setRole bool) {
739 if setLang {
740 if s.languages == nil {
741 s.languages = hmaps.NewOrderedIntSet()
742 }
743 s.languages.Set(vec.Language())
744 }
745 if setVer {
746 if s.versions == nil {
747 s.versions = hmaps.NewOrderedIntSet()
748 }
749 s.versions.Set(vec.Version())
750 }
751
752 if setRole {
753 if s.roles == nil {
754 s.roles = hmaps.NewOrderedIntSet()
755 }
756 s.roles.Set(vec.Role())
757 }
758 }
759
760 type IntSetsBuilder struct {
761 cfg *ConfiguredDimensions
762 s *IntSets
763
764 // Set when a Glob (e.g. "en") filter is provided but no matches are found.
765 GlobFilterMisses Bools
766 }
767
768 func (b *IntSetsBuilder) Build() *IntSets {
769 b.s.init()
770
771 if b.s.LenVectors() == 1 {
772 // Cache it or use the existing cached version, which will allow b.s to be GCed.
773 bb, _ := b.cfg.singleVectorStoreCache.GetOrCreate(b.s.VectorSample(), func() (*IntSets, error) {
774 return b.s, nil
775 })
776 return bb
777 }
778 return b.s
779 }
780
781 func (b *IntSetsBuilder) WithConfig(cfg IntSetsConfig) *IntSetsBuilder {
782 applyFilter := func(what string, values []string, matcher ConfiguredDimension) *hmaps.OrderedIntSet {
783 var result *hmaps.OrderedIntSet
784 if len(values) == 0 {
785
786 if cfg.ApplyDefaults > 0 {
787 result = hmaps.NewOrderedIntSet()
788 }
789 switch cfg.ApplyDefaults {
790 case IntSetsConfigApplyDefaultsIfNotSet:
791 result.Set(matcher.IndexDefault())
792 case IntSetsConfigApplyDefaultsAndAllLanguagesIfNotSet:
793 if what == "languages" {
794 for i := range matcher.ForEachIndex() {
795 result.Set(i)
796 }
797 } else {
798 result.Set(matcher.IndexDefault())
799 }
800 }
801
802 return result
803 }
804
805 filter, err := predicate.NewIndexStringPredicateFromGlobsAndRanges(values, matcher.ResolveIndex, hglob.GetGlobDot)
806 if err != nil {
807 panic(fmt.Errorf("failed to create filter for %s: %w", what, err))
808 }
809 iter, err := matcher.IndexMatch(filter)
810 if err != nil {
811 panic(fmt.Errorf("failed to match %s %q: %w", what, values, err))
812 }
813 for i := range iter {
814 if result == nil {
815 result = hmaps.NewOrderedIntSet()
816 }
817 result.Set(i)
818 }
819
820 return result
821 }
822
823 l := applyFilter("languages", cfg.Globs.Languages, b.cfg.ConfiguredLanguages)
824 v := applyFilter("versions", cfg.Globs.Versions, b.cfg.ConfiguredVersions)
825 r := applyFilter("roles", cfg.Globs.Roles, b.cfg.ConfiguredRoles)
826
827 b.GlobFilterMisses = Bools{
828 len(cfg.Globs.Languages) > 0 && l == nil,
829 len(cfg.Globs.Versions) > 0 && v == nil,
830 len(cfg.Globs.Roles) > 0 && r == nil,
831 }
832
833 b.s.languages = l
834 b.s.versions = v
835 b.s.roles = r
836
837 return b
838 }
839
840 func (s *IntSetsBuilder) WithLanguageIndices(idxs ...int) *IntSetsBuilder {
841 if len(idxs) == 0 {
842 return s
843 }
844 if s.s.languages == nil {
845 s.s.languages = hmaps.NewOrderedIntSet()
846 }
847 for _, i := range idxs {
848 s.s.languages.Set(i)
849 }
850 return s
851 }
852
853 func (s *IntSetsBuilder) WithVersionIndices(idxs ...int) *IntSetsBuilder {
854 if len(idxs) == 0 {
855 return s
856 }
857 if s.s.versions == nil {
858 s.s.versions = hmaps.NewOrderedIntSet()
859 }
860 for _, i := range idxs {
861 s.s.versions.Set(i)
862 }
863 return s
864 }
865
866 func (s *IntSetsBuilder) WithRoleIndices(idxs ...int) *IntSetsBuilder {
867 if len(idxs) == 0 {
868 return s
869 }
870 if s.s.roles == nil {
871 s.s.roles = hmaps.NewOrderedIntSet()
872 }
873 for _, i := range idxs {
874 s.s.roles.Set(i)
875 }
876 return s
877 }
878
879 func (s *IntSetsBuilder) WithDefaultsAndAllLanguagesIfNotSet() *IntSetsBuilder {
880 s.s.setDefaultsAndAllLAnguagesIfNotSet(s.cfg)
881 return s
882 }
883
884 func (s *IntSetsBuilder) WithAllIfNotSet() *IntSetsBuilder {
885 s.s.setAllIfNotSet(s.cfg)
886 return s
887 }
888
889 func (s *IntSetsBuilder) WithDefaultsIfNotSet() *IntSetsBuilder {
890 s.s.setDefaultsIfNotSet(s.cfg)
891 return s
892 }
893
894 func (s *IntSetsBuilder) WithDimensionsFromOtherIfNotSet(other VectorIterator) *IntSetsBuilder {
895 s.s.setDimensionsFromOtherIfNotSet(other)
896 return s
897 }
898
899 func (b *IntSetsBuilder) WithSets(languages, versions, roles *hmaps.OrderedIntSet) *IntSetsBuilder {
900 b.s.languages = languages
901 b.s.versions = versions
902 b.s.roles = roles
903 return b
904 }
905
906 type IntSetsConfigApplyDefaults int
907
908 const (
909 IntSetsConfigApplyDefaultsNone IntSetsConfigApplyDefaults = iota
910 IntSetsConfigApplyDefaultsIfNotSet
911 IntSetsConfigApplyDefaultsAndAllLanguagesIfNotSet
912 )
913
914 type IntSetsConfig struct {
915 ApplyDefaults IntSetsConfigApplyDefaults
916 Globs StringSlices
917 }
918
919 // Sites holds configuration about which sites a file/content/page/resource belongs to.
920 type Sites struct {
921 // Matrix defines what sites to build this content for.
922 Matrix StringSlices `mapstructure:"matrix" json:"matrix"`
923 // Complements defines what sites to complement with this content.
924 Complements StringSlices `mapstructure:"complements" json:"complements"`
925 }
926
927 func (s *Sites) Equal(other Sites) bool {
928 return s.Matrix.Equal(other.Matrix) && s.Complements.Equal(other.Complements)
929 }
930
931 func (s *Sites) SetFromParamsIfNotSet(params hmaps.Params) {
932 const (
933 matrixKey = "matrix"
934 complementsKey = "complements"
935 )
936
937 if m, ok := params[matrixKey]; ok {
938 s.Matrix.SetFromParamsIfNotSet(m.(hmaps.Params))
939 }
940 if f, ok := params[complementsKey]; ok {
941 s.Complements.SetFromParamsIfNotSet(f.(hmaps.Params))
942 }
943 }
944
945 // IsZero returns true if all slices are empty.
946 func (s Sites) IsZero() bool {
947 return s.Matrix.IsZero() && s.Complements.IsZero()
948 }
949
950 // StringSlices holds slices of Glob patterns for languages, versions, and roles.
951 type StringSlices struct {
952 Languages []string `mapstructure:"languages" json:"languages"`
953 Versions []string `mapstructure:"versions" json:"versions"`
954 Roles []string `mapstructure:"roles" json:"roles"`
955 }
956
957 func (d StringSlices) Equal(other StringSlices) bool {
958 return slices.Equal(d.Languages, other.Languages) &&
959 slices.Equal(d.Versions, other.Versions) &&
960 slices.Equal(d.Roles, other.Roles)
961 }
962
963 func (d *StringSlices) SetFromParamsIfNotSet(params hmaps.Params) {
964 const (
965 languagesKey = "languages"
966 versionsKey = "versions"
967 rolesKey = "roles"
968 )
969
970 if len(d.Languages) == 0 {
971 if v, ok := params[languagesKey]; ok {
972 d.Languages = types.ToStringSlicePreserveString(v)
973 }
974 }
975
976 if len(d.Versions) == 0 {
977 if v, ok := params[versionsKey]; ok {
978 d.Versions = types.ToStringSlicePreserveString(v)
979 }
980 }
981
982 if len(d.Roles) == 0 {
983 if v, ok := params[rolesKey]; ok {
984 d.Roles = types.ToStringSlicePreserveString(v)
985 }
986 }
987 }
988
989 func (d StringSlices) IsZero() bool {
990 return len(d.Languages) == 0 && len(d.Versions) == 0 && len(d.Roles) == 0
991 }
992
993 // Used in tests.
994 type testDimension struct {
995 names []string
996 }
997
998 func (m testDimension) Len() int {
999 return len(m.names)
1000 }
1001
1002 func (m testDimension) IndexDefault() int {
1003 return 0
1004 }
1005
1006 func (m *testDimension) ResolveIndex(name string) int {
1007 for i, n := range m.names {
1008 if n == name {
1009 return i
1010 }
1011 }
1012 return -1
1013 }
1014
1015 func (m *testDimension) ResolveName(i int) string {
1016 if i < 0 || i >= len(m.names) {
1017 return ""
1018 }
1019 return m.names[i]
1020 }
1021
1022 func (m *testDimension) ForEachIndex() iter.Seq[int] {
1023 return func(yield func(i int) bool) {
1024 for i := range m.names {
1025 if !yield(i) {
1026 return
1027 }
1028 }
1029 }
1030 }
1031
1032 func (m *testDimension) IndexMatch(match predicate.P[predicate.IndexString]) (iter.Seq[int], error) {
1033 return func(yield func(i int) bool) {
1034 for i, n := range m.names {
1035 if match(predicate.IndexString{Index: i, String: n}) {
1036 if !yield(i) {
1037 return
1038 }
1039 }
1040 }
1041 }, nil
1042 }
1043
1044 // NewTestingDimensions creates a new ConfiguredDimensions for testing.
1045 func NewTestingDimensions(languages, versions, roles []string) *ConfiguredDimensions {
1046 c := &ConfiguredDimensions{
1047 ConfiguredLanguages: &testDimension{names: languages},
1048 ConfiguredVersions: &testDimension{names: versions},
1049 ConfiguredRoles: &testDimension{names: roles},
1050 }
1051 if err := c.Init(); err != nil {
1052 panic(err)
1053 }
1054 return c
1055 }