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