| 1 |
|
| 2 |
|
| 3 |
package osfs |
| 4 |
|
| 5 |
import ( |
| 6 |
"path/filepath" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"github.com/go-git/go-billy/v6" |
| 10 |
"github.com/go-git/go-billy/v6/helper/chroot" |
| 11 |
"github.com/go-git/go-billy/v6/memfs" |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
var globalMemFs = memfs.New() |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
var Default = memfs.New() |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
func New(baseDir string, opts ...Option) billy.Filesystem { |
| 24 |
o := &options{} |
| 25 |
for _, opt := range opts { |
| 26 |
opt(o) |
| 27 |
} |
| 28 |
|
| 29 |
return newBoundOS(baseDir) |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
type BoundOS struct { |
| 35 |
billy.Filesystem |
| 36 |
baseDir string |
| 37 |
} |
| 38 |
|
| 39 |
func newBoundOS(d string) billy.Filesystem { |
| 40 |
baseDir := globalMemFs.Join("/", d) |
| 41 |
return &BoundOS{ |
| 42 |
Filesystem: chroot.New(globalMemFs, baseDir), |
| 43 |
baseDir: baseDir, |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
func (fs *BoundOS) Capabilities() billy.Capability { |
| 50 |
return billy.Capabilities(fs.Filesystem) |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
func (fs *BoundOS) Chroot(path string) (billy.Filesystem, error) { |
| 56 |
joined, err := fs.abs(path) |
| 57 |
if err != nil { |
| 58 |
return nil, err |
| 59 |
} |
| 60 |
return New(joined, WithBoundOS()), nil |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
func (fs *BoundOS) Root() string { |
| 65 |
return fs.baseDir |
| 66 |
} |
| 67 |
|
| 68 |
func (fs *BoundOS) abs(filename string) (string, error) { |
| 69 |
if filename == "." || filename == "" { |
| 70 |
return fs.baseDir, nil |
| 71 |
} |
| 72 |
|
| 73 |
filename = filepath.ToSlash(filename) |
| 74 |
filename = filepath.Clean(filename) |
| 75 |
if strings.HasPrefix(filename, "..") { |
| 76 |
return "", billy.ErrCrossedBoundary |
| 77 |
} |
| 78 |
|
| 79 |
filename = strings.TrimPrefix(filename, string(filepath.Separator)) |
| 80 |
return filepath.Clean(filepath.Join(fs.baseDir, filepath.FromSlash(filename))), nil |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
func WithBoundOS() Option { |
| 85 |
return func(o *options) { |
| 86 |
o.Type = BoundOSFS |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
func WithMmap() Option { |
| 94 |
return func(o *options) { |
| 95 |
o.mmap = true |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
type Option func(*options) |
| 100 |
|
| 101 |
type options struct { |
| 102 |
Type |
| 103 |
mmap bool |
| 104 |
} |
| 105 |
|
| 106 |
type Type int |
| 107 |
|
| 108 |
const ( |
| 109 |
BoundOSFS Type = iota |
| 110 |
) |