Debian Codegraph @

resources/resource/resources.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 resource contains Resource related types.
15 package resource
16
17 import (
18 "fmt"
19 "path"
20 "slices"
21 "strings"
22
23 "github.com/gohugoio/hashstructure"
24 "github.com/gohugoio/hugo/common/hashing"
25 "github.com/gohugoio/hugo/common/hmaps"
26 "github.com/gohugoio/hugo/common/hreflect"
27 "github.com/gohugoio/hugo/common/paths"
28 "github.com/gohugoio/hugo/hugofs/hglob"
29 "github.com/spf13/cast"
30 )
31
32 var _ ResourceFinder = (*Resources)(nil)
33
34 // Resources represents a slice of resources, which can be a mix of different types.
35 // I.e. both pages and images etc.
36 type Resources []Resource
37
38 type resourceMount struct {
39 R Resources
40 Base string
41 Target string
42 }
43
44 func (r resourceMount) Get(namev any) Resource {
45 name1, err := cast.ToStringE(namev)
46 if err != nil {
47 panic(err)
48 }
49
50 isTargetAbs := strings.HasPrefix(r.Target, "/")
51
52 if r.Target != "" {
53 name1 = strings.TrimPrefix(name1, r.Target)
54 if !isTargetAbs {
55 name1 = paths.TrimLeading(name1)
56 }
57 }
58
59 if r.Base != "" && isTargetAbs {
60 name1 = path.Join(r.Base, name1)
61 }
62
63 for _, res := range r.R {
64 name2 := res.Name()
65
66 if r.Base != "" && !isTargetAbs {
67 name2 = paths.TrimLeading(strings.TrimPrefix(name2, r.Base))
68 }
69
70 if strings.EqualFold(name1, name2) {
71 return res
72 }
73
74 }
75
76 return nil
77 }
78
79 // Mount mounts the given resources from base to the given target path.
80 // Note that leading slashes in target marks an absolute path.
81 // This method can be used in any of the template funcs that takes an importContext option, e.g. css.Build.
82 func (r Resources) Mount(base, target string) ResourceGetter {
83 return resourceMount{
84 R: r,
85 Base: base,
86 Target: target,
87 }
88 }
89
90 type ResourcesProvider interface {
91 // Resources returns a list of all resources.
92 Resources() Resources
93 }
94
95 // var _ resource.ResourceFinder = (*Namespace)(nil)
96 // ResourcesConverter converts a given slice of Resource objects to Resources.
97 type ResourcesConverter interface {
98 // For internal use.
99 ToResources() Resources
100 }
101
102 // ByType returns resources of a given resource type (e.g. "image").
103 func (r Resources) ByType(typ any) Resources {
104 tpstr, err := cast.ToStringE(typ)
105 if err != nil {
106 panic(err)
107 }
108 var filtered Resources
109
110 for _, resource := range r {
111 if resource.ResourceType() == tpstr {
112 filtered = append(filtered, resource)
113 }
114 }
115 return filtered
116 }
117
118 // Get locates the name given in Resources.
119 // The search is case insensitive.
120 func (r Resources) Get(name any) Resource {
121 if r == nil {
122 return nil
123 }
124 namestr, err := cast.ToStringE(name)
125 if err != nil {
126 panic(err)
127 }
128
129 isDotCurrent := strings.HasPrefix(namestr, "./")
130 if isDotCurrent {
131 namestr = strings.TrimPrefix(namestr, "./")
132 } else {
133 namestr = paths.AddLeadingSlash(namestr)
134 }
135
136 check := func(name string) bool {
137 if !isDotCurrent {
138 name = paths.AddLeadingSlash(name)
139 }
140 return strings.EqualFold(namestr, name)
141 }
142
143 // First check the Name.
144 // Note that this can be modified by the user in the front matter,
145 // also, it does not contain any language code.
146 for _, resource := range r {
147 if check(resource.Name()) {
148 return resource
149 }
150 }
151
152 // Finally, check the normalized name.
153 for _, resource := range r {
154 if nop, ok := resource.(NameNormalizedProvider); ok {
155 if check(nop.NameNormalized()) {
156 return resource
157 }
158 }
159 }
160
161 return nil
162 }
163
164 // GetMatch finds the first Resource matching the given pattern, or nil if none found.
165 // See Match for a more complete explanation about the rules used.
166 func (r Resources) GetMatch(pattern any) Resource {
167 patternstr, err := cast.ToStringE(pattern)
168 if err != nil {
169 panic(err)
170 }
171
172 g, err := hglob.GetGlob(paths.AddLeadingSlash(patternstr))
173 if err != nil {
174 panic(err)
175 }
176
177 for _, resource := range r {
178 if g.Match(paths.AddLeadingSlash(resource.Name())) {
179 return resource
180 }
181 }
182
183 // Finally, check the normalized name.
184 for _, resource := range r {
185 if nop, ok := resource.(NameNormalizedProvider); ok {
186 if g.Match(paths.AddLeadingSlash(nop.NameNormalized())) {
187 return resource
188 }
189 }
190 }
191
192 return nil
193 }
194
195 // Match gets all resources matching the given base filename prefix, e.g
196 // "*.png" will match all png files. The "*" does not match path delimiters (/),
197 // so if you organize your resources in sub-folders, you need to be explicit about it, e.g.:
198 // "images/*.png". To match any PNG image anywhere in the bundle you can do "**.png", and
199 // to match all PNG images below the images folder, use "images/**.jpg".
200 // The matching is case insensitive.
201 // Match matches by using the value of Resource.Name, which, by default, is a filename with
202 // path relative to the bundle root with Unix style slashes (/) and no leading slash, e.g. "images/logo.png".
203 // See https://github.com/gobwas/glob for the full rules set.
204 func (r Resources) Match(pattern any) Resources {
205 patternstr, err := cast.ToStringE(pattern)
206 if err != nil {
207 panic(err)
208 }
209
210 g, err := hglob.GetGlob(paths.AddLeadingSlash(patternstr))
211 if err != nil {
212 panic(err)
213 }
214
215 var matches Resources
216 for _, resource := range r {
217 if g.Match(paths.AddLeadingSlash(resource.Name())) {
218 matches = append(matches, resource)
219 }
220 }
221 if len(matches) == 0 {
222 // Fall back to the normalized name.
223 for _, resource := range r {
224 if nop, ok := resource.(NameNormalizedProvider); ok {
225 if g.Match(paths.AddLeadingSlash(nop.NameNormalized())) {
226 matches = append(matches, resource)
227 }
228 }
229 }
230 }
231 return matches
232 }
233
234 type translatedResource interface {
235 TranslationKey() string
236 }
237
238 // MergeByLanguage adds missing translations in r1 from r2.
239 func (r Resources) MergeByLanguage(r2 Resources) Resources {
240 result := slices.Clone(r)
241 m := make(map[string]bool)
242 for _, rr := range r {
243 if translated, ok := rr.(translatedResource); ok {
244 m[translated.TranslationKey()] = true
245 }
246 }
247
248 for _, rr := range r2 {
249 if translated, ok := rr.(translatedResource); ok {
250 if _, found := m[translated.TranslationKey()]; !found {
251 result = append(result, rr)
252 }
253 }
254 }
255 return result
256 }
257
258 // MergeByLanguageInterface is the generic version of MergeByLanguage. It
259 // is here just so it can be called from the tpl package.
260 // This is for internal use.
261 func (r Resources) MergeByLanguageInterface(in any) (any, error) {
262 r2, ok := in.(Resources)
263 if !ok {
264 return nil, fmt.Errorf("%T cannot be merged by language", in)
265 }
266 return r.MergeByLanguage(r2), nil
267 }
268
269 // Source is an internal template and not meant for use in the templates. It
270 // may change without notice.
271 type Source interface {
272 Publish() error
273 }
274
275 type ResourceGetter interface {
276 // Get locates the Resource with the given name in the current context (e.g. in .Page.Resources).
277 //
278 // It returns nil if no Resource could found, panics if name is invalid.
279 Get(name any) Resource
280 }
281
282 type IsProbablySameResourceGetter interface {
283 IsProbablySameResourceGetter(other ResourceGetter) bool
284 }
285
286 // StaleInfoResourceGetter is a ResourceGetter that also provides information about
287 // whether the underlying resources are stale.
288 type StaleInfoResourceGetter interface {
289 StaleInfo
290 ResourceGetter
291 }
292
293 // ResourceFinder provides methods to find Resources.
294 // Note that GetRemote (as found in resources.GetRemote) is
295 // not covered by this interface, as this is only available as a global template function.
296 type ResourceFinder interface {
297 ResourceGetter
298
299 // GetMatch finds the first Resource matching the given pattern, or nil if none found.
300 //
301 // See Match for a more complete explanation about the rules used.
302 //
303 // It returns nil if no Resource could found, panics if pattern is invalid.
304 GetMatch(pattern any) Resource
305
306 // Match gets all resources matching the given base path prefix, e.g
307 // "*.png" will match all png files. The "*" does not match path delimiters (/),
308 // so if you organize your resources in sub-folders, you need to be explicit about it, e.g.:
309 // "images/*.png". To match any PNG image anywhere in the bundle you can do "**.png", and
310 // to match all PNG images below the images folder, use "images/**.jpg".
311 //
312 // The matching is case insensitive.
313 //
314 // Match matches by using a relative pathwith Unix style slashes (/) and no
315 // leading slash, e.g. "images/logo.png".
316 //
317 // See https://github.com/gobwas/glob for the full rules set.
318 //
319 // See Match for a more complete explanation about the rules used.
320 //
321 // It returns nil if no Resources could found, panics if pattern is invalid.
322 Match(pattern any) Resources
323
324 // ByType returns resources of a given resource type (e.g. "image").
325 // It returns nil if no Resources could found, panics if typ is invalid.
326 ByType(typ any) Resources
327 }
328
329 var _ hashstructure.Hashable = (*cachedResourceGetter)(nil)
330
331 // NewCachedResourceGetter creates a new ResourceGetter from the given objects.
332 // If multiple objects are provided, they are merged into one where
333 // the first match wins.
334 func NewCachedResourceGetter(os ...any) *cachedResourceGetter {
335 var getters multiResourceGetter
336 for _, o := range os {
337 if g, ok := unwrapResourceGetter(o); ok {
338 getters = append(getters, g)
339 }
340 }
341
342 hash := hashing.HashUint64(getters)
343
344 return &cachedResourceGetter{
345 cache: hmaps.NewCache[string, Resource](),
346 delegate: getters,
347 hash: hash,
348 }
349 }
350
351 func (c *cachedResourceGetter) Hash() (uint64, error) {
352 return c.hash, nil
353 }
354
355 type multiResourceGetter []ResourceGetter
356
357 func (m multiResourceGetter) Get(name any) Resource {
358 for _, g := range m {
359 if res := g.Get(name); res != nil {
360 return res
361 }
362 }
363 return nil
364 }
365
366 var (
367 _ ResourceGetter = (*cachedResourceGetter)(nil)
368 _ IsProbablySameResourceGetter = (*cachedResourceGetter)(nil)
369 )
370
371 type cachedResourceGetter struct {
372 cache *hmaps.Cache[string, Resource]
373 delegate ResourceGetter
374 hash uint64
375 }
376
377 func (c *cachedResourceGetter) Get(name any) Resource {
378 namestr, err := cast.ToStringE(name)
379 if err != nil {
380 panic(err)
381 }
382 v, _ := c.cache.GetOrCreate(namestr, func() (Resource, error) {
383 v := c.delegate.Get(name)
384 return v, nil
385 })
386 return v
387 }
388
389 func (c *cachedResourceGetter) IsProbablySameResourceGetter(other ResourceGetter) bool {
390 isProbablyEq := true
391 c.cache.ForEeach(func(k string, v Resource) bool {
392 if v != other.Get(k) {
393 isProbablyEq = false
394 return false
395 }
396 return true
397 })
398
399 return isProbablyEq
400 }
401
402 func unwrapResourceGetter(v any) (ResourceGetter, bool) {
403 if v == nil {
404 return nil, false
405 }
406 switch vv := v.(type) {
407 case ResourceGetter:
408 return vv, true
409 case ResourcesProvider:
410 return vv.Resources(), true
411 default:
412 vvv, ok := hreflect.ToSliceAny(v)
413 if !ok {
414 return nil, false
415 }
416 var getters multiResourceGetter
417 for _, vv := range vvv {
418 if g, ok := unwrapResourceGetter(vv); ok {
419 getters = append(getters, g)
420 }
421 }
422 return getters, len(getters) > 0
423 }
424 }