Documentation
¶
Index ¶
- Constants
- Variables
- func AdminGroupName(osType OSType) string
- func AdminUserName(osType OSType) string
- func CopyFile(dstFs, srcFs VFSBase, dstPath, srcPath string) error
- func CopyFileHash(dstFs, srcFs VFSBase, dstPath, srcPath string, hasher hash.Hash) (sum []byte, err error)
- func DirExists(vfs VFSBase, path string) (bool, error)
- func Exists(vfs VFSBase, path string) (bool, error)
- func FromUnixPath[T VFSBase](vfs T, path string) string
- func Glob[T VFSBase](vfs T, pattern string) (matches []string, err error)
- func HashFile(vfs VFSBase, name string, hasher hash.Hash) (sum []byte, err error)
- func IsDir(vfs VFSBase, path string) (bool, error)
- func IsEmpty(vfs VFSBase, path string) (bool, error)
- func IsExist(err error) bool
- func IsNotExist(err error) bool
- func IsValidName(name string) bool
- func MkDirs[T VFSBase](vfs T, dirs []DirInfo, basePath string) error
- func MkdirTemp[T VFSBase](vfs T, dir, pattern string) (string, error)
- func ReadDir[T VFSBase](vfs T, name string) ([]fs.DirEntry, error)
- func ReadFile[T VFSBase](vfs T, name string) ([]byte, error)
- func SetUMask(mask fs.FileMode) error
- func SplitAbs[T VFSBase](vfs T, path string) (dir, file string)
- func Tree(vfs VFSBase, path string) string
- func UMask() fs.FileMode
- func WalkDir[T VFSBase](vfs T, root string, fn fs.WalkDirFunc) error
- func WriteFile[T VFSBase](vfs T, name string, data []byte, perm fs.FileMode) error
- type AlreadyExistsGroupError
- type AlreadyExistsUserError
- type ChRooter
- type Cloner
- type CustomError
- type DirInfo
- type DummyGroup
- type DummyIdm
- func (idm *DummyIdm) AddGroup(groupName string) (GroupReader, error)
- func (idm *DummyIdm) AddUser(userName, groupName string) (UserReader, error)
- func (idm *DummyIdm) AddUserToGroup(userName, groupName string) error
- func (idm *DummyIdm) AdminGroup() GroupReader
- func (idm *DummyIdm) AdminUser() UserReader
- func (idm *DummyIdm) DelGroup(groupName string) error
- func (idm *DummyIdm) DelUser(userName string) error
- func (idm *DummyIdm) DelUserFromGroup(userName, groupName string) error
- func (idm *DummyIdm) Features() Features
- func (idm *DummyIdm) HasFeature(feature Features) bool
- func (idm *DummyIdm) LookupGroup(groupName string) (GroupReader, error)
- func (idm *DummyIdm) LookupGroupId(gid int) (GroupReader, error)
- func (idm *DummyIdm) LookupUser(userName string) (UserReader, error)
- func (idm *DummyIdm) LookupUserId(uid int) (UserReader, error)
- func (idm *DummyIdm) OSType() OSType
- func (idm *DummyIdm) SetUserPrimaryGroup(userName, groupName string) error
- func (idm *DummyIdm) Type() string
- type DummyUser
- func (u *DummyUser) Gid() int
- func (u *DummyUser) Groups() []string
- func (u *DummyUser) GroupsId() []int
- func (u *DummyUser) IsAdmin() bool
- func (u *DummyUser) IsInGroupId(gid int) bool
- func (u *DummyUser) Name() string
- func (u *DummyUser) PrimaryGroup() string
- func (u *DummyUser) PrimaryGroupId() int
- func (u *DummyUser) Uid() int
- type ErrorsForOS
- type Featurer
- type Features
- type FeaturesMixin
- type File
- type FnVFS
- type GroupIdentifier
- type GroupReader
- type IOFS
- type IdmMgr
- type IdmMixin
- type IdmProvider
- type InvalidNameError
- type LinuxError
- type Namer
- type OSType
- type OSTypeMixin
- type OSTyper
- type OpenMode
- type PathIterator
- func (pi *PathIterator[_]) End() int
- func (pi *PathIterator[_]) IsLast() bool
- func (pi *PathIterator[_]) Left() string
- func (pi *PathIterator[_]) LeftPart() string
- func (pi *PathIterator[_]) Next() bool
- func (pi *PathIterator[_]) Part() string
- func (pi *PathIterator[_]) Path() string
- func (pi *PathIterator[_]) ReplacePart(newPath string) bool
- func (pi *PathIterator[_]) Reset()
- func (pi *PathIterator[_]) Right() string
- func (pi *PathIterator[_]) RightPart() string
- func (pi *PathIterator[_]) Start() int
- func (pi *PathIterator[_]) VolumeName() string
- func (pi *PathIterator[_]) VolumeNameLen() int
- type PathMixin
- func (pmx *PathMixin) Base(path string) string
- func (pmx *PathMixin) Clean(path string) string
- func (pmx *PathMixin) Dir(path string) string
- func (pmx *PathMixin) FromSlash(path string) string
- func (pmx *PathMixin) IsAbs(path string) bool
- func (pmx *PathMixin) IsPathSeparator(c uint8) bool
- func (pmx *PathMixin) Join(elem ...string) string
- func (pmx *PathMixin) Match(pattern, name string) (matched bool, err error)
- func (pmx *PathMixin) Rel(basepath, targpath string) (string, error)
- func (pmx *PathMixin) Split(path string) (dir, file string)
- func (pmx *PathMixin) ToSlash(path string) string
- func (pmx *PathMixin) ToSysStat(info fs.FileInfo) SysStater
- func (pmx *PathMixin) VolumeName(path string) string
- func (pmx *PathMixin) VolumeNameLen(path string) int
- type RndTree
- func (rt *RndTree) CreateDirs(baseDir string) error
- func (rt *RndTree) CreateFiles(baseDir string) error
- func (rt *RndTree) CreateSymlinks(baseDir string) error
- func (rt *RndTree) CreateTree(baseDir string) error
- func (rt *RndTree) Dirs() []*RndTreeDir
- func (rt *RndTree) Files() []*RndTreeFile
- func (rt *RndTree) GenTree()
- func (rt *RndTree) SymLinks() []*RndTreeSymLink
- type RndTreeDir
- type RndTreeFile
- type RndTreeOpts
- type RndTreeSymLink
- type SysError
- type SysStater
- type Typer
- type UMaskMixin
- type UMasker
- type UnknownError
- type UnknownGroupError
- type UnknownGroupIdError
- type UnknownUserError
- type UnknownUserIdError
- type UserDirMixin
- func (udmx *UserDirMixin) Abs(path string) (string, error)
- func (udmx *UserDirMixin) CurDir() string
- func (udmx *UserDirMixin) Getwd() (dir string, err error)
- func (udmx *UserDirMixin) Init(ost OSType, idm IdmMgr, user UserReader) error
- func (udmx *UserDirMixin) SetCurDir(curDir string) error
- func (udmx *UserDirMixin) TempDir() string
- func (udmx *UserDirMixin) User() UserReader
- func (udmx *UserDirMixin) UserHomeDir() (string, error)
- type UserIdentifier
- type UserMgr
- type UserReader
- type VFS
- type VFSBase
- type VFSPath
- type VFSUserDir
- type VolumeManager
- type WindowsError
Constants ¶
const ( OpReaddirent = "readdirent" OpReaddir = "readdir" )
Operation constants (most used).
const ( DefaultDirPerm = fs.FileMode(0o777) // DefaultDirPerm is the default permission for directories. DefaultFilePerm = fs.FileMode(0o666) // DefaultFilePerm is the default permission for files. DefaultName = "Default" // DefaultName is the default name. DefaultVolume = "C:" // DefaultVolume is the default volume name for Windows. NotImplemented = "not implemented" // NotImplemented is the return string of a non-implemented feature. // FileModeMask is the bitmask used for permissions. FileModeMask = fs.ModePerm | fs.ModeSticky | fs.ModeSetuid | fs.ModeSetgid )
const (
O_DIRECTORY = syscall.O_DIRECTORY
)
const OpWinCreateFile = "GetFileAttributesEx"
OpWinCreateFile is the name of the Windows CreateFile operation.
Variables ¶
var DefaultIdm = NewDummyIdm() //nolint:gochecknoglobals // Used as default Idm for other file systems.
DefaultIdm is the default identity manager for all file systems. It is a DummyIdm in which every function is not implemented.
var ErrSetOSType = errors.New("can't set OS type, use build tag 'avfs_setostype' to set OS type")
Functions ¶
func AdminGroupName ¶
AdminGroupName returns the default name of the administrator group of the file system.
func AdminUserName ¶
AdminUserName returns the default name of the administrator of the file system.
func CopyFileHash ¶
func CopyFileHash(dstFs, srcFs VFSBase, dstPath, srcPath string, hasher hash.Hash) (sum []byte, err error)
CopyFileHash copies a file between file systems and returns the hash sum of the source file.
func FromUnixPath ¶
FromUnixPath returns a valid path for Unix or Windows from a unix path. For Windows systems, absolute paths are prefixed with the default volume and relative paths are preserved.
func Glob ¶
Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in [Match]. The pattern may describe hierarchical names such as /usr/*/bin/ed (assuming the [Separator] is '/').
Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is [ErrBadPattern], when pattern is malformed.
func IsExist ¶
IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists. It is satisfied by ErrExist as well as some syscall errors.
This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrExist).
func IsNotExist ¶
IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.
This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist).
func IsValidName ¶
IsValidName checks if the input string is a valid username or group name.
func MkDirs ¶
MkDirs creates a set of directories with specified permissions, ownership, and base path.
func MkdirTemp ¶
MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. If pattern includes a "*", the random string replaces the last "*" instead. The directory is created with mode 0o700 (before umask). If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by [TempDir]. Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when it is no longer needed.
func ReadDir ¶
ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.
func ReadFile ¶
ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported. If there is an error, it will be of type [*PathError].
func SetUMask ¶
SetUMask sets the file mode creation mask. Umask must be set to 0 using umask(2) system call to be read, so its value is cached and protected by a mutex.
func SplitAbs ¶
SplitAbs splits an absolute path immediately preceding the final [Separator], separating it into a directory and file name component. If there is no [Separator] in path, SplitAbs returns an empty dir and file set to path. The returned values have the property that path = dir + [PathSeparator] + file.
func WalkDir ¶
func WalkDir[T VFSBase](vfs T, root string, fn fs.WalkDirFunc) error
WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.
All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.
The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.
WalkDir does not follow symbolic links.
WalkDir calls fn with paths that use the separator character appropriate for the operating system. This is unlike io/fs.WalkDir, which always uses slash separated paths.
func WriteFile ¶
WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.
Types ¶
type AlreadyExistsGroupError ¶
type AlreadyExistsGroupError string
AlreadyExistsGroupError is returned when the group name already exists.
func (AlreadyExistsGroupError) Error ¶
func (e AlreadyExistsGroupError) Error() string
type AlreadyExistsUserError ¶
type AlreadyExistsUserError string
AlreadyExistsUserError is returned when the user name already exists.
func (AlreadyExistsUserError) Error ¶
func (e AlreadyExistsUserError) Error() string
type ChRooter ¶
type ChRooter interface {
// Chroot changes the root to that specified in path.
// If the user has not root privileges, it returns a permission error.
// If there is an error, it will be of type [*PathError].
Chroot(path string) error
}
ChRooter is the interface that wraps the Chroot method.
type Cloner ¶
type Cloner interface {
// CloneWithUser returns a shallow copy of the current file system (see
// MemFs) acting as user and emulating ost.
//
// The directories of user (home and temporary) are not created: the clone
// only refers to them, and they must already exist in the shared content
// unless user is the administrator.
//
// If user is nil, the administrator of the identity manager is used.
// If ost is [OsUnknown], the OS type of the current file system is kept.
// If ost can't be set (see [ErrSetOSType]), it returns that error.
CloneWithUser(user UserReader, ost OSType) (VFS, error)
// CloneWithUserName returns a shallow copy of the current file system
// (see MemFs) acting as the user userName and emulating ost.
//
// If the user is not found, the returned error is of type
// [UnknownUserError].
CloneWithUserName(userName string, ost OSType) (VFS, error)
}
Cloner is the interface that wraps the cloning methods of a file system.
A clone shares the content (the nodes) of the file system it is copied from, but has its own identity: its own current user, working directory, home and temporary directories, and its own emulated OS type. Cloning is therefore the only way to obtain a file system acting as another user or emulating another OS — see VFSUserDir for why those are immutable.
A clone is safe for concurrent use together with the file system it was cloned from: the content is guarded by the locks of the shared storage, and each identity is only mutated through Chdir.
type CustomError ¶
type CustomError uintptr
const ( ErrNegativeOffset CustomError = customErrorBase - 1 // negative offset ErrFileClosing CustomError = customErrorBase - 2 // use of closed file ErrPatternHasSeparator CustomError = customErrorBase - 3 // pattern contains path separator ErrVolumeAlreadyExists CustomError = customErrorBase - 4 // Volume already exists. ErrVolumeNameInvalid CustomError = customErrorBase - 5 // Volume name is invalid. ErrVolumeWindows CustomError = customErrorBase - 6 // Volumes are available for Windows only. ErrNotSupported CustomError = customErrorBase - 7 // The operation is not supported. )
func (CustomError) Error ¶
func (i CustomError) Error() string
func (CustomError) String ¶
func (i CustomError) String() string
type DirInfo ¶
type DirInfo struct {
Path string // Path specifies the absolute path of the directory.
Perm fs.FileMode // Perm defines the permission bits for the directory as specified by the fs.FileMode type.
Uid int //
Gid int //
}
DirInfo represents metadata for a directory, including its path, permissions, and ownership identifiers.
func SystemDirs ¶
SystemDirs returns an array of system directories always present in the file system.
func UserDirsInfo ¶
func UserDirsInfo[T VFSBase](vfs T, u UserReader) []DirInfo
UserDirsInfo retrieves metadata for all user directories of the user u from the provided virtual file system (vfs). The home directory of u is always the first element of the returned slice.
type DummyGroup ¶
type DummyGroup struct {
// contains filtered or unexported fields
}
DummyGroup is the implementation of avfs.GroupReader.
func NewGroup ¶
func NewGroup(groupName string, gid int) *DummyGroup
NewGroup creates and returns a pointer to a DummyGroup with the specified group name and group ID.
type DummyIdm ¶
type DummyIdm struct {
// contains filtered or unexported fields
}
DummyIdm represent a non implemented identity manager using the avfs.IdmMgr interface.
func (*DummyIdm) AddGroup ¶
func (idm *DummyIdm) AddGroup(groupName string) (GroupReader, error)
AddGroup creates a new group with the specified name. If the group already exists, the returned error is of type avfs.AlreadyExistsGroupError.
func (*DummyIdm) AddUser ¶
func (idm *DummyIdm) AddUser(userName, groupName string) (UserReader, error)
AddUser creates a new user with the specified userName and the specified primary group groupName. If the user already exists, the returned error is of type avfs.AlreadyExistsUserError.
func (*DummyIdm) AddUserToGroup ¶
AddUserToGroup adds the user to the group. If the user or group is not found, the returned error is of type avfs.UnknownUserError or avfs.UnknownGroupError respectively.
func (*DummyIdm) AdminGroup ¶
func (idm *DummyIdm) AdminGroup() GroupReader
AdminGroup returns the administrators (root) group.
func (*DummyIdm) AdminUser ¶
func (idm *DummyIdm) AdminUser() UserReader
AdminUser returns the administrator (root) user.
func (*DummyIdm) DelGroup ¶
DelGroup deletes an existing group with the specified name. If the group is not found, the returned error is of type avfs.UnknownGroupError.
func (*DummyIdm) DelUser ¶
DelUser deletes an existing user with the specified name. If the user is not found, the returned error is of type avfs.UnknownUserError.
func (*DummyIdm) DelUserFromGroup ¶
DelUserFromGroup removes the user from the group. If the user or group is not found, the returned error is of type avfs.UnknownUserError or avfs.UnknownGroupError respectively.
func (*DummyIdm) Features ¶
Features returns the set of features provided by the file system or identity manager.
func (*DummyIdm) HasFeature ¶
HasFeature returns true if the file system or identity manager provides a given feature.
func (*DummyIdm) LookupGroup ¶
func (idm *DummyIdm) LookupGroup(groupName string) (GroupReader, error)
LookupGroup looks up a group by name. If the group is not found, the returned error is of type avfs.UnknownGroupError.
func (*DummyIdm) LookupGroupId ¶
func (idm *DummyIdm) LookupGroupId(gid int) (GroupReader, error)
LookupGroupId looks up a group by groupid. If the group is not found, the returned error is of type avfs.UnknownGroupIdError.
func (*DummyIdm) LookupUser ¶
func (idm *DummyIdm) LookupUser(userName string) (UserReader, error)
LookupUser looks up a user by username. If the user is not found, the returned error is of type avfs.UnknownUserError.
func (*DummyIdm) LookupUserId ¶
func (idm *DummyIdm) LookupUserId(uid int) (UserReader, error)
LookupUserId looks up a user by userid. If the user cannot be found, the returned error is of type avfs.UnknownUserIdError.
func (*DummyIdm) SetUserPrimaryGroup ¶
SetUserPrimaryGroup sets the primary group of a user to the specified group name. If the user or group is not found, the returned error is of type avfs.UnknownUserError or avfs.UnknownGroupError respectively. If the operation fails, the returned error is of type avfs.UnknownError.
type DummyUser ¶
type DummyUser struct {
// contains filtered or unexported fields
}
DummyUser is the implementation of avfs.UserReader.
func NewUser ¶
NewUser creates a new instance of DummyUser with the specified username, user ID (uid), and group ID (gid).
func (*DummyUser) Groups ¶
Groups returns a slice of strings representing the group names that the user belongs to. If an error occurs while fetching the group names, it returns nil.
func (*DummyUser) GroupsId ¶
GroupsId returns a slice group IDs that the user belongs to. If an error occurs while fetching the group IDs, it returns nil.
func (*DummyUser) IsInGroupId ¶
IsInGroupId returns true if the user is in the specified group ID.
func (*DummyUser) PrimaryGroup ¶
PrimaryGroup returns the primary group name of the user.
func (*DummyUser) PrimaryGroupId ¶
PrimaryGroupId returns the primary group ID of the OsUser. If an error occurs, it returns the maximum integer value.
type ErrorsForOS ¶
type ErrorsForOS struct {
BadFileDesc error // bad file descriptor.
DirNotEmpty error // Directory not empty.
FileClosing error // use of closed file.
FileExists error // File exists.
InvalidArgument error // invalid argument.
IsADirectory error // File Is a directory.
NegativeSeek error // Negative seek invalid argument.
NoSuchDir error // No such directory.
NoSuchFile error // No such file.
NotADirectory error // Not a directory.
OpNotPermitted error // operation not permitted.
PermDenied error // Permission denied.
TooManySymlinks error // Too many levels of symbolic links.
}
ErrorsForOS regroups errors depending on the OS emulated.
func ErrorsFor ¶
func ErrorsFor(osType OSType) *ErrorsForOS
type Featurer ¶
type Featurer interface {
// Features returns the set of features provided by the file system or identity manager.
Features() Features
// HasFeature returns true if the file system or identity manager provides a given feature.
HasFeature(feature Features) bool
}
Featurer is the interface that wraps the Features and HasFeature methods.
type Features ¶
type Features uint64
Features defines the set of features available on a file system.
const ( // FeatHardlink indicates that the file system supports hard links (link(), readlink() functions). FeatHardlink Features = 1 << iota // FeatIdentityMgr indicates that the file system features and identity manager and supports multiple users. FeatIdentityMgr // FeatSetOSType is set if the OS of the emulated file system may differ from // the host OS (build tag avfs_setostype). The OS type of a file system is // immutable: a file system emulating another OS is obtained by cloning // (see Cloner). FeatSetOSType // FeatReadOnly is set for read only file systems (see RoFs). FeatReadOnly // FeatReadOnlyIdm is set when identity manager is read only (see OsIdm). FeatReadOnlyIdm // FeatRealFS indicates that the file system is a real one, not emulated (see OsFS). FeatRealFS // FeatSubFS allow to create a new file system from the subtree rooted at an arbitrary directory. FeatSubFS // FeatSymlink indicates that the file system supports symbolic links (symlink(), evalSymlink() functions). FeatSymlink )
func BuildFeatures ¶
func BuildFeatures() Features
BuildFeatures returns the features available depending on build tags.
type FeaturesMixin ¶
type FeaturesMixin struct {
// contains filtered or unexported fields
}
FeaturesMixin is an embeddable default implementation of the Featurer interface.
func (*FeaturesMixin) Features ¶
func (fmx *FeaturesMixin) Features() Features
Features returns the set of features provided by the file system or identity manager.
func (*FeaturesMixin) HasFeature ¶
func (fmx *FeaturesMixin) HasFeature(feature Features) bool
HasFeature returns true if the file system or identity manager provides a given feature.
func (*FeaturesMixin) SetFeatures ¶
func (fmx *FeaturesMixin) SetFeatures(feature Features) error
SetFeatures sets the features of the file system or identity manager.
type File ¶
type File interface {
fs.File
fs.ReadDirFile
io.Reader
io.ReaderAt
io.StringWriter
io.Writer
io.WriterAt
io.WriteSeeker
// Chdir changes the current working directory to the file,
// which must be a directory.
// If there is an error, it will be of type [*PathError].
Chdir() error
// Chmod changes the mode of the file to mode.
// If there is an error, it will be of type [*PathError].
Chmod(mode fs.FileMode) error
// Chown changes the numeric uid and gid of the named file.
// If there is an error, it will be of type [*PathError].
//
// On Windows, it always returns the [syscall.EWINDOWS] error, wrapped
// in [*PathError].
Chown(uid, gid int) error
// Fd returns the system file descriptor or handle referencing the open file.
// If f is closed, the descriptor becomes invalid.
// If f is garbage collected, a finalizer may close the descriptor,
// making it invalid; see [runtime.SetFinalizer] for more information on when
// a finalizer might be run.
//
// Do not close the returned descriptor; that could cause a later
// close of f to close an unrelated descriptor.
//
// Fd's behavior differs on some platforms:
//
// - On Unix and Windows, [File.SetDeadline] methods will stop working.
// - On Windows, the file descriptor will be disassociated from the
// Go runtime I/O completion port if there are no concurrent I/O
// operations on the file.
//
// For most uses prefer the f.SyscallConn method.
Fd() uintptr
// Name returns the name of the file as presented to [Open].
//
// It is safe to call Name after [Close].
Name() string
// Readdirnames reads the contents of the directory associated with file
// and returns a slice of up to n names of files in the directory,
// in directory order. Subsequent calls on the same file will yield
// further names.
//
// If n > 0, Readdirnames returns at most n names. In this case, if
// Readdirnames returns an empty slice, it will return a non-nil error
// explaining why. At the end of a directory, the error is [io.EOF].
//
// If n <= 0, Readdirnames returns all the names from the directory in
// a single slice. In this case, if Readdirnames succeeds (reads all
// the way to the end of the directory), it returns the slice and a
// nil error. If it encounters an error before the end of the
// directory, Readdirnames returns the names read until that point and
// a non-nil error.
Readdirnames(n int) (names []string, err error)
// Sync commits the current contents of the file to stable storage.
// Typically, this means flushing the file system's in-memory copy
// of recently written data to disk.
Sync() error
// Truncate changes the size of the file.
// It does not change the I/O offset.
// If there is an error, it will be of type [*PathError].
Truncate(size int64) error
}
File represents a file in the file system.
func Create ¶
Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0o666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode [O_RDWR]. The directory containing the file must already exist. If there is an error, it will be of type [*PathError].
func CreateTemp ¶
CreateTemp creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". The file is created with mode 0o600 (before umask). If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by [TempDir]. Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file. The caller can use the file's Name method to find the pathname of the file. It is the caller's responsibility to remove the file when it is no longer needed.
type FnVFS ¶
type FnVFS uint
FnVFS defines the function names of a virtual file system that can return an error (see failfs.FailFS).
const ( FnAbs FnVFS = iota + 1 FnChdir FnChmod FnChown FnChtimes FnCreateTemp FnEvalSymlinks FnFileChdir FnFileChmod FnFileChown FnFileClose FnFileRead FnFileReadAt FnFileReadDir FnFileReaddirnames FnFileSeek FnFileStat FnFileSync FnFileTruncate FnFileWrite FnFileWriteAt FnGetwd FnLchown FnLink FnLstat FnMkdir FnMkdirAll FnMkdirTemp FnOpenFile FnReadDir FnReadFile FnReadlink FnRemove FnRemoveAll FnRename FnStat FnSub FnSymlink FnTruncate FnWalkDir FnWriteFile )
type GroupIdentifier ¶
type GroupIdentifier interface {
// Gid returns the primary group id.
Gid() int
}
GroupIdentifier is the interface that wraps the Gid method.
type GroupReader ¶
type GroupReader interface {
GroupIdentifier
Namer
}
GroupReader interface reads group information.
type IdmMgr ¶
type IdmMgr interface {
Featurer
OSTyper
Typer
UserMgr
// AdminGroup returns the administrator (root) group.
AdminGroup() GroupReader
// AdminUser returns the administrator (root) user.
AdminUser() UserReader
// AddGroup creates a new group with the specified name.
// If the group already exists, the returned error is of type avfs.AlreadyExistsGroupError.
AddGroup(groupName string) (GroupReader, error)
// AddUserToGroup adds the user to the group.
// If the user or group is not found, the returned error is of type avfs.UnknownUserError or avfs.UnknownGroupError respectively.
AddUserToGroup(userName, groupName string) error
// DelGroup deletes an existing group with the specified name.
// If the group is not found, the returned error is of type avfs.UnknownGroupError.
DelGroup(groupName string) error
// DelUserFromGroup removes the user from the group.
// If the user or group is not found, the returned error is of type avfs.UnknownUserError
// or avfs.UnknownGroupError respectively.
DelUserFromGroup(userName, groupName string) error
// LookupGroup looks up a group by name.
// If the group is not found, the returned error is of type avfs.UnknownGroupError.
LookupGroup(groupName string) (GroupReader, error)
// LookupGroupId looks up a group by groupid.
// If the group is not found, the returned error is of type avfs.UnknownGroupIdError.
LookupGroupId(gid int) (GroupReader, error)
// LookupUser looks up a user by username.
// If the user is not found, the returned error is of type avfs.UnknownUserError.
LookupUser(userName string) (UserReader, error)
// LookupUserId looks up a user by userid.
// If the user is not found, the returned error is of type avfs.UnknownUserIdError.
LookupUserId(uid int) (UserReader, error)
// SetUserPrimaryGroup sets the primary group of a user to the specified group name.
// If the user or group is not found, the returned error is of type avfs.UnknownUserError or avfs.UnknownGroupError respectively.
// If the operation fails, the returned error is of type avfs.UnknownError.
SetUserPrimaryGroup(userName, groupName string) error
}
IdmMgr interface manages identities (users and groups).
type IdmMixin ¶
type IdmMixin struct {
// contains filtered or unexported fields
}
IdmMixin is an embeddable default implementation of the IdmProvider interface.
type IdmProvider ¶
type IdmProvider interface {
// Idm returns the identity manager of the file system.
Idm() IdmMgr
// InitIdm sets the identity manager of the file system.
// It must be called once, during construction: the identity manager of a
// file system is immutable, so that the users a file system resolves can
// never change under a running operation.
// If the identity manager is nil, the idm avfs.DefaultIdm is set.
InitIdm(idm IdmMgr) error
}
IdmProvider is the interface that wraps Identity manager setting methods for file systems.
type InvalidNameError ¶
type InvalidNameError string
InvalidNameError is return when a username or a group name is invalid.
func (InvalidNameError) Error ¶
func (e InvalidNameError) Error() string
type LinuxError ¶
type LinuxError uintptr
LinuxError replaces syscall.Errno for Linux operating systems.
const ( ErrBadFileDesc LinuxError = errEBADF // bad file descriptor ErrCrossDevLink LinuxError = errEXDEV // invalid cross-device link ErrDirNotEmpty LinuxError = errENOTEMPTY // directory not empty ErrFileExists LinuxError = errEEXIST // file exists ErrInvalidArgument LinuxError = errEINVAL // invalid argument ErrIsADirectory LinuxError = errEISDIR // is a directory ErrNoSuchFileOrDir LinuxError = errENOENT // no such file or directory ErrNotADirectory LinuxError = errENOTDIR // not a directory ErrOpNotPermitted LinuxError = errEPERM // operation not permitted ErrPermDenied LinuxError = errEACCES // permission denied ErrTooManySymlinks LinuxError = errELOOP // too many levels of symbolic links )
Errors for Linux operating systems. See https://github.com/torvalds/linux/blob/master/tools/include/uapi/asm-generic/errno-base.h
func (LinuxError) Error ¶
func (i LinuxError) Error() string
Error returns the error string of the Linux operating system.
func (LinuxError) Is ¶
func (i LinuxError) Is(target error) bool
Is returns true if the LinuxError can be treated as equivalent to a target error. target is one of fs.ErrPermission, fs.ErrExist, fs.ErrNotExist.
func (LinuxError) String ¶
func (i LinuxError) String() string
type Namer ¶
type Namer interface {
Name() string
}
Namer is the interface that wraps the Name method.
type OSTypeMixin ¶
type OSTypeMixin struct {
// contains filtered or unexported fields
}
OSTypeMixin is an embeddable default implementation of the OSTyper interface.
func (*OSTypeMixin) DirMode ¶
func (osx *OSTypeMixin) DirMode() fs.FileMode
DirMode returns the default file mode for new directories.
func (*OSTypeMixin) FileMode ¶
func (osx *OSTypeMixin) FileMode() fs.FileMode
FileMode returns the default file mode for new files.
func (*OSTypeMixin) InitOSType ¶
func (osx *OSTypeMixin) InitOSType(osType OSType) error
InitOSType sets the OS type. It must be called once, during construction: the OS type of a file system is immutable, so a file system emulating another OS is obtained by cloning it (see avfs.Cloner), never by switching the OS of a live one. If the OS type can't be set, it returns an error.
func (*OSTypeMixin) OSType ¶
func (osx *OSTypeMixin) OSType() OSType
OSType returns the operating system type of the file system.
func (*OSTypeMixin) PathSeparator ¶
func (osx *OSTypeMixin) PathSeparator() uint8
PathSeparator return the OS-specific path separator.
type OSTyper ¶
type OSTyper interface {
// OSType returns the operating system type of the file system.
OSType() OSType
}
OSTyper is the interface that wraps the OS type related methods.
type OpenMode ¶
type OpenMode int
OpenMode defines constants used by OpenFile and CheckPermission functions.
const ( OpenLookup OpenMode = 0o001 // OpenLookup checks for lookup permission on a directory. OpenWrite OpenMode = 0o002 // OpenWrite opens or checks for write permission. OpenRead OpenMode = 0o004 // OpenRead opens or checks for read permission. OpenAppend OpenMode = 1 << iota // OpenAppend opens a file for appending (os.O_APPEND). OpenCreate // OpenCreate creates a file (os.O_CREATE). OpenCreateExcl // OpenCreateExcl creates a non existing file (os.O_EXCL). OpenTruncate // OpenTruncate truncates a file (os.O_TRUNC). OpenDir // OpenDir opens a directory (syscall.O_DIRECTORY) returns error otherwise. )
func ToOpenMode ¶
ToOpenMode returns the open mode from the input flags.
type PathIterator ¶
type PathIterator[T VFSBase] struct { // contains filtered or unexported fields }
PathIterator iterates through an absolute path. It returns each part of the path in successive calls to Next. The volume name (for Windows) is not considered as part of the path it is returned by VolumeName.
Sample code :
pi := NewPathIterator(vfs, path)
for pi.Next() {
fmt.Println(pi.Part())
}
The path below shows the different results of the PathIterator methods when thirdPart is the current Part :
/firstPart/secondPart/thirdPart/fourthPart/fifthPart
|- Part --|
Start End
|------- Left -------| |------ Right ------|
|----- LeftPart ---------------|
|----------- RightPart -------|
func NewPathIterator ¶
func NewPathIterator[T VFSBase](vfs T, path string) *PathIterator[T]
NewPathIterator creates a new path iterator from an absolute path.
func (*PathIterator[_]) End ¶
func (pi *PathIterator[_]) End() int
End returns the end position of the current Part.
func (*PathIterator[_]) IsLast ¶
func (pi *PathIterator[_]) IsLast() bool
IsLast returns true if the current Part is the last one.
func (*PathIterator[_]) Left ¶
func (pi *PathIterator[_]) Left() string
Left returns the left path of the current Part.
func (*PathIterator[_]) LeftPart ¶
func (pi *PathIterator[_]) LeftPart() string
LeftPart returns the left path and current Part.
func (*PathIterator[_]) Next ¶
func (pi *PathIterator[_]) Next() bool
Next iterates through the next Part of the path. It returns false if there's no more parts.
func (*PathIterator[_]) Part ¶
func (pi *PathIterator[_]) Part() string
Part returns the current Part.
func (*PathIterator[_]) Path ¶
func (pi *PathIterator[_]) Path() string
Path returns the path to iterate.
func (*PathIterator[_]) ReplacePart ¶
func (pi *PathIterator[_]) ReplacePart(newPath string) bool
ReplacePart replaces the current Part of the path with the new path. If the path iterator has been reset it returns true. It can be used in symbolic link replacement.
func (*PathIterator[_]) Right ¶
func (pi *PathIterator[_]) Right() string
Right returns the right path of the current Part.
func (*PathIterator[_]) RightPart ¶
func (pi *PathIterator[_]) RightPart() string
RightPart returns the right path and the current Part.
func (*PathIterator[_]) Start ¶
func (pi *PathIterator[_]) Start() int
Start returns the start position of the current Part.
func (*PathIterator[_]) VolumeName ¶
func (pi *PathIterator[_]) VolumeName() string
VolumeName returns leading volume name.
func (*PathIterator[_]) VolumeNameLen ¶
func (pi *PathIterator[_]) VolumeNameLen() int
VolumeNameLen returns length of the leading volume name on Windows. It returns 0 elsewhere.
type PathMixin ¶
type PathMixin struct {
FeaturesMixin // FeaturesMixin is an embeddable default implementation of the Featurer interface.
UMaskMixin // UMaskMixin is an embeddable default implementation of the UMasker interface.
OSTypeMixin // OSTypeMixin is an embeddable default implementation of the OSTyper interface.
}
PathMixin is an embeddable default implementation of the VFSPath interface.
func (*PathMixin) Base ¶
Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.
func (*PathMixin) Clean ¶
Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:
- Replace multiple [Separator] elements with a single one.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path, assuming Separator is '/'.
The returned path ends in a slash only if it represents a root directory, such as "/" on Unix or `C:\` on Windows.
Finally, any occurrences of slash are replaced by Separator.
If the result of this process is an empty string, Clean returns the string ".".
On Windows, Clean does not modify the volume name other than to replace occurrences of "/" with `\`. For example, Clean("//host/share/../x") returns `\\host\share\x`.
See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html
func (*PathMixin) Dir ¶
Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.
On Windows, given a volume-only name such as "C:", Dir returns "C:.", the current directory on drive C. To obtain the drive's root "C:\", use VolumeName combined with a separator.
func (*PathMixin) FromSlash ¶
FromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators.
See also the Localize function, which converts a slash-separated path as used by the io/fs package to an operating system path.
func (*PathMixin) IsPathSeparator ¶
IsPathSeparator reports whether c is a directory separator character.
func (*PathMixin) Join ¶
Join joins any number of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string. On Windows, the result will only be a UNC path if the first non-empty element is a UNC path.
func (*PathMixin) Match ¶
Match reports whether name matches the shell file name pattern. The pattern syntax is:
pattern:
{ term }
term:
'*' matches any sequence of non-Separator characters
'?' matches any single non-Separator character
'[' [ '^' ] { character-range } ']'
character class (must be non-empty)
c matches character c (c != '*', '?', '\\', '[')
'\\' c matches character c (except on Windows)
character-range:
c matches character c (c != '\\', '-', ']')
'\\' c matches character c (except on Windows)
lo '-' hi matches character c for lo <= c <= hi
Path segments in the pattern must be separated by Separator.
Match requires pattern to match all of name, not just a substring. The only possible returned error is [ErrBadPattern], when pattern is malformed.
On Windows, escaping is disabled. Instead, '\\' is treated as path separator.
func (*PathMixin) Rel ¶
Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
The returned path will always be relative to basepath, even if basepath and targpath share no elements. Rel calls Clean on the result.
An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it.
func (*PathMixin) Split ¶
Split splits path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.
func (*PathMixin) ToSlash ¶
ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.
func (*PathMixin) ToSysStat ¶
ToSysStat takes a value from fs.FileInfo.Sys() and returns a value that implements interface avfs.SysStater.
func (*PathMixin) VolumeName ¶
VolumeName returns leading volume name. Given "C:\foo\bar" it returns "C:" on Windows. Given "\\host\share\foo" it returns "\\host\share". On other platforms it returns "".
func (*PathMixin) VolumeNameLen ¶
VolumeNameLen returns the length of the leading volume name on Windows. It returns 0 elsewhere.
type RndTree ¶
type RndTree struct {
RndTreeOpts // RndTreeOpts regroups the options of the tree.
// contains filtered or unexported fields
}
RndTree is a random file system tree generator of directories, files and symbolic links.
func NewRndTree ¶
func NewRndTree(vfs VFSBase, opts *RndTreeOpts) *RndTree
NewRndTree returns a new random tree generator.
func (*RndTree) CreateDirs ¶
CreateDirs creates random directories.
func (*RndTree) CreateFiles ¶
CreateFiles creates random files.
func (*RndTree) CreateSymlinks ¶
CreateSymlinks creates random symbolic links.
func (*RndTree) CreateTree ¶
CreateTree creates a random tree structure.
func (*RndTree) Dirs ¶
func (rt *RndTree) Dirs() []*RndTreeDir
func (*RndTree) Files ¶
func (rt *RndTree) Files() []*RndTreeFile
func (*RndTree) GenTree ¶
func (rt *RndTree) GenTree()
GenTree generates a random tree and populates RndTree.Dirs, RndTree.Files and RndTree.SymLinks.
func (*RndTree) SymLinks ¶
func (rt *RndTree) SymLinks() []*RndTreeSymLink
type RndTreeDir ¶
RndTreeDir contains parameters to create a directory.
type RndTreeFile ¶
RndTreeFile contains parameters to create a file.
type RndTreeOpts ¶
type RndTreeOpts struct {
NbDirs int // NbDirs is the number of directories.
NbFiles int // NbFiles is the number of files.
NbSymlinks int // NbSymlinks is the number of symbolic links.
MaxFileSize int // MaxFileSize is maximum size of a file.
MaxDepth int // MaxDepth is the maximum depth of the tree.
}
RndTreeOpts defines the parameters to generate a random file system tree of directories, files and symbolic links.
type RndTreeSymLink ¶
type RndTreeSymLink struct {
OldName, NewName string
}
RndTreeSymLink contains parameters to create a symbolic link.
type SysError ¶
type SysError interface {
error
// No returns the underlying system error number.
No() uint
// Is returns true if the error can be treated as equivalent to a target error.
// target is one of fs.ErrPermission, fs.ErrExist, fs.ErrNotExist.
Is(target error) bool
}
SysError is an interface that wraps the underlying system error number.
type SysStater ¶
type SysStater interface {
GroupIdentifier
UserIdentifier
Nlink() uint64
}
SysStater is the interface returned by ToSysStat on all file systems.
type Typer ¶
type Typer interface {
// Type returns the type of the fileSystem or Identity manager.
Type() string
}
Typer is the interface that wraps the Type method.
type UMaskMixin ¶
type UMaskMixin struct {
// contains filtered or unexported fields
}
UMaskMixin is an embeddable default implementation of the UMasker interface.
func (*UMaskMixin) SetUMask ¶
func (umx *UMaskMixin) SetUMask(mask fs.FileMode) error
SetUMask sets the file mode creation mask.
func (*UMaskMixin) UMask ¶
func (umx *UMaskMixin) UMask() fs.FileMode
UMask returns the file mode creation mask.
type UMasker ¶
type UMasker interface {
// SetUMask sets the file mode creation mask.
SetUMask(mask fs.FileMode) error
// UMask returns the file mode creation mask.
UMask() fs.FileMode
}
UMasker is the interface that wraps umask related methods.
type UnknownError ¶
type UnknownError string
UnknownError is returned when there is an unknown error.
func (UnknownError) Error ¶
func (e UnknownError) Error() string
type UnknownGroupError ¶
type UnknownGroupError string
UnknownGroupError is returned by LookupGroup when a group cannot be found.
func (UnknownGroupError) Error ¶
func (e UnknownGroupError) Error() string
type UnknownGroupIdError ¶
type UnknownGroupIdError int
UnknownGroupIdError is returned by LookupGroupId when a group cannot be found.
func (UnknownGroupIdError) Error ¶
func (e UnknownGroupIdError) Error() string
type UnknownUserError ¶
type UnknownUserError string
UnknownUserError is returned by Lookup when a user cannot be found.
func (UnknownUserError) Error ¶
func (e UnknownUserError) Error() string
type UnknownUserIdError ¶
type UnknownUserIdError int
UnknownUserIdError is returned by LookupUserId when a user cannot be found.
func (UnknownUserIdError) Error ¶
func (e UnknownUserIdError) Error() string
type UserDirMixin ¶
type UserDirMixin struct {
IdmMixin // IdmMixin is an embeddable default implementation of the IdmProvider interface.
PathMixin // PathMixin is an embeddable default implementation of the VFSPath interface.
// contains filtered or unexported fields
}
UserDirMixin is an embeddable default implementation of the VFSUserDir interface.
Init must be called once during construction. The user, home and temporary directories are then read-only; only the current directory changes, through SetCurDir (used by Chdir).
func (*UserDirMixin) Abs ¶
func (udmx *UserDirMixin) Abs(path string) (string, error)
Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique. Abs calls [Clean] on the result.
func (*UserDirMixin) CurDir ¶
func (udmx *UserDirMixin) CurDir() string
CurDir returns the current directory.
func (*UserDirMixin) Getwd ¶
func (udmx *UserDirMixin) Getwd() (dir string, err error)
Getwd returns an absolute path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.
On Unix platforms, if the environment variable PWD provides an absolute name, and it is a name of the current directory, it is returned.
func (*UserDirMixin) Init ¶
func (udmx *UserDirMixin) Init(ost OSType, idm IdmMgr, user UserReader) error
Init initializes the identity and the user directories of the file system.
It must be called once, during construction, before any other method: it sets the emulated OS type (ost), the identity manager (idm), the current user (user, the identity manager administrator if nil) and the current directory, which is the home directory of user.
The home and temporary directories are derived from ost and user, so a file system acting as another user, or emulating another OS, must be built with — or cloned with — that identity. The home directory must exist in the file system: it is the directory a clone starts in.
func (*UserDirMixin) SetCurDir ¶
func (udmx *UserDirMixin) SetCurDir(curDir string) error
SetCurDir sets the current directory.
Unlike Chdir, it resolves nothing and checks no permission: the caller is responsible for having authorized the directory beforehand.
func (*UserDirMixin) TempDir ¶
func (udmx *UserDirMixin) TempDir() string
TempDir returns the default directory to use for temporary files.
On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.
The directory is neither guaranteed to exist nor have accessible permissions.
func (*UserDirMixin) User ¶
func (udmx *UserDirMixin) User() UserReader
User returns the current user.
func (*UserDirMixin) UserHomeDir ¶
func (udmx *UserDirMixin) UserHomeDir() (string, error)
UserHomeDir returns the current user's home directory.
On Unix, including macOS, it returns the $HOME environment variable. On Windows, it returns %USERPROFILE%. On Plan 9, it returns the $home environment variable.
If the expected variable is not set in the environment, UserHomeDir returns either a platform-specific default value or a non-nil error.
type UserIdentifier ¶
type UserIdentifier interface {
// Uid returns the user id.
Uid() int
}
UserIdentifier is the interface that wraps the Uid method.
type UserMgr ¶
type UserMgr interface {
// AddUser creates a new user with the specified userName and the specified primary group groupName.
// If the user already exists, the returned error is of type avfs.AlreadyExistsUserError.
AddUser(userName, groupName string) (UserReader, error)
// DelUser deletes an existing user with the specified name.
// If the user is not found, the returned error is of type avfs.UnknownUserError.
DelUser(userName string) error
}
UserMgr is an interface that defines methods to create and delete user accounts in the identity managers and file systems.
type UserReader ¶
type UserReader interface {
GroupIdentifier
UserIdentifier
Namer
// Groups returns a slice of strings representing the group names that the user belongs to.
// If an error occurs while fetching the group names, it returns nil.
Groups() []string
// GroupsId returns a slice group IDs that the user belongs to.
// If an error occurs while fetching the group IDs, it returns nil.
GroupsId() []int
// IsInGroupId returns true if the user is in the specified group ID.
IsInGroupId(gid int) bool
// IsAdmin returns true if the user has administrator (root) privileges.
IsAdmin() bool
// PrimaryGroup returns the primary group name of the user.
PrimaryGroup() string
// PrimaryGroupId returns the primary group ID of the OsUser.
// If an error occurs, it returns the maximum integer value.
PrimaryGroupId() int
}
UserReader reads user information.
type VFS ¶
type VFS interface {
VFSBase
// Open opens the named file for reading. If successful, methods on
// the returned file can be used for reading; the associated file
// descriptor has mode [O_RDONLY].
// If there is an error, it will be of type [*PathError].
Open(name string) (File, error)
// Sub returns an FS corresponding to the subtree rooted at dir.
Sub(dir string) (VFS, error)
}
VFS is the virtual file system interface. Any simulated or real file system should implement this interface.
type VFSBase ¶
type VFSBase interface {
Featurer
IdmProvider
Namer
OSTyper
Typer
UMasker
VFSPath
VFSUserDir
// Base returns the last element of path.
// Trailing path separators are removed before extracting the last element.
// If the path is empty, Base returns ".".
// If the path consists entirely of separators, Base returns a single separator.
Base(path string) string
// Chdir changes the current working directory to the named directory.
// If there is an error, it will be of type [*PathError].
Chdir(dir string) error
// Chmod changes the mode of the named file to mode.
// If the file is a symbolic link, it changes the mode of the link's target.
// If there is an error, it will be of type [*PathError].
//
// A different subset of the mode bits are used, depending on the
// operating system.
//
// On Unix, the mode's permission bits, [ModeSetuid], [ModeSetgid], and
// [ModeSticky] are used.
//
// On Windows, only the 0o200 bit (owner writable) of mode is used; it
// controls whether the file's read-only attribute is set or cleared.
// The other bits are currently unused. For compatibility with Go 1.12
// and earlier, use a non-zero mode. Use mode 0o400 for a read-only
// file and 0o600 for a readable+writable file.
//
// On Plan 9, the mode's permission bits, [ModeAppend], [ModeExclusive],
// and [ModeTemporary] are used.
Chmod(name string, mode fs.FileMode) error
// Chown changes the numeric uid and gid of the named file.
// If the file is a symbolic link, it changes the uid and gid of the link's target.
// A uid or gid of -1 means to not change that value.
// If there is an error, it will be of type [*PathError].
//
// On Windows or Plan 9, Chown always returns the [syscall.EWINDOWS] or
// [syscall.EPLAN9] error, wrapped in [*PathError].
Chown(name string, uid, gid int) error
// Chtimes changes the access and modification times of the named
// file, similar to the Unix utime() or utimes() functions.
// A zero [time.Time] value will leave the corresponding file time unchanged.
//
// The underlying filesystem may truncate or round the values to a
// less precise time unit.
// If there is an error, it will be of type [*PathError].
Chtimes(name string, atime, mtime time.Time) error
// Create creates or truncates the named file. If the file already exists,
// it is truncated. If the file does not exist, it is created with mode 0o666
// (before umask). If successful, methods on the returned File can
// be used for I/O; the associated file descriptor has mode [O_RDWR].
// The directory containing the file must already exist.
// If there is an error, it will be of type [*PathError].
Create(name string) (File, error)
// CreateTemp creates a new temporary file in the directory dir,
// opens the file for reading and writing, and returns the resulting file.
// The filename is generated by taking pattern and adding a random string to the end.
// If pattern includes a "*", the random string replaces the last "*".
// The file is created with mode 0o600 (before umask).
// If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by [TempDir].
// Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file.
// The caller can use the file's Name method to find the pathname of the file.
// It is the caller's responsibility to remove the file when it is no longer needed.
CreateTemp(dir, pattern string) (File, error)
// EvalSymlinks returns the path name after the evaluation of any symbolic
// links.
// If path is relative the result will be relative to the current directory,
// unless one of the components is an absolute symbolic link.
// EvalSymlinks calls [Clean] on the result.
EvalSymlinks(path string) (string, error)
// Glob returns the names of all files matching pattern or nil
// if there is no matching file. The syntax of patterns is the same
// as in [Match]. The pattern may describe hierarchical names such as
// /usr/*/bin/ed (assuming the [Separator] is '/').
//
// Glob ignores file system errors such as I/O errors reading directories.
// The only possible returned error is [ErrBadPattern], when pattern
// is malformed.
Glob(pattern string) (matches []string, err error)
// UserHomeDir returns the current user's home directory.
//
// On Unix, including macOS, it returns the $HOME environment variable.
// On Windows, it returns %USERPROFILE%.
// On Plan 9, it returns the $home environment variable.
//
// If the expected variable is not set in the environment, UserHomeDir
// returns either a platform-specific default value or a non-nil error.
UserHomeDir() (string, error)
// Idm returns the identity manager of the file system.
// If the file system does not have an identity manager, avfs.DefaultIdm is returned.
Idm() IdmMgr
// Lchown changes the numeric uid and gid of the named file.
// If the file is a symbolic link, it changes the uid and gid of the link itself.
// If there is an error, it will be of type [*PathError].
//
// On Windows, it always returns the [syscall.EWINDOWS] error, wrapped
// in [*PathError].
Lchown(name string, uid, gid int) error
// Link creates newname as a hard link to the oldname file.
// If there is an error, it will be of type *LinkError.
Link(oldname, newname string) error
// Lstat returns a [FileInfo] describing the named file.
// If the file is a symbolic link, the returned [FileInfo]
// describes the symbolic link. Lstat makes no attempt to follow the link.
// If there is an error, it will be of type [*PathError].
//
// On Windows, if the file is a reparse point that is a surrogate for another
// named entity (such as a symbolic link or mounted folder), the returned
// [FileInfo] describes the reparse point, and makes no attempt to resolve it.
Lstat(name string) (fs.FileInfo, error)
// Mkdir creates a new directory with the specified name and permission
// bits (before umask).
// If there is an error, it will be of type [*PathError].
Mkdir(name string, perm fs.FileMode) error
// MkdirAll creates a directory named path,
// along with any necessary parents, and returns nil,
// or else returns an error.
// The permission bits perm (before umask) are used for all
// directories that MkdirAll creates.
// If path is already a directory, MkdirAll does nothing
// and returns nil.
MkdirAll(path string, perm fs.FileMode) error
// MkdirTemp creates a new temporary directory in the directory dir
// and returns the pathname of the new directory.
// The new directory's name is generated by adding a random string to the end of pattern.
// If pattern includes a "*", the random string replaces the last "*" instead.
// The directory is created with mode 0o700 (before umask).
// If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by [TempDir].
// Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory.
// It is the caller's responsibility to remove the directory when it is no longer needed.
MkdirTemp(dir, pattern string) (string, error)
// OpenFile is the generalized open call; most users will use Open
// or Create instead. It opens the named file with specified flag
// ([O_RDONLY] etc.). If the file does not exist, and the [O_CREATE] flag
// is passed, it is created with mode perm (before umask);
// the containing directory must exist. If successful,
// methods on the returned File can be used for I/O.
// If there is an error, it will be of type [*PathError].
OpenFile(name string, flag int, perm fs.FileMode) (File, error)
// ReadDir reads the named directory,
// returning all its directory entries sorted by filename.
// If an error occurs reading the directory,
// ReadDir returns the entries it was able to read before the error,
// along with the error.
ReadDir(name string) ([]fs.DirEntry, error)
// ReadFile reads the named file and returns the contents.
// A successful call returns err == nil, not err == EOF.
// Because ReadFile reads the whole file, it does not treat an EOF from Read
// as an error to be reported.
// If there is an error, it will be of type [*PathError].
ReadFile(name string) ([]byte, error)
// Readlink returns the destination of the named symbolic link.
// If there is an error, it will be of type [*PathError].
//
// If the link destination is relative, Readlink returns the relative path
// without resolving it to an absolute one.
Readlink(name string) (string, error)
// Remove removes the named file or (empty) directory.
// If there is an error, it will be of type [*PathError].
Remove(name string) error
// RemoveAll removes path and any children it contains.
// It removes everything it can but returns the first error
// it encounters. If the path does not exist, RemoveAll
// returns nil (no error).
// If there is an error, it will be of type [*PathError].
RemoveAll(path string) error
// Rename renames (moves) oldpath to newpath.
// If newpath already exists and is not a directory, Rename replaces it.
// If newpath already exists and is a directory, Rename returns an error.
// OS-specific restrictions may apply when oldpath and newpath are in different directories.
// Even within the same directory, on non-Unix platforms Rename is not an atomic operation.
// If there is an error, it will be of type *LinkError.
Rename(oldpath, newpath string) error
// SameFile reports whether fi1 and fi2 describe the same file.
// For example, on Unix this means that the device and inode fields
// of the two underlying structures are identical; on other systems
// the decision may be based on the path names.
// SameFile only applies to results returned by this package's [Stat].
// It returns false in other cases.
SameFile(fi1, fi2 fs.FileInfo) bool
// Stat returns a [FileInfo] describing the named file.
// If there is an error, it will be of type [*PathError].
Stat(name string) (fs.FileInfo, error)
// Symlink creates newname as a symbolic link to oldname.
// On Windows, a symlink to a non-existent oldname creates a file symlink;
// if oldname is later created as a directory the symlink will not work.
// If there is an error, it will be of type *LinkError.
Symlink(oldname, newname string) error
// Truncate changes the size of the named file.
// If the file is a symbolic link, it changes the size of the link's target.
// If there is an error, it will be of type [*PathError].
Truncate(name string, size int64) error
// WalkDir walks the file tree rooted at root, calling fn for each file or
// directory in the tree, including root.
//
// All errors that arise visiting files and directories are filtered by fn:
// see the [fs.WalkDirFunc] documentation for details.
//
// The files are walked in lexical order, which makes the output deterministic
// but requires WalkDir to read an entire directory into memory before proceeding
// to walk that directory.
//
// WalkDir does not follow symbolic links.
//
// WalkDir calls fn with paths that use the separator character appropriate
// for the operating system. This is unlike [io/fs.WalkDir], which always
// uses slash separated paths.
WalkDir(root string, fn fs.WalkDirFunc) error
// WriteFile writes data to the named file, creating it if necessary.
// If the file does not exist, WriteFile creates it with permissions perm (before umask);
// otherwise WriteFile truncates it before writing, without changing permissions.
// Since WriteFile requires multiple system calls to complete, a failure mid-operation
// can leave the file in a partially written state.
WriteFile(name string, data []byte, perm fs.FileMode) error
}
VFSBase regroups the common methods to VFS and IOFS.
type VFSPath ¶
type VFSPath interface {
// Base returns the last element of path.
// Trailing path separators are removed before extracting the last element.
// If the path is empty, Base returns ".".
// If the path consists entirely of separators, Base returns a single separator.
Base(path string) string
// Clean returns the shortest path name equivalent to path
// by purely lexical processing. It applies the following rules
// iteratively until no further processing can be done:
//
// 1. Replace multiple [Separator] elements with a single one.
// 2. Eliminate each . path name element (the current directory).
// 3. Eliminate each inner .. path name element (the parent directory)
// along with the non-.. element that precedes it.
// 4. Eliminate .. elements that begin a rooted path:
// that is, replace "/.." by "/" at the beginning of a path,
// assuming Separator is '/'.
//
// The returned path ends in a slash only if it represents a root directory,
// such as "/" on Unix or `C:\` on Windows.
//
// Finally, any occurrences of slash are replaced by Separator.
//
// If the result of this process is an empty string, Clean
// returns the string ".".
//
// On Windows, Clean does not modify the volume name other than to replace
// occurrences of "/" with `\`.
// For example, Clean("//host/share/../x") returns `\\host\share\x`.
//
// See also Rob Pike, “Lexical File Names in Plan 9 or
// Getting Dot-Dot Right,”
// https://9p.io/sys/doc/lexnames.html
Clean(path string) string
// Dir returns all but the last element of path, typically the path's directory.
// After dropping the final element, Dir calls [Clean] on the path and trailing
// slashes are removed.
// If the path is empty, Dir returns ".".
// If the path consists entirely of separators, Dir returns a single separator.
// The returned path does not end in a separator unless it is the root directory.
//
// On Windows, given a volume-only name such as "C:", Dir returns "C:.",
// the current directory on drive C. To obtain the drive's root "C:\",
// use VolumeName combined with a separator.
Dir(path string) string
// FromSlash returns the result of replacing each slash ('/') character
// in path with a separator character. Multiple slashes are replaced
// by multiple separators.
//
// See also the Localize function, which converts a slash-separated path
// as used by the io/fs package to an operating system path.
FromSlash(path string) string
// IsAbs reports whether the path is absolute.
IsAbs(path string) bool
// IsPathSeparator reports whether c is a directory separator character.
IsPathSeparator(c uint8) bool
// Join joins any number of path elements into a single path,
// separating them with an OS specific Separator. Empty elements
// are ignored. The result is Cleaned. However, if the argument
// list is empty or all its elements are empty, Join returns
// an empty string.
// On Windows, the result will only be a UNC path if the first
// non-empty element is a UNC path.
Join(elem ...string) string
// Match reports whether name matches the shell file name pattern.
// The pattern syntax is:
//
// pattern:
// { term }
// term:
// '*' matches any sequence of non-Separator characters
// '?' matches any single non-Separator character
// '[' [ '^' ] { character-range } ']'
// character class (must be non-empty)
// c matches character c (c != '*', '?', '\\', '[')
// '\\' c matches character c (except on Windows)
//
// character-range:
// c matches character c (c != '\\', '-', ']')
// '\\' c matches character c (except on Windows)
// lo '-' hi matches character c for lo <= c <= hi
//
// Match requires pattern to match all of name, not just a substring.
// The only possible returned error is [ErrBadPattern], when pattern
// is malformed.
//
// On Windows, escaping is disabled. Instead, '\\' is treated as
// path separator.
Match(pattern, name string) (matched bool, err error)
// PathSeparator return the OS-specific path separator.
PathSeparator() uint8
// Rel returns a relative path that is lexically equivalent to targpath when
// joined to basepath with an intervening separator. That is,
// [Join](basepath, Rel(basepath, targpath)) is equivalent to targpath itself.
//
// The returned path will always be relative to basepath, even if basepath and
// targpath share no elements. Rel calls Clean on the result.
//
// An error is returned if targpath can't be made relative to basepath or if
// knowing the current working directory would be necessary to compute it.
Rel(basepath, targpath string) (string, error)
// Split splits path immediately following the final [Separator],
// separating it into a directory and file name component.
// If there is no Separator in path, Split returns an empty dir
// and file set to path.
// The returned values have the property that path = dir+file.
Split(path string) (dir, file string)
// ToSlash returns the result of replacing each separator character
// in path with a slash ('/') character. Multiple separators are
// replaced by multiple slashes.
ToSlash(path string) string
// ToSysStat takes a value from fs.FileInfo.Sys() and returns a value that implements interface avfs.SysStater.
ToSysStat(info fs.FileInfo) SysStater
// VolumeName returns leading volume name.
// Given "C:\foo\bar" it returns "C:" on Windows.
// Given "\\host\share\foo" it returns "\\host\share".
// On other platforms it returns "".
VolumeName(path string) string
// VolumeNameLen returns the length of the leading volume name on Windows.
// It returns 0 elsewhere.
VolumeNameLen(path string) int
}
VFSPath defines an interface for OS-specific path operations.
type VFSUserDir ¶
type VFSUserDir interface {
// Abs returns an absolute representation of path.
// If the path is not absolute it will be joined with the current
// working directory to turn it into an absolute path. The absolute
// path name for a given file is not guaranteed to be unique.
// Abs calls [Clean] on the result.
Abs(path string) (string, error)
// Getwd returns an absolute path name corresponding to the
// current directory. If the current directory can be
// reached via multiple paths (due to symbolic links),
// Getwd may return any one of them.
//
// On Unix platforms, if the environment variable PWD
// provides an absolute name, and it is a name of the
// current directory, it is returned.
Getwd() (dir string, err error)
// TempDir returns the default directory to use for temporary files.
//
// On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
// On Windows, it uses GetTempPath, returning the first non-empty
// value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
// On Plan 9, it returns /tmp.
//
// The directory is neither guaranteed to exist nor have accessible
// permissions.
TempDir() string
// User returns the current user.
User() UserReader
}
VFSUserDir is the interface that provides the identity and the directories associated with the current user of a file system.
The identity (user, home and temporary directories) and the emulated OS type are immutable: they are set once, when the file system is built. A file system acting as another user, or emulating another OS, is obtained by cloning (see Cloner), so that the identity a file system acts as can never change while an operation is in flight. The current working directory is the only mutable part, as it is for os.Chdir.
type VolumeManager ¶
type VolumeManager interface {
// VolumeAdd adds a new volume to a Windows file system.
// If there is an error, it will be of type [*PathError].
VolumeAdd(name string) error
// VolumeDelete deletes an existing volume and all its files from a Windows file system.
// If there is an error, it will be of type [*PathError].
VolumeDelete(name string) error
// VolumeList returns the volumes of the file system.
VolumeList() []string
}
VolumeManager is the interface that manage volumes for Windows file systems.
type WindowsError ¶
type WindowsError uintptr
WindowsError replaces syscall.Errno for Windows operating systems.
const ( ErrWinAccessDenied WindowsError = 5 // Access is denied. ErrWinAlreadyExists WindowsError = 183 // Cannot create a file when that file already exists. ErrWinBadNetPath WindowsError = 53 // Bad network path. ErrWinDirNameInvalid WindowsError = 0x10B // The directory name is invalid. ErrWinDirNotEmpty WindowsError = 145 // The directory is not empty. ErrWinFileExists WindowsError = 80 // The file exists. ErrWinFileNotFound WindowsError = 2 // The system cannot find the file specified. ErrWinIncorrectFunc WindowsError = 1 // Incorrect function. ErrWinInvalidParameter WindowsError = 0x57 // The parameter is incorrect. ErrWinIsADirectory WindowsError = 0x2000002A // is a directory ErrWinNegativeSeek WindowsError = 0x83 // An attempt was made to move the file pointer before the beginning of the file. ErrWinNotReparsePoint WindowsError = 4390 // The file or directory is not a reparse point. ErrWinInvalidHandle WindowsError = 6 // The handle is invalid. ErrWinInvalidName WindowsError = 0x7b // The filename, directory name, or volume label syntax is incorrect. ErrWinSharingViolation WindowsError = 32 // The process cannot access the file because it is being used by another process. ErrWinNotSupported WindowsError = 0x20000082 // not supported by windows ErrWinPathNotFound WindowsError = 3 // The system cannot find the path specified. ErrWinPrivilegeNotHeld WindowsError = 1314 // A required privilege is not held by the client. )
Errors for Windows operating systems. See https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes
func (WindowsError) Error ¶
func (i WindowsError) Error() string
Error returns the error string of the Windows operating system.
func (WindowsError) Is ¶
func (i WindowsError) Is(target error) bool
Is returns true if the WindowsError can be treated as equivalent to a target error. target is one of fs.ErrPermission, fs.ErrExist, fs.ErrNotExist.
func (WindowsError) No ¶
func (i WindowsError) No() uint
func (WindowsError) String ¶
func (i WindowsError) String() string
Source Files
¶
- copy.go
- dummyidm.go
- errors.go
- errors_custom.go
- errors_forlinux.go
- errors_forwindows.go
- features.go
- features_string.go
- fnvfs.go
- fnvfs_string.go
- idm.go
- ostype.go
- ostype_string.go
- pathiterator.go
- rndtree.go
- tree.go
- umask.go
- umask_unix.go
- vfs.go
- vfs_aferoutils.go
- vfs_linkname.go
- vfs_path.go
- vfs_path_ostype_on.go
- vfs_types.go
- vfs_types_unix.go
- vfs_userdir.go
Directories
¶
| Path | Synopsis |
|---|---|
|
idm
|
|
|
memidm
Package memidm implements an in memory identity manager.
|
Package memidm implements an in memory identity manager. |
|
osidm
Package osidm implements an identity manager using os functions.
|
Package osidm implements an identity manager using os functions. |
|
Package test implements a test suite available to all file systems.
|
Package test implements a test suite available to all file systems. |
|
testbuild
command
|
|
|
vfs
|
|
|
basepathfs
Package basepathfs restricts all operations to a given path within a file system.
|
Package basepathfs restricts all operations to a given path within a file system. |
|
failfs
Package failfs is a file system adapter to test failures in a base file system.
|
Package failfs is a file system adapter to test failures in a base file system. |
|
memfs
Package memfs implements an in memory file system.
|
Package memfs implements an in memory file system. |
|
orefafs
Package orefafs implements an Afero like in memory file system.
|
Package orefafs implements an Afero like in memory file system. |
|
osfs
Package osfs implements a file system using functions from os and path/filepath packages.
|
Package osfs implements a file system using functions from os and path/filepath packages. |
|
ostestfs
Package ostestfs implements a file system using functions from os and path/filepath packages.
|
Package ostestfs implements a file system using functions from os and path/filepath packages. |
|
rofs
Package rofs provides a read only file system on top of any other Avfs file system.
|
Package rofs provides a read only file system on top of any other Avfs file system. |