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