vcom/internal/vfs/paths.go

56 lines
1.8 KiB
Go
Raw Normal View History

package vfs
import (
"path"
"path/filepath"
"strings"
)
// PathOps are the path rules of an FS.
type PathOps interface {
Join(elem ...string) string
Dir(p string) string
Base(p string) string
Clean(p string) string
IsAbs(p string) bool
Sep() byte
}
// PosixPaths are slash-separated paths (sftp, archives).
var PosixPaths PathOps = posixPaths{}
// NativePaths follow the host OS (path/filepath); used by localfs.
var NativePaths PathOps = nativePaths{}
type posixPaths struct{}
func (posixPaths) Join(elem ...string) string { return path.Join(elem...) }
func (posixPaths) Dir(p string) string { return path.Dir(p) }
func (posixPaths) Base(p string) string { return path.Base(p) }
func (posixPaths) Clean(p string) string { return path.Clean(p) }
func (posixPaths) IsAbs(p string) bool { return path.IsAbs(p) }
func (posixPaths) Sep() byte { return '/' }
type nativePaths struct{}
func (nativePaths) Join(elem ...string) string { return filepath.Join(elem...) }
func (nativePaths) Dir(p string) string { return filepath.Dir(p) }
func (nativePaths) Base(p string) string { return filepath.Base(p) }
func (nativePaths) Clean(p string) string { return filepath.Clean(p) }
func (nativePaths) IsAbs(p string) bool { return filepath.IsAbs(p) }
func (nativePaths) Sep() byte { return filepath.Separator }
// IsWithin reports whether child equals parent or lies under it, comparing
// cleaned paths lexically with ops (no symlink resolution; see Within).
func IsWithin(ops PathOps, child, parent string) bool {
child, parent = ops.Clean(child), ops.Clean(parent)
if child == parent {
return true
}
sep := string(ops.Sep())
if !strings.HasSuffix(parent, sep) {
parent += sep
}
return strings.HasPrefix(child, parent)
}