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/gohugoio/hugo/common/hmaps"
21 "github.com/gohugoio/hugo/common/hstrings"
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(
157 fields,
158 func(fields SegmentMatcherFields) []string { return fields.Kind },
159 func(fields SegmentQuery) string { return fields.Kind },
160 ); err != nil {
161 return result, err
162 }
163 }
164 if len(fields.Path) > 0 {
165 if err := addToSection(
166 fields,
167 func(fields SegmentMatcherFields) []string { return fields.Path },
168 func(fields SegmentQuery) string { return fields.Path },
169 ); err != nil {
170 return result, err
171 }
172 }
173 if fields.Lang != "" {
174 hugo.DeprecateWithLogger("config segments.[...]lang ", "Use sites.matrix instead, see https://gohugo.io/configuration/segments/#segment-definition", "v0.153.0", s.logger.Logger())
175 fields.Sites.Matrix.Languages = []string{fields.Lang}
176 }
177 if !fields.Sites.Matrix.IsZero() {
178 intSetsCfg := sitesmatrix.IntSetsConfig{
179 Globs: fields.Sites.Matrix,
180 }
181 matrix := sitesmatrix.NewIntSetsBuilder(s.configuredDimensions).WithConfig(intSetsCfg).WithAllIfNotSet().Build()
182
183 addSectionMatcher(
184 func(fields SegmentQuery) predicate.Match {
185 return predicate.BoolMatch(matrix.HasVector(fields.Site))
186 },
187 )
188 }
189 if len(fields.Output) > 0 {
190 if err := addToSection(
191 fields,
192 func(fields SegmentMatcherFields) []string { return fields.Output },
193 func(fields SegmentQuery) string { return fields.Output },
194 ); err != nil {
195 return result, err
196 }
197 }
198
199 if result == nil {
200 result = section
201 } else {
202 result = result.Or(section)
203 }
204 section = nil
205
206 }
207 return result, nil
208 }
209
210 func (s *segmentsBuilder) build() (SegmentFilter, error) {
211 var sf segmentFilter
212
213 for _, segID := range s.segmentsToRender {
214 segCfg, ok := s.segmentCfg[segID]
215 if !ok {
216 continue
217 }
218
219 include, err := s.buildOne(segCfg.Includes)
220 if err != nil {
221 return nil, err
222 }
223
224 exclude, err := s.buildOne(segCfg.Excludes)
225 if err != nil {
226 return nil, err
227 }
228 if include == nil {
229 include = matchAll
230 }
231 if exclude == nil {
232 exclude = matchNothing
233 }
234 sf.segments = append(sf.segments, segmentPredicate{include: include, exclude: exclude})
235 }
236
237 if len(sf.segments) == 0 {
238 sf.segments = append(sf.segments, segmentPredicate{include: matchAll, exclude: matchNothing})
239 }
240
241 return sf, nil
242 }
243
244 func (b *Segments) InitConfig(logger loggers.Logger, _ sitesmatrix.VectorStore, configuredDimensions *sitesmatrix.ConfiguredDimensions) error {
245 if b.builder == nil || b.builder.isConfigInit {
246 return nil
247 }
248 b.builder.isConfigInit = true
249 b.builder.configuredDimensions = configuredDimensions
250 return b.compile()
251 }
252
253 var (
254 matchAll = func(SegmentQuery) predicate.Match { return predicate.True }
255 matchNothing = func(SegmentQuery) predicate.Match { return predicate.False }
256 )
257
258 type SegmentConfig struct {
259 Excludes []SegmentMatcherFields
260 Includes []SegmentMatcherFields
261 }
262
263 type SegmentQuery struct {
264 Kind string
265 Path string
266 Output string
267 Site sitesmatrix.Vector
268 }
269
270 // SegmentMatcherFields holds string slices of ordered filters for segment matching.
271 // The Glob patterns can be negated by prefixing with "! ".
272 // The first match wins (either include or exclude).
273 type SegmentMatcherFields struct {
274 Kind []string
275 Path []string
276 Output []string
277 Lang string // Deprecated: use Sites.Matrix instead.
278 Sites sitesmatrix.Sites // Note that we only use Sites.Matrix for now.
279 }
280
281 func getGlob(s string) (hstrings.Matcher, error) {
282 if s == "" {
283 return nil, nil
284 }
285 g, err := hglob.GetGlob(s)
286 if err != nil {
287 return nil, fmt.Errorf("failed to compile Glob %q: %w", s, err)
288 }
289 return g, nil
290 }
291
292 func DecodeSegments(in map[string]any, segmentsToRender []string, logger loggers.Logger) (*config.ConfigNamespace[map[string]SegmentConfig, *Segments], error) {
293 buildConfig := func(in any) (*Segments, any, error) {
294 m, err := hmaps.ToStringMapE(in)
295 if err != nil {
296 return nil, nil, err
297 }
298 if m == nil {
299 m = map[string]any{}
300 }
301 m = hmaps.CleanConfigStringMap(m)
302
303 var segmentCfg map[string]SegmentConfig
304 if err := mapstructure.WeakDecode(m, &segmentCfg); err != nil {
305 return nil, nil, err
306 }
307
308 sms := &Segments{
309 builder: &segmentsBuilder{
310 logger: logger,
311 segmentCfg: segmentCfg,
312 segmentsToRender: segmentsToRender,
313 },
314 }
315
316 return sms, nil, nil
317 }
318
319 ns, err := config.DecodeNamespace[map[string]SegmentConfig](in, buildConfig)
320 if err != nil {
321 return nil, fmt.Errorf("failed to decode segments: %w", err)
322 }
323 return ns, nil
324 }