Debian Codegraph @

hugolib/segments/segments.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 segments
15
16 import (
17 "fmt"
18 "strings"
19
20 "github.com/gobwas/glob"
21 "github.com/gohugoio/hugo/common/hmaps"
22 "github.com/gohugoio/hugo/common/hugo"
23 "github.com/gohugoio/hugo/common/loggers"
24 "github.com/gohugoio/hugo/common/predicate"
25 "github.com/gohugoio/hugo/config"
26 hglob "github.com/gohugoio/hugo/hugofs/hglob"
27 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
28 "github.com/mitchellh/mapstructure"
29 )
30
31 // Segments is a collection of named segments.
32 type Segments struct {
33 builder *segmentsBuilder
34
35 // SegmentFilter is the compiled filter for all segments to render.
36 SegmentFilter SegmentFilter
37 }
38
39 type SegmentFilter interface {
40 // ShouldExcludeCoarse returns whether the given fields should be excluded on a coarse level.
41 ShouldExcludeCoarse(SegmentQuery) bool
42
43 // ShouldExcludeFine returns whether the given fields should be excluded on a fine level.
44 ShouldExcludeFine(SegmentQuery) bool
45 }
46
47 type segmentFilter struct {
48 exclude predicate.PR[SegmentQuery]
49 include predicate.PR[SegmentQuery]
50 }
51
52 func (f segmentFilter) ShouldExcludeCoarse(q SegmentQuery) bool {
53 return f.exclude(q).OK()
54 }
55
56 func (f segmentFilter) ShouldExcludeFine(q SegmentQuery) bool {
57 return f.exclude(q).OK() || !f.include(q).OK()
58 }
59
60 type segmentsBuilder struct {
61 logger loggers.Logger
62 isConfigInit bool
63 configuredDimensions *sitesmatrix.ConfiguredDimensions
64 segmentCfg map[string]SegmentConfig
65 segmentsToRender []string
66 }
67
68 func (b *Segments) compile() error {
69 filter, err := b.builder.build()
70 if err != nil {
71 return err
72 }
73 b.SegmentFilter = filter
74 b.builder = nil
75 return nil
76 }
77
78 func (s *segmentsBuilder) buildOne(f []SegmentMatcherFields) (predicate.PR[SegmentQuery], error) {
79 if f == nil {
80 return matchNothing, nil
81 }
82 var (
83 result predicate.PR[SegmentQuery]
84 section predicate.PR[SegmentQuery]
85 )
86
87 addSectionMatcher := func(matcher predicate.PR[SegmentQuery]) {
88 if section == nil {
89 section = matcher
90 } else {
91 section = section.And(matcher)
92 }
93 }
94
95 addToSection := func(matcherFields SegmentMatcherFields, f1 func(fields SegmentMatcherFields) []string, f2 func(q SegmentQuery) string) error {
96 s1 := f1(matcherFields)
97 if s1 == nil {
98 // Nothing to match against.
99 return nil
100 }
101 var sliceMatcher predicate.PR[SegmentQuery]
102
103 for _, s := range s1 {
104 negate := strings.HasPrefix(s, hglob.NegationPrefix)
105 if negate {
106 s = strings.TrimPrefix(s, hglob.NegationPrefix)
107 }
108
109 g, err := getGlob(s)
110 if err != nil {
111 return err
112 }
113
114 m := func(fields SegmentQuery) predicate.Match {
115 s2 := f2(fields)
116 if s2 == "" {
117 return predicate.False
118 }
119 return predicate.BoolMatch(g.Match(s2) != negate)
120 }
121
122 if negate {
123 sliceMatcher = sliceMatcher.And(m)
124 } else {
125 sliceMatcher = sliceMatcher.Or(m)
126 }
127 }
128
129 if sliceMatcher != nil {
130 addSectionMatcher(sliceMatcher)
131 }
132
133 return nil
134 }
135
136 for _, fields := range f {
137 if len(fields.Kind) > 0 {
138 if err := addToSection(fields,
139 func(fields SegmentMatcherFields) []string { return fields.Kind },
140 func(fields SegmentQuery) string { return fields.Kind },
141 ); err != nil {
142 return result, err
143 }
144 }
145 if len(fields.Path) > 0 {
146 if err := addToSection(fields,
147 func(fields SegmentMatcherFields) []string { return fields.Path },
148 func(fields SegmentQuery) string { return fields.Path },
149 ); err != nil {
150 return result, err
151 }
152 }
153 if fields.Lang != "" {
154 hugo.DeprecateWithLogger("config segments.[...]lang ", "Use sites.matrix instead, see https://gohugo.io/configuration/segments/#segment-definition", "v0.153.0", s.logger.Logger())
155 fields.Sites.Matrix.Languages = []string{fields.Lang}
156 }
157 if !fields.Sites.Matrix.IsZero() {
158 intSetsCfg := sitesmatrix.IntSetsConfig{
159 Globs: fields.Sites.Matrix,
160 }
161 matrix := sitesmatrix.NewIntSetsBuilder(s.configuredDimensions).WithConfig(intSetsCfg).WithAllIfNotSet().Build()
162
163 addSectionMatcher(
164 func(fields SegmentQuery) predicate.Match {
165 return predicate.BoolMatch(matrix.HasVector(fields.Site))
166 },
167 )
168 }
169 if len(fields.Output) > 0 {
170 if err := addToSection(fields,
171 func(fields SegmentMatcherFields) []string { return fields.Output },
172 func(fields SegmentQuery) string { return fields.Output },
173 ); err != nil {
174 return result, err
175 }
176 }
177
178 if result == nil {
179 result = section
180 } else {
181 result = result.Or(section)
182 }
183 section = nil
184
185 }
186 return result, nil
187 }
188
189 func (s *segmentsBuilder) build() (SegmentFilter, error) {
190 var sf segmentFilter
191
192 for _, segID := range s.segmentsToRender {
193 segCfg, ok := s.segmentCfg[segID]
194 if !ok {
195 continue
196 }
197
198 include, err := s.buildOne(segCfg.Includes)
199 if err != nil {
200 return nil, err
201 }
202
203 exclude, err := s.buildOne(segCfg.Excludes)
204 if err != nil {
205 return nil, err
206 }
207 if sf.include == nil {
208 sf.include = include
209 } else {
210 sf.include = sf.include.Or(include)
211 }
212 if sf.exclude == nil {
213 sf.exclude = exclude
214 } else {
215 sf.exclude = sf.exclude.Or(exclude)
216 }
217 }
218
219 if sf.exclude == nil {
220 sf.exclude = matchNothing
221 }
222 if sf.include == nil {
223 sf.include = matchAll
224 }
225
226 return sf, nil
227 }
228
229 func (b *Segments) InitConfig(logger loggers.Logger, _ sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error {
230 if b.builder == nil || b.builder.isConfigInit {
231 return nil
232 }
233 b.builder.isConfigInit = true
234 b.builder.configuredDimensions = configuredDimensions
235 return b.compile()
236 }
237
238 var (
239 matchAll = func(SegmentQuery) predicate.Match { return predicate.True }
240 matchNothing = func(SegmentQuery) predicate.Match { return predicate.False }
241 )
242
243 type SegmentConfig struct {
244 Excludes []SegmentMatcherFields
245 Includes []SegmentMatcherFields
246 }
247
248 type SegmentQuery struct {
249 Kind string
250 Path string
251 Output string
252 Site sitesmatrix.Vector
253 }
254
255 // SegmentMatcherFields holds string slices of ordered filters for segment matching.
256 // The Glob patterns can be negated by prefixing with "! ".
257 // The first match wins (either include or exclude).
258 type SegmentMatcherFields struct {
259 Kind []string
260 Path []string
261 Output []string
262 Lang string // Deprecated: use Sites.Matrix instead.
263 Sites sitesmatrix.Sites // Note that we only use Sites.Matrix for now.
264 }
265
266 func getGlob(s string) (glob.Glob, error) {
267 if s == "" {
268 return nil, nil
269 }
270 g, err := hglob.GetGlob(s)
271 if err != nil {
272 return nil, fmt.Errorf("failed to compile Glob %q: %w", s, err)
273 }
274 return g, nil
275 }
276
277 func DecodeSegments(in map[string]any, segmentsToRender []string, logger loggers.Logger) (*config.ConfigNamespace[map[string]SegmentConfig, *Segments], error) {
278 buildConfig := func(in any) (*Segments, any, error) {
279 m, err := hmaps.ToStringMapE(in)
280 if err != nil {
281 return nil, nil, err
282 }
283 if m == nil {
284 m = map[string]any{}
285 }
286 m = hmaps.CleanConfigStringMap(m)
287
288 var segmentCfg map[string]SegmentConfig
289 if err := mapstructure.WeakDecode(m, &segmentCfg); err != nil {
290 return nil, nil, err
291 }
292
293 sms := &Segments{
294 builder: &segmentsBuilder{
295 logger: logger,
296 segmentCfg: segmentCfg,
297 segmentsToRender: segmentsToRender,
298 },
299 }
300
301 return sms, nil, nil
302 }
303
304 ns, err := config.DecodeNamespace[map[string]SegmentConfig](in, buildConfig)
305 if err != nil {
306 return nil, fmt.Errorf("failed to decode segments: %w", err)
307 }
308 return ns, nil
309 }