Debian Codegraph @

hugofs/component_fs.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 hugofs
15
16 import (
17 "context"
18 iofs "io/fs"
19 "os"
20 "path"
21 "runtime"
22 "sort"
23
24 "github.com/bep/helpers/contexthelpers"
25 "github.com/gohugoio/hugo/common/herrors"
26 "github.com/gohugoio/hugo/common/paths"
27 "github.com/gohugoio/hugo/config"
28 "github.com/gohugoio/hugo/hugofs/files"
29 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
30 "github.com/spf13/afero"
31 "golang.org/x/text/unicode/norm"
32 )
33
34 // NewComponentFs creates a new component filesystem.
35 func NewComponentFs(opts ComponentFsOptions) *componentFs {
36 if opts.Component == "" {
37 panic("ComponentFsOptions.PathParser.Component must be set")
38 }
39 if opts.Fs == nil {
40 panic("ComponentFsOptions.Fs must be set")
41 }
42 bfs := NewBasePathFs(opts.Fs, opts.Component)
43 return &componentFs{Fs: bfs, opts: opts}
44 }
45
46 var (
47 _ FilesystemUnwrapper = (*componentFs)(nil)
48 _ ReadDirWithContextDir = (*componentFsDir)(nil)
49 _ afero.Lstater = (*componentFs)(nil)
50 )
51
52 // componentFs is a filesystem that holds one of the Hugo components, e.g. content, layouts etc.
53 type componentFs struct {
54 afero.Fs
55
56 opts ComponentFsOptions
57 }
58
59 func (fs *componentFs) UnwrapFilesystem() afero.Fs {
60 return fs.Fs
61 }
62
63 type componentFsDir struct {
64 *noOpRegularFileOps
65 DirOnlyOps
66 name string // the name passed to Open
67 fs *componentFs
68 }
69
70 type (
71 contextKey uint8
72 )
73
74 const (
75 contextKeyIsInLeafBundle contextKey = iota
76 )
77
78 var componentFsContext = struct {
79 IsInLeafBundle contexthelpers.ContextDispatcher[bool]
80 }{
81 IsInLeafBundle: contexthelpers.NewContextDispatcher[bool](contextKeyIsInLeafBundle),
82 }
83
84 func (f *componentFsDir) ReadDirWithContext(ctx context.Context, count int) ([]iofs.DirEntry, context.Context, error) {
85 fis, err := f.DirOnlyOps.(iofs.ReadDirFile).ReadDir(-1)
86 if err != nil {
87 return nil, ctx, err
88 }
89
90 // Filter out any symlinks.
91 n := 0
92 for _, fi := range fis {
93 // IsDir will always be false for symlinks.
94 keep := fi.IsDir()
95 if !keep {
96 // This is unfortunate, but is the only way to determine if it is a symlink.
97 info, err := fi.Info()
98 if err != nil {
99 if herrors.IsNotExist(err) {
100 continue
101 }
102 return nil, ctx, err
103 }
104 if info.Mode()&os.ModeSymlink == 0 {
105 keep = true
106 }
107 }
108 if keep {
109 fis[n] = fi
110 n++
111 }
112 }
113
114 fis = fis[:n]
115 n = 0
116
117 for _, fi := range fis {
118 s := path.Join(f.name, fi.Name())
119 if _, ok := f.fs.applyMeta(fi, s); ok {
120 fis[n] = fi
121 n++
122 }
123 }
124
125 fis = fis[:n]
126 n = 0
127
128 sort.Slice(fis, func(i, j int) bool {
129 fimi, fimj := fis[i].(FileMetaInfo), fis[j].(FileMetaInfo)
130 if fimi.IsDir() != fimj.IsDir() {
131 return fimi.IsDir()
132 }
133 fimim, fimjm := fimi.Meta(), fimj.Meta()
134
135 bi, bj := fimim.PathInfo.Base(), fimjm.PathInfo.Base()
136 if bi == bj {
137 // Check mount weight first for same module (earlier mounts should win).
138 if fimim.ModuleOrdinal == fimjm.ModuleOrdinal && fimim.Weight != fimjm.Weight {
139 return fimim.Weight > fimjm.Weight
140 }
141 matrixi, matrixj := fimim.SitesMatrix, fimjm.SitesMatrix
142 l1, l2 := matrixi.LenVectors(), matrixj.LenVectors()
143 if l1 != l2 {
144 // Pull the ones with the least number of sites defined to the top.
145 return l1 < l2
146 }
147 }
148
149 if fimim.ModuleOrdinal != fimjm.ModuleOrdinal {
150 switch f.fs.opts.Component {
151 case files.ComponentFolderI18n:
152 // The way the language files gets loaded means that
153 // we need to provide the least important files first (e.g. the theme files).
154 return fimim.ModuleOrdinal > fimjm.ModuleOrdinal
155 default:
156 return fimim.ModuleOrdinal < fimjm.ModuleOrdinal
157 }
158 }
159
160 pii, pij := fimim.PathInfo, fimjm.PathInfo
161 if pii != nil {
162 basei, basej := pii.Base(), pij.Base()
163 exti, extj := pii.Ext(), pij.Ext()
164 if f.fs.opts.Component == files.ComponentFolderContent {
165 // Pull bundles to the top.
166 if pii.IsBundle() != pij.IsBundle() {
167 return pii.IsBundle()
168 }
169 }
170
171 if exti != extj {
172 return exti > extj
173 }
174
175 if basei != basej {
176 return basei < basej
177 }
178 }
179
180 if fimim.Weight != fimjm.Weight {
181 return fimim.Weight > fimjm.Weight
182 }
183
184 return fimi.Name() < fimj.Name()
185 })
186
187 if f.fs.opts.Component == files.ComponentFolderContent {
188 isInLeafBundle := componentFsContext.IsInLeafBundle.Get(ctx)
189 var isCurrentLeafBundle bool
190 for _, fi := range fis {
191 if fi.IsDir() {
192 continue
193 }
194
195 pi := fi.(FileMetaInfo).Meta().PathInfo
196
197 if pi.IsLeafBundle() {
198 isCurrentLeafBundle = true
199 break
200 }
201 }
202
203 if !isInLeafBundle && isCurrentLeafBundle {
204 ctx = componentFsContext.IsInLeafBundle.Set(ctx, true)
205 }
206
207 if isInLeafBundle || isCurrentLeafBundle {
208 for _, fi := range fis {
209 if fi.IsDir() {
210 continue
211 }
212 pi := fi.(FileMetaInfo).Meta().PathInfo
213
214 if pi.Type() != paths.TypeContentData {
215 // Everything below a leaf bundle is a resource.
216 isResource := isInLeafBundle && pi.Type() > paths.TypeFile
217 // Every sibling of a leaf bundle is a resource.
218 isResource = isResource || (isCurrentLeafBundle && !pi.IsLeafBundle())
219
220 if isResource {
221 paths.ModifyPathBundleTypeResource(pi)
222 }
223 }
224 }
225 }
226
227 }
228
229 type typeBase struct {
230 Type paths.Type
231 Base string
232 }
233
234 variants := make(map[typeBase][]sitesmatrix.VectorProvider)
235
236 for _, fi := range fis {
237
238 if !fi.IsDir() {
239 meta := fi.(FileMetaInfo).Meta()
240
241 pi := meta.PathInfo
242
243 if pi.Component() == files.ComponentFolderLayouts || pi.Component() == files.ComponentFolderContent {
244
245 var base string
246 switch pi.Component() {
247 case files.ComponentFolderContent:
248 base = pi.Base() + pi.Custom()
249 default:
250 base = pi.PathNoLang()
251 }
252
253 baseName := typeBase{pi.Type(), base}
254
255 // There may be multiple languge/version/role combinations for the same file.
256 // The most important come early.
257 matrixes, found := variants[baseName]
258
259 if found {
260 complement := meta.SitesMatrix.Complement(matrixes...)
261 if complement == nil || complement.LenVectors() == 0 {
262 continue
263 }
264 matrixes = append(matrixes, meta.SitesMatrix)
265 meta.SitesMatrix = complement
266
267 variants[baseName] = matrixes
268
269 } else {
270 matrixes = []sitesmatrix.VectorProvider{meta.SitesMatrix}
271 variants[baseName] = matrixes
272
273 }
274 }
275 }
276
277 fis[n] = fi
278 n++
279
280 }
281 fis = fis[:n]
282
283 return fis, ctx, nil
284 }
285
286 // ReadDir reads count entries from this virtual directory and
287 // sorts the entries according to the component filesystem rules.
288 func (f *componentFsDir) ReadDir(count int) ([]iofs.DirEntry, error) {
289 v, _, err := ReadDirWithContext(context.Background(), f.DirOnlyOps, count)
290 return v, err
291 }
292
293 func (f *componentFsDir) Stat() (iofs.FileInfo, error) {
294 fi, err := f.DirOnlyOps.Stat()
295 if err != nil {
296 return nil, err
297 }
298 fim, _ := f.fs.applyMeta(fi, f.name)
299 return fim, nil
300 }
301
302 func (fs *componentFs) Stat(name string) (os.FileInfo, error) {
303 fi, err := fs.Fs.Stat(name)
304 if err != nil {
305 return nil, err
306 }
307 fim, _ := fs.applyMeta(fi, name)
308 return fim, nil
309 }
310
311 func (fs *componentFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
312 if lstater, ok := fs.Fs.(afero.Lstater); ok {
313 fi, b, err := lstater.LstatIfPossible(name)
314 if err != nil {
315 return nil, false, err
316 }
317 fim, ok := fs.applyMeta(fi, name)
318 if !ok {
319 return nil, false, os.ErrNotExist
320 }
321 return fim, b, nil
322 }
323
324 fi, err := fs.Stat(name)
325 return fi, false, err
326 }
327
328 func (fs *componentFs) applyMeta(fi FileNameIsDir, name string) (FileMetaInfo, bool) {
329 if runtime.GOOS == "darwin" {
330 name = norm.NFC.String(name)
331 }
332 fim := fi.(FileMetaInfo)
333 meta := fim.Meta()
334 pi := fs.opts.Cfg.PathParser().Parse(fs.opts.Component, name)
335 if pi.Disabled() {
336 return fim, false
337 }
338
339 meta.PathInfo = pi
340 if !fim.IsDir() {
341 pp := fs.opts.Cfg.PathParser()
342 if fileLang := meta.PathInfo.Lang(); fileLang != "" {
343 if idx, ok := pp.LanguageIndex[fileLang]; ok {
344 // A valid lang set in filename.
345 // Give priority to myfile.sv.txt inside the sv filesystem.
346 meta.Weight++
347 meta.SitesMatrix = meta.SitesMatrix.WithLanguageIndices(idx)
348 if idx > 0 {
349 // Not the default language, add some weight.
350 meta.SitesMatrix = sitesmatrix.NewWeightedVectorStore(meta.SitesMatrix, 10)
351 }
352 }
353 }
354 // Filename identifiers for roles/versions replace any mount configuration for that dimension.
355 if roles := pi.Roles(); len(roles) > 0 {
356 var indices []int
357 for _, role := range roles {
358 if idx := pp.ConfiguredDimensions.ConfiguredRoles.ResolveIndex(role); idx >= 0 {
359 indices = append(indices, idx)
360 }
361 }
362 if len(indices) > 0 {
363 meta.SitesMatrix = meta.SitesMatrix.WithRoleIndices(indices...)
364 }
365 }
366 if versions := pi.Versions(); len(versions) > 0 {
367 var indices []int
368 for _, version := range versions {
369 if idx := pp.ConfiguredDimensions.ConfiguredVersions.ResolveIndex(version); idx >= 0 {
370 indices = append(indices, idx)
371 }
372 }
373 if len(indices) > 0 {
374 meta.SitesMatrix = meta.SitesMatrix.WithVersionIndices(indices...)
375 }
376 }
377 switch meta.Component {
378 case files.ComponentFolderLayouts:
379 // Eg. index.fr.html when French isn't defined,
380 // we want e.g. index.html to be used instead.
381 if len(pi.IdentifiersUnknown()) > 0 {
382 meta.Weight--
383 }
384 }
385 }
386
387 if fi.IsDir() {
388 meta.OpenFunc = func() (afero.File, error) {
389 return fs.Open(name)
390 }
391 }
392
393 return fim, true
394 }
395
396 func (f *componentFsDir) Readdir(count int) ([]os.FileInfo, error) {
397 panic("not supported: Use ReadDir")
398 }
399
400 func (f *componentFsDir) Readdirnames(count int) ([]string, error) {
401 dirsi, err := f.DirOnlyOps.(iofs.ReadDirFile).ReadDir(count)
402 if err != nil {
403 return nil, err
404 }
405
406 dirs := make([]string, len(dirsi))
407 for i, d := range dirsi {
408 dirs[i] = d.Name()
409 }
410 return dirs, nil
411 }
412
413 type ComponentFsOptions struct {
414 // The filesystem where one or more components are mounted.
415 Fs afero.Fs
416
417 // The component name, e.g. "content", "layouts" etc.
418 Component string
419
420 Cfg config.AllProvider
421 }
422
423 func (fs *componentFs) Open(name string) (afero.File, error) {
424 f, err := fs.Fs.Open(name)
425 if err != nil {
426 return nil, err
427 }
428
429 fi, err := f.Stat()
430 if err != nil {
431 if err != errIsDir {
432 f.Close()
433 return nil, err
434 }
435 } else if !fi.IsDir() {
436 return f, nil
437 }
438
439 return &componentFsDir{
440 DirOnlyOps: f,
441 name: name,
442 fs: fs,
443 }, nil
444 }
445
446 func (fs *componentFs) ReadDir(name string) ([]os.FileInfo, error) {
447 panic("not implemented")
448 }