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