main
1package polyfill
2
3import (
4 "os"
5 "path/filepath"
6
7 "github.com/go-git/go-billy/v5"
8)
9
10// Polyfill is a helper that implements all missing method from billy.Filesystem.
11type Polyfill struct {
12 billy.Basic
13 c capabilities
14}
15
16type capabilities struct{ tempfile, dir, symlink, chroot bool }
17
18// New creates a new filesystem wrapping up 'fs' the intercepts all the calls
19// made and errors if fs doesn't implement any of the billy interfaces.
20func New(fs billy.Basic) billy.Filesystem {
21 if original, ok := fs.(billy.Filesystem); ok {
22 return original
23 }
24
25 h := &Polyfill{Basic: fs}
26
27 _, h.c.tempfile = h.Basic.(billy.TempFile)
28 _, h.c.dir = h.Basic.(billy.Dir)
29 _, h.c.symlink = h.Basic.(billy.Symlink)
30 _, h.c.chroot = h.Basic.(billy.Chroot)
31 return h
32}
33
34func (h *Polyfill) TempFile(dir, prefix string) (billy.File, error) {
35 if !h.c.tempfile {
36 return nil, billy.ErrNotSupported
37 }
38
39 return h.Basic.(billy.TempFile).TempFile(dir, prefix)
40}
41
42func (h *Polyfill) ReadDir(path string) ([]os.FileInfo, error) {
43 if !h.c.dir {
44 return nil, billy.ErrNotSupported
45 }
46
47 return h.Basic.(billy.Dir).ReadDir(path)
48}
49
50func (h *Polyfill) MkdirAll(filename string, perm os.FileMode) error {
51 if !h.c.dir {
52 return billy.ErrNotSupported
53 }
54
55 return h.Basic.(billy.Dir).MkdirAll(filename, perm)
56}
57
58func (h *Polyfill) Symlink(target, link string) error {
59 if !h.c.symlink {
60 return billy.ErrNotSupported
61 }
62
63 return h.Basic.(billy.Symlink).Symlink(target, link)
64}
65
66func (h *Polyfill) Readlink(link string) (string, error) {
67 if !h.c.symlink {
68 return "", billy.ErrNotSupported
69 }
70
71 return h.Basic.(billy.Symlink).Readlink(link)
72}
73
74func (h *Polyfill) Lstat(path string) (os.FileInfo, error) {
75 if !h.c.symlink {
76 return nil, billy.ErrNotSupported
77 }
78
79 return h.Basic.(billy.Symlink).Lstat(path)
80}
81
82func (h *Polyfill) Chroot(path string) (billy.Filesystem, error) {
83 if !h.c.chroot {
84 return nil, billy.ErrNotSupported
85 }
86
87 return h.Basic.(billy.Chroot).Chroot(path)
88}
89
90func (h *Polyfill) Root() string {
91 if !h.c.chroot {
92 return string(filepath.Separator)
93 }
94
95 return h.Basic.(billy.Chroot).Root()
96}
97
98func (h *Polyfill) Underlying() billy.Basic {
99 return h.Basic
100}
101
102// Capabilities implements the Capable interface.
103func (h *Polyfill) Capabilities() billy.Capability {
104 return billy.Capabilities(h.Basic)
105}