Debian Codegraph @

hugolib/filesystems/basefs.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 filesystems provides the fine grained file systems used by Hugo. These
15 // are typically virtual filesystems that are composites of project and theme content.
16 package filesystems
17
18 import (
19 "context"
20 "fmt"
21 "io"
22 "os"
23 "path/filepath"
24 "strings"
25 "sync"
26
27 "github.com/bep/overlayfs"
28 "github.com/gohugoio/hugo/config"
29 "github.com/gohugoio/hugo/htesting"
30 "github.com/gohugoio/hugo/langs"
31
32 "github.com/gohugoio/hugo/common/herrors"
33 "github.com/gohugoio/hugo/common/hugo"
34 "github.com/gohugoio/hugo/common/loggers"
35
36 "github.com/rogpeppe/go-internal/lockedfile"
37
38 "github.com/gohugoio/hugo/hugofs/files"
39 "github.com/gohugoio/hugo/hugofs/hglob"
40
41 "github.com/gohugoio/hugo/modules"
42
43 hpaths "github.com/gohugoio/hugo/common/paths"
44 "github.com/gohugoio/hugo/hugofs"
45 "github.com/gohugoio/hugo/hugolib/paths"
46 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
47 "github.com/spf13/afero"
48 )
49
50 const (
51 // Used to control concurrency between multiple Hugo instances, e.g.
52 // a running server and building new content with 'hugo new'.
53 // It's placed in the project root.
54 lockFileBuild = ".hugo_build.lock"
55 )
56
57 var filePathSeparator = string(filepath.Separator)
58
59 // BaseFs contains the core base filesystems used by Hugo. The name "base" is used
60 // to underline that even if they can be composites, they all have a base path set to a specific
61 // resource folder, e.g "/my-project/content". So, no absolute filenames needed.
62 type BaseFs struct {
63 // SourceFilesystems contains the different source file systems.
64 *SourceFilesystems
65
66 // The source filesystem (needs absolute filenames).
67 SourceFs afero.Fs
68
69 // The project source.
70 ProjectSourceFs afero.Fs
71
72 // The filesystem used to publish the rendered site.
73 // This usually maps to /my-project/public.
74 PublishFs afero.Fs
75
76 // The filesystem used for static files.
77 PublishFsStatic afero.Fs
78
79 // A read-only filesystem starting from the project workDir.
80 WorkDir afero.Fs
81
82 theBigFs *filesystemsCollector
83
84 workingDir string
85
86 // Locks.
87 buildMu Lockable // <project>/.hugo_build.lock
88 }
89
90 type Lockable interface {
91 Lock() (unlock func(), err error)
92 }
93
94 type fakeLockfileMutex struct {
95 mu sync.Mutex
96 }
97
98 func (f *fakeLockfileMutex) Lock() (func(), error) {
99 f.mu.Lock()
100 return func() { f.mu.Unlock() }, nil
101 }
102
103 // Tries to acquire a build lock.
104 func (b *BaseFs) LockBuild() (unlock func(), err error) {
105 return b.buildMu.Lock()
106 }
107
108 func (b *BaseFs) WatchFilenames() []string {
109 var filenames []string
110 sourceFs := b.SourceFs
111
112 for _, rfs := range b.RootFss {
113 for _, component := range files.ComponentFolders {
114 fis, err := rfs.Mounts(component)
115 if err != nil {
116 continue
117 }
118
119 for _, fim := range fis {
120 meta := fim.Meta()
121 if !meta.Watch {
122 continue
123 }
124
125 if !fim.IsDir() {
126 filenames = append(filenames, meta.Filename)
127 continue
128 }
129
130 w := hugofs.NewWalkway(hugofs.WalkwayConfig{
131 Fs: sourceFs,
132 Root: meta.Filename,
133 WalkFn: func(ctx context.Context, path string, fi hugofs.FileMetaInfo) error {
134 if !fi.IsDir() {
135 return nil
136 }
137 if fi.Name() == ".git" ||
138 fi.Name() == "node_modules" || fi.Name() == "bower_components" {
139 return filepath.SkipDir
140 }
141 filenames = append(filenames, fi.Meta().Filename)
142 return nil
143 },
144 })
145
146 w.Walk()
147 }
148
149 }
150 }
151
152 return filenames
153 }
154
155 func (b *BaseFs) mountsForComponent(component string) []hugofs.FileMetaInfo {
156 var result []hugofs.FileMetaInfo
157 for _, rfs := range b.RootFss {
158 dirs, err := rfs.Mounts(component)
159 if err == nil {
160 result = append(result, dirs...)
161 }
162 }
163 return result
164 }
165
166 // AbsProjectContentDir tries to construct a filename below the most
167 // relevant content directory.
168 func (b *BaseFs) AbsProjectContentDir(filename string) (string, string, error) {
169 isAbs := filepath.IsAbs(filename)
170 for _, fi := range b.mountsForComponent(files.ComponentFolderContent) {
171 if !fi.IsDir() {
172 continue
173 }
174 meta := fi.Meta()
175 if !meta.IsProject {
176 continue
177 }
178
179 if isAbs {
180 if strings.HasPrefix(filename, meta.Filename) {
181 return strings.TrimPrefix(filename, meta.Filename+filePathSeparator), filename, nil
182 }
183 } else {
184 contentDir := strings.TrimPrefix(strings.TrimPrefix(meta.Filename, meta.BaseDir), filePathSeparator) + filePathSeparator
185
186 if after, ok := strings.CutPrefix(filename, contentDir); ok {
187 relFilename := after
188 absFilename := filepath.Join(meta.Filename, relFilename)
189 return relFilename, absFilename, nil
190 }
191 }
192
193 }
194
195 if !isAbs {
196 // A filename on the form "posts/mypage.md", put it inside
197 // the first content folder, usually <workDir>/content.
198 // Pick the first project dir (which is probably the most important one).
199 for _, dir := range b.SourceFilesystems.Content.mounts() {
200 if !dir.IsDir() {
201 continue
202 }
203 meta := dir.Meta()
204 if meta.IsProject {
205 return filename, filepath.Join(meta.Filename, filename), nil
206 }
207 }
208 }
209
210 return "", "", fmt.Errorf("could not determine content directory for %q", filename)
211 }
212
213 // ResolveJSConfigFile resolves the JS-related config file to a absolute
214 // filename. One example of such would be postcss.config.js.
215 func (b *BaseFs) ResolveJSConfigFile(name string) string {
216 // First look in assets/_jsconfig
217 fi, err := b.Assets.Fs.Stat(filepath.Join(files.FolderJSConfig, name))
218 if err == nil {
219 return fi.(hugofs.FileMetaInfo).Meta().Filename
220 }
221 // Fall back to the work dir.
222 fi, err = b.Work.Stat(name)
223 if err == nil {
224 return fi.(hugofs.FileMetaInfo).Meta().Filename
225 }
226
227 return ""
228 }
229
230 // SourceFilesystems contains the different source file systems. These can be
231 // composite file systems (theme and project etc.), and they have all root
232 // set to the source type the provides: data, i18n, static, layouts.
233 type SourceFilesystems struct {
234 Content *SourceFilesystem
235 Data *SourceFilesystem
236 I18n *SourceFilesystem
237 Layouts *SourceFilesystem
238 Archetypes *SourceFilesystem
239 Assets *SourceFilesystem
240
241 AssetsWithDuplicatesPreserved *SourceFilesystem
242
243 RootFss []*hugofs.RootMappingFs
244
245 // Writable filesystem on top the project's resources directory,
246 // with any sub module's resource fs layered below.
247 ResourcesCache afero.Fs
248
249 // The work folder (may be a composite of project and theme components).
250 Work afero.Fs
251
252 // When in multihost we have one static filesystem per language. The sync
253 // static files is currently done outside of the Hugo build (where there is
254 // a concept of a site per language).
255 // When in non-multihost mode there will be one entry in this map with a blank key.
256 Static map[string]*SourceFilesystem
257
258 conf config.AllProvider
259 }
260
261 // A SourceFilesystem holds the filesystem for a given source type in Hugo (data,
262 // i18n, layouts, static) and additional metadata to be able to use that filesystem
263 // in server mode.
264 type SourceFilesystem struct {
265 // Name matches one in files.ComponentFolders
266 Name string
267
268 // This is a virtual composite filesystem. It expects path relative to a context.
269 Fs afero.Fs
270
271 // The source filesystem (usually the OS filesystem).
272 SourceFs afero.Fs
273
274 // When syncing a source folder to the target (e.g. /public), this may
275 // be set to publish into a subfolder. This is used for static syncing
276 // in multihost mode.
277 PublishFolder string
278 }
279
280 // StaticFs returns the static filesystem for the given language.
281 // This can be a composite filesystem.
282 func (s SourceFilesystems) StaticFs(lang string) afero.Fs {
283 var staticFs afero.Fs = hugofs.NoOpFs
284
285 if fs, ok := s.Static[lang]; ok {
286 staticFs = fs.Fs
287 } else if fs, ok := s.Static[""]; ok {
288 staticFs = fs.Fs
289 }
290
291 return staticFs
292 }
293
294 // StatResource looks for a resource in these filesystems in order: static, assets and finally content.
295 // If found in any of them, it returns FileInfo and the relevant filesystem.
296 // Any non herrors.IsNotExist error will be returned.
297 // An herrors.IsNotExist error will be returned only if all filesystems return such an error.
298 // Note that if we only wanted to find the file, we could create a composite Afero fs,
299 // but we also need to know which filesystem root it lives in.
300 func (s SourceFilesystems) StatResource(lang, filename string) (fi os.FileInfo, fs afero.Fs, err error) {
301 for _, fsToCheck := range []afero.Fs{s.StaticFs(lang), s.Assets.Fs, s.Content.Fs} {
302 fs = fsToCheck
303 fi, err = fs.Stat(filename)
304 if err == nil || !herrors.IsNotExist(err) {
305 return
306 }
307 }
308 // Not found.
309 return
310 }
311
312 // IsStatic returns true if the given filename is a member of one of the static
313 // filesystems.
314 func (s SourceFilesystems) IsStatic(filename string) bool {
315 for _, staticFs := range s.Static {
316 if staticFs.Contains(filename) {
317 return true
318 }
319 }
320 return false
321 }
322
323 // IsContent returns true if the given filename is a member of the content filesystem.
324 func (s SourceFilesystems) IsContent(filename string) bool {
325 return s.Content.Contains(filename)
326 }
327
328 // ResolvePaths resolves the given filename to a list of paths in the filesystems.
329 func (s *SourceFilesystems) ResolvePaths(filename string) []hugofs.ComponentPath {
330 var cpss []hugofs.ComponentPath
331 for _, rfs := range s.RootFss {
332 cps, err := rfs.ReverseLookup(filename)
333 if err != nil {
334 panic(err)
335 }
336 cpss = append(cpss, cps...)
337 }
338 return cpss
339 }
340
341 // MakeStaticPathRelative makes an absolute static filename into a relative one.
342 // It will return an empty string if the filename is not a member of a static filesystem.
343 func (s SourceFilesystems) MakeStaticPathRelative(filename string) string {
344 for _, staticFs := range s.Static {
345 rel, _ := staticFs.MakePathRelative(filename, true)
346 if rel != "" {
347 return rel
348 }
349 }
350 return ""
351 }
352
353 // MakePathRelative creates a relative path from the given filename.
354 func (d *SourceFilesystem) MakePathRelative(filename string, checkExists bool) (string, bool) {
355 cps, err := d.ReverseLookup(filename, checkExists)
356 if err != nil {
357 panic(err)
358 }
359 if len(cps) == 0 {
360 return "", false
361 }
362
363 return filepath.FromSlash(cps[0].Path), true
364 }
365
366 // ReverseLookup returns the component paths for the given filename.
367 func (d *SourceFilesystem) ReverseLookup(filename string, checkExists bool) ([]hugofs.ComponentPath, error) {
368 var cps []hugofs.ComponentPath
369 hugofs.WalkFilesystems(d.Fs, func(fs afero.Fs) bool {
370 if rfs, ok := fs.(hugofs.ReverseLookupProvder); ok {
371 if c, err := rfs.ReverseLookupComponent(d.Name, filename); err == nil {
372 if checkExists {
373 n := 0
374 for _, cp := range c {
375 if _, err := d.Fs.Stat(filepath.FromSlash(cp.Path)); err == nil {
376 c[n] = cp
377 n++
378 }
379 }
380 c = c[:n]
381 }
382 cps = append(cps, c...)
383 }
384 }
385 return false
386 })
387 return cps, nil
388 }
389
390 func (d *SourceFilesystem) mounts() []hugofs.FileMetaInfo {
391 var m []hugofs.FileMetaInfo
392 hugofs.WalkFilesystems(d.Fs, func(fs afero.Fs) bool {
393 if rfs, ok := fs.(*hugofs.RootMappingFs); ok {
394 mounts, err := rfs.Mounts(d.Name)
395 if err == nil {
396 m = append(m, mounts...)
397 }
398 }
399 return false
400 })
401
402 // Filter out any mounts not belonging to this filesystem.
403 // TODO(bep) I think this is superfluous.
404 n := 0
405 for _, mm := range m {
406 if mm.Meta().Component == d.Name {
407 m[n] = mm
408 n++
409 }
410 }
411 m = m[:n]
412
413 return m
414 }
415
416 func (d *SourceFilesystem) RealFilename(rel string) string {
417 fi, err := d.Fs.Stat(rel)
418 if err != nil {
419 return rel
420 }
421 if realfi, ok := fi.(hugofs.FileMetaInfo); ok {
422 return realfi.Meta().Filename
423 }
424
425 return rel
426 }
427
428 // Contains returns whether the given filename is a member of the current filesystem.
429 // It's stat-free, so it also works for deleted files.
430 func (d *SourceFilesystem) Contains(filename string) bool {
431 cps, _ := d.ReverseLookup(filename, false)
432 return len(cps) > 0
433 }
434
435 // RealDirs gets a list of absolute paths to directories starting from the given
436 // path.
437 func (d *SourceFilesystem) RealDirs(from string) []string {
438 var dirnames []string
439 for _, m := range d.mounts() {
440 if !m.IsDir() {
441 continue
442 }
443 dirname := filepath.Join(m.Meta().Filename, from)
444 if _, err := d.SourceFs.Stat(dirname); err == nil {
445 dirnames = append(dirnames, dirname)
446 }
447 }
448 return dirnames
449 }
450
451 // RealPaths returns the absolute paths of all mounts in this filesystem.
452 func (d *SourceFilesystem) RealPaths(from string) []string {
453 var paths []string
454 for _, m := range d.mounts() {
455 p := filepath.Join(m.Meta().Filename, from)
456 if _, err := d.SourceFs.Stat(p); err == nil {
457 paths = append(paths, p)
458 }
459 }
460 return paths
461 }
462
463 // WithBaseFs allows reuse of some potentially expensive to create parts that remain
464 // the same across sites/languages.
465 func WithBaseFs(b *BaseFs) func(*BaseFs) error {
466 return func(bb *BaseFs) error {
467 bb.theBigFs = b.theBigFs
468 bb.SourceFilesystems = b.SourceFilesystems
469 return nil
470 }
471 }
472
473 // NewBase builds the filesystems used by Hugo given the paths and options provided.NewBase
474 func NewBase(p *paths.Paths, logger loggers.Logger, options ...func(*BaseFs) error) (*BaseFs, error) {
475 fs := p.Fs
476 if logger == nil {
477 logger = loggers.NewDefault()
478 }
479
480 publishFs := hugofs.NewBaseFileDecorator(fs.PublishDir)
481 projectSourceFs := hugofs.NewBaseFileDecorator(hugofs.NewBasePathFs(fs.Source, p.Cfg.BaseConfig().WorkingDir))
482 sourceFs := hugofs.NewBaseFileDecorator(fs.Source)
483 publishFsStatic := fs.PublishDirStatic
484
485 var buildMu Lockable
486 if p.Cfg.NoBuildLock() || htesting.IsTest {
487 buildMu = &fakeLockfileMutex{}
488 } else {
489 buildMu = lockedfile.MutexAt(filepath.Join(p.Cfg.BaseConfig().WorkingDir, lockFileBuild))
490 }
491
492 b := &BaseFs{
493 SourceFs: sourceFs,
494 ProjectSourceFs: projectSourceFs,
495 WorkDir: fs.WorkingDirReadOnly,
496 PublishFs: publishFs,
497 PublishFsStatic: publishFsStatic,
498 workingDir: p.Cfg.BaseConfig().WorkingDir,
499 buildMu: buildMu,
500 }
501
502 for _, opt := range options {
503 if err := opt(b); err != nil {
504 return nil, err
505 }
506 }
507
508 if b.theBigFs != nil && b.SourceFilesystems != nil {
509 return b, nil
510 }
511
512 builder := newSourceFilesystemsBuilder(p, logger, b)
513 sourceFilesystems, err := builder.Build()
514 if err != nil {
515 return nil, fmt.Errorf("build filesystems: %w", err)
516 }
517
518 b.SourceFilesystems = sourceFilesystems
519 b.theBigFs = builder.theBigFs
520
521 return b, nil
522 }
523
524 type sourceFilesystemsBuilder struct {
525 logger loggers.Logger
526 p *paths.Paths
527 sourceFs afero.Fs
528 result *SourceFilesystems
529 theBigFs *filesystemsCollector
530 }
531
532 func newSourceFilesystemsBuilder(p *paths.Paths, logger loggers.Logger, b *BaseFs) *sourceFilesystemsBuilder {
533 sourceFs := hugofs.NewBaseFileDecorator(p.Fs.Source)
534 return &sourceFilesystemsBuilder{
535 p: p, logger: logger, sourceFs: sourceFs, theBigFs: b.theBigFs,
536 result: &SourceFilesystems{
537 conf: p.Cfg,
538 },
539 }
540 }
541
542 func (b *sourceFilesystemsBuilder) newSourceFilesystem(name string, fs afero.Fs) *SourceFilesystem {
543 return &SourceFilesystem{
544 Name: name,
545 Fs: fs,
546 SourceFs: b.sourceFs,
547 }
548 }
549
550 func (b *sourceFilesystemsBuilder) Build() (*SourceFilesystems, error) {
551 if b.theBigFs == nil {
552 theBigFs, err := b.createMainOverlayFs(b.p)
553 if err != nil {
554 return nil, fmt.Errorf("create main fs: %w", err)
555 }
556
557 b.theBigFs = theBigFs
558 }
559
560 createView := func(componentID string, overlayFs *overlayfs.OverlayFs) *SourceFilesystem {
561 if b.theBigFs == nil || b.theBigFs.overlayMounts == nil {
562 return b.newSourceFilesystem(componentID, hugofs.NoOpFs)
563 }
564
565 fs := hugofs.NewComponentFs(
566 hugofs.ComponentFsOptions{
567 Fs: overlayFs,
568 Component: componentID,
569 Cfg: b.p.Cfg,
570 },
571 )
572
573 return b.newSourceFilesystem(componentID, fs)
574 }
575
576 b.result.Archetypes = createView(files.ComponentFolderArchetypes, b.theBigFs.overlayMounts)
577 b.result.Layouts = createView(files.ComponentFolderLayouts, b.theBigFs.overlayMounts)
578 b.result.Assets = createView(files.ComponentFolderAssets, b.theBigFs.overlayMounts)
579 b.result.ResourcesCache = b.theBigFs.overlayResources
580 b.result.RootFss = b.theBigFs.rootFss
581
582 // data and i18n needs a different merge strategy.
583 overlayMountsPreserveDupes := b.theBigFs.overlayMounts.WithDirsMerger(hugofs.AppendDirsMerger)
584 b.result.Data = createView(files.ComponentFolderData, overlayMountsPreserveDupes)
585 b.result.I18n = createView(files.ComponentFolderI18n, overlayMountsPreserveDupes)
586 b.result.AssetsWithDuplicatesPreserved = createView(files.ComponentFolderAssets, overlayMountsPreserveDupes)
587
588 contentFs := hugofs.NewComponentFs(
589 hugofs.ComponentFsOptions{
590 Fs: b.theBigFs.overlayMountsContent,
591 Component: files.ComponentFolderContent,
592 Cfg: b.p.Cfg,
593 },
594 )
595
596 b.result.Content = b.newSourceFilesystem(files.ComponentFolderContent, contentFs)
597 b.result.Work = hugofs.NewReadOnlyFs(b.theBigFs.overlayFull)
598
599 // Create static filesystem(s)
600 ms := make(map[string]*SourceFilesystem)
601 b.result.Static = ms
602
603 if b.theBigFs.staticPerLanguage != nil {
604 // Multihost mode
605 for k, v := range b.theBigFs.staticPerLanguage {
606 sfs := b.newSourceFilesystem(files.ComponentFolderStatic, v)
607 sfs.PublishFolder = k
608 ms[k] = sfs
609 }
610 } else {
611 bfs := hugofs.NewBasePathFs(b.theBigFs.overlayMountsStatic, files.ComponentFolderStatic)
612 ms[""] = b.newSourceFilesystem(files.ComponentFolderStatic, bfs)
613 }
614
615 return b.result, nil
616 }
617
618 func (b *sourceFilesystemsBuilder) createMainOverlayFs(p *paths.Paths) (*filesystemsCollector, error) {
619 var staticFsMap map[string]*overlayfs.OverlayFs
620 if b.p.Cfg.IsMultihost() {
621 languages := b.p.Cfg.Languages().(langs.Languages)
622 staticFsMap = make(map[string]*overlayfs.OverlayFs)
623 for _, l := range languages {
624 staticFsMap[l.Lang] = overlayfs.New(overlayfs.Options{})
625 }
626 }
627
628 collector := &filesystemsCollector{
629 sourceProject: b.sourceFs,
630 sourceModules: b.sourceFs,
631 staticPerLanguage: staticFsMap,
632
633 overlayMounts: overlayfs.New(overlayfs.Options{}),
634 overlayMountsContent: overlayfs.New(overlayfs.Options{DirsMerger: hugofs.AppendDirsMerger}),
635 overlayMountsStatic: overlayfs.New(overlayfs.Options{}),
636 overlayFull: overlayfs.New(overlayfs.Options{}),
637 overlayResources: overlayfs.New(overlayfs.Options{FirstWritable: true}),
638 }
639
640 mods := p.AllModules()
641
642 mounts := make([]mountsDescriptor, len(mods))
643
644 for i := range mods {
645 mod := mods[i]
646 dir := mod.Dir()
647
648 isMainProject := mod.Owner() == nil
649 mounts[i] = mountsDescriptor{
650 Module: mod,
651 dir: dir,
652 isMainProject: isMainProject,
653 ordinal: i,
654 }
655
656 }
657
658 err := b.createOverlayFs(collector, mounts)
659
660 return collector, err
661 }
662
663 func (b *sourceFilesystemsBuilder) isContentMount(mnt modules.Mount) bool {
664 return strings.HasPrefix(mnt.Target, files.ComponentFolderContent)
665 }
666
667 func (b *sourceFilesystemsBuilder) isStaticMount(mnt modules.Mount) bool {
668 return strings.HasPrefix(mnt.Target, files.ComponentFolderStatic)
669 }
670
671 func (b *sourceFilesystemsBuilder) isLayoutsMount(mnt modules.Mount) bool {
672 return strings.HasPrefix(mnt.Target, files.ComponentFolderLayouts)
673 }
674
675 func (b *sourceFilesystemsBuilder) createOverlayFs(
676 collector *filesystemsCollector,
677 mounts []mountsDescriptor,
678 ) error {
679 if len(mounts) == 0 {
680 appendNopIfEmpty := func(ofs *overlayfs.OverlayFs) *overlayfs.OverlayFs {
681 if ofs.NumFilesystems() > 0 {
682 return ofs
683 }
684 return ofs.Append(hugofs.NoOpFs)
685 }
686 collector.overlayMounts = appendNopIfEmpty(collector.overlayMounts)
687 collector.overlayMountsContent = appendNopIfEmpty(collector.overlayMountsContent)
688 collector.overlayMountsStatic = appendNopIfEmpty(collector.overlayMountsStatic)
689 collector.overlayMountsFull = appendNopIfEmpty(collector.overlayMountsFull)
690 collector.overlayFull = appendNopIfEmpty(collector.overlayFull)
691 collector.overlayResources = appendNopIfEmpty(collector.overlayResources)
692
693 return nil
694 }
695
696 for _, md := range mounts {
697 var (
698 fromTo []*hugofs.RootMapping
699 fromToContent []*hugofs.RootMapping
700 fromToStatic []*hugofs.RootMapping
701 )
702
703 absPathify := func(path string) (string, string) {
704 if filepath.IsAbs(path) {
705 return "", path
706 }
707 return md.dir, hpaths.AbsPathify(md.dir, path)
708 }
709
710 for i, mount := range md.Mounts() {
711 // Add more weight to early mounts.
712 // When two mounts contain the same filename,
713 // the first entry wins.
714 mountWeight := (10 + md.ordinal) * (len(md.Mounts()) - i)
715
716 patterns, hasLegacyIncludes, hasLegacyExcludes := mount.FilesToFilter()
717 if hasLegacyIncludes {
718 hugo.Deprecate("module.mounts.includeFiles", "Replaced by the simpler 'files' setting, see https://gohugo.io/configuration/module/#files", "v0.153.0")
719 }
720 if hasLegacyExcludes {
721 hugo.Deprecate("module.mounts.excludeFiles", "Replaced by the simpler 'files' setting, see https://gohugo.io/configuration/module/#files", "v0.153.0")
722 }
723
724 inclusionFilter, err := hglob.NewFilenameFilterV2(patterns)
725 if err != nil {
726 return err
727 }
728
729 base, filename := absPathify(mount.Source)
730
731 var matrix *sitesmatrix.IntSets
732 v := mount.Sites
733
734 needsDefaultsIfNotset := b.isContentMount(mount)
735 needsDefaultsAndAllLanguagesIfNotSet := b.isStaticMount(mount)
736 needsAllIfNotSet := b.isLayoutsMount(mount)
737
738 intSetsCfg := sitesmatrix.IntSetsConfig{
739 ApplyDefaults: 0,
740 Globs: v.Matrix,
741 }
742
743 matrixBuilder := sitesmatrix.NewIntSetsBuilder(b.p.Cfg.ConfiguredDimensions())
744
745 if !v.Matrix.IsZero() {
746 matrixBuilder.WithConfig(intSetsCfg)
747 if !matrixBuilder.GlobFilterMisses.IsZero() {
748 continue
749 }
750
751 if needsDefaultsIfNotset {
752 matrixBuilder.WithDefaultsIfNotSet()
753 }
754 if needsAllIfNotSet {
755 matrixBuilder.WithAllIfNotSet()
756 }
757
758 matrix = matrixBuilder.Build()
759 } else if needsAllIfNotSet {
760 matrixBuilder.WithAllIfNotSet()
761 matrix = matrixBuilder.Build()
762 } else if needsDefaultsAndAllLanguagesIfNotSet {
763 matrixBuilder.WithDefaultsAndAllLanguagesIfNotSet()
764 matrix = matrixBuilder.Build()
765 } else if needsDefaultsIfNotset {
766 matrix = b.p.Cfg.DefaultContentsitesMatrix()
767 } else {
768 if needsDefaultsIfNotset {
769 matrixBuilder.WithDefaultsIfNotSet()
770 }
771 matrix = matrixBuilder.Build()
772 }
773
774 var complements *sitesmatrix.IntSets
775 if !v.Complements.IsZero() {
776 intSetsCfg.Globs = v.Complements
777 intSetsCfg.ApplyDefaults = 0
778 matrixBuilder = sitesmatrix.NewIntSetsBuilder(b.p.Cfg.ConfiguredDimensions()).WithConfig(intSetsCfg).WithAllIfNotSet()
779 complements = matrixBuilder.Build()
780 }
781
782 rm := &hugofs.RootMapping{
783 From: mount.Target,
784 To: filename,
785 ToBase: base,
786 Module: md.Module,
787 ModuleOrdinal: md.ordinal,
788 IsProject: md.isMainProject,
789 Meta: &hugofs.FileMeta{
790 Watch: !mount.DisableWatch && md.Watch(),
791 Weight: mountWeight,
792 InclusionFilter: inclusionFilter,
793 SitesMatrix: matrix,
794 SitesComplements: complements,
795 },
796 }
797
798 isContentMount := b.isContentMount(mount)
799
800 if isContentMount {
801 fromToContent = append(fromToContent, rm)
802 } else if b.isStaticMount(mount) {
803 fromToStatic = append(fromToStatic, rm)
804 } else {
805 fromTo = append(fromTo, rm)
806 }
807 }
808
809 modBase := collector.sourceProject
810 if !md.isMainProject {
811 modBase = collector.sourceModules
812 }
813
814 sourceStatic := modBase
815
816 rmfs, err := hugofs.NewRootMappingFs(modBase, fromTo...)
817 if err != nil {
818 return err
819 }
820 rmfsContent, err := hugofs.NewRootMappingFs(modBase, fromToContent...)
821 if err != nil {
822 return err
823 }
824 rmfsStatic, err := hugofs.NewRootMappingFs(sourceStatic, fromToStatic...)
825 if err != nil {
826 return err
827 }
828
829 // We need to keep the list of directories for watching.
830 collector.addRootFs(rmfs)
831 collector.addRootFs(rmfsContent)
832 collector.addRootFs(rmfsStatic)
833
834 if collector.staticPerLanguage != nil {
835 for i, l := range b.p.Cfg.Languages().(langs.Languages) {
836 lang := l.Lang
837
838 lfs := rmfsStatic.Filter(func(rm *hugofs.RootMapping) bool {
839 return rm.Meta.SitesMatrix.HasLanguage(i)
840 })
841 bfs := hugofs.NewBasePathFs(lfs, files.ComponentFolderStatic)
842 collector.staticPerLanguage[lang] = collector.staticPerLanguage[lang].Append(bfs)
843 }
844 }
845
846 getResourcesDir := func() string {
847 if md.isMainProject {
848 return b.p.AbsResourcesDir
849 }
850 _, filename := absPathify(files.FolderResources)
851 return filename
852 }
853
854 collector.overlayMounts = collector.overlayMounts.Append(rmfs)
855 collector.overlayMountsContent = collector.overlayMountsContent.Append(rmfsContent)
856 collector.overlayMountsStatic = collector.overlayMountsStatic.Append(rmfsStatic)
857 collector.overlayFull = collector.overlayFull.Append(hugofs.NewBasePathFs(modBase, md.dir))
858 collector.overlayResources = collector.overlayResources.Append(hugofs.NewBasePathFs(modBase, getResourcesDir()))
859
860 }
861
862 return nil
863 }
864
865 //lint:ignore U1000 useful for debugging
866 func printFs(fs afero.Fs, path string, w io.Writer) {
867 if fs == nil {
868 return
869 }
870 afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
871 if err != nil {
872 return err
873 }
874 if info.IsDir() {
875 return nil
876 }
877 var filename string
878 if fim, ok := info.(hugofs.FileMetaInfo); ok {
879 filename = fim.Meta().Filename
880 }
881 fmt.Fprintf(w, " %q %q\n", path, filename)
882 return nil
883 })
884 }
885
886 type filesystemsCollector struct {
887 sourceProject afero.Fs // Source for project folders
888 sourceModules afero.Fs // Source for modules/themes
889
890 overlayMounts *overlayfs.OverlayFs
891 overlayMountsContent *overlayfs.OverlayFs
892 overlayMountsStatic *overlayfs.OverlayFs
893 overlayMountsFull *overlayfs.OverlayFs
894 overlayFull *overlayfs.OverlayFs
895 overlayResources *overlayfs.OverlayFs
896
897 rootFss []*hugofs.RootMappingFs
898
899 // Set if in multihost mode
900 staticPerLanguage map[string]*overlayfs.OverlayFs
901 }
902
903 func (c *filesystemsCollector) addRootFs(rfs *hugofs.RootMappingFs) {
904 c.rootFss = append(c.rootFss, rfs)
905 }
906
907 type mountsDescriptor struct {
908 modules.Module
909 dir string
910 isMainProject bool
911 ordinal int // zero based starting from the project.
912 }