Debian Codegraph @

common/predicate/predicate.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 predicate
15
16 import (
17 "iter"
18 "strings"
19
20 "github.com/gobwas/glob"
21 "github.com/gohugoio/hugo/hugofs/hglob"
22 )
23
24 // Match represents the result of a predicate evaluation.
25 type Match interface {
26 OK() bool
27 }
28
29 var (
30 // Predefined Match values for common cases.
31 True = BoolMatch(true)
32 False = BoolMatch(false)
33 )
34
35 // BoolMatch is a simple Match implementation based on a boolean value.
36 type BoolMatch bool
37
38 func (b BoolMatch) OK() bool {
39 return bool(b)
40 }
41
42 // breakMatch is a Match implementation that always returns false for OK() and signals to break evaluation.
43 type breakMatch struct{}
44
45 func (b breakMatch) OK() bool {
46 return false
47 }
48
49 var matchBreak = breakMatch{}
50
51 // P is a predicate function that tests whether a value of type T satisfies some condition.
52 type P[T any] func(T) bool
53
54 // Or returns a predicate that is a short-circuiting logical OR of this and the given predicates.
55 // Note that P[T] only supports Or. For chained AND/OR logic, use PR[T].
56 func (p P[T]) Or(ps ...P[T]) P[T] {
57 return func(v T) bool {
58 if p != nil && p(v) {
59 return true
60 }
61 for _, pp := range ps {
62 if pp(v) {
63 return true
64 }
65 }
66 return false
67 }
68 }
69
70 // PR is a predicate function that tests whether a value of type T satisfies some condition and returns a Match result.
71 type PR[T any] func(T) Match
72
73 // BoolFunc returns a P[T] version of this predicate.
74 func (p PR[T]) BoolFunc() P[T] {
75 return func(v T) bool {
76 if p == nil {
77 return false
78 }
79 return p(v).OK()
80 }
81 }
82
83 // And returns a predicate that is a short-circuiting logical AND of this and the given predicates.
84 func (p PR[T]) And(ps ...PR[T]) PR[T] {
85 return func(v T) Match {
86 if p != nil {
87 m := p(v)
88 if !m.OK() || shouldBreak(m) {
89 return matchBreak
90 }
91 }
92 for _, pp := range ps {
93 m := pp(v)
94 if !m.OK() || shouldBreak(m) {
95 return matchBreak
96 }
97 }
98 return BoolMatch(true)
99 }
100 }
101
102 // Or returns a predicate that is a short-circuiting logical OR of this and the given predicates.
103 func (p PR[T]) Or(ps ...PR[T]) PR[T] {
104 return func(v T) Match {
105 if p != nil {
106 m := p(v)
107 if m.OK() {
108 return m
109 }
110 if shouldBreak(m) {
111 return matchBreak
112 }
113 }
114 for _, pp := range ps {
115 m := pp(v)
116 if m.OK() {
117 return m
118 }
119 if shouldBreak(m) {
120 return matchBreak
121 }
122 }
123 return BoolMatch(false)
124 }
125 }
126
127 func shouldBreak(m Match) bool {
128 _, ok := m.(breakMatch)
129 return ok
130 }
131
132 // Filter returns a new slice holding only the elements of s that satisfy p.
133 // Filter modifies the contents of the slice s and returns the modified slice, which may have a smaller length.
134 func (p PR[T]) Filter(s []T) []T {
135 var n int
136 for _, v := range s {
137 if p(v).OK() {
138 s[n] = v
139 n++
140 }
141 }
142 return s[:n]
143 }
144
145 // FilterCopy returns a new slice holding only the elements of s that satisfy p.
146 func (p PR[T]) FilterCopy(s []T) []T {
147 var result []T
148 for _, v := range s {
149 if p(v).OK() {
150 result = append(result, v)
151 }
152 }
153 return result
154 }
155
156 const (
157 rangeOpNone = iota
158 rangeOpLT
159 rangeOpLTE
160 rangeOpGT
161 rangeOpGTE
162 rangeOpEQ
163 rangeOpNE
164 )
165
166 func cutRangeOp(s string) (op int, rest string) {
167 switch {
168 case strings.HasPrefix(s, ">= "):
169 return rangeOpGTE, s[3:]
170 case strings.HasPrefix(s, "<= "):
171 return rangeOpLTE, s[3:]
172 case strings.HasPrefix(s, "== "):
173 return rangeOpEQ, s[3:]
174 case strings.HasPrefix(s, "!= "):
175 return rangeOpNE, s[3:]
176 case strings.HasPrefix(s, "> "):
177 return rangeOpGT, s[2:]
178 case strings.HasPrefix(s, "< "):
179 return rangeOpLT, s[2:]
180 default:
181 return rangeOpNone, s
182 }
183 }
184
185 // NewStringPredicateFromGlobs creates a string predicate from the given glob patterns.
186 // A glob pattern starting with "!" is a negation pattern which will be ANDed with the rest.
187 func NewStringPredicateFromGlobs(patterns []string, getGlob func(pattern string) (glob.Glob, error)) (P[string], error) {
188 var p PR[string]
189 for _, pattern := range patterns {
190 pattern = strings.TrimSpace(pattern)
191 if pattern == "" {
192 continue
193 }
194 negate := strings.HasPrefix(pattern, hglob.NegationPrefix)
195 if negate {
196 pattern = pattern[2:]
197 g, err := getGlob(pattern)
198 if err != nil {
199 return nil, err
200 }
201 p = p.And(func(s string) Match {
202 return BoolMatch(!g.Match(s))
203 })
204 } else {
205 g, err := getGlob(pattern)
206 if err != nil {
207 return nil, err
208 }
209 p = p.Or(func(s string) Match {
210 return BoolMatch(g.Match(s))
211 })
212
213 }
214 }
215
216 return p.BoolFunc(), nil
217 }
218
219 // NewIndexStringPredicateFromGlobsAndRanges creates an IndexString predicate from the given glob patterns and range patterns.
220 // A glob pattern starting with "!" is a negation pattern which will be ANDed with the rest.
221 // A range pattern is one of "> value", ">= value", "< value" or "<= value".
222 func NewIndexStringPredicateFromGlobsAndRanges(patterns []string, getIndex func(s string) int, getGlob func(pattern string) (glob.Glob, error)) (P[IndexString], error) {
223 var p PR[IndexString]
224 for _, pattern := range patterns {
225 pattern = strings.TrimSpace(pattern)
226 if pattern == "" {
227 continue
228 }
229 negate := strings.HasPrefix(pattern, hglob.NegationPrefix)
230 if negate {
231 pattern = pattern[2:]
232 g, err := getGlob(pattern)
233 if err != nil {
234 return nil, err
235 }
236 p = p.And(func(s IndexString) Match {
237 return BoolMatch(!g.Match(s.String))
238 })
239 } else {
240 // This can be either a glob or a value prefixed with one of >, >=, < or <=.
241 o, v := cutRangeOp(pattern)
242 if o != rangeOpNone {
243 i := getIndex(v)
244 if i == -1 {
245 // No match possible.
246 p = p.And(func(s IndexString) Match {
247 return BoolMatch(false)
248 })
249 continue
250 }
251 switch o {
252 // The greater values starts at the top with index 0.
253 case rangeOpGT:
254 p = p.And(func(s IndexString) Match {
255 return BoolMatch(s.Index < i)
256 })
257 case rangeOpGTE:
258 p = p.And(func(s IndexString) Match {
259 return BoolMatch(s.Index <= i)
260 })
261 case rangeOpLT:
262 p = p.And(func(s IndexString) Match {
263 return BoolMatch(s.Index > i)
264 })
265 case rangeOpLTE:
266 p = p.And(func(s IndexString) Match {
267 return BoolMatch(s.Index >= i)
268 })
269 case rangeOpEQ:
270 p = p.And(func(s IndexString) Match {
271 return BoolMatch(s.Index == i)
272 })
273 case rangeOpNE:
274 p = p.And(func(s IndexString) Match {
275 return BoolMatch(s.Index != i)
276 })
277 }
278 } else {
279 g, err := getGlob(pattern)
280 if err != nil {
281 return nil, err
282 }
283 p = p.Or(func(s IndexString) Match {
284 return BoolMatch(g.Match(s.String))
285 })
286 }
287
288 }
289 }
290
291 return p.BoolFunc(), nil
292 }
293
294 type IndexString struct {
295 Index int
296 String string
297 }
298
299 type IndexMatcher interface {
300 IndexMatch(match P[IndexString]) (iter.Seq[int], error)
301 }