avfs

package module
v0.35.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2024 License: Apache-2.0 Imports: 19 Imported by: 4

README

AVFS

Another Virtual File System for Go

CI codecov PkgGoDev Release License Built with Mage

Overview

AVFS is a virtual file system abstraction, inspired mostly by Afero and Go standard library. It provides an abstraction layer to emulate the behavior of a file system that provides several features :

  • a set of constants, interfaces and types for all file systems
  • a test suite for all file systems (emulated or real)
  • each file system has its own package
  • a very basic identity manager allows testing of user related functions (Chown, Lchown) and file system permissions

Additionally, some file systems support :

  • user file creation mode mask (Umask) (MemFS, OrefaFS)
  • chroot (OSFS on Linux)
  • hard links (MemFS, OrefaFS)
  • symbolic links (MemFS)
  • multiple users concurrently (MemFS)
  • Linux and Windows emulation regardless of host operating system (MemFS, OrefaFS)

Installation

This package can be installed with the go install command :

go install github.com/avfs/avfs@latest

It is only tested with Go version >= 1.18

Getting started

To make an existing code work with AVFS :

  • replace all references of os, path/filepath with the variable used to initialize the file system (vfs in the following examples)
  • import the packages of the file systems and, if necessary, the avfs package and initialize the file system variable.
  • some file systems provide specific options available at initialization. For instance MemFS needs WithSystemDirs option to create /home, /root and /tmp directories.

Examples

The example below demonstrates the creation of a file, a symbolic link to this file, for a different file systems (depending on an environment variable). Error management has been omitted for the sake of simplicity :

package main

import (
	"bytes"
	"log"
	"os"
	
	"github.com/avfs/avfs"
	"github.com/avfs/avfs/vfs/memfs"
	"github.com/avfs/avfs/vfs/osfs"
)

func main() {
	var vfs avfs.VFS

	switch os.Getenv("ENV") {
	case "PROD": // The real file system for production.
		vfs = osfs.NewWithNoIdm()
	default: // in memory for tests.
		vfs = memfs.New()
	}

	// From this point all references of 'os', 'path/filepath'
	// should be replaced by 'vfs'
	rootDir, _ := vfs.MkdirTemp("", "avfs")
	defer vfs.RemoveAll(rootDir)

	aFilePath := vfs.Join(rootDir, "aFile.txt")

	content := []byte("randomContent")
	_ = vfs.WriteFile(aFilePath, content, 0o644)

	aFilePathSl := vfs.Join(rootDir, "aFileSymlink.txt")
	_ = vfs.Symlink(aFilePath, aFilePathSl)

	gotContentSl, _ := vfs.ReadFile(aFilePathSl)
	if !bytes.Equal(content, gotContentSl) {
		log.Fatalf("Symlink %s : want content to be %v, got %v",
			aFilePathSl, content, gotContentSl)
	}

	log.Printf("content from symbolic link %s : %s", aFilePathSl, gotContentSl)
}
Multiple users creating simultaneously directories

The example below demonstrates the concurrent creation of subdirectories under a root directory by several users in different goroutines (works only with MemFS) :

package main

import (
	"fmt"
	"log"
	"sync"

	"github.com/avfs/avfs"
	"github.com/avfs/avfs/idm/memidm"
	"github.com/avfs/avfs/vfs/memfs"
)

func main() {
	const (
		maxUsers  = 100
		groupName = "test_users"
	)

	idm := memidm.New()
	vfs := memfs.New()

	rootDir, _ := vfs.MkdirTemp("", "avfs")
	vfs.Chmod(rootDir, 0o777)

	g, _ := idm.GroupAdd(groupName)

	var wg sync.WaitGroup
	wg.Add(maxUsers)

	for i := 0; i < maxUsers; i++ {
		go func(i int) {
			defer wg.Done()

			userName := fmt.Sprintf("user_%08d", i)
			idm.UserAdd(userName, g.Name())

			vfsU, _ := vfs.Sub("/")
			vfsU.SetUser(userName)

			path := vfsU.Join(rootDir, userName)
			vfsU.Mkdir(path, avfs.DefaultDirPerm)
		}(i)
	}

	wg.Wait()

	entries, _ := vfs.ReadDir(rootDir)

	log.Println("number of dirs :", len(entries))
	for _, entry := range entries {
		info, _ := entry.Info()
		sst := vfs.ToSysStat(info)

		u, _ := idm.LookupUserId(sst.Uid())

		log.Println("dir :", info.Name(),
			", mode :", info.Mode(),
			", owner :", u.Name())
	}
}

Status

Almost ready for Windows.

File systems

All file systems implement at least avfs.FS and avfs.File interfaces. By default, each file system supported methods are the most commonly used from packages os and path/filepath. All methods have identical names as their functions counterparts. The following file systems are currently available :

File system Comments
BasePathFS file system that restricts all operations to a given path within a file system
MemFS In memory file system supporting major features of a linux file system (hard links, symbolic links, chroot, umask)
OrefaFS Afero like in memory file system
OsFS Operating system native file system
RoFS Read only file system

Supported methods

File system methods
avfs.VFS
Comments
Abs equivalent to filepath.Abs
Base equivalent to filepath.Base
Chdir equivalent to os.Chdir
Chmod equivalent to os.Chmod
Chown equivalent to os.Chown
Chtimes equivalent to os.Chtimes
Clean equivalent to filepath.Clean
Create equivalent to os.Create
CreateTemp equivalent to os.CreateTemp
Dir equivalent to filepath.Dir
EvalSymlinks equivalent to filepath.EvalSymlinks
FromSlash equivalent to filepath.FromSlash
Features returns the set of features provided by the file system or identity manager
Getwd equivalent to os.Getwd
Glob equivalent to filepath.Glob
HasFeature returns true if the file system or identity manager provides a given feature
Idm returns the identity manager of the file system
IsAbs equivalent to filepath.IsAbs
IsPathSeparator equivalent to filepath.IsPathSeparator
Join equivalent to filepath.Join
Lchown equivalent to os.Lchown
Link equivalent to os.Link
Lstat equivalent to os.Lstat
Match equivalent to filepath.Match
Mkdir equivalent to os.Mkdir
MkdirAll equivalent to os.MkdirAll
MkdirTemp equivalent to os.MkdirTemp
Open equivalent to os.Open
OpenFile equivalent to os.OpenFile
OSType returns the operating system type of the file system
PathSeparator equivalent to os.PathSeparator
ReadDir equivalent to os.ReadDir
ReadFile equivalent to os.ReadFile
Readlink equivalent to os.Readlink
Rel equivalent to filepath.Rel
Remove equivalent to os.Remove
RemoveAll equivalent to os.RemoveAll
Rename equivalent to os.Rename
SameFile equivalent to os.SameFile
SetUMask sets the file mode creation mask
SetUser sets and returns the current user
Split equivalent to filepath.Split
Stat equivalent to os.Stat
Sub equivalent to fs.Sub
Symlink equivalent to os.Symlink
TempDir equivalent to os.TempDir
ToSlash equivalent to filepath.ToSlash
ToSysStat takes a value from fs.FileInfo.Sys() and returns a value that implements interface avfs.SysStater
Truncate equivalent to os.Truncate
UMask returns the file mode creation mask
User returns the current user
Utils returns the file utils of the current file system
WalkDir equivalent to filepath.WalkDir
WriteFile equivalent to os.WriteFile
File methods
avfs.File
Comments
Chdir equivalent to os.File.Chdir
Chmod equivalent to os.File.Chmod
Chown equivalent to os.File.Chown
Close equivalent to os.File.Close
Fd equivalent to os.File.Fd
Name equivalent to os.File.Name
Read equivalent to os.File.Read
ReadAt equivalent to os.File.ReadAt
ReadDir equivalent to os.File.ReadDir
Readdirnames equivalent to os.File.Readdirnames
Seek equivalent to os.File.Seek
Stat equivalent to os.File.Stat
Truncate equivalent to os.File.Truncate
Write equivalent to os.File.Write
WriteAt equivalent to os.File.WriteAt
WriteString equivalent to os.File.WriteString

Identity Managers

Identity managers allow users and groups management. The ones implemented in avfs are just here to allow testing of functions related to users (Chown, Lchown) and access rights, so they just allow one default group per user.

All file systems supporting identity manager implement by default the identity manager DummyIdm where all functions returns avfs.ErrPermDenied.

Identity Manager Comments
DummyIdm dummy identity manager where all functions are not implemented
MemIdm In memory identity manager
OsIdm Identity manager using os functions
SQLiteIdm Identity manager backed by a SQLite database
Identity Manager methods
avfs.FS
avfs.IdentityMgr
Comments
AdminGroup returns the administrator group (root for Linux)
AdminUser returns the administrator user (root for Linux)
GroupAdd adds a new group
GroupDel deletes an existing group
LookupGroup looks up a group by name
LookupGroupId looks up a group by groupid
LookupUser looks up a user by username
LookupUserId looks up a user by userid
UserAdd adds a new user
UserDel deletes an existing user

Documentation

Index

Constants

View Source
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
)

Variables

View Source
var ErrSetOSType = errors.New("can't set OS type, use build tag 'avfs_setostype' to set OS type")
View Source
var NotImplementedIdm = NewDummyIdm() //nolint:gochecknoglobals // Used as default Idm for other file systems.

NotImplementedIdm is the default identity manager for all file systems.

Functions

func Abs added in v0.34.0

func Abs[T VFSBase](vfs T, path, curDir 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 AdminGroupName added in v0.3.2

func AdminGroupName(osType OSType) string

AdminGroupName returns the name of the administrator group of the file system.

func AdminUserName added in v0.3.2

func AdminUserName(osType OSType) string

AdminUserName returns the name of the administrator of the file system.

func Base added in v0.34.0

func Base[T VFSBase](_ T, path string) string

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 Clean added in v0.34.0

func Clean[T VFSBase](_ T, 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 ".".

See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,” https://9p.io/sys/doc/lexnames.html

func CopyFile added in v0.3.2

func CopyFile(dstFs, srcFs VFSBase, dstPath, srcPath string) error

CopyFile copies a file between file systems and returns an error if any.

func CopyFileHash added in v0.3.2

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 Dir added in v0.34.0

func Dir[T VFSBase](_ T, 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.

func DirExists added in v0.3.2

func DirExists(vfs VFSBase, path string) (bool, error)

DirExists checks if a path exists and is a directory.

func Exists added in v0.3.2

func Exists(vfs VFSBase, path string) (bool, error)

Exists Check if a file or directory exists.

func FromSlash added in v0.34.0

func FromSlash[T VFSBase](_ T, 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.

func FromUnixPath added in v0.3.2

func FromUnixPath[T VFSBase](vfs T, path string) string

FromUnixPath returns 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 added in v0.34.0

func Glob[T VFSBase](vfs T, pattern string) (matches []string, err 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.

func HashFile added in v0.3.2

func HashFile(vfs VFSBase, name string, hasher hash.Hash) (sum []byte, err error)

HashFile hashes a file and returns the hash sum.

func HomeDir

func HomeDir[T VFSBase](vfs T, basePath string) string

HomeDir returns the home directory of the file system.

func HomeDirPerm

func HomeDirPerm() fs.FileMode

HomeDirPerm return the default permission for home directories.

func HomeDirUser added in v0.24.0

func HomeDirUser[T VFSBase](vfs T, basePath string, u UserReader) string

HomeDirUser returns the home directory of the user. If the file system does not have an identity manager, the root directory is returned.

func IsAbs added in v0.34.0

func IsAbs[T VFSBase](_ T, path string) bool

IsAbs reports whether the path is absolute.

func IsDir added in v0.3.2

func IsDir(vfs VFSBase, path string) (bool, error)

IsDir checks if a given path is a directory.

func IsEmpty added in v0.3.2

func IsEmpty(vfs VFSBase, path string) (bool, error)

IsEmpty checks if a given file or directory is empty.

func IsExist added in v0.34.0

func IsExist(err error) bool

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 added in v0.34.0

func IsNotExist(err error) bool

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 IsPathSeparator added in v0.34.0

func IsPathSeparator[T VFSBase](_ T, c uint8) bool

IsPathSeparator reports whether c is a directory separator character.

func Join added in v0.34.0

func Join[T VFSBase](_ T, elem ...string) string

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 Match added in v0.34.0

func Match[T VFSBase](_ T, pattern, name string) (matched bool, err error)

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

character-range:
	c           matches character c (c != '\\', '-', ']')
	'\\' c      matches character c
	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.

func MkHomeDir added in v0.34.0

func MkHomeDir[T VFSBase](vfs T, basePath string, u UserReader) (string, error)

MkHomeDir creates and returns the home directory of a user. If there is an error, it will be of type *PathError.

func MkSystemDirs added in v0.34.0

func MkSystemDirs[T VFSBase](vfs T, dirs []DirInfo) error

MkSystemDirs creates the system directories of a file system.

func MkdirTemp added in v0.34.0

func MkdirTemp[T VFSBase](vfs T, dir, pattern string) (string, 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. 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 added in v0.34.0

func ReadDir[T VFSBase](vfs T, name string) ([]fs.DirEntry, 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.

func ReadFile added in v0.34.0

func ReadFile[T VFSBase](vfs T, name string) ([]byte, 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.

func Rel added in v0.34.0

func Rel[T VFSBase](_ T, basepath, targpath string) (string, error)

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. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. 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 calls Clean on the result.

func SetUMask added in v0.3.2

func SetUMask(mask fs.FileMode) error

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 SetUserByName added in v0.34.0

func SetUserByName[T VFSBase](vfs T, name string) error

SetUserByName sets the current user by name. If the user is not found, the returned error is of type UnknownUserError.

func Split added in v0.34.0

func Split[T VFSBase](_ T, path string) (dir, file string)

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 SplitAbs added in v0.34.0

func SplitAbs[T VFSBase](vfs T, path string) (dir, file string)

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, splitPath returns an empty dir and file set to path. The returned values have the property that path = dir + PathSeparator + file.

func TempDir added in v0.34.0

func TempDir[T VFSBase](vfs T) 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 TempDirUser added in v0.34.0

func TempDirUser[T VFSBase](vfs T, basePath, username string) string

TempDirUser returns the default directory to use for temporary files with for a specific user.

func ToSlash added in v0.34.0

func ToSlash[T VFSBase](_ T, path string) string

ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.

func Tree added in v0.34.0

func Tree(vfs VFSBase, path string) string

Tree returns a textual representation of the directory structure.

func UMask added in v0.3.2

func UMask() fs.FileMode

UMask returns the file mode creation mask.

func VolumeName added in v0.34.0

func VolumeName[T VFSBase](vfs T, path string) string

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 VolumeNameLen added in v0.34.0

func VolumeNameLen[T VFSBase](_ T, path string) int

VolumeNameLen returns length of the leading volume name on Windows. It returns 0 elsewhere.

func WalkDir added in v0.34.0

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.

func WriteFile added in v0.34.0

func WriteFile[T VFSBase](vfs T, name string, data []byte, perm fs.FileMode) 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.

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 avfs.errPermDenied is returned.
	// 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 {
	// Clone returns a shallow copy of the current file system (see MemFs).
	Clone() VFS
}

Cloner is the interface that wraps the Clone method.

type CurDirFn added in v0.34.0

type CurDirFn struct {
	// contains filtered or unexported fields
}

CurDirFn provides current directory functions to a file system.

func (*CurDirFn) CurDir added in v0.34.0

func (cdf *CurDirFn) CurDir() string

CurDir returns the current directory.

func (*CurDirFn) SetCurDir added in v0.34.0

func (cdf *CurDirFn) SetCurDir(curDir string) error

SetCurDir sets the current directory.

type CurDirMgr added in v0.34.0

type CurDirMgr interface {
	// CurDir returns the current directory.
	CurDir() string

	// SetCurDir sets the current directory.
	SetCurDir(curDir string) error
}

CurDirMgr is the interface that manages the current directory.

type CurUserFn added in v0.34.0

type CurUserFn struct {
	// contains filtered or unexported fields
}

CurUserFn provides current user functions to a file system.

func (*CurUserFn) SetUser added in v0.34.0

func (vst *CurUserFn) SetUser(user UserReader) error

SetUser sets the current user.

func (*CurUserFn) User added in v0.34.0

func (vst *CurUserFn) User() UserReader

User returns the current user.

type CurUserMgr added in v0.34.0

type CurUserMgr interface {
	// SetUser sets the current user.
	// If the user can't be changed an error is returned.
	SetUser(user UserReader) error

	// SetUserByName sets the current user by name.
	// If the user is not found, the returned error is of type UnknownUserError.
	SetUserByName(name string) error

	// User returns the current user.
	User() UserReader
}

CurUserMgr is the interface that wraps the current user related methods of a file system.

type CustomError added in v0.3.2

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.
)

func (CustomError) Error added in v0.3.2

func (i CustomError) Error() string

func (CustomError) String added in v0.3.2

func (i CustomError) String() string

type DirInfo added in v0.3.2

type DirInfo struct {
	Path string
	Perm fs.FileMode
}

DirInfo contains information to create a directory.

func SystemDirs added in v0.34.0

func SystemDirs[T VFSBase](vfs T, basePath string) []DirInfo

SystemDirs returns an array of system directories always present in the file system.

type DummyGroup added in v0.23.0

type DummyGroup struct {
	// contains filtered or unexported fields
}

DummyGroup is the implementation of avfs.GroupReader.

func NewGroup added in v0.34.0

func NewGroup(name string, gid int) *DummyGroup

func (*DummyGroup) Gid added in v0.23.0

func (g *DummyGroup) Gid() int

Gid returns the Group ID.

func (*DummyGroup) Name added in v0.23.0

func (g *DummyGroup) Name() string

Name returns the Group name.

type DummyIdm added in v0.23.0

type DummyIdm struct {
	// contains filtered or unexported fields
}

DummyIdm represent a non implemented identity manager using the avfs.IdentityMgr interface.

func NewDummyIdm added in v0.23.0

func NewDummyIdm() *DummyIdm

NewDummyIdm create a new identity manager.

func (*DummyIdm) AdminGroup added in v0.25.0

func (idm *DummyIdm) AdminGroup() GroupReader

AdminGroup returns the administrators (root) group.

func (*DummyIdm) AdminUser added in v0.25.0

func (idm *DummyIdm) AdminUser() UserReader

AdminUser returns the administrator (root) user.

func (*DummyIdm) Features added in v0.23.0

func (idm *DummyIdm) Features() Features

Features returns the set of features provided by the file system or identity manager.

func (*DummyIdm) GroupAdd added in v0.23.0

func (idm *DummyIdm) GroupAdd(name string) (GroupReader, error)

GroupAdd adds a new group.

func (*DummyIdm) GroupDel added in v0.23.0

func (idm *DummyIdm) GroupDel(name string) error

GroupDel deletes an existing group.

func (*DummyIdm) HasFeature added in v0.23.0

func (idm *DummyIdm) HasFeature(feature Features) bool

HasFeature returns true if the file system or identity manager provides a given feature.

func (*DummyIdm) LookupGroup added in v0.23.0

func (idm *DummyIdm) LookupGroup(name string) (GroupReader, error)

LookupGroup looks up a group by name. If the group cannot be found, the returned error is of type UnknownGroupError.

func (*DummyIdm) LookupGroupId added in v0.23.0

func (idm *DummyIdm) LookupGroupId(gid int) (GroupReader, error)

LookupGroupId looks up a group by groupid. If the group cannot be found, the returned error is of type UnknownGroupIdError.

func (*DummyIdm) LookupUser added in v0.23.0

func (idm *DummyIdm) LookupUser(name string) (UserReader, error)

LookupUser looks up a user by username. If the user cannot be found, the returned error is of type UnknownUserError.

func (*DummyIdm) LookupUserId added in v0.23.0

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 UnknownUserIdError.

func (*DummyIdm) OSType added in v0.34.0

func (idm *DummyIdm) OSType() OSType

OSType returns the operating system type of the identity manager.

func (*DummyIdm) Type added in v0.23.0

func (idm *DummyIdm) Type() string

Type returns the type of the fileSystem or Identity manager.

func (*DummyIdm) UserAdd added in v0.23.0

func (idm *DummyIdm) UserAdd(name, groupName string) (UserReader, error)

UserAdd adds a new user.

func (*DummyIdm) UserDel added in v0.23.0

func (idm *DummyIdm) UserDel(name string) error

UserDel deletes an existing group.

type DummyUser added in v0.23.0

type DummyUser struct {
	// contains filtered or unexported fields
}

DummyUser is the implementation of avfs.UserReader.

func NewUser added in v0.34.0

func NewUser(name string, uid, gid int) *DummyUser

func (*DummyUser) Gid added in v0.23.0

func (u *DummyUser) Gid() int

Gid returns the primary Group ID of the User.

func (*DummyUser) IsAdmin added in v0.25.0

func (u *DummyUser) IsAdmin() bool

IsAdmin returns true if the user has administrator (root) privileges.

func (*DummyUser) Name added in v0.23.0

func (u *DummyUser) Name() string

Name returns the username.

func (*DummyUser) Uid added in v0.23.0

func (u *DummyUser) Uid() int

Uid returns the User ID.

type ErrorIdentifier added in v0.3.2

type ErrorIdentifier interface {
	error

	// 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
}

ErrorIdentifier is the interface that wraps the Is method of an error.

type Errors added in v0.3.2

type Errors struct {
	BadFileDesc     error // bad file descriptor.
	DirNotEmpty     error // Directory not empty.
	FileExists      error // File exists.
	InvalidArgument error // invalid argument
	IsADirectory    error // File Is a directory.
	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.
}

Errors regroups errors depending on the OS emulated.

func (*Errors) SetOSType added in v0.3.2

func (e *Errors) SetOSType(osType OSType)

SetOSType sets errors depending on the operating system.

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 added in v0.3.2

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 can be changed (see MemFS).
	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 added in v0.3.2

func BuildFeatures() Features

BuildFeatures returns the features available depending on build tags.

func (Features) String added in v0.3.2

func (i Features) String() string

type FeaturesFn added in v0.34.0

type FeaturesFn struct {
	// contains filtered or unexported fields
}

FeaturesFn provides features functions to a file system or an identity manager.

func (*FeaturesFn) Features added in v0.34.0

func (ftf *FeaturesFn) Features() Features

Features returns the set of features provided by the file system or identity manager.

func (*FeaturesFn) HasFeature added in v0.34.0

func (ftf *FeaturesFn) HasFeature(feature Features) bool

HasFeature returns true if the file system or identity manager provides a given feature.

func (*FeaturesFn) SetFeatures added in v0.34.0

func (ftf *FeaturesFn) 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 integer Unix file descriptor referencing the open file.
	// The file descriptor is valid only until f.Close is called or f is garbage collected.
	// On Unix systems this will cause the SetDeadline methods to stop working.
	Fd() uintptr

	// Name returns the name of the file as presented to Open.
	Name() string

	// Readdirnames reads and returns a slice of names from the directory f.
	//
	// 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 added in v0.34.0

func Create[T VFSBase](vfs T, name string) (File, 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 0666 (before umask). If successful, methods on the returned DummyFile can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

func CreateTemp added in v0.34.0

func CreateTemp[T VFSBase](vfs T, dir, pattern 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 "*". 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 added in v0.34.0

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
	FnSetUser
	FnSetUserByName
	FnStat
	FnSub
	FnSymlink
	FnTruncate
	FnWalkDir
	FnWriteFile
)

func (FnVFS) String added in v0.34.0

func (i FnVFS) String() string

type GroupIdentifier added in v0.3.2

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 IOFS added in v0.3.2

type IOFS interface {
	VFSBase
	fs.FS
	fs.GlobFS
	fs.ReadDirFS
	fs.ReadFileFS
	fs.StatFS
	fs.SubFS
}

IOFS is the virtual file system interface implementing io/fs interfaces.

type IdentityMgr

type IdentityMgr interface {
	Featurer
	OSTyper
	Typer

	// AdminGroup returns the administrator (root) group.
	AdminGroup() GroupReader

	// AdminUser returns the administrator (root) user.
	AdminUser() UserReader

	// GroupAdd adds a new group.
	// If the group already exists, the returned error is of type AlreadyExistsGroupError.
	GroupAdd(name string) (GroupReader, error)

	// GroupDel deletes an existing group.
	// If the group is not found, the returned error is of type UnknownGroupError.
	GroupDel(name string) error

	// LookupGroup looks up a group by name.
	// If the group is not found, the returned error is of type UnknownGroupError.
	LookupGroup(name string) (GroupReader, error)

	// LookupGroupId looks up a group by groupid.
	// If the group is not found, the returned error is of type UnknownGroupIdError.
	LookupGroupId(gid int) (GroupReader, error)

	// LookupUser looks up a user by username.
	// If the user cannot be found, the returned error is of type UnknownUserError.
	LookupUser(name string) (UserReader, error)

	// LookupUserId looks up a user by userid.
	// If the user cannot be found, the returned error is of type UnknownUserIdError.
	LookupUserId(uid int) (UserReader, error)

	// UserAdd adds a new user.
	// If the user already exists, the returned error is of type AlreadyExistsUserError.
	UserAdd(name, groupName string) (UserReader, error)

	// UserDel deletes an existing user.
	UserDel(name string) error
}

IdentityMgr interface manages identities (users and groups).

type IdmFn added in v0.34.0

type IdmFn struct {
	// contains filtered or unexported fields
}

IdmFn provides identity manager functions to a file system.

func (*IdmFn) Idm added in v0.34.0

func (idf *IdmFn) Idm() IdentityMgr

Idm returns the identity manager of the file system.

func (*IdmFn) SetIdm added in v0.34.0

func (idf *IdmFn) SetIdm(idm IdentityMgr) error

SetIdm set the current identity manager. If the identity manager provider is nil, the idm NotImplementedIdm is set.

type IdmMgr added in v0.34.0

type IdmMgr interface {
	// Idm returns the identity manager of the file system.
	Idm() IdentityMgr

	// SetIdm set the current identity manager.
	// If the identity manager provider is nil, the idm dummyidm.NotImplementedIdm is set.
	SetIdm(idm IdentityMgr) error
}

IdmMgr is the interface that wraps Identity manager setting methods for file systems.

type LinuxError added in v0.3.2

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 added in v0.3.2

func (i LinuxError) Error() string

Error returns the error string of the Linux operating system.

func (LinuxError) Is added in v0.3.2

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 added in v0.3.2

func (i LinuxError) String() string

type Namer

type Namer interface {
	Name() string
}

Namer is the interface that wraps the Name method.

type OSType added in v0.3.2

type OSType uint16

OSType defines the operating system type.

const (
	OsUnknown OSType = iota // Unknown
	OsLinux                 // Linux
	OsWindows               // Windows
	OsDarwin                // Darwin
)

func CurrentOSType added in v0.3.2

func CurrentOSType() OSType

CurrentOSType returns the current OSType.

func (OSType) String added in v0.3.2

func (i OSType) String() string

type OSTypeFn added in v0.34.0

type OSTypeFn struct {
	// contains filtered or unexported fields
}

OSTypeFn provides OS type functions to a file system or an identity manager.

func (*OSTypeFn) OSType added in v0.34.0

func (osf *OSTypeFn) OSType() OSType

OSType returns the operating system type of the file system.

func (*OSTypeFn) PathSeparator added in v0.34.0

func (osf *OSTypeFn) PathSeparator() uint8

PathSeparator return the OS-specific path separator.

func (*OSTypeFn) SetOSType added in v0.34.0

func (osf *OSTypeFn) SetOSType(osType OSType) error

SetOSType sets the operating system Type. If the OS type can't be changed it returns an error.

type OSTyper added in v0.3.2

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 added in v0.3.2

type OpenMode uint16

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).
)

func ToOpenMode added in v0.34.0

func ToOpenMode(flag int) OpenMode

ToOpenMode returns the open mode from the input flags.

type PathIterator added in v0.3.2

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 added in v0.3.2

func NewPathIterator[T VFSBase](vfs T, path string) *PathIterator[T]

NewPathIterator creates a new path iterator from an absolute path.

func (*PathIterator[_]) End added in v0.3.2

func (pi *PathIterator[_]) End() int

End returns the end position of the current Part.

func (*PathIterator[_]) IsLast added in v0.3.2

func (pi *PathIterator[_]) IsLast() bool

IsLast returns true if the current Part is the last one.

func (*PathIterator[_]) Left added in v0.3.2

func (pi *PathIterator[_]) Left() string

Left returns the left path of the current Part.

func (*PathIterator[_]) LeftPart added in v0.3.2

func (pi *PathIterator[_]) LeftPart() string

LeftPart returns the left path and current Part.

func (*PathIterator[_]) Next added in v0.3.2

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 added in v0.3.2

func (pi *PathIterator[_]) Part() string

Part returns the current Part.

func (*PathIterator[_]) Path added in v0.3.2

func (pi *PathIterator[_]) Path() string

Path returns the path to iterate.

func (*PathIterator[_]) ReplacePart added in v0.3.2

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[_]) Reset added in v0.3.2

func (pi *PathIterator[_]) Reset()

Reset resets the iterator.

func (*PathIterator[_]) Right added in v0.3.2

func (pi *PathIterator[_]) Right() string

Right returns the right path of the current Part.

func (*PathIterator[_]) RightPart added in v0.3.2

func (pi *PathIterator[_]) RightPart() string

RightPart returns the right path and the current Part.

func (*PathIterator[_]) Start added in v0.3.2

func (pi *PathIterator[_]) Start() int

Start returns the start position of the current Part.

func (*PathIterator[_]) VolumeName added in v0.3.2

func (pi *PathIterator[_]) VolumeName() string

VolumeName returns leading volume name.

func (*PathIterator[_]) VolumeNameLen added in v0.3.2

func (pi *PathIterator[_]) VolumeNameLen() int

VolumeNameLen returns length of the leading volume name on Windows. It returns 0 elsewhere.

type RndTree added in v0.3.2

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 added in v0.3.2

func NewRndTree(vfs VFSBase, opts *RndTreeOpts) *RndTree

NewRndTree returns a new random tree generator.

func (*RndTree) CreateDirs added in v0.3.2

func (rt *RndTree) CreateDirs(baseDir string) error

CreateDirs creates random directories.

func (*RndTree) CreateFiles added in v0.3.2

func (rt *RndTree) CreateFiles(baseDir string) error

CreateFiles creates random files.

func (rt *RndTree) CreateSymlinks(baseDir string) error

CreateSymlinks creates random symbolic links.

func (*RndTree) CreateTree added in v0.3.2

func (rt *RndTree) CreateTree(baseDir string) error

CreateTree creates a random tree structure.

func (*RndTree) Dirs added in v0.3.2

func (rt *RndTree) Dirs() []*RndTreeDir

func (*RndTree) Files added in v0.3.2

func (rt *RndTree) Files() []*RndTreeFile

func (*RndTree) GenTree added in v0.3.2

func (rt *RndTree) GenTree()

GenTree generates a random tree and populates RndTree.Dirs, RndTree.Files and RndTree.SymLinks.

func (rt *RndTree) SymLinks() []*RndTreeSymLink

type RndTreeDir added in v0.3.2

type RndTreeDir struct {
	Name  string
	Depth int
}

RndTreeDir contains parameters to create a directory.

type RndTreeFile added in v0.3.2

type RndTreeFile struct {
	Name string
	Size int
}

RndTreeFile contains parameters to create a file.

type RndTreeOpts added in v0.3.2

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 struct {
	OldName, NewName string
}

RndTreeSymLink contains parameters to create a symbolic link.

type SysStater added in v0.3.2

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 UMaskFn added in v0.34.0

type UMaskFn struct {
	// contains filtered or unexported fields
}

UMaskFn provides UMask functions to file systems.

func (*UMaskFn) SetUMask added in v0.34.0

func (umf *UMaskFn) SetUMask(mask fs.FileMode) error

SetUMask sets the file mode creation mask.

func (*UMaskFn) UMask added in v0.34.0

func (umf *UMaskFn) 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 UserIdentifier added in v0.3.2

type UserIdentifier interface {
	// Uid returns the user id.
	Uid() int
}

UserIdentifier is the interface that wraps the Uid method.

type UserReader

type UserReader interface {
	GroupIdentifier
	UserIdentifier
	Namer

	// IsAdmin returns true if the user has administrator (root) privileges.
	IsAdmin() bool
}

UserReader reads user information.

type VFS added in v0.3.2

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 added in v0.3.2

type VFSBase interface {
	CurUserMgr
	Featurer
	IdmMgr
	Namer
	OSTyper
	Typer
	UMasker

	// 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)

	// 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 0200 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 0400 for a read-only
	// file and 0600 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
	// 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.
	//
	// The underlying file system 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

	// 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 ".".
	//
	// 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

	// Create creates the named file with mode 0666 (before umask), truncating
	// it if it already exists. If successful, methods on the returned
	// File can be used for I/O; the associated file descriptor has mode
	// O_RDWR.
	// 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 "*".
	// 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)

	// 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.
	Dir(path string) string

	// 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)

	// FromSlash returns the result of replacing each slash ('/') character
	// in path with a separator character. Multiple slashes are replaced
	// by multiple separators.
	FromSlash(path string) string

	// Getwd returns a rooted 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.
	Getwd() (dir string, err 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)

	// Idm returns the identity manager of the file system.
	// if the file system does not have an identity manager, avfs.DummyIdm is returned.
	Idm() IdentityMgr

	// 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, adding a
	// separating slash if necessary. The result is Cleaned; in particular,
	// all empty strings are ignored.
	Join(elem ...string) string

	// 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.
	Lstat(name string) (fs.FileInfo, error)

	// 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
	//
	//	character-range:
	//		c           matches character c (c != '\\', '-', ']')
	//		'\\' c      matches character c
	//		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)

	// 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.
	// 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.) and perm (before umask), if applicable. 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)

	// PathSeparator return the OS-specific path separator.
	PathSeparator() uint8

	// 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 file named by filename 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.
	ReadFile(filename string) ([]byte, error)

	// Readlink returns the destination of the named symbolic link.
	// If there is an error, it will be of type *PathError.
	Readlink(name string) (string, error)

	// 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.
	// On success, the returned path will always be relative to basepath,
	// even if basepath and targpath share no elements.
	// 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 calls Clean on the result.
	Rel(basepath, targpath 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).
	RemoveAll(path string) error

	// Rename renames (moves) oldpath to newpath.
	// If newpath already exists and is not a directory, Rename replaces it.
	// OS-specific restrictions may apply when oldpath and newpath are in different directories.
	// 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

	// 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)

	// 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.
	// If there is an error, it will be of type *LinkError.
	Symlink(oldname, newname string) 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

	// 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

	// 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(root string, fn fs.WalkDirFunc) error

	// WriteFile writes data to a file named by filename.
	// If the file does not exist, WriteFile creates it with permissions perm;
	// otherwise WriteFile truncates it before writing.
	WriteFile(filename string, data []byte, perm fs.FileMode) error
}

VFSBase regroups the common methods to VFS and IOFS.

type VolumeManager added in v0.3.2

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 added in v0.3.2

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.
	ErrWinIsADirectory     WindowsError = 21         // 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.
	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 added in v0.3.2

func (i WindowsError) Error() string

Error returns the error string of the Windows operating system.

func (WindowsError) Is added in v0.3.2

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) String added in v0.3.2

func (i WindowsError) String() string

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.
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL