|
| 1 | +package httpfs |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "path" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/go-git/go-billy/v5" |
| 9 | +) |
| 10 | + |
| 11 | +// BillyFs is the set of required billy filesystem interfaces. |
| 12 | +type BillyFs interface { |
| 13 | + billy.Basic |
| 14 | + billy.Dir |
| 15 | +} |
| 16 | + |
| 17 | +// FileSystem implements the HTTP filesystem. |
| 18 | +type FileSystem struct { |
| 19 | + // fs is the billy filesystem |
| 20 | + fs BillyFs |
| 21 | + // prefix is the filesystem prefix for HTTP |
| 22 | + prefix string |
| 23 | +} |
| 24 | + |
| 25 | +// NewFileSystem constructs the FileSystem from a Billy FileSystem. |
| 26 | +// |
| 27 | +// Prefix is a path prefix to prepend to file paths for HTTP. |
| 28 | +// The prefix is trimmed from the paths when opening files. |
| 29 | +func NewFileSystem(fs BillyFs, prefix string) *FileSystem { |
| 30 | + if len(prefix) != 0 { |
| 31 | + prefix = path.Clean(prefix) |
| 32 | + } |
| 33 | + return &FileSystem{fs: fs, prefix: prefix} |
| 34 | +} |
| 35 | + |
| 36 | +// Open opens the file at the given path. |
| 37 | +func (f *FileSystem) Open(name string) (http.File, error) { |
| 38 | + name = path.Clean(name) |
| 39 | + if len(f.prefix) != 0 { |
| 40 | + name = strings.TrimPrefix(name, f.prefix) |
| 41 | + name = path.Clean(name) |
| 42 | + } |
| 43 | + if strings.HasPrefix(name, "/") { |
| 44 | + name = name[1:] |
| 45 | + } |
| 46 | + |
| 47 | + fi, err := f.fs.Stat(name) |
| 48 | + if err != nil { |
| 49 | + return nil, err |
| 50 | + } |
| 51 | + if fi.IsDir() { |
| 52 | + return NewDir(f.fs, name), nil |
| 53 | + } |
| 54 | + return NewFile(f.fs, name) |
| 55 | +} |
| 56 | + |
| 57 | +// _ is a type assertion |
| 58 | +var _ http.FileSystem = ((*FileSystem)(nil)) |
0 commit comments