refine BasePathFs implementation

This commit is contained in:
Steve Francia 2016-01-11 16:32:08 -05:00
parent 76b64e1d85
commit a3ed628486
2 changed files with 5 additions and 8 deletions

View File

@ -20,16 +20,13 @@ type BasePathFs struct {
path string path string
} }
// NewBasePathFs applies filepath.Clean on creation
func NewBasePathFs(source Fs, path string) *BasePathFs {
return &BasePathFs{source: source, path: filepath.Clean(path) + string(os.PathSeparator)}
}
// on a file outside the base path it returns the given file name and an error, // on a file outside the base path it returns the given file name and an error,
// else the given file with the base path prepended // else the given file with the base path prepended
func (b *BasePathFs) RealPath(name string) (path string, err error) { func (b *BasePathFs) RealPath(name string) (path string, err error) {
path = filepath.Clean(filepath.Join(b.path, name)) bpath := filepath.Clean(b.path) + string(os.PathSeparator)
if !strings.HasPrefix(path, b.path) {
path = filepath.Clean(filepath.Join(bpath, name))
if !strings.HasPrefix(path, bpath) {
return name, os.ErrNotExist return name, os.ErrNotExist
} }
return path, nil return path, nil

View File

@ -7,7 +7,7 @@ import (
func TestBasePath(t *testing.T) { func TestBasePath(t *testing.T) {
baseFs := &MemMapFs{} baseFs := &MemMapFs{}
baseFs.MkdirAll("/base/path/tmp", 0777) baseFs.MkdirAll("/base/path/tmp", 0777)
bp := NewBasePathFs(baseFs, "/base/path") bp := &BasePathFs{source: baseFs, path: "/base/path"}
if _, err := bp.Create("/tmp/foo"); err != nil { if _, err := bp.Create("/tmp/foo"); err != nil {
t.Errorf("Failed to set real path") t.Errorf("Failed to set real path")