Debian Codegraph @

hugofs/rootmapping_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 "errors"
18 "fmt"
19 iofs "io/fs"
20 "os"
21 "path"
22 "path/filepath"
23 "strings"
24 "sync/atomic"
25
26 "github.com/gohugoio/hugo/common/herrors"
27 "github.com/gohugoio/hugo/common/paths"
28
29 "github.com/bep/overlayfs"
30 "github.com/gohugoio/hugo/hugofs/files"
31 "github.com/gohugoio/hugo/hugofs/hglob"
32
33 radix "github.com/gohugoio/go-radix"
34 "github.com/spf13/afero"
35 )
36
37 var filepathSeparator = string(filepath.Separator)
38
39 var _ ReverseLookupProvder = (*RootMappingFs)(nil)
40
41 // NewRootMappingFs creates a new RootMappingFs on top of the provided with
42 // root mappings with some optional metadata about the root.
43 // Note that From represents a virtual root that maps to the actual filename in To.
44 func NewRootMappingFs(fs afero.Fs, rms ...*RootMapping) (*RootMappingFs, error) {
45 rootMapToReal := radix.New[[]*RootMapping]()
46 realMapToRoot := radix.New[[]*RootMapping]()
47 id := fmt.Sprintf("rfs-%d", rootMappingFsCounter.Add(1))
48 symlinks := newSymlinkChecker(fs)
49
50 addMapping := func(key string, rm *RootMapping, to *radix.Tree[[]*RootMapping]) {
51 mappings, _ := to.Get(key)
52 mappings = append(mappings, rm)
53 to.Insert(key, mappings)
54 }
55
56 for _, rm := range rms {
57 rm.clean()
58
59 rm.FromBase = files.ResolveComponentFolder(rm.From)
60
61 if len(rm.To) < 2 {
62 panic(fmt.Sprintf("invalid root mapping; from/to: %s/%s", rm.From, rm.To))
63 }
64
65 // Don't allow a symlinked mount root (or any directory between it and
66 // the module root) to escape the module. The main project is exempt;
67 // its mount sources may be absolute, so a symlink gains nothing.
68 if !rm.IsProject {
69 symlink, err := symlinks.isSymlinkOrHasSymlinkParent(rm.ToBase, rm.To)
70 if err != nil {
71 return nil, err
72 }
73 if symlink {
74 continue
75 }
76 }
77
78 fi, err := fs.Stat(rm.To)
79 if err != nil {
80 if os.IsNotExist(err) {
81 continue
82 }
83 return nil, err
84 }
85
86 if rm.Meta == nil {
87 rm.Meta = NewFileMeta()
88 }
89
90 if rm.FromBase == "" {
91 panic(" rm.FromBase is empty")
92 }
93
94 rm.Meta.Component = rm.FromBase
95 rm.Meta.Module = rm.Module
96 rm.Meta.ModuleOrdinal = rm.ModuleOrdinal
97 rm.Meta.IsProject = rm.IsProject
98 rm.Meta.BaseDir = rm.ToBase
99
100 if !fi.IsDir() {
101 // We do allow single file mounts.
102 // However, the file system logic will be much simpler with just directories.
103 // So, convert this mount into a directory mount with a renamer,
104 // which will tell the caller if name should be included.
105 dirFrom, nameFrom := filepath.Split(rm.From)
106 dirTo, nameTo := filepath.Split(rm.To)
107 dirFrom, dirTo = strings.TrimSuffix(dirFrom, filepathSeparator), strings.TrimSuffix(dirTo, filepathSeparator)
108 rm.From = dirFrom
109 singleFileMeta := rm.Meta.Copy()
110 singleFileMeta.Name = nameFrom
111 rm.fiSingleFile = NewFileMetaInfo(fi, singleFileMeta)
112 rm.To = dirTo
113
114 rm.Meta.Rename = func(name string, toFrom bool) (string, bool) {
115 if toFrom {
116 if name == nameTo {
117 return nameFrom, true
118 }
119 return "", false
120 }
121
122 if name == nameFrom {
123 return nameTo, true
124 }
125
126 return "", false
127 }
128 nameToFilename := filepathSeparator + nameTo
129
130 rm.Meta.InclusionFilter = rm.Meta.InclusionFilter.Append(hglob.NewFilenameFilterForInclusionFunc(
131 func(filename string) bool {
132 return nameToFilename == filename
133 },
134 ))
135
136 // Refresh the FileInfo object.
137 fi, err = fs.Stat(rm.To)
138 if err != nil {
139 if herrors.IsNotExist(err) {
140 continue
141 }
142 return nil, err
143 }
144 }
145
146 // Extract "blog" from "content/blog"
147 rm.path = strings.TrimPrefix(strings.TrimPrefix(rm.From, rm.FromBase), filepathSeparator)
148 rm.Meta.SourceRoot = fi.(MetaProvider).Meta().Filename
149
150 meta := rm.Meta.Copy()
151
152 if !fi.IsDir() {
153 _, name := filepath.Split(rm.From)
154 meta.Name = name
155 }
156
157 rm.fi = NewFileMetaInfo(fi, meta)
158
159 addMapping(filepathSeparator+rm.From, rm, rootMapToReal)
160 rev := rm.To
161 if !strings.HasPrefix(rev, filepathSeparator) {
162 rev = filepathSeparator + rev
163 }
164
165 addMapping(rev, rm, realMapToRoot)
166
167 }
168
169 rfs := &RootMappingFs{
170 id: id,
171 Fs: fs,
172 rootMapToReal: rootMapToReal,
173 realMapToRoot: realMapToRoot,
174 symlinks: symlinks,
175 }
176
177 return rfs, nil
178 }
179
180 func newRootMappingFsFromFromTo(
181 baseDir string,
182 fs afero.Fs,
183 fromTo ...string,
184 ) (*RootMappingFs, error) {
185 rms := make([]*RootMapping, len(fromTo)/2)
186 for i, j := 0, 0; j < len(fromTo); i, j = i+1, j+2 {
187 rms[i] = &RootMapping{
188 From: fromTo[j],
189 To: fromTo[j+1],
190 ToBase: baseDir,
191 }
192 }
193
194 return NewRootMappingFs(fs, rms...)
195 }
196
197 // RootMapping describes a virtual file or directory mount.
198 type RootMapping struct {
199 From string // The virtual mount.
200 FromBase string // The base directory of the virtual mount.
201 To string // The source directory or file.
202 ToBase string // The base of To. May be empty if an absolute path was provided.
203 Module Module // The module.
204 ModuleOrdinal int // The module ordinal starting with 0 which is the project.
205 IsProject bool // Whether this is a mount in the main project.
206 Meta *FileMeta // File metadata (lang etc.)
207
208 fi FileMetaInfo
209 fiSingleFile FileMetaInfo // Also set when this mounts represents a single file with a rename func.
210 path string // The virtual mount point, e.g. "blog".
211 }
212
213 type keyRootMappings struct {
214 key string
215 roots []*RootMapping
216 }
217
218 func (rm *RootMapping) clean() {
219 rm.From = strings.Trim(filepath.Clean(rm.From), filepathSeparator)
220 rm.To = filepath.Clean(rm.To)
221 }
222
223 func (r RootMapping) filename(name string) string {
224 if name == "" {
225 return r.To
226 }
227 return filepath.Join(r.To, strings.TrimPrefix(name, r.From))
228 }
229
230 func (r RootMapping) trimFrom(name string) string {
231 if name == "" {
232 return ""
233 }
234 return strings.TrimPrefix(name, r.From)
235 }
236
237 var _ FilesystemUnwrapper = (*RootMappingFs)(nil)
238
239 // A RootMappingFs maps several roots into one. Note that the root of this filesystem
240 // is directories only, and they will be returned in Readdir and Readdirnames
241 // in the order given.
242 type RootMappingFs struct {
243 id string
244 afero.Fs
245 rootMapToReal *radix.Tree[[]*RootMapping]
246 realMapToRoot *radix.Tree[[]*RootMapping]
247 symlinks *symlinkChecker
248 }
249
250 var rootMappingFsCounter atomic.Int32
251
252 func (fs *RootMappingFs) Mounts(base string) ([]FileMetaInfo, error) {
253 base = filepathSeparator + fs.cleanName(base)
254 roots := fs.getRootsWithPrefix(base)
255
256 if roots == nil {
257 return nil, nil
258 }
259
260 fss := make([]FileMetaInfo, 0, len(roots))
261 for _, r := range roots {
262 if r.fiSingleFile != nil {
263 // A single file mount.
264 fss = append(fss, r.fiSingleFile)
265 continue
266 }
267 bfs := NewBasePathFs(fs.Fs, r.To)
268 fs := bfs
269 if r.Meta.InclusionFilter != nil {
270 fs = newFilenameFilterFs(fs, r.To, r.Meta.InclusionFilter)
271 }
272 fs = decorateDirs(fs, r.Meta)
273 fi, err := fs.Stat("")
274 if err != nil {
275 continue
276 }
277 fss = append(fss, fi.(FileMetaInfo))
278 }
279
280 return fss, nil
281 }
282
283 func (fs *RootMappingFs) Key() string {
284 return fs.id
285 }
286
287 func (fs *RootMappingFs) UnwrapFilesystem() afero.Fs {
288 return fs.Fs
289 }
290
291 // Filter creates a copy of this filesystem with only mappings matching a filter.
292 func (fs RootMappingFs) Filter(f func(m *RootMapping) bool) *RootMappingFs {
293 rootMapToReal := radix.New[[]*RootMapping]()
294 var walkFn radix.WalkFn[[]*RootMapping] = func(b string, rms []*RootMapping) (radix.WalkFlag, []*RootMapping, error) {
295 var nrms []*RootMapping
296 for _, rm := range rms {
297 if f(rm) {
298 nrms = append(nrms, rm)
299 }
300 }
301 if len(nrms) != 0 {
302 rootMapToReal.Insert(b, nrms)
303 }
304 return radix.WalkContinue, nil, nil
305 }
306 fs.rootMapToReal.Walk(walkFn)
307
308 fs.rootMapToReal = rootMapToReal
309
310 return &fs
311 }
312
313 // Open opens the named file for reading.
314 func (fs *RootMappingFs) Open(name string) (afero.File, error) {
315 fis, err := fs.doStat(name)
316 if err != nil {
317 return nil, err
318 }
319
320 return fs.newUnionFile(fis...)
321 }
322
323 // Stat returns the os.FileInfo structure describing a given file. If there is
324 // an error, it will be of type *os.PathError.
325 // If multiple roots are found, the last one will be used.
326 func (fs *RootMappingFs) Stat(name string) (os.FileInfo, error) {
327 fis, err := fs.doStat(name)
328 if err != nil {
329 return nil, err
330 }
331 return fis[len(fis)-1], nil
332 }
333
334 type ComponentPath struct {
335 Component string
336 Path string
337 Watch bool
338 }
339
340 func (c ComponentPath) ComponentPathJoined() string {
341 return path.Join(c.Component, c.Path)
342 }
343
344 type ReverseLookupProvder interface {
345 ReverseLookup(filename string) ([]ComponentPath, error)
346 ReverseLookupComponent(component, filename string) ([]ComponentPath, error)
347 }
348
349 // func (fs *RootMappingFs) ReverseStat(filename string) ([]FileMetaInfo, error)
350 func (fs *RootMappingFs) ReverseLookup(filename string) ([]ComponentPath, error) {
351 return fs.ReverseLookupComponent("", filename)
352 }
353
354 func (fs *RootMappingFs) ReverseLookupComponent(component, filename string) ([]ComponentPath, error) {
355 filename = fs.cleanName(filename)
356 key := filepathSeparator + filename
357
358 s, roots := fs.getRootsReverse(key)
359
360 if len(roots) == 0 {
361 return nil, nil
362 }
363
364 var cps []ComponentPath
365
366 base := strings.TrimPrefix(key, s)
367 dir, name := filepath.Split(base)
368
369 for _, first := range roots {
370 if component != "" && first.FromBase != component {
371 continue
372 }
373
374 var filename string
375 if first.Meta.Rename != nil {
376 // Single file mount.
377 if newname, ok := first.Meta.Rename(name, true); ok {
378 filename = filepathSeparator + filepath.Join(first.path, dir, newname)
379 } else {
380 continue
381 }
382 } else {
383 // Now we know that this file _could_ be in this fs.
384 filename = filepathSeparator + filepath.Join(first.path, dir, name)
385 }
386
387 cps = append(cps, ComponentPath{
388 Component: first.FromBase,
389 Path: paths.ToSlashTrimLeading(filename),
390 Watch: first.Meta.Watch,
391 })
392 }
393
394 return cps, nil
395 }
396
397 func (fs *RootMappingFs) hasPrefix(prefix string) bool {
398 hasPrefix := false
399 var walkFn radix.WalkFn[[]*RootMapping] = func(b string, rms []*RootMapping) (radix.WalkFlag, []*RootMapping, error) {
400 hasPrefix = true
401 return radix.WalkStop, nil, nil
402 }
403 fs.rootMapToReal.WalkPrefix(prefix, walkFn)
404
405 return hasPrefix
406 }
407
408 func (fs *RootMappingFs) getRoot(key string) []*RootMapping {
409 v, _ := fs.rootMapToReal.Get(key)
410 return v
411 }
412
413 func (fs *RootMappingFs) getRoots(key string) (string, []*RootMapping) {
414 tree := fs.rootMapToReal
415 levels := strings.Count(key, filepathSeparator)
416 seen := make(map[*RootMapping]bool)
417
418 var roots []*RootMapping
419 var s string
420
421 for {
422 var found bool
423 ss, vv, found := tree.LongestPrefix(key)
424
425 if !found || (levels < 2 && ss == key) {
426 break
427 }
428
429 for _, rm := range vv {
430 if !seen[rm] {
431 seen[rm] = true
432 roots = append(roots, rm)
433 }
434 }
435 s = ss
436
437 // We may have more than one root for this key, so walk up.
438 oldKey := key
439 key = filepath.Dir(key)
440 if key == oldKey {
441 break
442 }
443 }
444
445 return s, roots
446 }
447
448 func (fs *RootMappingFs) getRootsReverse(key string) (string, []*RootMapping) {
449 tree := fs.realMapToRoot
450 s, v, _ := tree.LongestPrefix(key)
451 return s, v
452 }
453
454 func (fs *RootMappingFs) getRootsWithPrefix(prefix string) []*RootMapping {
455 var roots []*RootMapping
456 var walkFn radix.WalkFn[[]*RootMapping] = func(b string, v []*RootMapping) (radix.WalkFlag, []*RootMapping, error) {
457 roots = append(roots, v...)
458 return radix.WalkContinue, nil, nil
459 }
460 fs.rootMapToReal.WalkPrefix(prefix, walkFn)
461
462 return roots
463 }
464
465 func (fs *RootMappingFs) getAncestors(prefix string) []keyRootMappings {
466 var roots []keyRootMappings
467 var walkFn radix.WalkFn[[]*RootMapping] = func(s string, v []*RootMapping) (radix.WalkFlag, []*RootMapping, error) {
468 if strings.HasPrefix(prefix, s+filepathSeparator) {
469 roots = append(roots, keyRootMappings{
470 key: s,
471 roots: v,
472 })
473 }
474 return radix.WalkContinue, nil, nil
475 }
476 fs.rootMapToReal.WalkPath(prefix, walkFn)
477
478 return roots
479 }
480
481 func (fs *RootMappingFs) newUnionFile(fis ...FileMetaInfo) (afero.File, error) {
482 if len(fis) == 1 {
483 return fis[0].Meta().Open()
484 }
485
486 if !fis[0].IsDir() {
487 // Pick the last file mount.
488 return fis[len(fis)-1].Meta().Open()
489 }
490
491 openers := make([]func() (afero.File, error), len(fis))
492 for i := len(fis) - 1; i >= 0; i-- {
493 fi := fis[i]
494 openers[i] = func() (afero.File, error) {
495 meta := fi.Meta()
496 f, err := meta.Open()
497 if err != nil {
498 return nil, err
499 }
500 return &rootMappingDir{DirOnlyOps: f, fs: fs, name: meta.Name, meta: meta}, nil
501 }
502 }
503
504 merge := func(lofi, bofi []iofs.DirEntry) []iofs.DirEntry {
505 // Ignore duplicate directory entries
506 for _, fi1 := range bofi {
507 var found bool
508 for _, fi2 := range lofi {
509 if !fi2.IsDir() {
510 continue
511 }
512 if fi1.Name() == fi2.Name() {
513 found = true
514 break
515 }
516 }
517 if !found {
518 lofi = append(lofi, fi1)
519 }
520 }
521
522 return lofi
523 }
524
525 info := func() (os.FileInfo, error) {
526 return fis[0], nil
527 }
528
529 return overlayfs.OpenDir(merge, info, openers...)
530 }
531
532 func (fs *RootMappingFs) cleanName(name string) string {
533 name = strings.Trim(filepath.Clean(name), filepathSeparator)
534 if name == "." {
535 name = ""
536 }
537 return name
538 }
539
540 func (rfs *RootMappingFs) collectDirEntries(prefix string) ([]iofs.DirEntry, error) {
541 prefix = filepathSeparator + rfs.cleanName(prefix)
542
543 var fis []iofs.DirEntry
544
545 seen := make(map[string]bool) // Prevent duplicate directories
546 level := strings.Count(prefix, filepathSeparator)
547
548 collectDir := func(rm *RootMapping, fi FileMetaInfo) error {
549 f, err := fi.Meta().Open()
550 if err != nil {
551 return err
552 }
553 direntries, err := f.(iofs.ReadDirFile).ReadDir(-1)
554 if err != nil {
555 f.Close()
556 return err
557 }
558
559 for _, fi := range direntries {
560
561 meta := fi.(FileMetaInfo).Meta()
562 meta.Merge(rm.Meta)
563
564 if !rm.Meta.InclusionFilter.Match(strings.TrimPrefix(meta.Filename, meta.SourceRoot), fi.IsDir()) {
565 continue
566 }
567
568 if fi.IsDir() {
569 name := fi.Name()
570 if seen[name] {
571 continue
572 }
573 seen[name] = true
574 opener := func() (afero.File, error) {
575 return rfs.Open(filepath.Join(rm.From, name))
576 }
577 fi = newDirNameOnlyFileInfo(name, meta, opener)
578 } else if rm.Meta.Rename != nil {
579 n, ok := rm.Meta.Rename(fi.Name(), true)
580 if !ok {
581 continue
582 }
583 fi.(MetaProvider).Meta().Name = n
584 }
585 fis = append(fis, fi)
586 }
587
588 f.Close()
589
590 return nil
591 }
592
593 // First add any real files/directories.
594 rms := rfs.getRoot(prefix)
595 for _, rm := range rms {
596 if err := collectDir(rm, rm.fi); err != nil {
597 return nil, err
598 }
599 }
600
601 // Next add any file mounts inside the given directory.
602 prefixInside := prefix + filepathSeparator
603 var walkFn radix.WalkFn[[]*RootMapping] = func(s string, rms []*RootMapping) (radix.WalkFlag, []*RootMapping, error) {
604 if (strings.Count(s, filepathSeparator) - level) != 1 {
605 // This directory is not part of the current, but we
606 // need to include the first name part to make it
607 // navigable.
608 path := strings.TrimPrefix(s, prefixInside)
609 parts := strings.Split(path, filepathSeparator)
610 name := parts[0]
611
612 if seen[name] {
613 return radix.WalkContinue, nil, nil
614 }
615 seen[name] = true
616 opener := func() (afero.File, error) {
617 return rfs.Open(path)
618 }
619
620 fi := newDirNameOnlyFileInfo(name, nil, opener)
621 fis = append(fis, fi)
622
623 return radix.WalkContinue, nil, nil
624 }
625
626 for _, rm := range rms {
627 name := filepath.Base(rm.From)
628 if seen[name] {
629 continue
630 }
631 seen[name] = true
632 opener := func() (afero.File, error) {
633 return rfs.Open(rm.From)
634 }
635 fi := newDirNameOnlyFileInfo(name, rm.Meta, opener)
636 fis = append(fis, fi)
637 }
638
639 return radix.WalkContinue, nil, nil
640 }
641 rfs.rootMapToReal.WalkPrefix(prefixInside, walkFn)
642
643 // Finally add any ancestor dirs with files in this directory.
644 ancestors := rfs.getAncestors(prefix)
645 for _, root := range ancestors {
646 subdir := strings.TrimPrefix(prefix, root.key)
647 for _, rm := range root.roots {
648 if rm.fi.IsDir() {
649 fi, err := rm.fi.Meta().JoinStat(subdir)
650 if err == nil {
651 // Apply the same symlink rules as statRoot.
652 symlink, err := rfs.symlinks.isSymlinkOrHasSymlinkParent(rm.To, fi.Meta().Filename)
653 if err != nil {
654 return nil, err
655 }
656 if symlink {
657 continue
658 }
659 if err := collectDir(rm, fi); err != nil {
660 return nil, err
661 }
662 }
663 }
664 }
665 }
666
667 return fis, nil
668 }
669
670 func (fs *RootMappingFs) doStat(name string) ([]FileMetaInfo, error) {
671 fis, err := fs.doDoStat(name)
672 if err != nil {
673 return nil, err
674 }
675 // Sanity check. Check that all is either file or directories.
676 var isDir, isFile bool
677 for _, fi := range fis {
678 if fi.IsDir() {
679 isDir = true
680 } else {
681 isFile = true
682 }
683 }
684 if isDir && isFile {
685 // For now.
686 return nil, os.ErrNotExist
687 }
688
689 return fis, nil
690 }
691
692 func (fs *RootMappingFs) doDoStat(name string) ([]FileMetaInfo, error) {
693 name = fs.cleanName(name)
694 key := filepathSeparator + name
695
696 roots := fs.getRoot(key)
697
698 if roots == nil {
699 if fs.hasPrefix(key) {
700 // We have directories mounted below this.
701 // Make it look like a directory.
702 return []FileMetaInfo{newDirNameOnlyFileInfo(name, nil, fs.virtualDirOpener(name))}, nil
703 }
704
705 // Find any real directories with this key.
706 _, roots := fs.getRoots(key)
707 if roots == nil {
708 return nil, &os.PathError{Op: "LStat", Path: name, Err: os.ErrNotExist}
709 }
710
711 var err error
712 var fis []FileMetaInfo
713
714 for _, rm := range roots {
715 var fi FileMetaInfo
716 fi, err = fs.statRoot(rm, name)
717 if err == nil {
718 fis = append(fis, fi)
719 }
720 }
721
722 if fis != nil {
723 return fis, nil
724 }
725
726 if err == nil {
727 err = &os.PathError{Op: "LStat", Path: name, Err: err}
728 }
729
730 return nil, err
731 }
732
733 return []FileMetaInfo{newDirNameOnlyFileInfo(name, roots[0].Meta, fs.virtualDirOpener(name))}, nil
734 }
735
736 func (fs *RootMappingFs) statRoot(root *RootMapping, filename string) (FileMetaInfo, error) {
737 dir, name := filepath.Split(filename)
738 if root.Meta.Rename != nil {
739 n, ok := root.Meta.Rename(name, false)
740 if !ok {
741 return nil, os.ErrNotExist
742 }
743 filename = filepath.Join(dir, n)
744 }
745
746 if !root.Meta.InclusionFilter.Match(root.trimFrom(filename), true) {
747 return nil, os.ErrNotExist
748 }
749
750 filename = root.filename(filename)
751 fi, err := LstatIfPossible(fs.Fs, filename)
752 if err != nil {
753 return nil, err
754 }
755
756 // Don't allow symlinks to escape the mount, neither as the file itself
757 // nor as any directory between it and the mount root.
758 if fi.Mode()&os.ModeSymlink != 0 {
759 return nil, os.ErrNotExist
760 }
761 symlinkParent, err := fs.symlinks.hasSymlinkParent(root.To, filepath.Dir(filename))
762 if err != nil {
763 return nil, err
764 }
765 if symlinkParent {
766 return nil, os.ErrNotExist
767 }
768
769 var opener func() (afero.File, error)
770 if !fi.IsDir() {
771 // Open the file directly.
772 // Opens the real file directly.
773 opener = func() (afero.File, error) {
774 return fs.Fs.Open(filename)
775 }
776 } else if root.Meta.Rename != nil {
777 // A single file mount where we have mounted the containing directory.
778 n, ok := root.Meta.Rename(fi.Name(), true)
779 if !ok {
780 return nil, os.ErrNotExist
781 }
782 meta := fi.(MetaProvider).Meta()
783 meta.Name = n
784 // Opens the real file directly.
785 opener = func() (afero.File, error) {
786 return fs.Fs.Open(filename)
787 }
788 } else {
789 // Make sure metadata gets applied in ReadDir.
790 opener = fs.realDirOpener(filename, root.Meta)
791 }
792
793 fim := decorateFileInfo(fi, opener, "", root.Meta)
794
795 return fim, nil
796 }
797
798 func (fs *RootMappingFs) virtualDirOpener(name string) func() (afero.File, error) {
799 return func() (afero.File, error) { return &rootMappingDir{name: name, fs: fs}, nil }
800 }
801
802 func (fs *RootMappingFs) realDirOpener(name string, meta *FileMeta) func() (afero.File, error) {
803 return func() (afero.File, error) {
804 f, err := fs.Fs.Open(name)
805 if err != nil {
806 return nil, err
807 }
808 return &rootMappingDir{name: name, meta: meta, fs: fs, DirOnlyOps: f}, nil
809 }
810 }
811
812 var _ iofs.ReadDirFile = (*rootMappingDir)(nil)
813
814 type rootMappingDir struct {
815 *noOpRegularFileOps
816 DirOnlyOps
817 fs *RootMappingFs
818 name string
819 meta *FileMeta
820 }
821
822 func (f *rootMappingDir) Close() error {
823 if f.DirOnlyOps == nil {
824 return nil
825 }
826 return f.DirOnlyOps.Close()
827 }
828
829 func (f *rootMappingDir) Name() string {
830 return f.name
831 }
832
833 func (f *rootMappingDir) ReadDir(count int) ([]iofs.DirEntry, error) {
834 if f.DirOnlyOps != nil {
835 fis, err := f.DirOnlyOps.(iofs.ReadDirFile).ReadDir(count)
836 if err != nil {
837 return nil, err
838 }
839
840 var result []iofs.DirEntry
841 for _, fi := range fis {
842 fim := decorateFileInfo(fi, nil, "", f.meta)
843 meta := fim.Meta()
844 if f.meta.InclusionFilter.Match(strings.TrimPrefix(meta.Filename, meta.SourceRoot), fim.IsDir()) {
845 result = append(result, fim)
846 }
847 }
848 return result, nil
849 }
850
851 return f.fs.collectDirEntries(f.name)
852 }
853
854 // Sentinel error to signal that a file is a directory.
855 var errIsDir = errors.New("isDir")
856
857 func (f *rootMappingDir) Stat() (iofs.FileInfo, error) {
858 return nil, errIsDir
859 }
860
861 func (f *rootMappingDir) Readdir(count int) ([]os.FileInfo, error) {
862 panic("not supported: use ReadDir")
863 }
864
865 // Note that Readdirnames preserves the order of the underlying filesystem(s),
866 // which is usually directory order.
867 func (f *rootMappingDir) Readdirnames(count int) ([]string, error) {
868 dirs, err := f.ReadDir(count)
869 if err != nil {
870 return nil, err
871 }
872 return dirEntriesToNames(dirs), nil
873 }
874
875 func dirEntriesToNames(fis []iofs.DirEntry) []string {
876 names := make([]string, len(fis))
877 for i, d := range fis {
878 names[i] = d.Name()
879 }
880 return names
881 }